[x86] Rewrite a core part of the new vector shuffle lowering to handle
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
663
664   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
665     // f32 and f64 use SSE.
666     // Set up the FP register classes.
667     addRegisterClass(MVT::f32, &X86::FR32RegClass);
668     addRegisterClass(MVT::f64, &X86::FR64RegClass);
669
670     // Use ANDPD to simulate FABS.
671     setOperationAction(ISD::FABS , MVT::f64, Custom);
672     setOperationAction(ISD::FABS , MVT::f32, Custom);
673
674     // Use XORP to simulate FNEG.
675     setOperationAction(ISD::FNEG , MVT::f64, Custom);
676     setOperationAction(ISD::FNEG , MVT::f32, Custom);
677
678     // Use ANDPD and ORPD to simulate FCOPYSIGN.
679     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
680     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
681
682     // Lower this to FGETSIGNx86 plus an AND.
683     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
684     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
685
686     // We don't support sin/cos/fmod
687     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
688     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
689     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
690     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
691     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
692     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
693
694     // Expand FP immediates into loads from the stack, except for the special
695     // cases we handle.
696     addLegalFPImmediate(APFloat(+0.0)); // xorpd
697     addLegalFPImmediate(APFloat(+0.0f)); // xorps
698   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
699     // Use SSE for f32, x87 for f64.
700     // Set up the FP register classes.
701     addRegisterClass(MVT::f32, &X86::FR32RegClass);
702     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
703
704     // Use ANDPS to simulate FABS.
705     setOperationAction(ISD::FABS , MVT::f32, Custom);
706
707     // Use XORP to simulate FNEG.
708     setOperationAction(ISD::FNEG , MVT::f32, Custom);
709
710     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
711
712     // Use ANDPS and ORPS to simulate FCOPYSIGN.
713     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
714     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
715
716     // We don't support sin/cos/fmod
717     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
718     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
719     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
720
721     // Special cases we handle for FP constants.
722     addLegalFPImmediate(APFloat(+0.0f)); // xorps
723     addLegalFPImmediate(APFloat(+0.0)); // FLD0
724     addLegalFPImmediate(APFloat(+1.0)); // FLD1
725     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
726     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
727
728     if (!TM.Options.UnsafeFPMath) {
729       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
730       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
731       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
732     }
733   } else if (!TM.Options.UseSoftFloat) {
734     // f32 and f64 in x87.
735     // Set up the FP register classes.
736     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
737     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
738
739     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
740     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
741     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
743
744     if (!TM.Options.UnsafeFPMath) {
745       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
746       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
747       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
749       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
751     }
752     addLegalFPImmediate(APFloat(+0.0)); // FLD0
753     addLegalFPImmediate(APFloat(+1.0)); // FLD1
754     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
755     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
756     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
757     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
758     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
759     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
760   }
761
762   // We don't support FMA.
763   setOperationAction(ISD::FMA, MVT::f64, Expand);
764   setOperationAction(ISD::FMA, MVT::f32, Expand);
765
766   // Long double always uses X87.
767   if (!TM.Options.UseSoftFloat) {
768     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
769     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
770     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
771     {
772       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
773       addLegalFPImmediate(TmpFlt);  // FLD0
774       TmpFlt.changeSign();
775       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
776
777       bool ignored;
778       APFloat TmpFlt2(+1.0);
779       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
780                       &ignored);
781       addLegalFPImmediate(TmpFlt2);  // FLD1
782       TmpFlt2.changeSign();
783       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
784     }
785
786     if (!TM.Options.UnsafeFPMath) {
787       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
788       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
789       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
790     }
791
792     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
793     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
794     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
795     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
796     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
797     setOperationAction(ISD::FMA, MVT::f80, Expand);
798   }
799
800   // Always use a library call for pow.
801   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
802   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
804
805   setOperationAction(ISD::FLOG, MVT::f80, Expand);
806   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
808   setOperationAction(ISD::FEXP, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
810
811   // First set operation action for all vector types to either promote
812   // (for widening) or expand (for scalarization). Then we will selectively
813   // turn on ones that can be effectively codegen'd.
814   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
815            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
816     MVT VT = (MVT::SimpleValueType)i;
817     setOperationAction(ISD::ADD , VT, Expand);
818     setOperationAction(ISD::SUB , VT, Expand);
819     setOperationAction(ISD::FADD, VT, Expand);
820     setOperationAction(ISD::FNEG, VT, Expand);
821     setOperationAction(ISD::FSUB, VT, Expand);
822     setOperationAction(ISD::MUL , VT, Expand);
823     setOperationAction(ISD::FMUL, VT, Expand);
824     setOperationAction(ISD::SDIV, VT, Expand);
825     setOperationAction(ISD::UDIV, VT, Expand);
826     setOperationAction(ISD::FDIV, VT, Expand);
827     setOperationAction(ISD::SREM, VT, Expand);
828     setOperationAction(ISD::UREM, VT, Expand);
829     setOperationAction(ISD::LOAD, VT, Expand);
830     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
831     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
832     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
833     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
834     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::FABS, VT, Expand);
836     setOperationAction(ISD::FSIN, VT, Expand);
837     setOperationAction(ISD::FSINCOS, VT, Expand);
838     setOperationAction(ISD::FCOS, VT, Expand);
839     setOperationAction(ISD::FSINCOS, VT, Expand);
840     setOperationAction(ISD::FREM, VT, Expand);
841     setOperationAction(ISD::FMA,  VT, Expand);
842     setOperationAction(ISD::FPOWI, VT, Expand);
843     setOperationAction(ISD::FSQRT, VT, Expand);
844     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
845     setOperationAction(ISD::FFLOOR, VT, Expand);
846     setOperationAction(ISD::FCEIL, VT, Expand);
847     setOperationAction(ISD::FTRUNC, VT, Expand);
848     setOperationAction(ISD::FRINT, VT, Expand);
849     setOperationAction(ISD::FNEARBYINT, VT, Expand);
850     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
851     setOperationAction(ISD::MULHS, VT, Expand);
852     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
853     setOperationAction(ISD::MULHU, VT, Expand);
854     setOperationAction(ISD::SDIVREM, VT, Expand);
855     setOperationAction(ISD::UDIVREM, VT, Expand);
856     setOperationAction(ISD::FPOW, VT, Expand);
857     setOperationAction(ISD::CTPOP, VT, Expand);
858     setOperationAction(ISD::CTTZ, VT, Expand);
859     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
860     setOperationAction(ISD::CTLZ, VT, Expand);
861     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
862     setOperationAction(ISD::SHL, VT, Expand);
863     setOperationAction(ISD::SRA, VT, Expand);
864     setOperationAction(ISD::SRL, VT, Expand);
865     setOperationAction(ISD::ROTL, VT, Expand);
866     setOperationAction(ISD::ROTR, VT, Expand);
867     setOperationAction(ISD::BSWAP, VT, Expand);
868     setOperationAction(ISD::SETCC, VT, Expand);
869     setOperationAction(ISD::FLOG, VT, Expand);
870     setOperationAction(ISD::FLOG2, VT, Expand);
871     setOperationAction(ISD::FLOG10, VT, Expand);
872     setOperationAction(ISD::FEXP, VT, Expand);
873     setOperationAction(ISD::FEXP2, VT, Expand);
874     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
875     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
876     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
877     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
879     setOperationAction(ISD::TRUNCATE, VT, Expand);
880     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
881     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
882     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
883     setOperationAction(ISD::VSELECT, VT, Expand);
884     setOperationAction(ISD::SELECT_CC, VT, Expand);
885     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
886              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
887       setTruncStoreAction(VT,
888                           (MVT::SimpleValueType)InnerVT, Expand);
889     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
890     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
891
892     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
893     // we have to deal with them whether we ask for Expansion or not. Setting
894     // Expand causes its own optimisation problems though, so leave them legal.
895     if (VT.getVectorElementType() == MVT::i1)
896       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
897   }
898
899   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
900   // with -msoft-float, disable use of MMX as well.
901   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
902     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
903     // No operations on x86mmx supported, everything uses intrinsics.
904   }
905
906   // MMX-sized vectors (other than x86mmx) are expected to be expanded
907   // into smaller operations.
908   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
909   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
910   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
912   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
913   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
914   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
915   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
916   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
917   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
918   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
919   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
920   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
921   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
922   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
923   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
924   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
928   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
929   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
930   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
931   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
933   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
937
938   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
939     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
940
941     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
942     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
946     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
947     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
948     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
949     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
950     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
951     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
952     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
953   }
954
955   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
956     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
957
958     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
959     // registers cannot be used even for integer operations.
960     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
961     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
962     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
963     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
964
965     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
966     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
967     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
968     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
969     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
970     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
971     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
972     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
974     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
975     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
976     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
977     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
978     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
979     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
980     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
981     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
985     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
986     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
987
988     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
989     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
992
993     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
998
999     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1000     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001       MVT VT = (MVT::SimpleValueType)i;
1002       // Do not attempt to custom lower non-power-of-2 vectors
1003       if (!isPowerOf2_32(VT.getVectorNumElements()))
1004         continue;
1005       // Do not attempt to custom lower non-128-bit vectors
1006       if (!VT.is128BitVector())
1007         continue;
1008       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1009       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1010       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1011     }
1012
1013     // We support custom legalizing of sext and anyext loads for specific
1014     // memory vector types which we can load as a scalar (or sequence of
1015     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1016     // loads these must work with a single scalar load.
1017     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1018     if (Subtarget->is64Bit()) {
1019       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1021     }
1022     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1028
1029     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1031     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1033     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1034     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1035
1036     if (Subtarget->is64Bit()) {
1037       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1038       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1039     }
1040
1041     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1042     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1043       MVT VT = (MVT::SimpleValueType)i;
1044
1045       // Do not attempt to promote non-128-bit vectors
1046       if (!VT.is128BitVector())
1047         continue;
1048
1049       setOperationAction(ISD::AND,    VT, Promote);
1050       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1051       setOperationAction(ISD::OR,     VT, Promote);
1052       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1053       setOperationAction(ISD::XOR,    VT, Promote);
1054       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1055       setOperationAction(ISD::LOAD,   VT, Promote);
1056       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1057       setOperationAction(ISD::SELECT, VT, Promote);
1058       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1059     }
1060
1061     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1062
1063     // Custom lower v2i64 and v2f64 selects.
1064     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1065     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1066     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1067     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1068
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1070     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1071
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1074     // As there is no 64-bit GPR available, we need build a special custom
1075     // sequence to convert from v2i32 to v2f32.
1076     if (!Subtarget->is64Bit())
1077       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1078
1079     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1080     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1081
1082     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1083
1084     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1085     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1087   }
1088
1089   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1090     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1091     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1092     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1093     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1094     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1095     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1096     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1097     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1098     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1099     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1100
1101     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1102     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1103     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1104     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1105     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1106     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1107     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1108     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1109     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1110     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1111
1112     // FIXME: Do we need to handle scalar-to-vector here?
1113     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1114
1115     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1116     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1120     // There is no BLENDI for byte vectors. We don't need to custom lower
1121     // some vselects for now.
1122     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1123
1124     // SSE41 brings specific instructions for doing vector sign extend even in
1125     // cases where we don't have SRA.
1126     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1129
1130     // i8 and i16 vectors are custom because the source register and source
1131     // source memory operand types are not the same width.  f32 vectors are
1132     // custom since the immediate controlling the insert encodes additional
1133     // information.
1134     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1138
1139     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1143
1144     // FIXME: these should be Legal, but that's only for the case where
1145     // the index is constant.  For now custom expand to deal with that.
1146     if (Subtarget->is64Bit()) {
1147       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1148       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1149     }
1150   }
1151
1152   if (Subtarget->hasSSE2()) {
1153     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1154     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1155
1156     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1157     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1158
1159     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1160     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1161
1162     // In the customized shift lowering, the legal cases in AVX2 will be
1163     // recognized.
1164     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1165     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1166
1167     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1168     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1169
1170     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1171   }
1172
1173   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1174     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1175     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1176     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1180
1181     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1182     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1184
1185     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1186     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1190     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1191     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1192     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1193     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1194     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1196     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1197
1198     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1199     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1203     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1204     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1205     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1206     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1207     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1209     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1210
1211     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1212     // even though v8i16 is a legal type.
1213     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1214     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1216
1217     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1219     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1220
1221     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1223
1224     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1225
1226     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1227     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1228
1229     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1230     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1231
1232     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1233     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1234
1235     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1236     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1239
1240     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1241     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1243
1244     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1245     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1248
1249     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1252     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1255     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1258     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1261
1262     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1263       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1264       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1267       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1269     }
1270
1271     if (Subtarget->hasInt256()) {
1272       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1273       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1276
1277       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1278       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1281
1282       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1283       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1284       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1285       // Don't lower v32i8 because there is no 128-bit byte mul
1286
1287       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1288       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1290       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1291
1292       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1293       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1294     } else {
1295       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1296       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1299
1300       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1301       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1304
1305       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1306       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1308       // Don't lower v32i8 because there is no 128-bit byte mul
1309     }
1310
1311     // In the customized shift lowering, the legal cases in AVX2 will be
1312     // recognized.
1313     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1314     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1315
1316     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1317     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1318
1319     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1320
1321     // Custom lower several nodes for 256-bit types.
1322     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1323              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1324       MVT VT = (MVT::SimpleValueType)i;
1325
1326       // Extract subvector is special because the value type
1327       // (result) is 128-bit but the source is 256-bit wide.
1328       if (VT.is128BitVector())
1329         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1330
1331       // Do not attempt to custom lower other non-256-bit vectors
1332       if (!VT.is256BitVector())
1333         continue;
1334
1335       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1336       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1337       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1338       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1339       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1340       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1341       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1342     }
1343
1344     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1345     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1346       MVT VT = (MVT::SimpleValueType)i;
1347
1348       // Do not attempt to promote non-256-bit vectors
1349       if (!VT.is256BitVector())
1350         continue;
1351
1352       setOperationAction(ISD::AND,    VT, Promote);
1353       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1354       setOperationAction(ISD::OR,     VT, Promote);
1355       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1356       setOperationAction(ISD::XOR,    VT, Promote);
1357       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1358       setOperationAction(ISD::LOAD,   VT, Promote);
1359       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1360       setOperationAction(ISD::SELECT, VT, Promote);
1361       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1362     }
1363   }
1364
1365   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1366     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1370
1371     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1372     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1373     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1374
1375     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1376     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1377     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1378     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1379     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1380     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1386
1387     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1392     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1393
1394     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1399     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1400     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1401     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1402
1403     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1406     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1407     if (Subtarget->is64Bit()) {
1408       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1411       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1412     }
1413     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1417     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1418     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1421     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1422     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1423
1424     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1425     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1437
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1444
1445     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1446     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1447
1448     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1449
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1459
1460     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1461     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1462
1463     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1464     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1465
1466     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1469     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1470
1471     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1472     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1473
1474     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1475     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1476
1477     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1479     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1481     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1482     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1483
1484     if (Subtarget->hasCDI()) {
1485       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1486       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1487     }
1488
1489     // Custom lower several nodes.
1490     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1491              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1492       MVT VT = (MVT::SimpleValueType)i;
1493
1494       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1495       // Extract subvector is special because the value type
1496       // (result) is 256/128-bit but the source is 512-bit wide.
1497       if (VT.is128BitVector() || VT.is256BitVector())
1498         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1499
1500       if (VT.getVectorElementType() == MVT::i1)
1501         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1502
1503       // Do not attempt to custom lower other non-512-bit vectors
1504       if (!VT.is512BitVector())
1505         continue;
1506
1507       if ( EltSize >= 32) {
1508         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1509         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1510         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1511         setOperationAction(ISD::VSELECT,             VT, Legal);
1512         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1513         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1514         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1515       }
1516     }
1517     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1518       MVT VT = (MVT::SimpleValueType)i;
1519
1520       // Do not attempt to promote non-256-bit vectors
1521       if (!VT.is512BitVector())
1522         continue;
1523
1524       setOperationAction(ISD::SELECT, VT, Promote);
1525       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1526     }
1527   }// has  AVX-512
1528
1529   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1530     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1531     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1532   }
1533
1534   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1535   // of this type with custom code.
1536   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1537            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1538     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1539                        Custom);
1540   }
1541
1542   // We want to custom lower some of our intrinsics.
1543   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1544   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1546   if (!Subtarget->is64Bit())
1547     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1548
1549   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1550   // handle type legalization for these operations here.
1551   //
1552   // FIXME: We really should do custom legalization for addition and
1553   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1554   // than generic legalization for 64-bit multiplication-with-overflow, though.
1555   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1556     // Add/Sub/Mul with overflow operations are custom lowered.
1557     MVT VT = IntVTs[i];
1558     setOperationAction(ISD::SADDO, VT, Custom);
1559     setOperationAction(ISD::UADDO, VT, Custom);
1560     setOperationAction(ISD::SSUBO, VT, Custom);
1561     setOperationAction(ISD::USUBO, VT, Custom);
1562     setOperationAction(ISD::SMULO, VT, Custom);
1563     setOperationAction(ISD::UMULO, VT, Custom);
1564   }
1565
1566   // There are no 8-bit 3-address imul/mul instructions
1567   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1568   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1569
1570   if (!Subtarget->is64Bit()) {
1571     // These libcalls are not available in 32-bit.
1572     setLibcallName(RTLIB::SHL_I128, nullptr);
1573     setLibcallName(RTLIB::SRL_I128, nullptr);
1574     setLibcallName(RTLIB::SRA_I128, nullptr);
1575   }
1576
1577   // Combine sin / cos into one node or libcall if possible.
1578   if (Subtarget->hasSinCos()) {
1579     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1580     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1581     if (Subtarget->isTargetDarwin()) {
1582       // For MacOSX, we don't want to the normal expansion of a libcall to
1583       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1584       // traffic.
1585       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1586       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1587     }
1588   }
1589
1590   if (Subtarget->isTargetWin64()) {
1591     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1592     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::SREM, MVT::i128, Custom);
1594     setOperationAction(ISD::UREM, MVT::i128, Custom);
1595     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1596     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1597   }
1598
1599   // We have target-specific dag combine patterns for the following nodes:
1600   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1601   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1602   setTargetDAGCombine(ISD::VSELECT);
1603   setTargetDAGCombine(ISD::SELECT);
1604   setTargetDAGCombine(ISD::SHL);
1605   setTargetDAGCombine(ISD::SRA);
1606   setTargetDAGCombine(ISD::SRL);
1607   setTargetDAGCombine(ISD::OR);
1608   setTargetDAGCombine(ISD::AND);
1609   setTargetDAGCombine(ISD::ADD);
1610   setTargetDAGCombine(ISD::FADD);
1611   setTargetDAGCombine(ISD::FSUB);
1612   setTargetDAGCombine(ISD::FMA);
1613   setTargetDAGCombine(ISD::SUB);
1614   setTargetDAGCombine(ISD::LOAD);
1615   setTargetDAGCombine(ISD::STORE);
1616   setTargetDAGCombine(ISD::ZERO_EXTEND);
1617   setTargetDAGCombine(ISD::ANY_EXTEND);
1618   setTargetDAGCombine(ISD::SIGN_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1620   setTargetDAGCombine(ISD::TRUNCATE);
1621   setTargetDAGCombine(ISD::SINT_TO_FP);
1622   setTargetDAGCombine(ISD::SETCC);
1623   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1624   setTargetDAGCombine(ISD::BUILD_VECTOR);
1625   if (Subtarget->is64Bit())
1626     setTargetDAGCombine(ISD::MUL);
1627   setTargetDAGCombine(ISD::XOR);
1628
1629   computeRegisterProperties();
1630
1631   // On Darwin, -Os means optimize for size without hurting performance,
1632   // do not reduce the limit.
1633   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1634   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1635   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1636   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1637   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1638   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1639   setPrefLoopAlignment(4); // 2^4 bytes.
1640
1641   // Predictable cmov don't hurt on atom because it's in-order.
1642   PredictableSelectIsExpensive = !Subtarget->isAtom();
1643
1644   setPrefFunctionAlignment(4); // 2^4 bytes.
1645 }
1646
1647 // This has so far only been implemented for 64-bit MachO.
1648 bool X86TargetLowering::useLoadStackGuardNode() const {
1649   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1650          Subtarget->is64Bit();
1651 }
1652
1653 TargetLoweringBase::LegalizeTypeAction
1654 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1655   if (ExperimentalVectorWideningLegalization &&
1656       VT.getVectorNumElements() != 1 &&
1657       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1658     return TypeWidenVector;
1659
1660   return TargetLoweringBase::getPreferredVectorAction(VT);
1661 }
1662
1663 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1664   if (!VT.isVector())
1665     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1666
1667   if (Subtarget->hasAVX512())
1668     switch(VT.getVectorNumElements()) {
1669     case  8: return MVT::v8i1;
1670     case 16: return MVT::v16i1;
1671   }
1672
1673   return VT.changeVectorElementTypeToInteger();
1674 }
1675
1676 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1677 /// the desired ByVal argument alignment.
1678 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1679   if (MaxAlign == 16)
1680     return;
1681   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1682     if (VTy->getBitWidth() == 128)
1683       MaxAlign = 16;
1684   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1685     unsigned EltAlign = 0;
1686     getMaxByValAlign(ATy->getElementType(), EltAlign);
1687     if (EltAlign > MaxAlign)
1688       MaxAlign = EltAlign;
1689   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1690     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1691       unsigned EltAlign = 0;
1692       getMaxByValAlign(STy->getElementType(i), EltAlign);
1693       if (EltAlign > MaxAlign)
1694         MaxAlign = EltAlign;
1695       if (MaxAlign == 16)
1696         break;
1697     }
1698   }
1699 }
1700
1701 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1702 /// function arguments in the caller parameter area. For X86, aggregates
1703 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1704 /// are at 4-byte boundaries.
1705 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1706   if (Subtarget->is64Bit()) {
1707     // Max of 8 and alignment of type.
1708     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1709     if (TyAlign > 8)
1710       return TyAlign;
1711     return 8;
1712   }
1713
1714   unsigned Align = 4;
1715   if (Subtarget->hasSSE1())
1716     getMaxByValAlign(Ty, Align);
1717   return Align;
1718 }
1719
1720 /// getOptimalMemOpType - Returns the target specific optimal type for load
1721 /// and store operations as a result of memset, memcpy, and memmove
1722 /// lowering. If DstAlign is zero that means it's safe to destination
1723 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1724 /// means there isn't a need to check it against alignment requirement,
1725 /// probably because the source does not need to be loaded. If 'IsMemset' is
1726 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1727 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1728 /// source is constant so it does not need to be loaded.
1729 /// It returns EVT::Other if the type should be determined using generic
1730 /// target-independent logic.
1731 EVT
1732 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1733                                        unsigned DstAlign, unsigned SrcAlign,
1734                                        bool IsMemset, bool ZeroMemset,
1735                                        bool MemcpyStrSrc,
1736                                        MachineFunction &MF) const {
1737   const Function *F = MF.getFunction();
1738   if ((!IsMemset || ZeroMemset) &&
1739       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1740                                        Attribute::NoImplicitFloat)) {
1741     if (Size >= 16 &&
1742         (Subtarget->isUnalignedMemAccessFast() ||
1743          ((DstAlign == 0 || DstAlign >= 16) &&
1744           (SrcAlign == 0 || SrcAlign >= 16)))) {
1745       if (Size >= 32) {
1746         if (Subtarget->hasInt256())
1747           return MVT::v8i32;
1748         if (Subtarget->hasFp256())
1749           return MVT::v8f32;
1750       }
1751       if (Subtarget->hasSSE2())
1752         return MVT::v4i32;
1753       if (Subtarget->hasSSE1())
1754         return MVT::v4f32;
1755     } else if (!MemcpyStrSrc && Size >= 8 &&
1756                !Subtarget->is64Bit() &&
1757                Subtarget->hasSSE2()) {
1758       // Do not use f64 to lower memcpy if source is string constant. It's
1759       // better to use i32 to avoid the loads.
1760       return MVT::f64;
1761     }
1762   }
1763   if (Subtarget->is64Bit() && Size >= 8)
1764     return MVT::i64;
1765   return MVT::i32;
1766 }
1767
1768 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1769   if (VT == MVT::f32)
1770     return X86ScalarSSEf32;
1771   else if (VT == MVT::f64)
1772     return X86ScalarSSEf64;
1773   return true;
1774 }
1775
1776 bool
1777 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1778                                                   unsigned,
1779                                                   unsigned,
1780                                                   bool *Fast) const {
1781   if (Fast)
1782     *Fast = Subtarget->isUnalignedMemAccessFast();
1783   return true;
1784 }
1785
1786 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1787 /// current function.  The returned value is a member of the
1788 /// MachineJumpTableInfo::JTEntryKind enum.
1789 unsigned X86TargetLowering::getJumpTableEncoding() const {
1790   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1791   // symbol.
1792   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1793       Subtarget->isPICStyleGOT())
1794     return MachineJumpTableInfo::EK_Custom32;
1795
1796   // Otherwise, use the normal jump table encoding heuristics.
1797   return TargetLowering::getJumpTableEncoding();
1798 }
1799
1800 const MCExpr *
1801 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1802                                              const MachineBasicBlock *MBB,
1803                                              unsigned uid,MCContext &Ctx) const{
1804   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1805          Subtarget->isPICStyleGOT());
1806   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1807   // entries.
1808   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1809                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1810 }
1811
1812 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1813 /// jumptable.
1814 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1815                                                     SelectionDAG &DAG) const {
1816   if (!Subtarget->is64Bit())
1817     // This doesn't have SDLoc associated with it, but is not really the
1818     // same as a Register.
1819     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1820   return Table;
1821 }
1822
1823 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1824 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1825 /// MCExpr.
1826 const MCExpr *X86TargetLowering::
1827 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1828                              MCContext &Ctx) const {
1829   // X86-64 uses RIP relative addressing based on the jump table label.
1830   if (Subtarget->isPICStyleRIPRel())
1831     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1832
1833   // Otherwise, the reference is relative to the PIC base.
1834   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1835 }
1836
1837 // FIXME: Why this routine is here? Move to RegInfo!
1838 std::pair<const TargetRegisterClass*, uint8_t>
1839 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1840   const TargetRegisterClass *RRC = nullptr;
1841   uint8_t Cost = 1;
1842   switch (VT.SimpleTy) {
1843   default:
1844     return TargetLowering::findRepresentativeClass(VT);
1845   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1846     RRC = Subtarget->is64Bit() ?
1847       (const TargetRegisterClass*)&X86::GR64RegClass :
1848       (const TargetRegisterClass*)&X86::GR32RegClass;
1849     break;
1850   case MVT::x86mmx:
1851     RRC = &X86::VR64RegClass;
1852     break;
1853   case MVT::f32: case MVT::f64:
1854   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1855   case MVT::v4f32: case MVT::v2f64:
1856   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1857   case MVT::v4f64:
1858     RRC = &X86::VR128RegClass;
1859     break;
1860   }
1861   return std::make_pair(RRC, Cost);
1862 }
1863
1864 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1865                                                unsigned &Offset) const {
1866   if (!Subtarget->isTargetLinux())
1867     return false;
1868
1869   if (Subtarget->is64Bit()) {
1870     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1871     Offset = 0x28;
1872     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1873       AddressSpace = 256;
1874     else
1875       AddressSpace = 257;
1876   } else {
1877     // %gs:0x14 on i386
1878     Offset = 0x14;
1879     AddressSpace = 256;
1880   }
1881   return true;
1882 }
1883
1884 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1885                                             unsigned DestAS) const {
1886   assert(SrcAS != DestAS && "Expected different address spaces!");
1887
1888   return SrcAS < 256 && DestAS < 256;
1889 }
1890
1891 //===----------------------------------------------------------------------===//
1892 //               Return Value Calling Convention Implementation
1893 //===----------------------------------------------------------------------===//
1894
1895 #include "X86GenCallingConv.inc"
1896
1897 bool
1898 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1899                                   MachineFunction &MF, bool isVarArg,
1900                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1901                         LLVMContext &Context) const {
1902   SmallVector<CCValAssign, 16> RVLocs;
1903   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1904   return CCInfo.CheckReturn(Outs, RetCC_X86);
1905 }
1906
1907 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1908   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1909   return ScratchRegs;
1910 }
1911
1912 SDValue
1913 X86TargetLowering::LowerReturn(SDValue Chain,
1914                                CallingConv::ID CallConv, bool isVarArg,
1915                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1916                                const SmallVectorImpl<SDValue> &OutVals,
1917                                SDLoc dl, SelectionDAG &DAG) const {
1918   MachineFunction &MF = DAG.getMachineFunction();
1919   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1920
1921   SmallVector<CCValAssign, 16> RVLocs;
1922   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1923   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1924
1925   SDValue Flag;
1926   SmallVector<SDValue, 6> RetOps;
1927   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1928   // Operand #1 = Bytes To Pop
1929   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1930                    MVT::i16));
1931
1932   // Copy the result values into the output registers.
1933   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1934     CCValAssign &VA = RVLocs[i];
1935     assert(VA.isRegLoc() && "Can only return in registers!");
1936     SDValue ValToCopy = OutVals[i];
1937     EVT ValVT = ValToCopy.getValueType();
1938
1939     // Promote values to the appropriate types
1940     if (VA.getLocInfo() == CCValAssign::SExt)
1941       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1942     else if (VA.getLocInfo() == CCValAssign::ZExt)
1943       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1944     else if (VA.getLocInfo() == CCValAssign::AExt)
1945       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1946     else if (VA.getLocInfo() == CCValAssign::BCvt)
1947       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1948
1949     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1950            "Unexpected FP-extend for return value.");  
1951
1952     // If this is x86-64, and we disabled SSE, we can't return FP values,
1953     // or SSE or MMX vectors.
1954     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1955          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1956           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1957       report_fatal_error("SSE register return with SSE disabled");
1958     }
1959     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1960     // llvm-gcc has never done it right and no one has noticed, so this
1961     // should be OK for now.
1962     if (ValVT == MVT::f64 &&
1963         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1964       report_fatal_error("SSE2 register return with SSE2 disabled");
1965
1966     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1967     // the RET instruction and handled by the FP Stackifier.
1968     if (VA.getLocReg() == X86::FP0 ||
1969         VA.getLocReg() == X86::FP1) {
1970       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1971       // change the value to the FP stack register class.
1972       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1973         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1974       RetOps.push_back(ValToCopy);
1975       // Don't emit a copytoreg.
1976       continue;
1977     }
1978
1979     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1980     // which is returned in RAX / RDX.
1981     if (Subtarget->is64Bit()) {
1982       if (ValVT == MVT::x86mmx) {
1983         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1984           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1985           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1986                                   ValToCopy);
1987           // If we don't have SSE2 available, convert to v4f32 so the generated
1988           // register is legal.
1989           if (!Subtarget->hasSSE2())
1990             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1991         }
1992       }
1993     }
1994
1995     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1996     Flag = Chain.getValue(1);
1997     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1998   }
1999
2000   // The x86-64 ABIs require that for returning structs by value we copy
2001   // the sret argument into %rax/%eax (depending on ABI) for the return.
2002   // Win32 requires us to put the sret argument to %eax as well.
2003   // We saved the argument into a virtual register in the entry block,
2004   // so now we copy the value out and into %rax/%eax.
2005   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2006       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2007     MachineFunction &MF = DAG.getMachineFunction();
2008     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2009     unsigned Reg = FuncInfo->getSRetReturnReg();
2010     assert(Reg &&
2011            "SRetReturnReg should have been set in LowerFormalArguments().");
2012     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2013
2014     unsigned RetValReg
2015         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2016           X86::RAX : X86::EAX;
2017     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2018     Flag = Chain.getValue(1);
2019
2020     // RAX/EAX now acts like a return value.
2021     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2022   }
2023
2024   RetOps[0] = Chain;  // Update chain.
2025
2026   // Add the flag if we have it.
2027   if (Flag.getNode())
2028     RetOps.push_back(Flag);
2029
2030   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2031 }
2032
2033 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2034   if (N->getNumValues() != 1)
2035     return false;
2036   if (!N->hasNUsesOfValue(1, 0))
2037     return false;
2038
2039   SDValue TCChain = Chain;
2040   SDNode *Copy = *N->use_begin();
2041   if (Copy->getOpcode() == ISD::CopyToReg) {
2042     // If the copy has a glue operand, we conservatively assume it isn't safe to
2043     // perform a tail call.
2044     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2045       return false;
2046     TCChain = Copy->getOperand(0);
2047   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2048     return false;
2049
2050   bool HasRet = false;
2051   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2052        UI != UE; ++UI) {
2053     if (UI->getOpcode() != X86ISD::RET_FLAG)
2054       return false;
2055     HasRet = true;
2056   }
2057
2058   if (!HasRet)
2059     return false;
2060
2061   Chain = TCChain;
2062   return true;
2063 }
2064
2065 EVT
2066 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2067                                             ISD::NodeType ExtendKind) const {
2068   MVT ReturnMVT;
2069   // TODO: Is this also valid on 32-bit?
2070   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2071     ReturnMVT = MVT::i8;
2072   else
2073     ReturnMVT = MVT::i32;
2074
2075   EVT MinVT = getRegisterType(Context, ReturnMVT);
2076   return VT.bitsLT(MinVT) ? MinVT : VT;
2077 }
2078
2079 /// LowerCallResult - Lower the result values of a call into the
2080 /// appropriate copies out of appropriate physical registers.
2081 ///
2082 SDValue
2083 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2084                                    CallingConv::ID CallConv, bool isVarArg,
2085                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2086                                    SDLoc dl, SelectionDAG &DAG,
2087                                    SmallVectorImpl<SDValue> &InVals) const {
2088
2089   // Assign locations to each value returned by this call.
2090   SmallVector<CCValAssign, 16> RVLocs;
2091   bool Is64Bit = Subtarget->is64Bit();
2092   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2093                  *DAG.getContext());
2094   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2095
2096   // Copy all of the result registers out of their specified physreg.
2097   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2098     CCValAssign &VA = RVLocs[i];
2099     EVT CopyVT = VA.getValVT();
2100
2101     // If this is x86-64, and we disabled SSE, we can't return FP values
2102     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2103         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2104       report_fatal_error("SSE register return with SSE disabled");
2105     }
2106
2107     // If we prefer to use the value in xmm registers, copy it out as f80 and
2108     // use a truncate to move it from fp stack reg to xmm reg.
2109     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2110         isScalarFPTypeInSSEReg(VA.getValVT()))
2111       CopyVT = MVT::f80;
2112
2113     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2114                                CopyVT, InFlag).getValue(1);
2115     SDValue Val = Chain.getValue(0);
2116
2117     if (CopyVT != VA.getValVT())
2118       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2119                         // This truncation won't change the value.
2120                         DAG.getIntPtrConstant(1));
2121
2122     InFlag = Chain.getValue(2);
2123     InVals.push_back(Val);
2124   }
2125
2126   return Chain;
2127 }
2128
2129 //===----------------------------------------------------------------------===//
2130 //                C & StdCall & Fast Calling Convention implementation
2131 //===----------------------------------------------------------------------===//
2132 //  StdCall calling convention seems to be standard for many Windows' API
2133 //  routines and around. It differs from C calling convention just a little:
2134 //  callee should clean up the stack, not caller. Symbols should be also
2135 //  decorated in some fancy way :) It doesn't support any vector arguments.
2136 //  For info on fast calling convention see Fast Calling Convention (tail call)
2137 //  implementation LowerX86_32FastCCCallTo.
2138
2139 /// CallIsStructReturn - Determines whether a call uses struct return
2140 /// semantics.
2141 enum StructReturnType {
2142   NotStructReturn,
2143   RegStructReturn,
2144   StackStructReturn
2145 };
2146 static StructReturnType
2147 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2148   if (Outs.empty())
2149     return NotStructReturn;
2150
2151   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2152   if (!Flags.isSRet())
2153     return NotStructReturn;
2154   if (Flags.isInReg())
2155     return RegStructReturn;
2156   return StackStructReturn;
2157 }
2158
2159 /// ArgsAreStructReturn - Determines whether a function uses struct
2160 /// return semantics.
2161 static StructReturnType
2162 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2163   if (Ins.empty())
2164     return NotStructReturn;
2165
2166   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2167   if (!Flags.isSRet())
2168     return NotStructReturn;
2169   if (Flags.isInReg())
2170     return RegStructReturn;
2171   return StackStructReturn;
2172 }
2173
2174 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2175 /// by "Src" to address "Dst" with size and alignment information specified by
2176 /// the specific parameter attribute. The copy will be passed as a byval
2177 /// function parameter.
2178 static SDValue
2179 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2180                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2181                           SDLoc dl) {
2182   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2183
2184   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2185                        /*isVolatile*/false, /*AlwaysInline=*/true,
2186                        MachinePointerInfo(), MachinePointerInfo());
2187 }
2188
2189 /// IsTailCallConvention - Return true if the calling convention is one that
2190 /// supports tail call optimization.
2191 static bool IsTailCallConvention(CallingConv::ID CC) {
2192   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2193           CC == CallingConv::HiPE);
2194 }
2195
2196 /// \brief Return true if the calling convention is a C calling convention.
2197 static bool IsCCallConvention(CallingConv::ID CC) {
2198   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2199           CC == CallingConv::X86_64_SysV);
2200 }
2201
2202 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2203   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2204     return false;
2205
2206   CallSite CS(CI);
2207   CallingConv::ID CalleeCC = CS.getCallingConv();
2208   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2209     return false;
2210
2211   return true;
2212 }
2213
2214 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2215 /// a tailcall target by changing its ABI.
2216 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2217                                    bool GuaranteedTailCallOpt) {
2218   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2219 }
2220
2221 SDValue
2222 X86TargetLowering::LowerMemArgument(SDValue Chain,
2223                                     CallingConv::ID CallConv,
2224                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2225                                     SDLoc dl, SelectionDAG &DAG,
2226                                     const CCValAssign &VA,
2227                                     MachineFrameInfo *MFI,
2228                                     unsigned i) const {
2229   // Create the nodes corresponding to a load from this parameter slot.
2230   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2231   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2232       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2233   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2234   EVT ValVT;
2235
2236   // If value is passed by pointer we have address passed instead of the value
2237   // itself.
2238   if (VA.getLocInfo() == CCValAssign::Indirect)
2239     ValVT = VA.getLocVT();
2240   else
2241     ValVT = VA.getValVT();
2242
2243   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2244   // changed with more analysis.
2245   // In case of tail call optimization mark all arguments mutable. Since they
2246   // could be overwritten by lowering of arguments in case of a tail call.
2247   if (Flags.isByVal()) {
2248     unsigned Bytes = Flags.getByValSize();
2249     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2250     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2251     return DAG.getFrameIndex(FI, getPointerTy());
2252   } else {
2253     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2254                                     VA.getLocMemOffset(), isImmutable);
2255     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2256     return DAG.getLoad(ValVT, dl, Chain, FIN,
2257                        MachinePointerInfo::getFixedStack(FI),
2258                        false, false, false, 0);
2259   }
2260 }
2261
2262 SDValue
2263 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2264                                         CallingConv::ID CallConv,
2265                                         bool isVarArg,
2266                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2267                                         SDLoc dl,
2268                                         SelectionDAG &DAG,
2269                                         SmallVectorImpl<SDValue> &InVals)
2270                                           const {
2271   MachineFunction &MF = DAG.getMachineFunction();
2272   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2273
2274   const Function* Fn = MF.getFunction();
2275   if (Fn->hasExternalLinkage() &&
2276       Subtarget->isTargetCygMing() &&
2277       Fn->getName() == "main")
2278     FuncInfo->setForceFramePointer(true);
2279
2280   MachineFrameInfo *MFI = MF.getFrameInfo();
2281   bool Is64Bit = Subtarget->is64Bit();
2282   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2283
2284   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2285          "Var args not supported with calling convention fastcc, ghc or hipe");
2286
2287   // Assign locations to all of the incoming arguments.
2288   SmallVector<CCValAssign, 16> ArgLocs;
2289   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2290
2291   // Allocate shadow area for Win64
2292   if (IsWin64)
2293     CCInfo.AllocateStack(32, 8);
2294
2295   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2296
2297   unsigned LastVal = ~0U;
2298   SDValue ArgValue;
2299   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2300     CCValAssign &VA = ArgLocs[i];
2301     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2302     // places.
2303     assert(VA.getValNo() != LastVal &&
2304            "Don't support value assigned to multiple locs yet");
2305     (void)LastVal;
2306     LastVal = VA.getValNo();
2307
2308     if (VA.isRegLoc()) {
2309       EVT RegVT = VA.getLocVT();
2310       const TargetRegisterClass *RC;
2311       if (RegVT == MVT::i32)
2312         RC = &X86::GR32RegClass;
2313       else if (Is64Bit && RegVT == MVT::i64)
2314         RC = &X86::GR64RegClass;
2315       else if (RegVT == MVT::f32)
2316         RC = &X86::FR32RegClass;
2317       else if (RegVT == MVT::f64)
2318         RC = &X86::FR64RegClass;
2319       else if (RegVT.is512BitVector())
2320         RC = &X86::VR512RegClass;
2321       else if (RegVT.is256BitVector())
2322         RC = &X86::VR256RegClass;
2323       else if (RegVT.is128BitVector())
2324         RC = &X86::VR128RegClass;
2325       else if (RegVT == MVT::x86mmx)
2326         RC = &X86::VR64RegClass;
2327       else if (RegVT == MVT::i1)
2328         RC = &X86::VK1RegClass;
2329       else if (RegVT == MVT::v8i1)
2330         RC = &X86::VK8RegClass;
2331       else if (RegVT == MVT::v16i1)
2332         RC = &X86::VK16RegClass;
2333       else if (RegVT == MVT::v32i1)
2334         RC = &X86::VK32RegClass;
2335       else if (RegVT == MVT::v64i1)
2336         RC = &X86::VK64RegClass;
2337       else
2338         llvm_unreachable("Unknown argument type!");
2339
2340       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2341       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2342
2343       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2344       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2345       // right size.
2346       if (VA.getLocInfo() == CCValAssign::SExt)
2347         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2348                                DAG.getValueType(VA.getValVT()));
2349       else if (VA.getLocInfo() == CCValAssign::ZExt)
2350         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2351                                DAG.getValueType(VA.getValVT()));
2352       else if (VA.getLocInfo() == CCValAssign::BCvt)
2353         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2354
2355       if (VA.isExtInLoc()) {
2356         // Handle MMX values passed in XMM regs.
2357         if (RegVT.isVector())
2358           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2359         else
2360           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2361       }
2362     } else {
2363       assert(VA.isMemLoc());
2364       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2365     }
2366
2367     // If value is passed via pointer - do a load.
2368     if (VA.getLocInfo() == CCValAssign::Indirect)
2369       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2370                              MachinePointerInfo(), false, false, false, 0);
2371
2372     InVals.push_back(ArgValue);
2373   }
2374
2375   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2376     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2377       // The x86-64 ABIs require that for returning structs by value we copy
2378       // the sret argument into %rax/%eax (depending on ABI) for the return.
2379       // Win32 requires us to put the sret argument to %eax as well.
2380       // Save the argument into a virtual register so that we can access it
2381       // from the return points.
2382       if (Ins[i].Flags.isSRet()) {
2383         unsigned Reg = FuncInfo->getSRetReturnReg();
2384         if (!Reg) {
2385           MVT PtrTy = getPointerTy();
2386           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2387           FuncInfo->setSRetReturnReg(Reg);
2388         }
2389         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2390         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2391         break;
2392       }
2393     }
2394   }
2395
2396   unsigned StackSize = CCInfo.getNextStackOffset();
2397   // Align stack specially for tail calls.
2398   if (FuncIsMadeTailCallSafe(CallConv,
2399                              MF.getTarget().Options.GuaranteedTailCallOpt))
2400     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2401
2402   // If the function takes variable number of arguments, make a frame index for
2403   // the start of the first vararg value... for expansion of llvm.va_start.
2404   if (isVarArg) {
2405     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2406                     CallConv != CallingConv::X86_ThisCall)) {
2407       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2408     }
2409     if (Is64Bit) {
2410       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2411
2412       // FIXME: We should really autogenerate these arrays
2413       static const MCPhysReg GPR64ArgRegsWin64[] = {
2414         X86::RCX, X86::RDX, X86::R8,  X86::R9
2415       };
2416       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2417         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2418       };
2419       static const MCPhysReg XMMArgRegs64Bit[] = {
2420         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2421         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2422       };
2423       const MCPhysReg *GPR64ArgRegs;
2424       unsigned NumXMMRegs = 0;
2425
2426       if (IsWin64) {
2427         // The XMM registers which might contain var arg parameters are shadowed
2428         // in their paired GPR.  So we only need to save the GPR to their home
2429         // slots.
2430         TotalNumIntRegs = 4;
2431         GPR64ArgRegs = GPR64ArgRegsWin64;
2432       } else {
2433         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2434         GPR64ArgRegs = GPR64ArgRegs64Bit;
2435
2436         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2437                                                 TotalNumXMMRegs);
2438       }
2439       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2440                                                        TotalNumIntRegs);
2441
2442       bool NoImplicitFloatOps = Fn->getAttributes().
2443         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2444       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2445              "SSE register cannot be used when SSE is disabled!");
2446       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2447                NoImplicitFloatOps) &&
2448              "SSE register cannot be used when SSE is disabled!");
2449       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2450           !Subtarget->hasSSE1())
2451         // Kernel mode asks for SSE to be disabled, so don't push them
2452         // on the stack.
2453         TotalNumXMMRegs = 0;
2454
2455       if (IsWin64) {
2456         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2457         // Get to the caller-allocated home save location.  Add 8 to account
2458         // for the return address.
2459         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2460         FuncInfo->setRegSaveFrameIndex(
2461           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2462         // Fixup to set vararg frame on shadow area (4 x i64).
2463         if (NumIntRegs < 4)
2464           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2465       } else {
2466         // For X86-64, if there are vararg parameters that are passed via
2467         // registers, then we must store them to their spots on the stack so
2468         // they may be loaded by deferencing the result of va_next.
2469         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2470         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2471         FuncInfo->setRegSaveFrameIndex(
2472           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2473                                false));
2474       }
2475
2476       // Store the integer parameter registers.
2477       SmallVector<SDValue, 8> MemOps;
2478       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2479                                         getPointerTy());
2480       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2481       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2482         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2483                                   DAG.getIntPtrConstant(Offset));
2484         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2485                                      &X86::GR64RegClass);
2486         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2487         SDValue Store =
2488           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2489                        MachinePointerInfo::getFixedStack(
2490                          FuncInfo->getRegSaveFrameIndex(), Offset),
2491                        false, false, 0);
2492         MemOps.push_back(Store);
2493         Offset += 8;
2494       }
2495
2496       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2497         // Now store the XMM (fp + vector) parameter registers.
2498         SmallVector<SDValue, 12> SaveXMMOps;
2499         SaveXMMOps.push_back(Chain);
2500
2501         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2502         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2503         SaveXMMOps.push_back(ALVal);
2504
2505         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2506                                FuncInfo->getRegSaveFrameIndex()));
2507         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2508                                FuncInfo->getVarArgsFPOffset()));
2509
2510         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2511           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2512                                        &X86::VR128RegClass);
2513           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2514           SaveXMMOps.push_back(Val);
2515         }
2516         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2517                                      MVT::Other, SaveXMMOps));
2518       }
2519
2520       if (!MemOps.empty())
2521         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2522     }
2523   }
2524
2525   // Some CCs need callee pop.
2526   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2527                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2528     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2529   } else {
2530     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2531     // If this is an sret function, the return should pop the hidden pointer.
2532     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2533         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2534         argsAreStructReturn(Ins) == StackStructReturn)
2535       FuncInfo->setBytesToPopOnReturn(4);
2536   }
2537
2538   if (!Is64Bit) {
2539     // RegSaveFrameIndex is X86-64 only.
2540     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2541     if (CallConv == CallingConv::X86_FastCall ||
2542         CallConv == CallingConv::X86_ThisCall)
2543       // fastcc functions can't have varargs.
2544       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2545   }
2546
2547   FuncInfo->setArgumentStackSize(StackSize);
2548
2549   return Chain;
2550 }
2551
2552 SDValue
2553 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2554                                     SDValue StackPtr, SDValue Arg,
2555                                     SDLoc dl, SelectionDAG &DAG,
2556                                     const CCValAssign &VA,
2557                                     ISD::ArgFlagsTy Flags) const {
2558   unsigned LocMemOffset = VA.getLocMemOffset();
2559   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2560   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2561   if (Flags.isByVal())
2562     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2563
2564   return DAG.getStore(Chain, dl, Arg, PtrOff,
2565                       MachinePointerInfo::getStack(LocMemOffset),
2566                       false, false, 0);
2567 }
2568
2569 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2570 /// optimization is performed and it is required.
2571 SDValue
2572 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2573                                            SDValue &OutRetAddr, SDValue Chain,
2574                                            bool IsTailCall, bool Is64Bit,
2575                                            int FPDiff, SDLoc dl) const {
2576   // Adjust the Return address stack slot.
2577   EVT VT = getPointerTy();
2578   OutRetAddr = getReturnAddressFrameIndex(DAG);
2579
2580   // Load the "old" Return address.
2581   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2582                            false, false, false, 0);
2583   return SDValue(OutRetAddr.getNode(), 1);
2584 }
2585
2586 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2587 /// optimization is performed and it is required (FPDiff!=0).
2588 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2589                                         SDValue Chain, SDValue RetAddrFrIdx,
2590                                         EVT PtrVT, unsigned SlotSize,
2591                                         int FPDiff, SDLoc dl) {
2592   // Store the return address to the appropriate stack slot.
2593   if (!FPDiff) return Chain;
2594   // Calculate the new stack slot for the return address.
2595   int NewReturnAddrFI =
2596     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2597                                          false);
2598   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2599   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2600                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2601                        false, false, 0);
2602   return Chain;
2603 }
2604
2605 SDValue
2606 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2607                              SmallVectorImpl<SDValue> &InVals) const {
2608   SelectionDAG &DAG                     = CLI.DAG;
2609   SDLoc &dl                             = CLI.DL;
2610   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2611   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2612   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2613   SDValue Chain                         = CLI.Chain;
2614   SDValue Callee                        = CLI.Callee;
2615   CallingConv::ID CallConv              = CLI.CallConv;
2616   bool &isTailCall                      = CLI.IsTailCall;
2617   bool isVarArg                         = CLI.IsVarArg;
2618
2619   MachineFunction &MF = DAG.getMachineFunction();
2620   bool Is64Bit        = Subtarget->is64Bit();
2621   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2622   StructReturnType SR = callIsStructReturn(Outs);
2623   bool IsSibcall      = false;
2624
2625   if (MF.getTarget().Options.DisableTailCalls)
2626     isTailCall = false;
2627
2628   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2629   if (IsMustTail) {
2630     // Force this to be a tail call.  The verifier rules are enough to ensure
2631     // that we can lower this successfully without moving the return address
2632     // around.
2633     isTailCall = true;
2634   } else if (isTailCall) {
2635     // Check if it's really possible to do a tail call.
2636     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2637                     isVarArg, SR != NotStructReturn,
2638                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2639                     Outs, OutVals, Ins, DAG);
2640
2641     // Sibcalls are automatically detected tailcalls which do not require
2642     // ABI changes.
2643     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2644       IsSibcall = true;
2645
2646     if (isTailCall)
2647       ++NumTailCalls;
2648   }
2649
2650   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2651          "Var args not supported with calling convention fastcc, ghc or hipe");
2652
2653   // Analyze operands of the call, assigning locations to each operand.
2654   SmallVector<CCValAssign, 16> ArgLocs;
2655   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2656
2657   // Allocate shadow area for Win64
2658   if (IsWin64)
2659     CCInfo.AllocateStack(32, 8);
2660
2661   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2662
2663   // Get a count of how many bytes are to be pushed on the stack.
2664   unsigned NumBytes = CCInfo.getNextStackOffset();
2665   if (IsSibcall)
2666     // This is a sibcall. The memory operands are available in caller's
2667     // own caller's stack.
2668     NumBytes = 0;
2669   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2670            IsTailCallConvention(CallConv))
2671     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2672
2673   int FPDiff = 0;
2674   if (isTailCall && !IsSibcall && !IsMustTail) {
2675     // Lower arguments at fp - stackoffset + fpdiff.
2676     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2677     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2678
2679     FPDiff = NumBytesCallerPushed - NumBytes;
2680
2681     // Set the delta of movement of the returnaddr stackslot.
2682     // But only set if delta is greater than previous delta.
2683     if (FPDiff < X86Info->getTCReturnAddrDelta())
2684       X86Info->setTCReturnAddrDelta(FPDiff);
2685   }
2686
2687   unsigned NumBytesToPush = NumBytes;
2688   unsigned NumBytesToPop = NumBytes;
2689
2690   // If we have an inalloca argument, all stack space has already been allocated
2691   // for us and be right at the top of the stack.  We don't support multiple
2692   // arguments passed in memory when using inalloca.
2693   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2694     NumBytesToPush = 0;
2695     if (!ArgLocs.back().isMemLoc())
2696       report_fatal_error("cannot use inalloca attribute on a register "
2697                          "parameter");
2698     if (ArgLocs.back().getLocMemOffset() != 0)
2699       report_fatal_error("any parameter with the inalloca attribute must be "
2700                          "the only memory argument");
2701   }
2702
2703   if (!IsSibcall)
2704     Chain = DAG.getCALLSEQ_START(
2705         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2706
2707   SDValue RetAddrFrIdx;
2708   // Load return address for tail calls.
2709   if (isTailCall && FPDiff)
2710     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2711                                     Is64Bit, FPDiff, dl);
2712
2713   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2714   SmallVector<SDValue, 8> MemOpChains;
2715   SDValue StackPtr;
2716
2717   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2718   // of tail call optimization arguments are handle later.
2719   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2720       DAG.getSubtarget().getRegisterInfo());
2721   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2722     // Skip inalloca arguments, they have already been written.
2723     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2724     if (Flags.isInAlloca())
2725       continue;
2726
2727     CCValAssign &VA = ArgLocs[i];
2728     EVT RegVT = VA.getLocVT();
2729     SDValue Arg = OutVals[i];
2730     bool isByVal = Flags.isByVal();
2731
2732     // Promote the value if needed.
2733     switch (VA.getLocInfo()) {
2734     default: llvm_unreachable("Unknown loc info!");
2735     case CCValAssign::Full: break;
2736     case CCValAssign::SExt:
2737       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2738       break;
2739     case CCValAssign::ZExt:
2740       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2741       break;
2742     case CCValAssign::AExt:
2743       if (RegVT.is128BitVector()) {
2744         // Special case: passing MMX values in XMM registers.
2745         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2746         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2747         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2748       } else
2749         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2750       break;
2751     case CCValAssign::BCvt:
2752       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2753       break;
2754     case CCValAssign::Indirect: {
2755       // Store the argument.
2756       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2757       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2758       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2759                            MachinePointerInfo::getFixedStack(FI),
2760                            false, false, 0);
2761       Arg = SpillSlot;
2762       break;
2763     }
2764     }
2765
2766     if (VA.isRegLoc()) {
2767       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2768       if (isVarArg && IsWin64) {
2769         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2770         // shadow reg if callee is a varargs function.
2771         unsigned ShadowReg = 0;
2772         switch (VA.getLocReg()) {
2773         case X86::XMM0: ShadowReg = X86::RCX; break;
2774         case X86::XMM1: ShadowReg = X86::RDX; break;
2775         case X86::XMM2: ShadowReg = X86::R8; break;
2776         case X86::XMM3: ShadowReg = X86::R9; break;
2777         }
2778         if (ShadowReg)
2779           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2780       }
2781     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2782       assert(VA.isMemLoc());
2783       if (!StackPtr.getNode())
2784         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2785                                       getPointerTy());
2786       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2787                                              dl, DAG, VA, Flags));
2788     }
2789   }
2790
2791   if (!MemOpChains.empty())
2792     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2793
2794   if (Subtarget->isPICStyleGOT()) {
2795     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2796     // GOT pointer.
2797     if (!isTailCall) {
2798       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2799                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2800     } else {
2801       // If we are tail calling and generating PIC/GOT style code load the
2802       // address of the callee into ECX. The value in ecx is used as target of
2803       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2804       // for tail calls on PIC/GOT architectures. Normally we would just put the
2805       // address of GOT into ebx and then call target@PLT. But for tail calls
2806       // ebx would be restored (since ebx is callee saved) before jumping to the
2807       // target@PLT.
2808
2809       // Note: The actual moving to ECX is done further down.
2810       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2811       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2812           !G->getGlobal()->hasProtectedVisibility())
2813         Callee = LowerGlobalAddress(Callee, DAG);
2814       else if (isa<ExternalSymbolSDNode>(Callee))
2815         Callee = LowerExternalSymbol(Callee, DAG);
2816     }
2817   }
2818
2819   if (Is64Bit && isVarArg && !IsWin64) {
2820     // From AMD64 ABI document:
2821     // For calls that may call functions that use varargs or stdargs
2822     // (prototype-less calls or calls to functions containing ellipsis (...) in
2823     // the declaration) %al is used as hidden argument to specify the number
2824     // of SSE registers used. The contents of %al do not need to match exactly
2825     // the number of registers, but must be an ubound on the number of SSE
2826     // registers used and is in the range 0 - 8 inclusive.
2827
2828     // Count the number of XMM registers allocated.
2829     static const MCPhysReg XMMArgRegs[] = {
2830       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2831       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2832     };
2833     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2834     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2835            && "SSE registers cannot be used when SSE is disabled");
2836
2837     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2838                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2839   }
2840
2841   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2842   // don't need this because the eligibility check rejects calls that require
2843   // shuffling arguments passed in memory.
2844   if (!IsSibcall && isTailCall) {
2845     // Force all the incoming stack arguments to be loaded from the stack
2846     // before any new outgoing arguments are stored to the stack, because the
2847     // outgoing stack slots may alias the incoming argument stack slots, and
2848     // the alias isn't otherwise explicit. This is slightly more conservative
2849     // than necessary, because it means that each store effectively depends
2850     // on every argument instead of just those arguments it would clobber.
2851     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2852
2853     SmallVector<SDValue, 8> MemOpChains2;
2854     SDValue FIN;
2855     int FI = 0;
2856     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2857       CCValAssign &VA = ArgLocs[i];
2858       if (VA.isRegLoc())
2859         continue;
2860       assert(VA.isMemLoc());
2861       SDValue Arg = OutVals[i];
2862       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2863       // Skip inalloca arguments.  They don't require any work.
2864       if (Flags.isInAlloca())
2865         continue;
2866       // Create frame index.
2867       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2868       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2869       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2870       FIN = DAG.getFrameIndex(FI, getPointerTy());
2871
2872       if (Flags.isByVal()) {
2873         // Copy relative to framepointer.
2874         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2875         if (!StackPtr.getNode())
2876           StackPtr = DAG.getCopyFromReg(Chain, dl,
2877                                         RegInfo->getStackRegister(),
2878                                         getPointerTy());
2879         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2880
2881         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2882                                                          ArgChain,
2883                                                          Flags, DAG, dl));
2884       } else {
2885         // Store relative to framepointer.
2886         MemOpChains2.push_back(
2887           DAG.getStore(ArgChain, dl, Arg, FIN,
2888                        MachinePointerInfo::getFixedStack(FI),
2889                        false, false, 0));
2890       }
2891     }
2892
2893     if (!MemOpChains2.empty())
2894       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2895
2896     // Store the return address to the appropriate stack slot.
2897     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2898                                      getPointerTy(), RegInfo->getSlotSize(),
2899                                      FPDiff, dl);
2900   }
2901
2902   // Build a sequence of copy-to-reg nodes chained together with token chain
2903   // and flag operands which copy the outgoing args into registers.
2904   SDValue InFlag;
2905   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2906     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2907                              RegsToPass[i].second, InFlag);
2908     InFlag = Chain.getValue(1);
2909   }
2910
2911   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2912     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2913     // In the 64-bit large code model, we have to make all calls
2914     // through a register, since the call instruction's 32-bit
2915     // pc-relative offset may not be large enough to hold the whole
2916     // address.
2917   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2918     // If the callee is a GlobalAddress node (quite common, every direct call
2919     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2920     // it.
2921
2922     // We should use extra load for direct calls to dllimported functions in
2923     // non-JIT mode.
2924     const GlobalValue *GV = G->getGlobal();
2925     if (!GV->hasDLLImportStorageClass()) {
2926       unsigned char OpFlags = 0;
2927       bool ExtraLoad = false;
2928       unsigned WrapperKind = ISD::DELETED_NODE;
2929
2930       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2931       // external symbols most go through the PLT in PIC mode.  If the symbol
2932       // has hidden or protected visibility, or if it is static or local, then
2933       // we don't need to use the PLT - we can directly call it.
2934       if (Subtarget->isTargetELF() &&
2935           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2936           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2937         OpFlags = X86II::MO_PLT;
2938       } else if (Subtarget->isPICStyleStubAny() &&
2939                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2940                  (!Subtarget->getTargetTriple().isMacOSX() ||
2941                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2942         // PC-relative references to external symbols should go through $stub,
2943         // unless we're building with the leopard linker or later, which
2944         // automatically synthesizes these stubs.
2945         OpFlags = X86II::MO_DARWIN_STUB;
2946       } else if (Subtarget->isPICStyleRIPRel() &&
2947                  isa<Function>(GV) &&
2948                  cast<Function>(GV)->getAttributes().
2949                    hasAttribute(AttributeSet::FunctionIndex,
2950                                 Attribute::NonLazyBind)) {
2951         // If the function is marked as non-lazy, generate an indirect call
2952         // which loads from the GOT directly. This avoids runtime overhead
2953         // at the cost of eager binding (and one extra byte of encoding).
2954         OpFlags = X86II::MO_GOTPCREL;
2955         WrapperKind = X86ISD::WrapperRIP;
2956         ExtraLoad = true;
2957       }
2958
2959       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2960                                           G->getOffset(), OpFlags);
2961
2962       // Add a wrapper if needed.
2963       if (WrapperKind != ISD::DELETED_NODE)
2964         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2965       // Add extra indirection if needed.
2966       if (ExtraLoad)
2967         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2968                              MachinePointerInfo::getGOT(),
2969                              false, false, false, 0);
2970     }
2971   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2972     unsigned char OpFlags = 0;
2973
2974     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2975     // external symbols should go through the PLT.
2976     if (Subtarget->isTargetELF() &&
2977         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2978       OpFlags = X86II::MO_PLT;
2979     } else if (Subtarget->isPICStyleStubAny() &&
2980                (!Subtarget->getTargetTriple().isMacOSX() ||
2981                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2982       // PC-relative references to external symbols should go through $stub,
2983       // unless we're building with the leopard linker or later, which
2984       // automatically synthesizes these stubs.
2985       OpFlags = X86II::MO_DARWIN_STUB;
2986     }
2987
2988     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2989                                          OpFlags);
2990   }
2991
2992   // Returns a chain & a flag for retval copy to use.
2993   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2994   SmallVector<SDValue, 8> Ops;
2995
2996   if (!IsSibcall && isTailCall) {
2997     Chain = DAG.getCALLSEQ_END(Chain,
2998                                DAG.getIntPtrConstant(NumBytesToPop, true),
2999                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3000     InFlag = Chain.getValue(1);
3001   }
3002
3003   Ops.push_back(Chain);
3004   Ops.push_back(Callee);
3005
3006   if (isTailCall)
3007     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3008
3009   // Add argument registers to the end of the list so that they are known live
3010   // into the call.
3011   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3012     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3013                                   RegsToPass[i].second.getValueType()));
3014
3015   // Add a register mask operand representing the call-preserved registers.
3016   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3017   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3018   assert(Mask && "Missing call preserved mask for calling convention");
3019   Ops.push_back(DAG.getRegisterMask(Mask));
3020
3021   if (InFlag.getNode())
3022     Ops.push_back(InFlag);
3023
3024   if (isTailCall) {
3025     // We used to do:
3026     //// If this is the first return lowered for this function, add the regs
3027     //// to the liveout set for the function.
3028     // This isn't right, although it's probably harmless on x86; liveouts
3029     // should be computed from returns not tail calls.  Consider a void
3030     // function making a tail call to a function returning int.
3031     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3032   }
3033
3034   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3035   InFlag = Chain.getValue(1);
3036
3037   // Create the CALLSEQ_END node.
3038   unsigned NumBytesForCalleeToPop;
3039   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3040                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3041     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3042   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3043            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3044            SR == StackStructReturn)
3045     // If this is a call to a struct-return function, the callee
3046     // pops the hidden struct pointer, so we have to push it back.
3047     // This is common for Darwin/X86, Linux & Mingw32 targets.
3048     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3049     NumBytesForCalleeToPop = 4;
3050   else
3051     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3052
3053   // Returns a flag for retval copy to use.
3054   if (!IsSibcall) {
3055     Chain = DAG.getCALLSEQ_END(Chain,
3056                                DAG.getIntPtrConstant(NumBytesToPop, true),
3057                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3058                                                      true),
3059                                InFlag, dl);
3060     InFlag = Chain.getValue(1);
3061   }
3062
3063   // Handle result values, copying them out of physregs into vregs that we
3064   // return.
3065   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3066                          Ins, dl, DAG, InVals);
3067 }
3068
3069 //===----------------------------------------------------------------------===//
3070 //                Fast Calling Convention (tail call) implementation
3071 //===----------------------------------------------------------------------===//
3072
3073 //  Like std call, callee cleans arguments, convention except that ECX is
3074 //  reserved for storing the tail called function address. Only 2 registers are
3075 //  free for argument passing (inreg). Tail call optimization is performed
3076 //  provided:
3077 //                * tailcallopt is enabled
3078 //                * caller/callee are fastcc
3079 //  On X86_64 architecture with GOT-style position independent code only local
3080 //  (within module) calls are supported at the moment.
3081 //  To keep the stack aligned according to platform abi the function
3082 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3083 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3084 //  If a tail called function callee has more arguments than the caller the
3085 //  caller needs to make sure that there is room to move the RETADDR to. This is
3086 //  achieved by reserving an area the size of the argument delta right after the
3087 //  original RETADDR, but before the saved framepointer or the spilled registers
3088 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3089 //  stack layout:
3090 //    arg1
3091 //    arg2
3092 //    RETADDR
3093 //    [ new RETADDR
3094 //      move area ]
3095 //    (possible EBP)
3096 //    ESI
3097 //    EDI
3098 //    local1 ..
3099
3100 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3101 /// for a 16 byte align requirement.
3102 unsigned
3103 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3104                                                SelectionDAG& DAG) const {
3105   MachineFunction &MF = DAG.getMachineFunction();
3106   const TargetMachine &TM = MF.getTarget();
3107   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3108       TM.getSubtargetImpl()->getRegisterInfo());
3109   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3110   unsigned StackAlignment = TFI.getStackAlignment();
3111   uint64_t AlignMask = StackAlignment - 1;
3112   int64_t Offset = StackSize;
3113   unsigned SlotSize = RegInfo->getSlotSize();
3114   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3115     // Number smaller than 12 so just add the difference.
3116     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3117   } else {
3118     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3119     Offset = ((~AlignMask) & Offset) + StackAlignment +
3120       (StackAlignment-SlotSize);
3121   }
3122   return Offset;
3123 }
3124
3125 /// MatchingStackOffset - Return true if the given stack call argument is
3126 /// already available in the same position (relatively) of the caller's
3127 /// incoming argument stack.
3128 static
3129 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3130                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3131                          const X86InstrInfo *TII) {
3132   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3133   int FI = INT_MAX;
3134   if (Arg.getOpcode() == ISD::CopyFromReg) {
3135     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3136     if (!TargetRegisterInfo::isVirtualRegister(VR))
3137       return false;
3138     MachineInstr *Def = MRI->getVRegDef(VR);
3139     if (!Def)
3140       return false;
3141     if (!Flags.isByVal()) {
3142       if (!TII->isLoadFromStackSlot(Def, FI))
3143         return false;
3144     } else {
3145       unsigned Opcode = Def->getOpcode();
3146       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3147           Def->getOperand(1).isFI()) {
3148         FI = Def->getOperand(1).getIndex();
3149         Bytes = Flags.getByValSize();
3150       } else
3151         return false;
3152     }
3153   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3154     if (Flags.isByVal())
3155       // ByVal argument is passed in as a pointer but it's now being
3156       // dereferenced. e.g.
3157       // define @foo(%struct.X* %A) {
3158       //   tail call @bar(%struct.X* byval %A)
3159       // }
3160       return false;
3161     SDValue Ptr = Ld->getBasePtr();
3162     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3163     if (!FINode)
3164       return false;
3165     FI = FINode->getIndex();
3166   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3167     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3168     FI = FINode->getIndex();
3169     Bytes = Flags.getByValSize();
3170   } else
3171     return false;
3172
3173   assert(FI != INT_MAX);
3174   if (!MFI->isFixedObjectIndex(FI))
3175     return false;
3176   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3177 }
3178
3179 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3180 /// for tail call optimization. Targets which want to do tail call
3181 /// optimization should implement this function.
3182 bool
3183 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3184                                                      CallingConv::ID CalleeCC,
3185                                                      bool isVarArg,
3186                                                      bool isCalleeStructRet,
3187                                                      bool isCallerStructRet,
3188                                                      Type *RetTy,
3189                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3190                                     const SmallVectorImpl<SDValue> &OutVals,
3191                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3192                                                      SelectionDAG &DAG) const {
3193   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3194     return false;
3195
3196   // If -tailcallopt is specified, make fastcc functions tail-callable.
3197   const MachineFunction &MF = DAG.getMachineFunction();
3198   const Function *CallerF = MF.getFunction();
3199
3200   // If the function return type is x86_fp80 and the callee return type is not,
3201   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3202   // perform a tailcall optimization here.
3203   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3204     return false;
3205
3206   CallingConv::ID CallerCC = CallerF->getCallingConv();
3207   bool CCMatch = CallerCC == CalleeCC;
3208   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3209   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3210
3211   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3212     if (IsTailCallConvention(CalleeCC) && CCMatch)
3213       return true;
3214     return false;
3215   }
3216
3217   // Look for obvious safe cases to perform tail call optimization that do not
3218   // require ABI changes. This is what gcc calls sibcall.
3219
3220   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3221   // emit a special epilogue.
3222   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3223       DAG.getSubtarget().getRegisterInfo());
3224   if (RegInfo->needsStackRealignment(MF))
3225     return false;
3226
3227   // Also avoid sibcall optimization if either caller or callee uses struct
3228   // return semantics.
3229   if (isCalleeStructRet || isCallerStructRet)
3230     return false;
3231
3232   // An stdcall/thiscall caller is expected to clean up its arguments; the
3233   // callee isn't going to do that.
3234   // FIXME: this is more restrictive than needed. We could produce a tailcall
3235   // when the stack adjustment matches. For example, with a thiscall that takes
3236   // only one argument.
3237   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3238                    CallerCC == CallingConv::X86_ThisCall))
3239     return false;
3240
3241   // Do not sibcall optimize vararg calls unless all arguments are passed via
3242   // registers.
3243   if (isVarArg && !Outs.empty()) {
3244
3245     // Optimizing for varargs on Win64 is unlikely to be safe without
3246     // additional testing.
3247     if (IsCalleeWin64 || IsCallerWin64)
3248       return false;
3249
3250     SmallVector<CCValAssign, 16> ArgLocs;
3251     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3252                    *DAG.getContext());
3253
3254     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3255     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3256       if (!ArgLocs[i].isRegLoc())
3257         return false;
3258   }
3259
3260   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3261   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3262   // this into a sibcall.
3263   bool Unused = false;
3264   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3265     if (!Ins[i].Used) {
3266       Unused = true;
3267       break;
3268     }
3269   }
3270   if (Unused) {
3271     SmallVector<CCValAssign, 16> RVLocs;
3272     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3273                    *DAG.getContext());
3274     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3275     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3276       CCValAssign &VA = RVLocs[i];
3277       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3278         return false;
3279     }
3280   }
3281
3282   // If the calling conventions do not match, then we'd better make sure the
3283   // results are returned in the same way as what the caller expects.
3284   if (!CCMatch) {
3285     SmallVector<CCValAssign, 16> RVLocs1;
3286     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3287                     *DAG.getContext());
3288     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3289
3290     SmallVector<CCValAssign, 16> RVLocs2;
3291     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3292                     *DAG.getContext());
3293     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3294
3295     if (RVLocs1.size() != RVLocs2.size())
3296       return false;
3297     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3298       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3299         return false;
3300       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3301         return false;
3302       if (RVLocs1[i].isRegLoc()) {
3303         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3304           return false;
3305       } else {
3306         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3307           return false;
3308       }
3309     }
3310   }
3311
3312   // If the callee takes no arguments then go on to check the results of the
3313   // call.
3314   if (!Outs.empty()) {
3315     // Check if stack adjustment is needed. For now, do not do this if any
3316     // argument is passed on the stack.
3317     SmallVector<CCValAssign, 16> ArgLocs;
3318     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3319                    *DAG.getContext());
3320
3321     // Allocate shadow area for Win64
3322     if (IsCalleeWin64)
3323       CCInfo.AllocateStack(32, 8);
3324
3325     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3326     if (CCInfo.getNextStackOffset()) {
3327       MachineFunction &MF = DAG.getMachineFunction();
3328       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3329         return false;
3330
3331       // Check if the arguments are already laid out in the right way as
3332       // the caller's fixed stack objects.
3333       MachineFrameInfo *MFI = MF.getFrameInfo();
3334       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3335       const X86InstrInfo *TII =
3336           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3337       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3338         CCValAssign &VA = ArgLocs[i];
3339         SDValue Arg = OutVals[i];
3340         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3341         if (VA.getLocInfo() == CCValAssign::Indirect)
3342           return false;
3343         if (!VA.isRegLoc()) {
3344           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3345                                    MFI, MRI, TII))
3346             return false;
3347         }
3348       }
3349     }
3350
3351     // If the tailcall address may be in a register, then make sure it's
3352     // possible to register allocate for it. In 32-bit, the call address can
3353     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3354     // callee-saved registers are restored. These happen to be the same
3355     // registers used to pass 'inreg' arguments so watch out for those.
3356     if (!Subtarget->is64Bit() &&
3357         ((!isa<GlobalAddressSDNode>(Callee) &&
3358           !isa<ExternalSymbolSDNode>(Callee)) ||
3359          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3360       unsigned NumInRegs = 0;
3361       // In PIC we need an extra register to formulate the address computation
3362       // for the callee.
3363       unsigned MaxInRegs =
3364         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3365
3366       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3367         CCValAssign &VA = ArgLocs[i];
3368         if (!VA.isRegLoc())
3369           continue;
3370         unsigned Reg = VA.getLocReg();
3371         switch (Reg) {
3372         default: break;
3373         case X86::EAX: case X86::EDX: case X86::ECX:
3374           if (++NumInRegs == MaxInRegs)
3375             return false;
3376           break;
3377         }
3378       }
3379     }
3380   }
3381
3382   return true;
3383 }
3384
3385 FastISel *
3386 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3387                                   const TargetLibraryInfo *libInfo) const {
3388   return X86::createFastISel(funcInfo, libInfo);
3389 }
3390
3391 //===----------------------------------------------------------------------===//
3392 //                           Other Lowering Hooks
3393 //===----------------------------------------------------------------------===//
3394
3395 static bool MayFoldLoad(SDValue Op) {
3396   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3397 }
3398
3399 static bool MayFoldIntoStore(SDValue Op) {
3400   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3401 }
3402
3403 static bool isTargetShuffle(unsigned Opcode) {
3404   switch(Opcode) {
3405   default: return false;
3406   case X86ISD::PSHUFB:
3407   case X86ISD::PSHUFD:
3408   case X86ISD::PSHUFHW:
3409   case X86ISD::PSHUFLW:
3410   case X86ISD::SHUFP:
3411   case X86ISD::PALIGNR:
3412   case X86ISD::MOVLHPS:
3413   case X86ISD::MOVLHPD:
3414   case X86ISD::MOVHLPS:
3415   case X86ISD::MOVLPS:
3416   case X86ISD::MOVLPD:
3417   case X86ISD::MOVSHDUP:
3418   case X86ISD::MOVSLDUP:
3419   case X86ISD::MOVDDUP:
3420   case X86ISD::MOVSS:
3421   case X86ISD::MOVSD:
3422   case X86ISD::UNPCKL:
3423   case X86ISD::UNPCKH:
3424   case X86ISD::VPERMILP:
3425   case X86ISD::VPERM2X128:
3426   case X86ISD::VPERMI:
3427     return true;
3428   }
3429 }
3430
3431 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3432                                     SDValue V1, SelectionDAG &DAG) {
3433   switch(Opc) {
3434   default: llvm_unreachable("Unknown x86 shuffle node");
3435   case X86ISD::MOVSHDUP:
3436   case X86ISD::MOVSLDUP:
3437   case X86ISD::MOVDDUP:
3438     return DAG.getNode(Opc, dl, VT, V1);
3439   }
3440 }
3441
3442 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3443                                     SDValue V1, unsigned TargetMask,
3444                                     SelectionDAG &DAG) {
3445   switch(Opc) {
3446   default: llvm_unreachable("Unknown x86 shuffle node");
3447   case X86ISD::PSHUFD:
3448   case X86ISD::PSHUFHW:
3449   case X86ISD::PSHUFLW:
3450   case X86ISD::VPERMILP:
3451   case X86ISD::VPERMI:
3452     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3453   }
3454 }
3455
3456 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3457                                     SDValue V1, SDValue V2, unsigned TargetMask,
3458                                     SelectionDAG &DAG) {
3459   switch(Opc) {
3460   default: llvm_unreachable("Unknown x86 shuffle node");
3461   case X86ISD::PALIGNR:
3462   case X86ISD::VALIGN:
3463   case X86ISD::SHUFP:
3464   case X86ISD::VPERM2X128:
3465     return DAG.getNode(Opc, dl, VT, V1, V2,
3466                        DAG.getConstant(TargetMask, MVT::i8));
3467   }
3468 }
3469
3470 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3471                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3472   switch(Opc) {
3473   default: llvm_unreachable("Unknown x86 shuffle node");
3474   case X86ISD::MOVLHPS:
3475   case X86ISD::MOVLHPD:
3476   case X86ISD::MOVHLPS:
3477   case X86ISD::MOVLPS:
3478   case X86ISD::MOVLPD:
3479   case X86ISD::MOVSS:
3480   case X86ISD::MOVSD:
3481   case X86ISD::UNPCKL:
3482   case X86ISD::UNPCKH:
3483     return DAG.getNode(Opc, dl, VT, V1, V2);
3484   }
3485 }
3486
3487 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3488   MachineFunction &MF = DAG.getMachineFunction();
3489   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3490       DAG.getSubtarget().getRegisterInfo());
3491   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3492   int ReturnAddrIndex = FuncInfo->getRAIndex();
3493
3494   if (ReturnAddrIndex == 0) {
3495     // Set up a frame object for the return address.
3496     unsigned SlotSize = RegInfo->getSlotSize();
3497     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3498                                                            -(int64_t)SlotSize,
3499                                                            false);
3500     FuncInfo->setRAIndex(ReturnAddrIndex);
3501   }
3502
3503   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3504 }
3505
3506 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3507                                        bool hasSymbolicDisplacement) {
3508   // Offset should fit into 32 bit immediate field.
3509   if (!isInt<32>(Offset))
3510     return false;
3511
3512   // If we don't have a symbolic displacement - we don't have any extra
3513   // restrictions.
3514   if (!hasSymbolicDisplacement)
3515     return true;
3516
3517   // FIXME: Some tweaks might be needed for medium code model.
3518   if (M != CodeModel::Small && M != CodeModel::Kernel)
3519     return false;
3520
3521   // For small code model we assume that latest object is 16MB before end of 31
3522   // bits boundary. We may also accept pretty large negative constants knowing
3523   // that all objects are in the positive half of address space.
3524   if (M == CodeModel::Small && Offset < 16*1024*1024)
3525     return true;
3526
3527   // For kernel code model we know that all object resist in the negative half
3528   // of 32bits address space. We may not accept negative offsets, since they may
3529   // be just off and we may accept pretty large positive ones.
3530   if (M == CodeModel::Kernel && Offset > 0)
3531     return true;
3532
3533   return false;
3534 }
3535
3536 /// isCalleePop - Determines whether the callee is required to pop its
3537 /// own arguments. Callee pop is necessary to support tail calls.
3538 bool X86::isCalleePop(CallingConv::ID CallingConv,
3539                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3540   if (IsVarArg)
3541     return false;
3542
3543   switch (CallingConv) {
3544   default:
3545     return false;
3546   case CallingConv::X86_StdCall:
3547     return !is64Bit;
3548   case CallingConv::X86_FastCall:
3549     return !is64Bit;
3550   case CallingConv::X86_ThisCall:
3551     return !is64Bit;
3552   case CallingConv::Fast:
3553     return TailCallOpt;
3554   case CallingConv::GHC:
3555     return TailCallOpt;
3556   case CallingConv::HiPE:
3557     return TailCallOpt;
3558   }
3559 }
3560
3561 /// \brief Return true if the condition is an unsigned comparison operation.
3562 static bool isX86CCUnsigned(unsigned X86CC) {
3563   switch (X86CC) {
3564   default: llvm_unreachable("Invalid integer condition!");
3565   case X86::COND_E:     return true;
3566   case X86::COND_G:     return false;
3567   case X86::COND_GE:    return false;
3568   case X86::COND_L:     return false;
3569   case X86::COND_LE:    return false;
3570   case X86::COND_NE:    return true;
3571   case X86::COND_B:     return true;
3572   case X86::COND_A:     return true;
3573   case X86::COND_BE:    return true;
3574   case X86::COND_AE:    return true;
3575   }
3576   llvm_unreachable("covered switch fell through?!");
3577 }
3578
3579 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3580 /// specific condition code, returning the condition code and the LHS/RHS of the
3581 /// comparison to make.
3582 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3583                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3584   if (!isFP) {
3585     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3586       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3587         // X > -1   -> X == 0, jump !sign.
3588         RHS = DAG.getConstant(0, RHS.getValueType());
3589         return X86::COND_NS;
3590       }
3591       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3592         // X < 0   -> X == 0, jump on sign.
3593         return X86::COND_S;
3594       }
3595       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3596         // X < 1   -> X <= 0
3597         RHS = DAG.getConstant(0, RHS.getValueType());
3598         return X86::COND_LE;
3599       }
3600     }
3601
3602     switch (SetCCOpcode) {
3603     default: llvm_unreachable("Invalid integer condition!");
3604     case ISD::SETEQ:  return X86::COND_E;
3605     case ISD::SETGT:  return X86::COND_G;
3606     case ISD::SETGE:  return X86::COND_GE;
3607     case ISD::SETLT:  return X86::COND_L;
3608     case ISD::SETLE:  return X86::COND_LE;
3609     case ISD::SETNE:  return X86::COND_NE;
3610     case ISD::SETULT: return X86::COND_B;
3611     case ISD::SETUGT: return X86::COND_A;
3612     case ISD::SETULE: return X86::COND_BE;
3613     case ISD::SETUGE: return X86::COND_AE;
3614     }
3615   }
3616
3617   // First determine if it is required or is profitable to flip the operands.
3618
3619   // If LHS is a foldable load, but RHS is not, flip the condition.
3620   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3621       !ISD::isNON_EXTLoad(RHS.getNode())) {
3622     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3623     std::swap(LHS, RHS);
3624   }
3625
3626   switch (SetCCOpcode) {
3627   default: break;
3628   case ISD::SETOLT:
3629   case ISD::SETOLE:
3630   case ISD::SETUGT:
3631   case ISD::SETUGE:
3632     std::swap(LHS, RHS);
3633     break;
3634   }
3635
3636   // On a floating point condition, the flags are set as follows:
3637   // ZF  PF  CF   op
3638   //  0 | 0 | 0 | X > Y
3639   //  0 | 0 | 1 | X < Y
3640   //  1 | 0 | 0 | X == Y
3641   //  1 | 1 | 1 | unordered
3642   switch (SetCCOpcode) {
3643   default: llvm_unreachable("Condcode should be pre-legalized away");
3644   case ISD::SETUEQ:
3645   case ISD::SETEQ:   return X86::COND_E;
3646   case ISD::SETOLT:              // flipped
3647   case ISD::SETOGT:
3648   case ISD::SETGT:   return X86::COND_A;
3649   case ISD::SETOLE:              // flipped
3650   case ISD::SETOGE:
3651   case ISD::SETGE:   return X86::COND_AE;
3652   case ISD::SETUGT:              // flipped
3653   case ISD::SETULT:
3654   case ISD::SETLT:   return X86::COND_B;
3655   case ISD::SETUGE:              // flipped
3656   case ISD::SETULE:
3657   case ISD::SETLE:   return X86::COND_BE;
3658   case ISD::SETONE:
3659   case ISD::SETNE:   return X86::COND_NE;
3660   case ISD::SETUO:   return X86::COND_P;
3661   case ISD::SETO:    return X86::COND_NP;
3662   case ISD::SETOEQ:
3663   case ISD::SETUNE:  return X86::COND_INVALID;
3664   }
3665 }
3666
3667 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3668 /// code. Current x86 isa includes the following FP cmov instructions:
3669 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3670 static bool hasFPCMov(unsigned X86CC) {
3671   switch (X86CC) {
3672   default:
3673     return false;
3674   case X86::COND_B:
3675   case X86::COND_BE:
3676   case X86::COND_E:
3677   case X86::COND_P:
3678   case X86::COND_A:
3679   case X86::COND_AE:
3680   case X86::COND_NE:
3681   case X86::COND_NP:
3682     return true;
3683   }
3684 }
3685
3686 /// isFPImmLegal - Returns true if the target can instruction select the
3687 /// specified FP immediate natively. If false, the legalizer will
3688 /// materialize the FP immediate as a load from a constant pool.
3689 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3690   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3691     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3692       return true;
3693   }
3694   return false;
3695 }
3696
3697 /// \brief Returns true if it is beneficial to convert a load of a constant
3698 /// to just the constant itself.
3699 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3700                                                           Type *Ty) const {
3701   assert(Ty->isIntegerTy());
3702
3703   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3704   if (BitSize == 0 || BitSize > 64)
3705     return false;
3706   return true;
3707 }
3708
3709 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3710 /// the specified range (L, H].
3711 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3712   return (Val < 0) || (Val >= Low && Val < Hi);
3713 }
3714
3715 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3716 /// specified value.
3717 static bool isUndefOrEqual(int Val, int CmpVal) {
3718   return (Val < 0 || Val == CmpVal);
3719 }
3720
3721 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3722 /// from position Pos and ending in Pos+Size, falls within the specified
3723 /// sequential range (L, L+Pos]. or is undef.
3724 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3725                                        unsigned Pos, unsigned Size, int Low) {
3726   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3727     if (!isUndefOrEqual(Mask[i], Low))
3728       return false;
3729   return true;
3730 }
3731
3732 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3733 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3734 /// the second operand.
3735 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3736   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3737     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3738   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3739     return (Mask[0] < 2 && Mask[1] < 2);
3740   return false;
3741 }
3742
3743 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3744 /// is suitable for input to PSHUFHW.
3745 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3746   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3747     return false;
3748
3749   // Lower quadword copied in order or undef.
3750   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3751     return false;
3752
3753   // Upper quadword shuffled.
3754   for (unsigned i = 4; i != 8; ++i)
3755     if (!isUndefOrInRange(Mask[i], 4, 8))
3756       return false;
3757
3758   if (VT == MVT::v16i16) {
3759     // Lower quadword copied in order or undef.
3760     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3761       return false;
3762
3763     // Upper quadword shuffled.
3764     for (unsigned i = 12; i != 16; ++i)
3765       if (!isUndefOrInRange(Mask[i], 12, 16))
3766         return false;
3767   }
3768
3769   return true;
3770 }
3771
3772 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3773 /// is suitable for input to PSHUFLW.
3774 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3775   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3776     return false;
3777
3778   // Upper quadword copied in order.
3779   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3780     return false;
3781
3782   // Lower quadword shuffled.
3783   for (unsigned i = 0; i != 4; ++i)
3784     if (!isUndefOrInRange(Mask[i], 0, 4))
3785       return false;
3786
3787   if (VT == MVT::v16i16) {
3788     // Upper quadword copied in order.
3789     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3790       return false;
3791
3792     // Lower quadword shuffled.
3793     for (unsigned i = 8; i != 12; ++i)
3794       if (!isUndefOrInRange(Mask[i], 8, 12))
3795         return false;
3796   }
3797
3798   return true;
3799 }
3800
3801 /// \brief Return true if the mask specifies a shuffle of elements that is
3802 /// suitable for input to intralane (palignr) or interlane (valign) vector
3803 /// right-shift.
3804 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3805   unsigned NumElts = VT.getVectorNumElements();
3806   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3807   unsigned NumLaneElts = NumElts/NumLanes;
3808
3809   // Do not handle 64-bit element shuffles with palignr.
3810   if (NumLaneElts == 2)
3811     return false;
3812
3813   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3814     unsigned i;
3815     for (i = 0; i != NumLaneElts; ++i) {
3816       if (Mask[i+l] >= 0)
3817         break;
3818     }
3819
3820     // Lane is all undef, go to next lane
3821     if (i == NumLaneElts)
3822       continue;
3823
3824     int Start = Mask[i+l];
3825
3826     // Make sure its in this lane in one of the sources
3827     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3828         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3829       return false;
3830
3831     // If not lane 0, then we must match lane 0
3832     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3833       return false;
3834
3835     // Correct second source to be contiguous with first source
3836     if (Start >= (int)NumElts)
3837       Start -= NumElts - NumLaneElts;
3838
3839     // Make sure we're shifting in the right direction.
3840     if (Start <= (int)(i+l))
3841       return false;
3842
3843     Start -= i;
3844
3845     // Check the rest of the elements to see if they are consecutive.
3846     for (++i; i != NumLaneElts; ++i) {
3847       int Idx = Mask[i+l];
3848
3849       // Make sure its in this lane
3850       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3851           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3852         return false;
3853
3854       // If not lane 0, then we must match lane 0
3855       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3856         return false;
3857
3858       if (Idx >= (int)NumElts)
3859         Idx -= NumElts - NumLaneElts;
3860
3861       if (!isUndefOrEqual(Idx, Start+i))
3862         return false;
3863
3864     }
3865   }
3866
3867   return true;
3868 }
3869
3870 /// \brief Return true if the node specifies a shuffle of elements that is
3871 /// suitable for input to PALIGNR.
3872 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3873                           const X86Subtarget *Subtarget) {
3874   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3875       (VT.is256BitVector() && !Subtarget->hasInt256()))
3876     // FIXME: Add AVX512BW.
3877     return false;
3878
3879   return isAlignrMask(Mask, VT, false);
3880 }
3881
3882 /// \brief Return true if the node specifies a shuffle of elements that is
3883 /// suitable for input to VALIGN.
3884 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3885                           const X86Subtarget *Subtarget) {
3886   // FIXME: Add AVX512VL.
3887   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3888     return false;
3889   return isAlignrMask(Mask, VT, true);
3890 }
3891
3892 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3893 /// the two vector operands have swapped position.
3894 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3895                                      unsigned NumElems) {
3896   for (unsigned i = 0; i != NumElems; ++i) {
3897     int idx = Mask[i];
3898     if (idx < 0)
3899       continue;
3900     else if (idx < (int)NumElems)
3901       Mask[i] = idx + NumElems;
3902     else
3903       Mask[i] = idx - NumElems;
3904   }
3905 }
3906
3907 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3908 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3909 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3910 /// reverse of what x86 shuffles want.
3911 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3912
3913   unsigned NumElems = VT.getVectorNumElements();
3914   unsigned NumLanes = VT.getSizeInBits()/128;
3915   unsigned NumLaneElems = NumElems/NumLanes;
3916
3917   if (NumLaneElems != 2 && NumLaneElems != 4)
3918     return false;
3919
3920   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3921   bool symetricMaskRequired =
3922     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3923
3924   // VSHUFPSY divides the resulting vector into 4 chunks.
3925   // The sources are also splitted into 4 chunks, and each destination
3926   // chunk must come from a different source chunk.
3927   //
3928   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3929   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3930   //
3931   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3932   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3933   //
3934   // VSHUFPDY divides the resulting vector into 4 chunks.
3935   // The sources are also splitted into 4 chunks, and each destination
3936   // chunk must come from a different source chunk.
3937   //
3938   //  SRC1 =>      X3       X2       X1       X0
3939   //  SRC2 =>      Y3       Y2       Y1       Y0
3940   //
3941   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3942   //
3943   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3944   unsigned HalfLaneElems = NumLaneElems/2;
3945   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3946     for (unsigned i = 0; i != NumLaneElems; ++i) {
3947       int Idx = Mask[i+l];
3948       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3949       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3950         return false;
3951       // For VSHUFPSY, the mask of the second half must be the same as the
3952       // first but with the appropriate offsets. This works in the same way as
3953       // VPERMILPS works with masks.
3954       if (!symetricMaskRequired || Idx < 0)
3955         continue;
3956       if (MaskVal[i] < 0) {
3957         MaskVal[i] = Idx - l;
3958         continue;
3959       }
3960       if ((signed)(Idx - l) != MaskVal[i])
3961         return false;
3962     }
3963   }
3964
3965   return true;
3966 }
3967
3968 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3969 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3970 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3971   if (!VT.is128BitVector())
3972     return false;
3973
3974   unsigned NumElems = VT.getVectorNumElements();
3975
3976   if (NumElems != 4)
3977     return false;
3978
3979   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3980   return isUndefOrEqual(Mask[0], 6) &&
3981          isUndefOrEqual(Mask[1], 7) &&
3982          isUndefOrEqual(Mask[2], 2) &&
3983          isUndefOrEqual(Mask[3], 3);
3984 }
3985
3986 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3987 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3988 /// <2, 3, 2, 3>
3989 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3990   if (!VT.is128BitVector())
3991     return false;
3992
3993   unsigned NumElems = VT.getVectorNumElements();
3994
3995   if (NumElems != 4)
3996     return false;
3997
3998   return isUndefOrEqual(Mask[0], 2) &&
3999          isUndefOrEqual(Mask[1], 3) &&
4000          isUndefOrEqual(Mask[2], 2) &&
4001          isUndefOrEqual(Mask[3], 3);
4002 }
4003
4004 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4005 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4006 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4007   if (!VT.is128BitVector())
4008     return false;
4009
4010   unsigned NumElems = VT.getVectorNumElements();
4011
4012   if (NumElems != 2 && NumElems != 4)
4013     return false;
4014
4015   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4016     if (!isUndefOrEqual(Mask[i], i + NumElems))
4017       return false;
4018
4019   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4020     if (!isUndefOrEqual(Mask[i], i))
4021       return false;
4022
4023   return true;
4024 }
4025
4026 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4027 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4028 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4029   if (!VT.is128BitVector())
4030     return false;
4031
4032   unsigned NumElems = VT.getVectorNumElements();
4033
4034   if (NumElems != 2 && NumElems != 4)
4035     return false;
4036
4037   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4038     if (!isUndefOrEqual(Mask[i], i))
4039       return false;
4040
4041   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4042     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4043       return false;
4044
4045   return true;
4046 }
4047
4048 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4049 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4050 /// i. e: If all but one element come from the same vector.
4051 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4052   // TODO: Deal with AVX's VINSERTPS
4053   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4054     return false;
4055
4056   unsigned CorrectPosV1 = 0;
4057   unsigned CorrectPosV2 = 0;
4058   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4059     if (Mask[i] == -1) {
4060       ++CorrectPosV1;
4061       ++CorrectPosV2;
4062       continue;
4063     }
4064
4065     if (Mask[i] == i)
4066       ++CorrectPosV1;
4067     else if (Mask[i] == i + 4)
4068       ++CorrectPosV2;
4069   }
4070
4071   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4072     // We have 3 elements (undefs count as elements from any vector) from one
4073     // vector, and one from another.
4074     return true;
4075
4076   return false;
4077 }
4078
4079 //
4080 // Some special combinations that can be optimized.
4081 //
4082 static
4083 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4084                                SelectionDAG &DAG) {
4085   MVT VT = SVOp->getSimpleValueType(0);
4086   SDLoc dl(SVOp);
4087
4088   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4089     return SDValue();
4090
4091   ArrayRef<int> Mask = SVOp->getMask();
4092
4093   // These are the special masks that may be optimized.
4094   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4095   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4096   bool MatchEvenMask = true;
4097   bool MatchOddMask  = true;
4098   for (int i=0; i<8; ++i) {
4099     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4100       MatchEvenMask = false;
4101     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4102       MatchOddMask = false;
4103   }
4104
4105   if (!MatchEvenMask && !MatchOddMask)
4106     return SDValue();
4107
4108   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4109
4110   SDValue Op0 = SVOp->getOperand(0);
4111   SDValue Op1 = SVOp->getOperand(1);
4112
4113   if (MatchEvenMask) {
4114     // Shift the second operand right to 32 bits.
4115     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4116     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4117   } else {
4118     // Shift the first operand left to 32 bits.
4119     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4120     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4121   }
4122   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4123   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4124 }
4125
4126 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4127 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4128 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4129                          bool HasInt256, bool V2IsSplat = false) {
4130
4131   assert(VT.getSizeInBits() >= 128 &&
4132          "Unsupported vector type for unpckl");
4133
4134   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4135   unsigned NumLanes;
4136   unsigned NumOf256BitLanes;
4137   unsigned NumElts = VT.getVectorNumElements();
4138   if (VT.is256BitVector()) {
4139     if (NumElts != 4 && NumElts != 8 &&
4140         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4141     return false;
4142     NumLanes = 2;
4143     NumOf256BitLanes = 1;
4144   } else if (VT.is512BitVector()) {
4145     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4146            "Unsupported vector type for unpckh");
4147     NumLanes = 2;
4148     NumOf256BitLanes = 2;
4149   } else {
4150     NumLanes = 1;
4151     NumOf256BitLanes = 1;
4152   }
4153
4154   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4155   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4156
4157   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4158     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4159       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4160         int BitI  = Mask[l256*NumEltsInStride+l+i];
4161         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4162         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4163           return false;
4164         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4165           return false;
4166         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4167           return false;
4168       }
4169     }
4170   }
4171   return true;
4172 }
4173
4174 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4175 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4176 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4177                          bool HasInt256, bool V2IsSplat = false) {
4178   assert(VT.getSizeInBits() >= 128 &&
4179          "Unsupported vector type for unpckh");
4180
4181   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4182   unsigned NumLanes;
4183   unsigned NumOf256BitLanes;
4184   unsigned NumElts = VT.getVectorNumElements();
4185   if (VT.is256BitVector()) {
4186     if (NumElts != 4 && NumElts != 8 &&
4187         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4188     return false;
4189     NumLanes = 2;
4190     NumOf256BitLanes = 1;
4191   } else if (VT.is512BitVector()) {
4192     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4193            "Unsupported vector type for unpckh");
4194     NumLanes = 2;
4195     NumOf256BitLanes = 2;
4196   } else {
4197     NumLanes = 1;
4198     NumOf256BitLanes = 1;
4199   }
4200
4201   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4202   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4203
4204   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4205     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4206       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4207         int BitI  = Mask[l256*NumEltsInStride+l+i];
4208         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4209         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4210           return false;
4211         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4212           return false;
4213         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4214           return false;
4215       }
4216     }
4217   }
4218   return true;
4219 }
4220
4221 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4222 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4223 /// <0, 0, 1, 1>
4224 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4225   unsigned NumElts = VT.getVectorNumElements();
4226   bool Is256BitVec = VT.is256BitVector();
4227
4228   if (VT.is512BitVector())
4229     return false;
4230   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4231          "Unsupported vector type for unpckh");
4232
4233   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4234       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4235     return false;
4236
4237   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4238   // FIXME: Need a better way to get rid of this, there's no latency difference
4239   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4240   // the former later. We should also remove the "_undef" special mask.
4241   if (NumElts == 4 && Is256BitVec)
4242     return false;
4243
4244   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4245   // independently on 128-bit lanes.
4246   unsigned NumLanes = VT.getSizeInBits()/128;
4247   unsigned NumLaneElts = NumElts/NumLanes;
4248
4249   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4250     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4251       int BitI  = Mask[l+i];
4252       int BitI1 = Mask[l+i+1];
4253
4254       if (!isUndefOrEqual(BitI, j))
4255         return false;
4256       if (!isUndefOrEqual(BitI1, j))
4257         return false;
4258     }
4259   }
4260
4261   return true;
4262 }
4263
4264 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4265 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4266 /// <2, 2, 3, 3>
4267 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4268   unsigned NumElts = VT.getVectorNumElements();
4269
4270   if (VT.is512BitVector())
4271     return false;
4272
4273   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4274          "Unsupported vector type for unpckh");
4275
4276   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4277       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4278     return false;
4279
4280   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4281   // independently on 128-bit lanes.
4282   unsigned NumLanes = VT.getSizeInBits()/128;
4283   unsigned NumLaneElts = NumElts/NumLanes;
4284
4285   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4286     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4287       int BitI  = Mask[l+i];
4288       int BitI1 = Mask[l+i+1];
4289       if (!isUndefOrEqual(BitI, j))
4290         return false;
4291       if (!isUndefOrEqual(BitI1, j))
4292         return false;
4293     }
4294   }
4295   return true;
4296 }
4297
4298 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4299 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4300 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4301   if (!VT.is512BitVector())
4302     return false;
4303
4304   unsigned NumElts = VT.getVectorNumElements();
4305   unsigned HalfSize = NumElts/2;
4306   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4307     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4308       *Imm = 1;
4309       return true;
4310     }
4311   }
4312   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4313     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4314       *Imm = 0;
4315       return true;
4316     }
4317   }
4318   return false;
4319 }
4320
4321 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4322 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4323 /// MOVSD, and MOVD, i.e. setting the lowest element.
4324 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4325   if (VT.getVectorElementType().getSizeInBits() < 32)
4326     return false;
4327   if (!VT.is128BitVector())
4328     return false;
4329
4330   unsigned NumElts = VT.getVectorNumElements();
4331
4332   if (!isUndefOrEqual(Mask[0], NumElts))
4333     return false;
4334
4335   for (unsigned i = 1; i != NumElts; ++i)
4336     if (!isUndefOrEqual(Mask[i], i))
4337       return false;
4338
4339   return true;
4340 }
4341
4342 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4343 /// as permutations between 128-bit chunks or halves. As an example: this
4344 /// shuffle bellow:
4345 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4346 /// The first half comes from the second half of V1 and the second half from the
4347 /// the second half of V2.
4348 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4349   if (!HasFp256 || !VT.is256BitVector())
4350     return false;
4351
4352   // The shuffle result is divided into half A and half B. In total the two
4353   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4354   // B must come from C, D, E or F.
4355   unsigned HalfSize = VT.getVectorNumElements()/2;
4356   bool MatchA = false, MatchB = false;
4357
4358   // Check if A comes from one of C, D, E, F.
4359   for (unsigned Half = 0; Half != 4; ++Half) {
4360     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4361       MatchA = true;
4362       break;
4363     }
4364   }
4365
4366   // Check if B comes from one of C, D, E, F.
4367   for (unsigned Half = 0; Half != 4; ++Half) {
4368     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4369       MatchB = true;
4370       break;
4371     }
4372   }
4373
4374   return MatchA && MatchB;
4375 }
4376
4377 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4378 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4379 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4380   MVT VT = SVOp->getSimpleValueType(0);
4381
4382   unsigned HalfSize = VT.getVectorNumElements()/2;
4383
4384   unsigned FstHalf = 0, SndHalf = 0;
4385   for (unsigned i = 0; i < HalfSize; ++i) {
4386     if (SVOp->getMaskElt(i) > 0) {
4387       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4388       break;
4389     }
4390   }
4391   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4392     if (SVOp->getMaskElt(i) > 0) {
4393       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4394       break;
4395     }
4396   }
4397
4398   return (FstHalf | (SndHalf << 4));
4399 }
4400
4401 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4402 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4403   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4404   if (EltSize < 32)
4405     return false;
4406
4407   unsigned NumElts = VT.getVectorNumElements();
4408   Imm8 = 0;
4409   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4410     for (unsigned i = 0; i != NumElts; ++i) {
4411       if (Mask[i] < 0)
4412         continue;
4413       Imm8 |= Mask[i] << (i*2);
4414     }
4415     return true;
4416   }
4417
4418   unsigned LaneSize = 4;
4419   SmallVector<int, 4> MaskVal(LaneSize, -1);
4420
4421   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4422     for (unsigned i = 0; i != LaneSize; ++i) {
4423       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4424         return false;
4425       if (Mask[i+l] < 0)
4426         continue;
4427       if (MaskVal[i] < 0) {
4428         MaskVal[i] = Mask[i+l] - l;
4429         Imm8 |= MaskVal[i] << (i*2);
4430         continue;
4431       }
4432       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4433         return false;
4434     }
4435   }
4436   return true;
4437 }
4438
4439 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4440 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4441 /// Note that VPERMIL mask matching is different depending whether theunderlying
4442 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4443 /// to the same elements of the low, but to the higher half of the source.
4444 /// In VPERMILPD the two lanes could be shuffled independently of each other
4445 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4446 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4447   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4448   if (VT.getSizeInBits() < 256 || EltSize < 32)
4449     return false;
4450   bool symetricMaskRequired = (EltSize == 32);
4451   unsigned NumElts = VT.getVectorNumElements();
4452
4453   unsigned NumLanes = VT.getSizeInBits()/128;
4454   unsigned LaneSize = NumElts/NumLanes;
4455   // 2 or 4 elements in one lane
4456
4457   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4458   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4459     for (unsigned i = 0; i != LaneSize; ++i) {
4460       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4461         return false;
4462       if (symetricMaskRequired) {
4463         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4464           ExpectedMaskVal[i] = Mask[i+l] - l;
4465           continue;
4466         }
4467         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4468           return false;
4469       }
4470     }
4471   }
4472   return true;
4473 }
4474
4475 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4476 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4477 /// element of vector 2 and the other elements to come from vector 1 in order.
4478 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4479                                bool V2IsSplat = false, bool V2IsUndef = false) {
4480   if (!VT.is128BitVector())
4481     return false;
4482
4483   unsigned NumOps = VT.getVectorNumElements();
4484   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4485     return false;
4486
4487   if (!isUndefOrEqual(Mask[0], 0))
4488     return false;
4489
4490   for (unsigned i = 1; i != NumOps; ++i)
4491     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4492           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4493           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4494       return false;
4495
4496   return true;
4497 }
4498
4499 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4500 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4501 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4502 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4503                            const X86Subtarget *Subtarget) {
4504   if (!Subtarget->hasSSE3())
4505     return false;
4506
4507   unsigned NumElems = VT.getVectorNumElements();
4508
4509   if ((VT.is128BitVector() && NumElems != 4) ||
4510       (VT.is256BitVector() && NumElems != 8) ||
4511       (VT.is512BitVector() && NumElems != 16))
4512     return false;
4513
4514   // "i+1" is the value the indexed mask element must have
4515   for (unsigned i = 0; i != NumElems; i += 2)
4516     if (!isUndefOrEqual(Mask[i], i+1) ||
4517         !isUndefOrEqual(Mask[i+1], i+1))
4518       return false;
4519
4520   return true;
4521 }
4522
4523 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4524 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4525 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4526 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4527                            const X86Subtarget *Subtarget) {
4528   if (!Subtarget->hasSSE3())
4529     return false;
4530
4531   unsigned NumElems = VT.getVectorNumElements();
4532
4533   if ((VT.is128BitVector() && NumElems != 4) ||
4534       (VT.is256BitVector() && NumElems != 8) ||
4535       (VT.is512BitVector() && NumElems != 16))
4536     return false;
4537
4538   // "i" is the value the indexed mask element must have
4539   for (unsigned i = 0; i != NumElems; i += 2)
4540     if (!isUndefOrEqual(Mask[i], i) ||
4541         !isUndefOrEqual(Mask[i+1], i))
4542       return false;
4543
4544   return true;
4545 }
4546
4547 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4548 /// specifies a shuffle of elements that is suitable for input to 256-bit
4549 /// version of MOVDDUP.
4550 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4551   if (!HasFp256 || !VT.is256BitVector())
4552     return false;
4553
4554   unsigned NumElts = VT.getVectorNumElements();
4555   if (NumElts != 4)
4556     return false;
4557
4558   for (unsigned i = 0; i != NumElts/2; ++i)
4559     if (!isUndefOrEqual(Mask[i], 0))
4560       return false;
4561   for (unsigned i = NumElts/2; i != NumElts; ++i)
4562     if (!isUndefOrEqual(Mask[i], NumElts/2))
4563       return false;
4564   return true;
4565 }
4566
4567 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4568 /// specifies a shuffle of elements that is suitable for input to 128-bit
4569 /// version of MOVDDUP.
4570 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4571   if (!VT.is128BitVector())
4572     return false;
4573
4574   unsigned e = VT.getVectorNumElements() / 2;
4575   for (unsigned i = 0; i != e; ++i)
4576     if (!isUndefOrEqual(Mask[i], i))
4577       return false;
4578   for (unsigned i = 0; i != e; ++i)
4579     if (!isUndefOrEqual(Mask[e+i], i))
4580       return false;
4581   return true;
4582 }
4583
4584 /// isVEXTRACTIndex - Return true if the specified
4585 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4586 /// suitable for instruction that extract 128 or 256 bit vectors
4587 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4588   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4589   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4590     return false;
4591
4592   // The index should be aligned on a vecWidth-bit boundary.
4593   uint64_t Index =
4594     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4595
4596   MVT VT = N->getSimpleValueType(0);
4597   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4598   bool Result = (Index * ElSize) % vecWidth == 0;
4599
4600   return Result;
4601 }
4602
4603 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4604 /// operand specifies a subvector insert that is suitable for input to
4605 /// insertion of 128 or 256-bit subvectors
4606 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4607   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4608   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4609     return false;
4610   // The index should be aligned on a vecWidth-bit boundary.
4611   uint64_t Index =
4612     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4613
4614   MVT VT = N->getSimpleValueType(0);
4615   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4616   bool Result = (Index * ElSize) % vecWidth == 0;
4617
4618   return Result;
4619 }
4620
4621 bool X86::isVINSERT128Index(SDNode *N) {
4622   return isVINSERTIndex(N, 128);
4623 }
4624
4625 bool X86::isVINSERT256Index(SDNode *N) {
4626   return isVINSERTIndex(N, 256);
4627 }
4628
4629 bool X86::isVEXTRACT128Index(SDNode *N) {
4630   return isVEXTRACTIndex(N, 128);
4631 }
4632
4633 bool X86::isVEXTRACT256Index(SDNode *N) {
4634   return isVEXTRACTIndex(N, 256);
4635 }
4636
4637 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4638 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4639 /// Handles 128-bit and 256-bit.
4640 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4641   MVT VT = N->getSimpleValueType(0);
4642
4643   assert((VT.getSizeInBits() >= 128) &&
4644          "Unsupported vector type for PSHUF/SHUFP");
4645
4646   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4647   // independently on 128-bit lanes.
4648   unsigned NumElts = VT.getVectorNumElements();
4649   unsigned NumLanes = VT.getSizeInBits()/128;
4650   unsigned NumLaneElts = NumElts/NumLanes;
4651
4652   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4653          "Only supports 2, 4 or 8 elements per lane");
4654
4655   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4656   unsigned Mask = 0;
4657   for (unsigned i = 0; i != NumElts; ++i) {
4658     int Elt = N->getMaskElt(i);
4659     if (Elt < 0) continue;
4660     Elt &= NumLaneElts - 1;
4661     unsigned ShAmt = (i << Shift) % 8;
4662     Mask |= Elt << ShAmt;
4663   }
4664
4665   return Mask;
4666 }
4667
4668 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4669 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4670 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4671   MVT VT = N->getSimpleValueType(0);
4672
4673   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4674          "Unsupported vector type for PSHUFHW");
4675
4676   unsigned NumElts = VT.getVectorNumElements();
4677
4678   unsigned Mask = 0;
4679   for (unsigned l = 0; l != NumElts; l += 8) {
4680     // 8 nodes per lane, but we only care about the last 4.
4681     for (unsigned i = 0; i < 4; ++i) {
4682       int Elt = N->getMaskElt(l+i+4);
4683       if (Elt < 0) continue;
4684       Elt &= 0x3; // only 2-bits.
4685       Mask |= Elt << (i * 2);
4686     }
4687   }
4688
4689   return Mask;
4690 }
4691
4692 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4693 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4694 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4695   MVT VT = N->getSimpleValueType(0);
4696
4697   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4698          "Unsupported vector type for PSHUFHW");
4699
4700   unsigned NumElts = VT.getVectorNumElements();
4701
4702   unsigned Mask = 0;
4703   for (unsigned l = 0; l != NumElts; l += 8) {
4704     // 8 nodes per lane, but we only care about the first 4.
4705     for (unsigned i = 0; i < 4; ++i) {
4706       int Elt = N->getMaskElt(l+i);
4707       if (Elt < 0) continue;
4708       Elt &= 0x3; // only 2-bits
4709       Mask |= Elt << (i * 2);
4710     }
4711   }
4712
4713   return Mask;
4714 }
4715
4716 /// \brief Return the appropriate immediate to shuffle the specified
4717 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4718 /// VALIGN (if Interlane is true) instructions.
4719 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4720                                            bool InterLane) {
4721   MVT VT = SVOp->getSimpleValueType(0);
4722   unsigned EltSize = InterLane ? 1 :
4723     VT.getVectorElementType().getSizeInBits() >> 3;
4724
4725   unsigned NumElts = VT.getVectorNumElements();
4726   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4727   unsigned NumLaneElts = NumElts/NumLanes;
4728
4729   int Val = 0;
4730   unsigned i;
4731   for (i = 0; i != NumElts; ++i) {
4732     Val = SVOp->getMaskElt(i);
4733     if (Val >= 0)
4734       break;
4735   }
4736   if (Val >= (int)NumElts)
4737     Val -= NumElts - NumLaneElts;
4738
4739   assert(Val - i > 0 && "PALIGNR imm should be positive");
4740   return (Val - i) * EltSize;
4741 }
4742
4743 /// \brief Return the appropriate immediate to shuffle the specified
4744 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4745 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4746   return getShuffleAlignrImmediate(SVOp, false);
4747 }
4748
4749 /// \brief Return the appropriate immediate to shuffle the specified
4750 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4751 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4752   return getShuffleAlignrImmediate(SVOp, true);
4753 }
4754
4755
4756 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4757   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4758   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4759     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4760
4761   uint64_t Index =
4762     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4763
4764   MVT VecVT = N->getOperand(0).getSimpleValueType();
4765   MVT ElVT = VecVT.getVectorElementType();
4766
4767   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4768   return Index / NumElemsPerChunk;
4769 }
4770
4771 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4772   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4773   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4774     llvm_unreachable("Illegal insert subvector for VINSERT");
4775
4776   uint64_t Index =
4777     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4778
4779   MVT VecVT = N->getSimpleValueType(0);
4780   MVT ElVT = VecVT.getVectorElementType();
4781
4782   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4783   return Index / NumElemsPerChunk;
4784 }
4785
4786 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4787 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4788 /// and VINSERTI128 instructions.
4789 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4790   return getExtractVEXTRACTImmediate(N, 128);
4791 }
4792
4793 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4794 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4795 /// and VINSERTI64x4 instructions.
4796 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4797   return getExtractVEXTRACTImmediate(N, 256);
4798 }
4799
4800 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4801 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4802 /// and VINSERTI128 instructions.
4803 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4804   return getInsertVINSERTImmediate(N, 128);
4805 }
4806
4807 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4808 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4809 /// and VINSERTI64x4 instructions.
4810 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4811   return getInsertVINSERTImmediate(N, 256);
4812 }
4813
4814 /// isZero - Returns true if Elt is a constant integer zero
4815 static bool isZero(SDValue V) {
4816   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4817   return C && C->isNullValue();
4818 }
4819
4820 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4821 /// constant +0.0.
4822 bool X86::isZeroNode(SDValue Elt) {
4823   if (isZero(Elt))
4824     return true;
4825   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4826     return CFP->getValueAPF().isPosZero();
4827   return false;
4828 }
4829
4830 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4831 /// match movhlps. The lower half elements should come from upper half of
4832 /// V1 (and in order), and the upper half elements should come from the upper
4833 /// half of V2 (and in order).
4834 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4835   if (!VT.is128BitVector())
4836     return false;
4837   if (VT.getVectorNumElements() != 4)
4838     return false;
4839   for (unsigned i = 0, e = 2; i != e; ++i)
4840     if (!isUndefOrEqual(Mask[i], i+2))
4841       return false;
4842   for (unsigned i = 2; i != 4; ++i)
4843     if (!isUndefOrEqual(Mask[i], i+4))
4844       return false;
4845   return true;
4846 }
4847
4848 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4849 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4850 /// required.
4851 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4852   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4853     return false;
4854   N = N->getOperand(0).getNode();
4855   if (!ISD::isNON_EXTLoad(N))
4856     return false;
4857   if (LD)
4858     *LD = cast<LoadSDNode>(N);
4859   return true;
4860 }
4861
4862 // Test whether the given value is a vector value which will be legalized
4863 // into a load.
4864 static bool WillBeConstantPoolLoad(SDNode *N) {
4865   if (N->getOpcode() != ISD::BUILD_VECTOR)
4866     return false;
4867
4868   // Check for any non-constant elements.
4869   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4870     switch (N->getOperand(i).getNode()->getOpcode()) {
4871     case ISD::UNDEF:
4872     case ISD::ConstantFP:
4873     case ISD::Constant:
4874       break;
4875     default:
4876       return false;
4877     }
4878
4879   // Vectors of all-zeros and all-ones are materialized with special
4880   // instructions rather than being loaded.
4881   return !ISD::isBuildVectorAllZeros(N) &&
4882          !ISD::isBuildVectorAllOnes(N);
4883 }
4884
4885 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4886 /// match movlp{s|d}. The lower half elements should come from lower half of
4887 /// V1 (and in order), and the upper half elements should come from the upper
4888 /// half of V2 (and in order). And since V1 will become the source of the
4889 /// MOVLP, it must be either a vector load or a scalar load to vector.
4890 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4891                                ArrayRef<int> Mask, MVT VT) {
4892   if (!VT.is128BitVector())
4893     return false;
4894
4895   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4896     return false;
4897   // Is V2 is a vector load, don't do this transformation. We will try to use
4898   // load folding shufps op.
4899   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4900     return false;
4901
4902   unsigned NumElems = VT.getVectorNumElements();
4903
4904   if (NumElems != 2 && NumElems != 4)
4905     return false;
4906   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4907     if (!isUndefOrEqual(Mask[i], i))
4908       return false;
4909   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4910     if (!isUndefOrEqual(Mask[i], i+NumElems))
4911       return false;
4912   return true;
4913 }
4914
4915 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4916 /// to an zero vector.
4917 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4918 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4919   SDValue V1 = N->getOperand(0);
4920   SDValue V2 = N->getOperand(1);
4921   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4922   for (unsigned i = 0; i != NumElems; ++i) {
4923     int Idx = N->getMaskElt(i);
4924     if (Idx >= (int)NumElems) {
4925       unsigned Opc = V2.getOpcode();
4926       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4927         continue;
4928       if (Opc != ISD::BUILD_VECTOR ||
4929           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4930         return false;
4931     } else if (Idx >= 0) {
4932       unsigned Opc = V1.getOpcode();
4933       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4934         continue;
4935       if (Opc != ISD::BUILD_VECTOR ||
4936           !X86::isZeroNode(V1.getOperand(Idx)))
4937         return false;
4938     }
4939   }
4940   return true;
4941 }
4942
4943 /// getZeroVector - Returns a vector of specified type with all zero elements.
4944 ///
4945 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4946                              SelectionDAG &DAG, SDLoc dl) {
4947   assert(VT.isVector() && "Expected a vector type");
4948
4949   // Always build SSE zero vectors as <4 x i32> bitcasted
4950   // to their dest type. This ensures they get CSE'd.
4951   SDValue Vec;
4952   if (VT.is128BitVector()) {  // SSE
4953     if (Subtarget->hasSSE2()) {  // SSE2
4954       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4955       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4956     } else { // SSE1
4957       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4958       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4959     }
4960   } else if (VT.is256BitVector()) { // AVX
4961     if (Subtarget->hasInt256()) { // AVX2
4962       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4963       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4964       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4965     } else {
4966       // 256-bit logic and arithmetic instructions in AVX are all
4967       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4968       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4969       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4970       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4971     }
4972   } else if (VT.is512BitVector()) { // AVX-512
4973       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4974       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4975                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4976       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4977   } else if (VT.getScalarType() == MVT::i1) {
4978     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4979     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4980     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4981     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4982   } else
4983     llvm_unreachable("Unexpected vector type");
4984
4985   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4986 }
4987
4988 /// getOnesVector - Returns a vector of specified type with all bits set.
4989 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4990 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4991 /// Then bitcast to their original type, ensuring they get CSE'd.
4992 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4993                              SDLoc dl) {
4994   assert(VT.isVector() && "Expected a vector type");
4995
4996   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4997   SDValue Vec;
4998   if (VT.is256BitVector()) {
4999     if (HasInt256) { // AVX2
5000       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5001       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5002     } else { // AVX
5003       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5004       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5005     }
5006   } else if (VT.is128BitVector()) {
5007     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5008   } else
5009     llvm_unreachable("Unexpected vector type");
5010
5011   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5012 }
5013
5014 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5015 /// that point to V2 points to its first element.
5016 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5017   for (unsigned i = 0; i != NumElems; ++i) {
5018     if (Mask[i] > (int)NumElems) {
5019       Mask[i] = NumElems;
5020     }
5021   }
5022 }
5023
5024 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5025 /// operation of specified width.
5026 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5027                        SDValue V2) {
5028   unsigned NumElems = VT.getVectorNumElements();
5029   SmallVector<int, 8> Mask;
5030   Mask.push_back(NumElems);
5031   for (unsigned i = 1; i != NumElems; ++i)
5032     Mask.push_back(i);
5033   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5034 }
5035
5036 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5037 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5038                           SDValue V2) {
5039   unsigned NumElems = VT.getVectorNumElements();
5040   SmallVector<int, 8> Mask;
5041   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5042     Mask.push_back(i);
5043     Mask.push_back(i + NumElems);
5044   }
5045   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5046 }
5047
5048 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5049 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5050                           SDValue V2) {
5051   unsigned NumElems = VT.getVectorNumElements();
5052   SmallVector<int, 8> Mask;
5053   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5054     Mask.push_back(i + Half);
5055     Mask.push_back(i + NumElems + Half);
5056   }
5057   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5058 }
5059
5060 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5061 // a generic shuffle instruction because the target has no such instructions.
5062 // Generate shuffles which repeat i16 and i8 several times until they can be
5063 // represented by v4f32 and then be manipulated by target suported shuffles.
5064 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5065   MVT VT = V.getSimpleValueType();
5066   int NumElems = VT.getVectorNumElements();
5067   SDLoc dl(V);
5068
5069   while (NumElems > 4) {
5070     if (EltNo < NumElems/2) {
5071       V = getUnpackl(DAG, dl, VT, V, V);
5072     } else {
5073       V = getUnpackh(DAG, dl, VT, V, V);
5074       EltNo -= NumElems/2;
5075     }
5076     NumElems >>= 1;
5077   }
5078   return V;
5079 }
5080
5081 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5082 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5083   MVT VT = V.getSimpleValueType();
5084   SDLoc dl(V);
5085
5086   if (VT.is128BitVector()) {
5087     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5088     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5089     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5090                              &SplatMask[0]);
5091   } else if (VT.is256BitVector()) {
5092     // To use VPERMILPS to splat scalars, the second half of indicies must
5093     // refer to the higher part, which is a duplication of the lower one,
5094     // because VPERMILPS can only handle in-lane permutations.
5095     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5096                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5097
5098     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5099     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5100                              &SplatMask[0]);
5101   } else
5102     llvm_unreachable("Vector size not supported");
5103
5104   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5105 }
5106
5107 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5108 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5109   MVT SrcVT = SV->getSimpleValueType(0);
5110   SDValue V1 = SV->getOperand(0);
5111   SDLoc dl(SV);
5112
5113   int EltNo = SV->getSplatIndex();
5114   int NumElems = SrcVT.getVectorNumElements();
5115   bool Is256BitVec = SrcVT.is256BitVector();
5116
5117   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5118          "Unknown how to promote splat for type");
5119
5120   // Extract the 128-bit part containing the splat element and update
5121   // the splat element index when it refers to the higher register.
5122   if (Is256BitVec) {
5123     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5124     if (EltNo >= NumElems/2)
5125       EltNo -= NumElems/2;
5126   }
5127
5128   // All i16 and i8 vector types can't be used directly by a generic shuffle
5129   // instruction because the target has no such instruction. Generate shuffles
5130   // which repeat i16 and i8 several times until they fit in i32, and then can
5131   // be manipulated by target suported shuffles.
5132   MVT EltVT = SrcVT.getVectorElementType();
5133   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5134     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5135
5136   // Recreate the 256-bit vector and place the same 128-bit vector
5137   // into the low and high part. This is necessary because we want
5138   // to use VPERM* to shuffle the vectors
5139   if (Is256BitVec) {
5140     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5141   }
5142
5143   return getLegalSplat(DAG, V1, EltNo);
5144 }
5145
5146 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5147 /// vector of zero or undef vector.  This produces a shuffle where the low
5148 /// element of V2 is swizzled into the zero/undef vector, landing at element
5149 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5150 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5151                                            bool IsZero,
5152                                            const X86Subtarget *Subtarget,
5153                                            SelectionDAG &DAG) {
5154   MVT VT = V2.getSimpleValueType();
5155   SDValue V1 = IsZero
5156     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5157   unsigned NumElems = VT.getVectorNumElements();
5158   SmallVector<int, 16> MaskVec;
5159   for (unsigned i = 0; i != NumElems; ++i)
5160     // If this is the insertion idx, put the low elt of V2 here.
5161     MaskVec.push_back(i == Idx ? NumElems : i);
5162   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5163 }
5164
5165 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5166 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5167 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5168 /// shuffles which use a single input multiple times, and in those cases it will
5169 /// adjust the mask to only have indices within that single input.
5170 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5171                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5172   unsigned NumElems = VT.getVectorNumElements();
5173   SDValue ImmN;
5174
5175   IsUnary = false;
5176   bool IsFakeUnary = false;
5177   switch(N->getOpcode()) {
5178   case X86ISD::SHUFP:
5179     ImmN = N->getOperand(N->getNumOperands()-1);
5180     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5181     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5182     break;
5183   case X86ISD::UNPCKH:
5184     DecodeUNPCKHMask(VT, Mask);
5185     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5186     break;
5187   case X86ISD::UNPCKL:
5188     DecodeUNPCKLMask(VT, Mask);
5189     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5190     break;
5191   case X86ISD::MOVHLPS:
5192     DecodeMOVHLPSMask(NumElems, Mask);
5193     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5194     break;
5195   case X86ISD::MOVLHPS:
5196     DecodeMOVLHPSMask(NumElems, Mask);
5197     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5198     break;
5199   case X86ISD::PALIGNR:
5200     ImmN = N->getOperand(N->getNumOperands()-1);
5201     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5202     break;
5203   case X86ISD::PSHUFD:
5204   case X86ISD::VPERMILP:
5205     ImmN = N->getOperand(N->getNumOperands()-1);
5206     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5207     IsUnary = true;
5208     break;
5209   case X86ISD::PSHUFHW:
5210     ImmN = N->getOperand(N->getNumOperands()-1);
5211     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5212     IsUnary = true;
5213     break;
5214   case X86ISD::PSHUFLW:
5215     ImmN = N->getOperand(N->getNumOperands()-1);
5216     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5217     IsUnary = true;
5218     break;
5219   case X86ISD::PSHUFB: {
5220     IsUnary = true;
5221     SDValue MaskNode = N->getOperand(1);
5222     while (MaskNode->getOpcode() == ISD::BITCAST)
5223       MaskNode = MaskNode->getOperand(0);
5224
5225     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5226       // If we have a build-vector, then things are easy.
5227       EVT VT = MaskNode.getValueType();
5228       assert(VT.isVector() &&
5229              "Can't produce a non-vector with a build_vector!");
5230       if (!VT.isInteger())
5231         return false;
5232
5233       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5234
5235       SmallVector<uint64_t, 32> RawMask;
5236       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5237         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5238         if (!CN)
5239           return false;
5240         APInt MaskElement = CN->getAPIntValue();
5241
5242         // We now have to decode the element which could be any integer size and
5243         // extract each byte of it.
5244         for (int j = 0; j < NumBytesPerElement; ++j) {
5245           // Note that this is x86 and so always little endian: the low byte is
5246           // the first byte of the mask.
5247           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5248           MaskElement = MaskElement.lshr(8);
5249         }
5250       }
5251       DecodePSHUFBMask(RawMask, Mask);
5252       break;
5253     }
5254
5255     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5256     if (!MaskLoad)
5257       return false;
5258
5259     SDValue Ptr = MaskLoad->getBasePtr();
5260     if (Ptr->getOpcode() == X86ISD::Wrapper)
5261       Ptr = Ptr->getOperand(0);
5262
5263     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5264     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5265       return false;
5266
5267     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5268       // FIXME: Support AVX-512 here.
5269       if (!C->getType()->isVectorTy() ||
5270           (C->getNumElements() != 16 && C->getNumElements() != 32))
5271         return false;
5272
5273       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5274       DecodePSHUFBMask(C, Mask);
5275       break;
5276     }
5277
5278     return false;
5279   }
5280   case X86ISD::VPERMI:
5281     ImmN = N->getOperand(N->getNumOperands()-1);
5282     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5283     IsUnary = true;
5284     break;
5285   case X86ISD::MOVSS:
5286   case X86ISD::MOVSD: {
5287     // The index 0 always comes from the first element of the second source,
5288     // this is why MOVSS and MOVSD are used in the first place. The other
5289     // elements come from the other positions of the first source vector
5290     Mask.push_back(NumElems);
5291     for (unsigned i = 1; i != NumElems; ++i) {
5292       Mask.push_back(i);
5293     }
5294     break;
5295   }
5296   case X86ISD::VPERM2X128:
5297     ImmN = N->getOperand(N->getNumOperands()-1);
5298     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5299     if (Mask.empty()) return false;
5300     break;
5301   case X86ISD::MOVDDUP:
5302   case X86ISD::MOVLHPD:
5303   case X86ISD::MOVLPD:
5304   case X86ISD::MOVLPS:
5305   case X86ISD::MOVSHDUP:
5306   case X86ISD::MOVSLDUP:
5307     // Not yet implemented
5308     return false;
5309   default: llvm_unreachable("unknown target shuffle node");
5310   }
5311
5312   // If we have a fake unary shuffle, the shuffle mask is spread across two
5313   // inputs that are actually the same node. Re-map the mask to always point
5314   // into the first input.
5315   if (IsFakeUnary)
5316     for (int &M : Mask)
5317       if (M >= (int)Mask.size())
5318         M -= Mask.size();
5319
5320   return true;
5321 }
5322
5323 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5324 /// element of the result of the vector shuffle.
5325 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5326                                    unsigned Depth) {
5327   if (Depth == 6)
5328     return SDValue();  // Limit search depth.
5329
5330   SDValue V = SDValue(N, 0);
5331   EVT VT = V.getValueType();
5332   unsigned Opcode = V.getOpcode();
5333
5334   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5335   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5336     int Elt = SV->getMaskElt(Index);
5337
5338     if (Elt < 0)
5339       return DAG.getUNDEF(VT.getVectorElementType());
5340
5341     unsigned NumElems = VT.getVectorNumElements();
5342     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5343                                          : SV->getOperand(1);
5344     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5345   }
5346
5347   // Recurse into target specific vector shuffles to find scalars.
5348   if (isTargetShuffle(Opcode)) {
5349     MVT ShufVT = V.getSimpleValueType();
5350     unsigned NumElems = ShufVT.getVectorNumElements();
5351     SmallVector<int, 16> ShuffleMask;
5352     bool IsUnary;
5353
5354     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5355       return SDValue();
5356
5357     int Elt = ShuffleMask[Index];
5358     if (Elt < 0)
5359       return DAG.getUNDEF(ShufVT.getVectorElementType());
5360
5361     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5362                                          : N->getOperand(1);
5363     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5364                                Depth+1);
5365   }
5366
5367   // Actual nodes that may contain scalar elements
5368   if (Opcode == ISD::BITCAST) {
5369     V = V.getOperand(0);
5370     EVT SrcVT = V.getValueType();
5371     unsigned NumElems = VT.getVectorNumElements();
5372
5373     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5374       return SDValue();
5375   }
5376
5377   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5378     return (Index == 0) ? V.getOperand(0)
5379                         : DAG.getUNDEF(VT.getVectorElementType());
5380
5381   if (V.getOpcode() == ISD::BUILD_VECTOR)
5382     return V.getOperand(Index);
5383
5384   return SDValue();
5385 }
5386
5387 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5388 /// shuffle operation which come from a consecutively from a zero. The
5389 /// search can start in two different directions, from left or right.
5390 /// We count undefs as zeros until PreferredNum is reached.
5391 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5392                                          unsigned NumElems, bool ZerosFromLeft,
5393                                          SelectionDAG &DAG,
5394                                          unsigned PreferredNum = -1U) {
5395   unsigned NumZeros = 0;
5396   for (unsigned i = 0; i != NumElems; ++i) {
5397     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5398     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5399     if (!Elt.getNode())
5400       break;
5401
5402     if (X86::isZeroNode(Elt))
5403       ++NumZeros;
5404     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5405       NumZeros = std::min(NumZeros + 1, PreferredNum);
5406     else
5407       break;
5408   }
5409
5410   return NumZeros;
5411 }
5412
5413 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5414 /// correspond consecutively to elements from one of the vector operands,
5415 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5416 static
5417 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5418                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5419                               unsigned NumElems, unsigned &OpNum) {
5420   bool SeenV1 = false;
5421   bool SeenV2 = false;
5422
5423   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5424     int Idx = SVOp->getMaskElt(i);
5425     // Ignore undef indicies
5426     if (Idx < 0)
5427       continue;
5428
5429     if (Idx < (int)NumElems)
5430       SeenV1 = true;
5431     else
5432       SeenV2 = true;
5433
5434     // Only accept consecutive elements from the same vector
5435     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5436       return false;
5437   }
5438
5439   OpNum = SeenV1 ? 0 : 1;
5440   return true;
5441 }
5442
5443 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5444 /// logical left shift of a vector.
5445 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5446                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5447   unsigned NumElems =
5448     SVOp->getSimpleValueType(0).getVectorNumElements();
5449   unsigned NumZeros = getNumOfConsecutiveZeros(
5450       SVOp, NumElems, false /* check zeros from right */, DAG,
5451       SVOp->getMaskElt(0));
5452   unsigned OpSrc;
5453
5454   if (!NumZeros)
5455     return false;
5456
5457   // Considering the elements in the mask that are not consecutive zeros,
5458   // check if they consecutively come from only one of the source vectors.
5459   //
5460   //               V1 = {X, A, B, C}     0
5461   //                         \  \  \    /
5462   //   vector_shuffle V1, V2 <1, 2, 3, X>
5463   //
5464   if (!isShuffleMaskConsecutive(SVOp,
5465             0,                   // Mask Start Index
5466             NumElems-NumZeros,   // Mask End Index(exclusive)
5467             NumZeros,            // Where to start looking in the src vector
5468             NumElems,            // Number of elements in vector
5469             OpSrc))              // Which source operand ?
5470     return false;
5471
5472   isLeft = false;
5473   ShAmt = NumZeros;
5474   ShVal = SVOp->getOperand(OpSrc);
5475   return true;
5476 }
5477
5478 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5479 /// logical left shift of a vector.
5480 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5481                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5482   unsigned NumElems =
5483     SVOp->getSimpleValueType(0).getVectorNumElements();
5484   unsigned NumZeros = getNumOfConsecutiveZeros(
5485       SVOp, NumElems, true /* check zeros from left */, DAG,
5486       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5487   unsigned OpSrc;
5488
5489   if (!NumZeros)
5490     return false;
5491
5492   // Considering the elements in the mask that are not consecutive zeros,
5493   // check if they consecutively come from only one of the source vectors.
5494   //
5495   //                           0    { A, B, X, X } = V2
5496   //                          / \    /  /
5497   //   vector_shuffle V1, V2 <X, X, 4, 5>
5498   //
5499   if (!isShuffleMaskConsecutive(SVOp,
5500             NumZeros,     // Mask Start Index
5501             NumElems,     // Mask End Index(exclusive)
5502             0,            // Where to start looking in the src vector
5503             NumElems,     // Number of elements in vector
5504             OpSrc))       // Which source operand ?
5505     return false;
5506
5507   isLeft = true;
5508   ShAmt = NumZeros;
5509   ShVal = SVOp->getOperand(OpSrc);
5510   return true;
5511 }
5512
5513 /// isVectorShift - Returns true if the shuffle can be implemented as a
5514 /// logical left or right shift of a vector.
5515 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5516                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5517   // Although the logic below support any bitwidth size, there are no
5518   // shift instructions which handle more than 128-bit vectors.
5519   if (!SVOp->getSimpleValueType(0).is128BitVector())
5520     return false;
5521
5522   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5523       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5524     return true;
5525
5526   return false;
5527 }
5528
5529 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5530 ///
5531 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5532                                        unsigned NumNonZero, unsigned NumZero,
5533                                        SelectionDAG &DAG,
5534                                        const X86Subtarget* Subtarget,
5535                                        const TargetLowering &TLI) {
5536   if (NumNonZero > 8)
5537     return SDValue();
5538
5539   SDLoc dl(Op);
5540   SDValue V;
5541   bool First = true;
5542   for (unsigned i = 0; i < 16; ++i) {
5543     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5544     if (ThisIsNonZero && First) {
5545       if (NumZero)
5546         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5547       else
5548         V = DAG.getUNDEF(MVT::v8i16);
5549       First = false;
5550     }
5551
5552     if ((i & 1) != 0) {
5553       SDValue ThisElt, LastElt;
5554       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5555       if (LastIsNonZero) {
5556         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5557                               MVT::i16, Op.getOperand(i-1));
5558       }
5559       if (ThisIsNonZero) {
5560         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5561         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5562                               ThisElt, DAG.getConstant(8, MVT::i8));
5563         if (LastIsNonZero)
5564           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5565       } else
5566         ThisElt = LastElt;
5567
5568       if (ThisElt.getNode())
5569         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5570                         DAG.getIntPtrConstant(i/2));
5571     }
5572   }
5573
5574   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5575 }
5576
5577 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5578 ///
5579 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5580                                      unsigned NumNonZero, unsigned NumZero,
5581                                      SelectionDAG &DAG,
5582                                      const X86Subtarget* Subtarget,
5583                                      const TargetLowering &TLI) {
5584   if (NumNonZero > 4)
5585     return SDValue();
5586
5587   SDLoc dl(Op);
5588   SDValue V;
5589   bool First = true;
5590   for (unsigned i = 0; i < 8; ++i) {
5591     bool isNonZero = (NonZeros & (1 << i)) != 0;
5592     if (isNonZero) {
5593       if (First) {
5594         if (NumZero)
5595           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5596         else
5597           V = DAG.getUNDEF(MVT::v8i16);
5598         First = false;
5599       }
5600       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5601                       MVT::v8i16, V, Op.getOperand(i),
5602                       DAG.getIntPtrConstant(i));
5603     }
5604   }
5605
5606   return V;
5607 }
5608
5609 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5610 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5611                                      unsigned NonZeros, unsigned NumNonZero,
5612                                      unsigned NumZero, SelectionDAG &DAG,
5613                                      const X86Subtarget *Subtarget,
5614                                      const TargetLowering &TLI) {
5615   // We know there's at least one non-zero element
5616   unsigned FirstNonZeroIdx = 0;
5617   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5618   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5619          X86::isZeroNode(FirstNonZero)) {
5620     ++FirstNonZeroIdx;
5621     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5622   }
5623
5624   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5625       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5626     return SDValue();
5627
5628   SDValue V = FirstNonZero.getOperand(0);
5629   MVT VVT = V.getSimpleValueType();
5630   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5631     return SDValue();
5632
5633   unsigned FirstNonZeroDst =
5634       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5635   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5636   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5637   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5638
5639   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5640     SDValue Elem = Op.getOperand(Idx);
5641     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5642       continue;
5643
5644     // TODO: What else can be here? Deal with it.
5645     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5646       return SDValue();
5647
5648     // TODO: Some optimizations are still possible here
5649     // ex: Getting one element from a vector, and the rest from another.
5650     if (Elem.getOperand(0) != V)
5651       return SDValue();
5652
5653     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5654     if (Dst == Idx)
5655       ++CorrectIdx;
5656     else if (IncorrectIdx == -1U) {
5657       IncorrectIdx = Idx;
5658       IncorrectDst = Dst;
5659     } else
5660       // There was already one element with an incorrect index.
5661       // We can't optimize this case to an insertps.
5662       return SDValue();
5663   }
5664
5665   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5666     SDLoc dl(Op);
5667     EVT VT = Op.getSimpleValueType();
5668     unsigned ElementMoveMask = 0;
5669     if (IncorrectIdx == -1U)
5670       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5671     else
5672       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5673
5674     SDValue InsertpsMask =
5675         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5676     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5677   }
5678
5679   return SDValue();
5680 }
5681
5682 /// getVShift - Return a vector logical shift node.
5683 ///
5684 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5685                          unsigned NumBits, SelectionDAG &DAG,
5686                          const TargetLowering &TLI, SDLoc dl) {
5687   assert(VT.is128BitVector() && "Unknown type for VShift");
5688   EVT ShVT = MVT::v2i64;
5689   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5690   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5691   return DAG.getNode(ISD::BITCAST, dl, VT,
5692                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5693                              DAG.getConstant(NumBits,
5694                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5695 }
5696
5697 static SDValue
5698 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5699
5700   // Check if the scalar load can be widened into a vector load. And if
5701   // the address is "base + cst" see if the cst can be "absorbed" into
5702   // the shuffle mask.
5703   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5704     SDValue Ptr = LD->getBasePtr();
5705     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5706       return SDValue();
5707     EVT PVT = LD->getValueType(0);
5708     if (PVT != MVT::i32 && PVT != MVT::f32)
5709       return SDValue();
5710
5711     int FI = -1;
5712     int64_t Offset = 0;
5713     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5714       FI = FINode->getIndex();
5715       Offset = 0;
5716     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5717                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5718       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5719       Offset = Ptr.getConstantOperandVal(1);
5720       Ptr = Ptr.getOperand(0);
5721     } else {
5722       return SDValue();
5723     }
5724
5725     // FIXME: 256-bit vector instructions don't require a strict alignment,
5726     // improve this code to support it better.
5727     unsigned RequiredAlign = VT.getSizeInBits()/8;
5728     SDValue Chain = LD->getChain();
5729     // Make sure the stack object alignment is at least 16 or 32.
5730     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5731     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5732       if (MFI->isFixedObjectIndex(FI)) {
5733         // Can't change the alignment. FIXME: It's possible to compute
5734         // the exact stack offset and reference FI + adjust offset instead.
5735         // If someone *really* cares about this. That's the way to implement it.
5736         return SDValue();
5737       } else {
5738         MFI->setObjectAlignment(FI, RequiredAlign);
5739       }
5740     }
5741
5742     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5743     // Ptr + (Offset & ~15).
5744     if (Offset < 0)
5745       return SDValue();
5746     if ((Offset % RequiredAlign) & 3)
5747       return SDValue();
5748     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5749     if (StartOffset)
5750       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5751                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5752
5753     int EltNo = (Offset - StartOffset) >> 2;
5754     unsigned NumElems = VT.getVectorNumElements();
5755
5756     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5757     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5758                              LD->getPointerInfo().getWithOffset(StartOffset),
5759                              false, false, false, 0);
5760
5761     SmallVector<int, 8> Mask;
5762     for (unsigned i = 0; i != NumElems; ++i)
5763       Mask.push_back(EltNo);
5764
5765     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5766   }
5767
5768   return SDValue();
5769 }
5770
5771 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5772 /// vector of type 'VT', see if the elements can be replaced by a single large
5773 /// load which has the same value as a build_vector whose operands are 'elts'.
5774 ///
5775 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5776 ///
5777 /// FIXME: we'd also like to handle the case where the last elements are zero
5778 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5779 /// There's even a handy isZeroNode for that purpose.
5780 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5781                                         SDLoc &DL, SelectionDAG &DAG,
5782                                         bool isAfterLegalize) {
5783   EVT EltVT = VT.getVectorElementType();
5784   unsigned NumElems = Elts.size();
5785
5786   LoadSDNode *LDBase = nullptr;
5787   unsigned LastLoadedElt = -1U;
5788
5789   // For each element in the initializer, see if we've found a load or an undef.
5790   // If we don't find an initial load element, or later load elements are
5791   // non-consecutive, bail out.
5792   for (unsigned i = 0; i < NumElems; ++i) {
5793     SDValue Elt = Elts[i];
5794
5795     if (!Elt.getNode() ||
5796         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5797       return SDValue();
5798     if (!LDBase) {
5799       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5800         return SDValue();
5801       LDBase = cast<LoadSDNode>(Elt.getNode());
5802       LastLoadedElt = i;
5803       continue;
5804     }
5805     if (Elt.getOpcode() == ISD::UNDEF)
5806       continue;
5807
5808     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5809     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5810       return SDValue();
5811     LastLoadedElt = i;
5812   }
5813
5814   // If we have found an entire vector of loads and undefs, then return a large
5815   // load of the entire vector width starting at the base pointer.  If we found
5816   // consecutive loads for the low half, generate a vzext_load node.
5817   if (LastLoadedElt == NumElems - 1) {
5818
5819     if (isAfterLegalize &&
5820         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5821       return SDValue();
5822
5823     SDValue NewLd = SDValue();
5824
5825     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5826       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5827                           LDBase->getPointerInfo(),
5828                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5829                           LDBase->isInvariant(), 0);
5830     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5831                         LDBase->getPointerInfo(),
5832                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5833                         LDBase->isInvariant(), LDBase->getAlignment());
5834
5835     if (LDBase->hasAnyUseOfValue(1)) {
5836       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5837                                      SDValue(LDBase, 1),
5838                                      SDValue(NewLd.getNode(), 1));
5839       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5840       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5841                              SDValue(NewLd.getNode(), 1));
5842     }
5843
5844     return NewLd;
5845   }
5846   if (NumElems == 4 && LastLoadedElt == 1 &&
5847       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5848     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5849     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5850     SDValue ResNode =
5851         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5852                                 LDBase->getPointerInfo(),
5853                                 LDBase->getAlignment(),
5854                                 false/*isVolatile*/, true/*ReadMem*/,
5855                                 false/*WriteMem*/);
5856
5857     // Make sure the newly-created LOAD is in the same position as LDBase in
5858     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5859     // update uses of LDBase's output chain to use the TokenFactor.
5860     if (LDBase->hasAnyUseOfValue(1)) {
5861       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5862                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5863       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5864       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5865                              SDValue(ResNode.getNode(), 1));
5866     }
5867
5868     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5869   }
5870   return SDValue();
5871 }
5872
5873 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5874 /// to generate a splat value for the following cases:
5875 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5876 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5877 /// a scalar load, or a constant.
5878 /// The VBROADCAST node is returned when a pattern is found,
5879 /// or SDValue() otherwise.
5880 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5881                                     SelectionDAG &DAG) {
5882   if (!Subtarget->hasFp256())
5883     return SDValue();
5884
5885   MVT VT = Op.getSimpleValueType();
5886   SDLoc dl(Op);
5887
5888   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5889          "Unsupported vector type for broadcast.");
5890
5891   SDValue Ld;
5892   bool ConstSplatVal;
5893
5894   switch (Op.getOpcode()) {
5895     default:
5896       // Unknown pattern found.
5897       return SDValue();
5898
5899     case ISD::BUILD_VECTOR: {
5900       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5901       BitVector UndefElements;
5902       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5903
5904       // We need a splat of a single value to use broadcast, and it doesn't
5905       // make any sense if the value is only in one element of the vector.
5906       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5907         return SDValue();
5908
5909       Ld = Splat;
5910       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5911                        Ld.getOpcode() == ISD::ConstantFP);
5912
5913       // Make sure that all of the users of a non-constant load are from the
5914       // BUILD_VECTOR node.
5915       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5916         return SDValue();
5917       break;
5918     }
5919
5920     case ISD::VECTOR_SHUFFLE: {
5921       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5922
5923       // Shuffles must have a splat mask where the first element is
5924       // broadcasted.
5925       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5926         return SDValue();
5927
5928       SDValue Sc = Op.getOperand(0);
5929       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5930           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5931
5932         if (!Subtarget->hasInt256())
5933           return SDValue();
5934
5935         // Use the register form of the broadcast instruction available on AVX2.
5936         if (VT.getSizeInBits() >= 256)
5937           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5938         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5939       }
5940
5941       Ld = Sc.getOperand(0);
5942       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5943                        Ld.getOpcode() == ISD::ConstantFP);
5944
5945       // The scalar_to_vector node and the suspected
5946       // load node must have exactly one user.
5947       // Constants may have multiple users.
5948
5949       // AVX-512 has register version of the broadcast
5950       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5951         Ld.getValueType().getSizeInBits() >= 32;
5952       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5953           !hasRegVer))
5954         return SDValue();
5955       break;
5956     }
5957   }
5958
5959   bool IsGE256 = (VT.getSizeInBits() >= 256);
5960
5961   // Handle the broadcasting a single constant scalar from the constant pool
5962   // into a vector. On Sandybridge it is still better to load a constant vector
5963   // from the constant pool and not to broadcast it from a scalar.
5964   if (ConstSplatVal && Subtarget->hasInt256()) {
5965     EVT CVT = Ld.getValueType();
5966     assert(!CVT.isVector() && "Must not broadcast a vector type");
5967     unsigned ScalarSize = CVT.getSizeInBits();
5968
5969     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5970       const Constant *C = nullptr;
5971       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5972         C = CI->getConstantIntValue();
5973       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5974         C = CF->getConstantFPValue();
5975
5976       assert(C && "Invalid constant type");
5977
5978       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5979       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5980       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5981       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5982                        MachinePointerInfo::getConstantPool(),
5983                        false, false, false, Alignment);
5984
5985       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5986     }
5987   }
5988
5989   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5990   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5991
5992   // Handle AVX2 in-register broadcasts.
5993   if (!IsLoad && Subtarget->hasInt256() &&
5994       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5995     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5996
5997   // The scalar source must be a normal load.
5998   if (!IsLoad)
5999     return SDValue();
6000
6001   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6002     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6003
6004   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6005   // double since there is no vbroadcastsd xmm
6006   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6007     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6008       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6009   }
6010
6011   // Unsupported broadcast.
6012   return SDValue();
6013 }
6014
6015 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6016 /// underlying vector and index.
6017 ///
6018 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6019 /// index.
6020 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6021                                          SDValue ExtIdx) {
6022   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6023   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6024     return Idx;
6025
6026   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6027   // lowered this:
6028   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6029   // to:
6030   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6031   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6032   //                           undef)
6033   //                       Constant<0>)
6034   // In this case the vector is the extract_subvector expression and the index
6035   // is 2, as specified by the shuffle.
6036   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6037   SDValue ShuffleVec = SVOp->getOperand(0);
6038   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6039   assert(ShuffleVecVT.getVectorElementType() ==
6040          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6041
6042   int ShuffleIdx = SVOp->getMaskElt(Idx);
6043   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6044     ExtractedFromVec = ShuffleVec;
6045     return ShuffleIdx;
6046   }
6047   return Idx;
6048 }
6049
6050 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6051   MVT VT = Op.getSimpleValueType();
6052
6053   // Skip if insert_vec_elt is not supported.
6054   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6055   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6056     return SDValue();
6057
6058   SDLoc DL(Op);
6059   unsigned NumElems = Op.getNumOperands();
6060
6061   SDValue VecIn1;
6062   SDValue VecIn2;
6063   SmallVector<unsigned, 4> InsertIndices;
6064   SmallVector<int, 8> Mask(NumElems, -1);
6065
6066   for (unsigned i = 0; i != NumElems; ++i) {
6067     unsigned Opc = Op.getOperand(i).getOpcode();
6068
6069     if (Opc == ISD::UNDEF)
6070       continue;
6071
6072     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6073       // Quit if more than 1 elements need inserting.
6074       if (InsertIndices.size() > 1)
6075         return SDValue();
6076
6077       InsertIndices.push_back(i);
6078       continue;
6079     }
6080
6081     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6082     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6083     // Quit if non-constant index.
6084     if (!isa<ConstantSDNode>(ExtIdx))
6085       return SDValue();
6086     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6087
6088     // Quit if extracted from vector of different type.
6089     if (ExtractedFromVec.getValueType() != VT)
6090       return SDValue();
6091
6092     if (!VecIn1.getNode())
6093       VecIn1 = ExtractedFromVec;
6094     else if (VecIn1 != ExtractedFromVec) {
6095       if (!VecIn2.getNode())
6096         VecIn2 = ExtractedFromVec;
6097       else if (VecIn2 != ExtractedFromVec)
6098         // Quit if more than 2 vectors to shuffle
6099         return SDValue();
6100     }
6101
6102     if (ExtractedFromVec == VecIn1)
6103       Mask[i] = Idx;
6104     else if (ExtractedFromVec == VecIn2)
6105       Mask[i] = Idx + NumElems;
6106   }
6107
6108   if (!VecIn1.getNode())
6109     return SDValue();
6110
6111   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6112   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6113   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6114     unsigned Idx = InsertIndices[i];
6115     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6116                      DAG.getIntPtrConstant(Idx));
6117   }
6118
6119   return NV;
6120 }
6121
6122 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6123 SDValue
6124 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6125
6126   MVT VT = Op.getSimpleValueType();
6127   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6128          "Unexpected type in LowerBUILD_VECTORvXi1!");
6129
6130   SDLoc dl(Op);
6131   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6132     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6133     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6134     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6135   }
6136
6137   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6138     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6139     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6140     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6141   }
6142
6143   bool AllContants = true;
6144   uint64_t Immediate = 0;
6145   int NonConstIdx = -1;
6146   bool IsSplat = true;
6147   unsigned NumNonConsts = 0;
6148   unsigned NumConsts = 0;
6149   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6150     SDValue In = Op.getOperand(idx);
6151     if (In.getOpcode() == ISD::UNDEF)
6152       continue;
6153     if (!isa<ConstantSDNode>(In)) {
6154       AllContants = false;
6155       NonConstIdx = idx;
6156       NumNonConsts++;
6157     }
6158     else {
6159       NumConsts++;
6160       if (cast<ConstantSDNode>(In)->getZExtValue())
6161       Immediate |= (1ULL << idx);
6162     }
6163     if (In != Op.getOperand(0))
6164       IsSplat = false;
6165   }
6166
6167   if (AllContants) {
6168     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6169       DAG.getConstant(Immediate, MVT::i16));
6170     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6171                        DAG.getIntPtrConstant(0));
6172   }
6173
6174   if (NumNonConsts == 1 && NonConstIdx != 0) {
6175     SDValue DstVec;
6176     if (NumConsts) {
6177       SDValue VecAsImm = DAG.getConstant(Immediate,
6178                                          MVT::getIntegerVT(VT.getSizeInBits()));
6179       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6180     }
6181     else 
6182       DstVec = DAG.getUNDEF(VT);
6183     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6184                        Op.getOperand(NonConstIdx),
6185                        DAG.getIntPtrConstant(NonConstIdx));
6186   }
6187   if (!IsSplat && (NonConstIdx != 0))
6188     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6189   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6190   SDValue Select;
6191   if (IsSplat)
6192     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6193                           DAG.getConstant(-1, SelectVT),
6194                           DAG.getConstant(0, SelectVT));
6195   else
6196     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6197                          DAG.getConstant((Immediate | 1), SelectVT),
6198                          DAG.getConstant(Immediate, SelectVT));
6199   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6200 }
6201
6202 /// \brief Return true if \p N implements a horizontal binop and return the
6203 /// operands for the horizontal binop into V0 and V1.
6204 /// 
6205 /// This is a helper function of PerformBUILD_VECTORCombine.
6206 /// This function checks that the build_vector \p N in input implements a
6207 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6208 /// operation to match.
6209 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6210 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6211 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6212 /// arithmetic sub.
6213 ///
6214 /// This function only analyzes elements of \p N whose indices are
6215 /// in range [BaseIdx, LastIdx).
6216 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6217                               SelectionDAG &DAG,
6218                               unsigned BaseIdx, unsigned LastIdx,
6219                               SDValue &V0, SDValue &V1) {
6220   EVT VT = N->getValueType(0);
6221
6222   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6223   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6224          "Invalid Vector in input!");
6225   
6226   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6227   bool CanFold = true;
6228   unsigned ExpectedVExtractIdx = BaseIdx;
6229   unsigned NumElts = LastIdx - BaseIdx;
6230   V0 = DAG.getUNDEF(VT);
6231   V1 = DAG.getUNDEF(VT);
6232
6233   // Check if N implements a horizontal binop.
6234   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6235     SDValue Op = N->getOperand(i + BaseIdx);
6236
6237     // Skip UNDEFs.
6238     if (Op->getOpcode() == ISD::UNDEF) {
6239       // Update the expected vector extract index.
6240       if (i * 2 == NumElts)
6241         ExpectedVExtractIdx = BaseIdx;
6242       ExpectedVExtractIdx += 2;
6243       continue;
6244     }
6245
6246     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6247
6248     if (!CanFold)
6249       break;
6250
6251     SDValue Op0 = Op.getOperand(0);
6252     SDValue Op1 = Op.getOperand(1);
6253
6254     // Try to match the following pattern:
6255     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6256     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6257         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6258         Op0.getOperand(0) == Op1.getOperand(0) &&
6259         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6260         isa<ConstantSDNode>(Op1.getOperand(1)));
6261     if (!CanFold)
6262       break;
6263
6264     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6265     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6266
6267     if (i * 2 < NumElts) {
6268       if (V0.getOpcode() == ISD::UNDEF)
6269         V0 = Op0.getOperand(0);
6270     } else {
6271       if (V1.getOpcode() == ISD::UNDEF)
6272         V1 = Op0.getOperand(0);
6273       if (i * 2 == NumElts)
6274         ExpectedVExtractIdx = BaseIdx;
6275     }
6276
6277     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6278     if (I0 == ExpectedVExtractIdx)
6279       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6280     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6281       // Try to match the following dag sequence:
6282       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6283       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6284     } else
6285       CanFold = false;
6286
6287     ExpectedVExtractIdx += 2;
6288   }
6289
6290   return CanFold;
6291 }
6292
6293 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6294 /// a concat_vector. 
6295 ///
6296 /// This is a helper function of PerformBUILD_VECTORCombine.
6297 /// This function expects two 256-bit vectors called V0 and V1.
6298 /// At first, each vector is split into two separate 128-bit vectors.
6299 /// Then, the resulting 128-bit vectors are used to implement two
6300 /// horizontal binary operations. 
6301 ///
6302 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6303 ///
6304 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6305 /// the two new horizontal binop.
6306 /// When Mode is set, the first horizontal binop dag node would take as input
6307 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6308 /// horizontal binop dag node would take as input the lower 128-bit of V1
6309 /// and the upper 128-bit of V1.
6310 ///   Example:
6311 ///     HADD V0_LO, V0_HI
6312 ///     HADD V1_LO, V1_HI
6313 ///
6314 /// Otherwise, the first horizontal binop dag node takes as input the lower
6315 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6316 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6317 ///   Example:
6318 ///     HADD V0_LO, V1_LO
6319 ///     HADD V0_HI, V1_HI
6320 ///
6321 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6322 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6323 /// the upper 128-bits of the result.
6324 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6325                                      SDLoc DL, SelectionDAG &DAG,
6326                                      unsigned X86Opcode, bool Mode,
6327                                      bool isUndefLO, bool isUndefHI) {
6328   EVT VT = V0.getValueType();
6329   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6330          "Invalid nodes in input!");
6331
6332   unsigned NumElts = VT.getVectorNumElements();
6333   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6334   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6335   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6336   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6337   EVT NewVT = V0_LO.getValueType();
6338
6339   SDValue LO = DAG.getUNDEF(NewVT);
6340   SDValue HI = DAG.getUNDEF(NewVT);
6341
6342   if (Mode) {
6343     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6344     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6345       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6346     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6347       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6348   } else {
6349     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6350     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6351                        V1_LO->getOpcode() != ISD::UNDEF))
6352       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6353
6354     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6355                        V1_HI->getOpcode() != ISD::UNDEF))
6356       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6357   }
6358
6359   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6360 }
6361
6362 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6363 /// sequence of 'vadd + vsub + blendi'.
6364 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6365                            const X86Subtarget *Subtarget) {
6366   SDLoc DL(BV);
6367   EVT VT = BV->getValueType(0);
6368   unsigned NumElts = VT.getVectorNumElements();
6369   SDValue InVec0 = DAG.getUNDEF(VT);
6370   SDValue InVec1 = DAG.getUNDEF(VT);
6371
6372   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6373           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6374
6375   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6376   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6377   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6378     return SDValue();
6379
6380   // Odd-numbered elements in the input build vector are obtained from
6381   // adding two integer/float elements.
6382   // Even-numbered elements in the input build vector are obtained from
6383   // subtracting two integer/float elements.
6384   unsigned ExpectedOpcode = ISD::FSUB;
6385   unsigned NextExpectedOpcode = ISD::FADD;
6386   bool AddFound = false;
6387   bool SubFound = false;
6388
6389   for (unsigned i = 0, e = NumElts; i != e; i++) {
6390     SDValue Op = BV->getOperand(i);
6391       
6392     // Skip 'undef' values.
6393     unsigned Opcode = Op.getOpcode();
6394     if (Opcode == ISD::UNDEF) {
6395       std::swap(ExpectedOpcode, NextExpectedOpcode);
6396       continue;
6397     }
6398       
6399     // Early exit if we found an unexpected opcode.
6400     if (Opcode != ExpectedOpcode)
6401       return SDValue();
6402
6403     SDValue Op0 = Op.getOperand(0);
6404     SDValue Op1 = Op.getOperand(1);
6405
6406     // Try to match the following pattern:
6407     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6408     // Early exit if we cannot match that sequence.
6409     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6410         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6411         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6412         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6413         Op0.getOperand(1) != Op1.getOperand(1))
6414       return SDValue();
6415
6416     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6417     if (I0 != i)
6418       return SDValue();
6419
6420     // We found a valid add/sub node. Update the information accordingly.
6421     if (i & 1)
6422       AddFound = true;
6423     else
6424       SubFound = true;
6425
6426     // Update InVec0 and InVec1.
6427     if (InVec0.getOpcode() == ISD::UNDEF)
6428       InVec0 = Op0.getOperand(0);
6429     if (InVec1.getOpcode() == ISD::UNDEF)
6430       InVec1 = Op1.getOperand(0);
6431
6432     // Make sure that operands in input to each add/sub node always
6433     // come from a same pair of vectors.
6434     if (InVec0 != Op0.getOperand(0)) {
6435       if (ExpectedOpcode == ISD::FSUB)
6436         return SDValue();
6437
6438       // FADD is commutable. Try to commute the operands
6439       // and then test again.
6440       std::swap(Op0, Op1);
6441       if (InVec0 != Op0.getOperand(0))
6442         return SDValue();
6443     }
6444
6445     if (InVec1 != Op1.getOperand(0))
6446       return SDValue();
6447
6448     // Update the pair of expected opcodes.
6449     std::swap(ExpectedOpcode, NextExpectedOpcode);
6450   }
6451
6452   // Don't try to fold this build_vector into a VSELECT if it has
6453   // too many UNDEF operands.
6454   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6455       InVec1.getOpcode() != ISD::UNDEF) {
6456     // Emit a sequence of vector add and sub followed by a VSELECT.
6457     // The new VSELECT will be lowered into a BLENDI.
6458     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6459     // and emit a single ADDSUB instruction.
6460     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6461     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6462
6463     // Construct the VSELECT mask.
6464     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6465     EVT SVT = MaskVT.getVectorElementType();
6466     unsigned SVTBits = SVT.getSizeInBits();
6467     SmallVector<SDValue, 8> Ops;
6468
6469     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6470       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6471                             APInt::getAllOnesValue(SVTBits);
6472       SDValue Constant = DAG.getConstant(Value, SVT);
6473       Ops.push_back(Constant);
6474     }
6475
6476     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6477     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6478   }
6479   
6480   return SDValue();
6481 }
6482
6483 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6484                                           const X86Subtarget *Subtarget) {
6485   SDLoc DL(N);
6486   EVT VT = N->getValueType(0);
6487   unsigned NumElts = VT.getVectorNumElements();
6488   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6489   SDValue InVec0, InVec1;
6490
6491   // Try to match an ADDSUB.
6492   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6493       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6494     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6495     if (Value.getNode())
6496       return Value;
6497   }
6498
6499   // Try to match horizontal ADD/SUB.
6500   unsigned NumUndefsLO = 0;
6501   unsigned NumUndefsHI = 0;
6502   unsigned Half = NumElts/2;
6503
6504   // Count the number of UNDEF operands in the build_vector in input.
6505   for (unsigned i = 0, e = Half; i != e; ++i)
6506     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6507       NumUndefsLO++;
6508
6509   for (unsigned i = Half, e = NumElts; i != e; ++i)
6510     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6511       NumUndefsHI++;
6512
6513   // Early exit if this is either a build_vector of all UNDEFs or all the
6514   // operands but one are UNDEF.
6515   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6516     return SDValue();
6517
6518   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6519     // Try to match an SSE3 float HADD/HSUB.
6520     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6521       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6522     
6523     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6524       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6525   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6526     // Try to match an SSSE3 integer HADD/HSUB.
6527     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6528       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6529     
6530     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6531       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6532   }
6533   
6534   if (!Subtarget->hasAVX())
6535     return SDValue();
6536
6537   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6538     // Try to match an AVX horizontal add/sub of packed single/double
6539     // precision floating point values from 256-bit vectors.
6540     SDValue InVec2, InVec3;
6541     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6542         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6543         ((InVec0.getOpcode() == ISD::UNDEF ||
6544           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6545         ((InVec1.getOpcode() == ISD::UNDEF ||
6546           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6547       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6548
6549     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6550         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6551         ((InVec0.getOpcode() == ISD::UNDEF ||
6552           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6553         ((InVec1.getOpcode() == ISD::UNDEF ||
6554           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6555       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6556   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6557     // Try to match an AVX2 horizontal add/sub of signed integers.
6558     SDValue InVec2, InVec3;
6559     unsigned X86Opcode;
6560     bool CanFold = true;
6561
6562     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6563         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6564         ((InVec0.getOpcode() == ISD::UNDEF ||
6565           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6566         ((InVec1.getOpcode() == ISD::UNDEF ||
6567           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6568       X86Opcode = X86ISD::HADD;
6569     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6570         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6571         ((InVec0.getOpcode() == ISD::UNDEF ||
6572           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6573         ((InVec1.getOpcode() == ISD::UNDEF ||
6574           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6575       X86Opcode = X86ISD::HSUB;
6576     else
6577       CanFold = false;
6578
6579     if (CanFold) {
6580       // Fold this build_vector into a single horizontal add/sub.
6581       // Do this only if the target has AVX2.
6582       if (Subtarget->hasAVX2())
6583         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6584  
6585       // Do not try to expand this build_vector into a pair of horizontal
6586       // add/sub if we can emit a pair of scalar add/sub.
6587       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6588         return SDValue();
6589
6590       // Convert this build_vector into a pair of horizontal binop followed by
6591       // a concat vector.
6592       bool isUndefLO = NumUndefsLO == Half;
6593       bool isUndefHI = NumUndefsHI == Half;
6594       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6595                                    isUndefLO, isUndefHI);
6596     }
6597   }
6598
6599   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6600        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6601     unsigned X86Opcode;
6602     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6603       X86Opcode = X86ISD::HADD;
6604     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6605       X86Opcode = X86ISD::HSUB;
6606     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6607       X86Opcode = X86ISD::FHADD;
6608     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6609       X86Opcode = X86ISD::FHSUB;
6610     else
6611       return SDValue();
6612
6613     // Don't try to expand this build_vector into a pair of horizontal add/sub
6614     // if we can simply emit a pair of scalar add/sub.
6615     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6616       return SDValue();
6617
6618     // Convert this build_vector into two horizontal add/sub followed by
6619     // a concat vector.
6620     bool isUndefLO = NumUndefsLO == Half;
6621     bool isUndefHI = NumUndefsHI == Half;
6622     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6623                                  isUndefLO, isUndefHI);
6624   }
6625
6626   return SDValue();
6627 }
6628
6629 SDValue
6630 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6631   SDLoc dl(Op);
6632
6633   MVT VT = Op.getSimpleValueType();
6634   MVT ExtVT = VT.getVectorElementType();
6635   unsigned NumElems = Op.getNumOperands();
6636
6637   // Generate vectors for predicate vectors.
6638   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6639     return LowerBUILD_VECTORvXi1(Op, DAG);
6640
6641   // Vectors containing all zeros can be matched by pxor and xorps later
6642   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6643     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6644     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6645     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6646       return Op;
6647
6648     return getZeroVector(VT, Subtarget, DAG, dl);
6649   }
6650
6651   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6652   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6653   // vpcmpeqd on 256-bit vectors.
6654   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6655     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6656       return Op;
6657
6658     if (!VT.is512BitVector())
6659       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6660   }
6661
6662   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6663   if (Broadcast.getNode())
6664     return Broadcast;
6665
6666   unsigned EVTBits = ExtVT.getSizeInBits();
6667
6668   unsigned NumZero  = 0;
6669   unsigned NumNonZero = 0;
6670   unsigned NonZeros = 0;
6671   bool IsAllConstants = true;
6672   SmallSet<SDValue, 8> Values;
6673   for (unsigned i = 0; i < NumElems; ++i) {
6674     SDValue Elt = Op.getOperand(i);
6675     if (Elt.getOpcode() == ISD::UNDEF)
6676       continue;
6677     Values.insert(Elt);
6678     if (Elt.getOpcode() != ISD::Constant &&
6679         Elt.getOpcode() != ISD::ConstantFP)
6680       IsAllConstants = false;
6681     if (X86::isZeroNode(Elt))
6682       NumZero++;
6683     else {
6684       NonZeros |= (1 << i);
6685       NumNonZero++;
6686     }
6687   }
6688
6689   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6690   if (NumNonZero == 0)
6691     return DAG.getUNDEF(VT);
6692
6693   // Special case for single non-zero, non-undef, element.
6694   if (NumNonZero == 1) {
6695     unsigned Idx = countTrailingZeros(NonZeros);
6696     SDValue Item = Op.getOperand(Idx);
6697
6698     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6699     // the value are obviously zero, truncate the value to i32 and do the
6700     // insertion that way.  Only do this if the value is non-constant or if the
6701     // value is a constant being inserted into element 0.  It is cheaper to do
6702     // a constant pool load than it is to do a movd + shuffle.
6703     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6704         (!IsAllConstants || Idx == 0)) {
6705       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6706         // Handle SSE only.
6707         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6708         EVT VecVT = MVT::v4i32;
6709         unsigned VecElts = 4;
6710
6711         // Truncate the value (which may itself be a constant) to i32, and
6712         // convert it to a vector with movd (S2V+shuffle to zero extend).
6713         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6714         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6715         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6716
6717         // Now we have our 32-bit value zero extended in the low element of
6718         // a vector.  If Idx != 0, swizzle it into place.
6719         if (Idx != 0) {
6720           SmallVector<int, 4> Mask;
6721           Mask.push_back(Idx);
6722           for (unsigned i = 1; i != VecElts; ++i)
6723             Mask.push_back(i);
6724           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6725                                       &Mask[0]);
6726         }
6727         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6728       }
6729     }
6730
6731     // If we have a constant or non-constant insertion into the low element of
6732     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6733     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6734     // depending on what the source datatype is.
6735     if (Idx == 0) {
6736       if (NumZero == 0)
6737         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6738
6739       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6740           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6741         if (VT.is256BitVector() || VT.is512BitVector()) {
6742           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6743           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6744                              Item, DAG.getIntPtrConstant(0));
6745         }
6746         assert(VT.is128BitVector() && "Expected an SSE value type!");
6747         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6748         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6749         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6750       }
6751
6752       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6753         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6754         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6755         if (VT.is256BitVector()) {
6756           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6757           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6758         } else {
6759           assert(VT.is128BitVector() && "Expected an SSE value type!");
6760           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6761         }
6762         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6763       }
6764     }
6765
6766     // Is it a vector logical left shift?
6767     if (NumElems == 2 && Idx == 1 &&
6768         X86::isZeroNode(Op.getOperand(0)) &&
6769         !X86::isZeroNode(Op.getOperand(1))) {
6770       unsigned NumBits = VT.getSizeInBits();
6771       return getVShift(true, VT,
6772                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6773                                    VT, Op.getOperand(1)),
6774                        NumBits/2, DAG, *this, dl);
6775     }
6776
6777     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6778       return SDValue();
6779
6780     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6781     // is a non-constant being inserted into an element other than the low one,
6782     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6783     // movd/movss) to move this into the low element, then shuffle it into
6784     // place.
6785     if (EVTBits == 32) {
6786       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6787
6788       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6789       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6790       SmallVector<int, 8> MaskVec;
6791       for (unsigned i = 0; i != NumElems; ++i)
6792         MaskVec.push_back(i == Idx ? 0 : 1);
6793       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6794     }
6795   }
6796
6797   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6798   if (Values.size() == 1) {
6799     if (EVTBits == 32) {
6800       // Instead of a shuffle like this:
6801       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6802       // Check if it's possible to issue this instead.
6803       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6804       unsigned Idx = countTrailingZeros(NonZeros);
6805       SDValue Item = Op.getOperand(Idx);
6806       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6807         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6808     }
6809     return SDValue();
6810   }
6811
6812   // A vector full of immediates; various special cases are already
6813   // handled, so this is best done with a single constant-pool load.
6814   if (IsAllConstants)
6815     return SDValue();
6816
6817   // For AVX-length vectors, build the individual 128-bit pieces and use
6818   // shuffles to put them in place.
6819   if (VT.is256BitVector() || VT.is512BitVector()) {
6820     SmallVector<SDValue, 64> V;
6821     for (unsigned i = 0; i != NumElems; ++i)
6822       V.push_back(Op.getOperand(i));
6823
6824     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6825
6826     // Build both the lower and upper subvector.
6827     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6828                                 makeArrayRef(&V[0], NumElems/2));
6829     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6830                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6831
6832     // Recreate the wider vector with the lower and upper part.
6833     if (VT.is256BitVector())
6834       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6835     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6836   }
6837
6838   // Let legalizer expand 2-wide build_vectors.
6839   if (EVTBits == 64) {
6840     if (NumNonZero == 1) {
6841       // One half is zero or undef.
6842       unsigned Idx = countTrailingZeros(NonZeros);
6843       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6844                                  Op.getOperand(Idx));
6845       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6846     }
6847     return SDValue();
6848   }
6849
6850   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6851   if (EVTBits == 8 && NumElems == 16) {
6852     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6853                                         Subtarget, *this);
6854     if (V.getNode()) return V;
6855   }
6856
6857   if (EVTBits == 16 && NumElems == 8) {
6858     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6859                                       Subtarget, *this);
6860     if (V.getNode()) return V;
6861   }
6862
6863   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6864   if (EVTBits == 32 && NumElems == 4) {
6865     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6866                                       NumZero, DAG, Subtarget, *this);
6867     if (V.getNode())
6868       return V;
6869   }
6870
6871   // If element VT is == 32 bits, turn it into a number of shuffles.
6872   SmallVector<SDValue, 8> V(NumElems);
6873   if (NumElems == 4 && NumZero > 0) {
6874     for (unsigned i = 0; i < 4; ++i) {
6875       bool isZero = !(NonZeros & (1 << i));
6876       if (isZero)
6877         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6878       else
6879         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6880     }
6881
6882     for (unsigned i = 0; i < 2; ++i) {
6883       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6884         default: break;
6885         case 0:
6886           V[i] = V[i*2];  // Must be a zero vector.
6887           break;
6888         case 1:
6889           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6890           break;
6891         case 2:
6892           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6893           break;
6894         case 3:
6895           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6896           break;
6897       }
6898     }
6899
6900     bool Reverse1 = (NonZeros & 0x3) == 2;
6901     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6902     int MaskVec[] = {
6903       Reverse1 ? 1 : 0,
6904       Reverse1 ? 0 : 1,
6905       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6906       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6907     };
6908     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6909   }
6910
6911   if (Values.size() > 1 && VT.is128BitVector()) {
6912     // Check for a build vector of consecutive loads.
6913     for (unsigned i = 0; i < NumElems; ++i)
6914       V[i] = Op.getOperand(i);
6915
6916     // Check for elements which are consecutive loads.
6917     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6918     if (LD.getNode())
6919       return LD;
6920
6921     // Check for a build vector from mostly shuffle plus few inserting.
6922     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6923     if (Sh.getNode())
6924       return Sh;
6925
6926     // For SSE 4.1, use insertps to put the high elements into the low element.
6927     if (getSubtarget()->hasSSE41()) {
6928       SDValue Result;
6929       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6930         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6931       else
6932         Result = DAG.getUNDEF(VT);
6933
6934       for (unsigned i = 1; i < NumElems; ++i) {
6935         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6936         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6937                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6938       }
6939       return Result;
6940     }
6941
6942     // Otherwise, expand into a number of unpckl*, start by extending each of
6943     // our (non-undef) elements to the full vector width with the element in the
6944     // bottom slot of the vector (which generates no code for SSE).
6945     for (unsigned i = 0; i < NumElems; ++i) {
6946       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6947         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6948       else
6949         V[i] = DAG.getUNDEF(VT);
6950     }
6951
6952     // Next, we iteratively mix elements, e.g. for v4f32:
6953     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6954     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6955     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6956     unsigned EltStride = NumElems >> 1;
6957     while (EltStride != 0) {
6958       for (unsigned i = 0; i < EltStride; ++i) {
6959         // If V[i+EltStride] is undef and this is the first round of mixing,
6960         // then it is safe to just drop this shuffle: V[i] is already in the
6961         // right place, the one element (since it's the first round) being
6962         // inserted as undef can be dropped.  This isn't safe for successive
6963         // rounds because they will permute elements within both vectors.
6964         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6965             EltStride == NumElems/2)
6966           continue;
6967
6968         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6969       }
6970       EltStride >>= 1;
6971     }
6972     return V[0];
6973   }
6974   return SDValue();
6975 }
6976
6977 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6978 // to create 256-bit vectors from two other 128-bit ones.
6979 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6980   SDLoc dl(Op);
6981   MVT ResVT = Op.getSimpleValueType();
6982
6983   assert((ResVT.is256BitVector() ||
6984           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6985
6986   SDValue V1 = Op.getOperand(0);
6987   SDValue V2 = Op.getOperand(1);
6988   unsigned NumElems = ResVT.getVectorNumElements();
6989   if(ResVT.is256BitVector())
6990     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6991
6992   if (Op.getNumOperands() == 4) {
6993     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6994                                 ResVT.getVectorNumElements()/2);
6995     SDValue V3 = Op.getOperand(2);
6996     SDValue V4 = Op.getOperand(3);
6997     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6998       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6999   }
7000   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7001 }
7002
7003 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7004   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7005   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7006          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7007           Op.getNumOperands() == 4)));
7008
7009   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7010   // from two other 128-bit ones.
7011
7012   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7013   return LowerAVXCONCAT_VECTORS(Op, DAG);
7014 }
7015
7016
7017 //===----------------------------------------------------------------------===//
7018 // Vector shuffle lowering
7019 //
7020 // This is an experimental code path for lowering vector shuffles on x86. It is
7021 // designed to handle arbitrary vector shuffles and blends, gracefully
7022 // degrading performance as necessary. It works hard to recognize idiomatic
7023 // shuffles and lower them to optimal instruction patterns without leaving
7024 // a framework that allows reasonably efficient handling of all vector shuffle
7025 // patterns.
7026 //===----------------------------------------------------------------------===//
7027
7028 /// \brief Tiny helper function to identify a no-op mask.
7029 ///
7030 /// This is a somewhat boring predicate function. It checks whether the mask
7031 /// array input, which is assumed to be a single-input shuffle mask of the kind
7032 /// used by the X86 shuffle instructions (not a fully general
7033 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7034 /// in-place shuffle are 'no-op's.
7035 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7036   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7037     if (Mask[i] != -1 && Mask[i] != i)
7038       return false;
7039   return true;
7040 }
7041
7042 /// \brief Helper function to classify a mask as a single-input mask.
7043 ///
7044 /// This isn't a generic single-input test because in the vector shuffle
7045 /// lowering we canonicalize single inputs to be the first input operand. This
7046 /// means we can more quickly test for a single input by only checking whether
7047 /// an input from the second operand exists. We also assume that the size of
7048 /// mask corresponds to the size of the input vectors which isn't true in the
7049 /// fully general case.
7050 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7051   for (int M : Mask)
7052     if (M >= (int)Mask.size())
7053       return false;
7054   return true;
7055 }
7056
7057 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7058 ///
7059 /// This helper function produces an 8-bit shuffle immediate corresponding to
7060 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7061 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7062 /// example.
7063 ///
7064 /// NB: We rely heavily on "undef" masks preserving the input lane.
7065 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7066                                           SelectionDAG &DAG) {
7067   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7068   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7069   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7070   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7071   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7072
7073   unsigned Imm = 0;
7074   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7075   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7076   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7077   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7078   return DAG.getConstant(Imm, MVT::i8);
7079 }
7080
7081 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7082 ///
7083 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7084 /// support for floating point shuffles but not integer shuffles. These
7085 /// instructions will incur a domain crossing penalty on some chips though so
7086 /// it is better to avoid lowering through this for integer vectors where
7087 /// possible.
7088 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7089                                        const X86Subtarget *Subtarget,
7090                                        SelectionDAG &DAG) {
7091   SDLoc DL(Op);
7092   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7093   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7094   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7095   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7096   ArrayRef<int> Mask = SVOp->getMask();
7097   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7098
7099   if (isSingleInputShuffleMask(Mask)) {
7100     // Straight shuffle of a single input vector. Simulate this by using the
7101     // single input as both of the "inputs" to this instruction..
7102     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7103     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7104                        DAG.getConstant(SHUFPDMask, MVT::i8));
7105   }
7106   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7107   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7108
7109   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7110   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7111                      DAG.getConstant(SHUFPDMask, MVT::i8));
7112 }
7113
7114 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7115 ///
7116 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7117 /// the integer unit to minimize domain crossing penalties. However, for blends
7118 /// it falls back to the floating point shuffle operation with appropriate bit
7119 /// casting.
7120 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7121                                        const X86Subtarget *Subtarget,
7122                                        SelectionDAG &DAG) {
7123   SDLoc DL(Op);
7124   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7125   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7126   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7127   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7128   ArrayRef<int> Mask = SVOp->getMask();
7129   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7130
7131   if (isSingleInputShuffleMask(Mask)) {
7132     // Straight shuffle of a single input vector. For everything from SSE2
7133     // onward this has a single fast instruction with no scary immediates.
7134     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7135     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7136     int WidenedMask[4] = {
7137         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7138         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7139     return DAG.getNode(
7140         ISD::BITCAST, DL, MVT::v2i64,
7141         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7142                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7143   }
7144
7145   // We implement this with SHUFPD which is pretty lame because it will likely
7146   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7147   // However, all the alternatives are still more cycles and newer chips don't
7148   // have this problem. It would be really nice if x86 had better shuffles here.
7149   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7150   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7151   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7152                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7153 }
7154
7155 /// \brief Lower 4-lane 32-bit floating point shuffles.
7156 ///
7157 /// Uses instructions exclusively from the floating point unit to minimize
7158 /// domain crossing penalties, as these are sufficient to implement all v4f32
7159 /// shuffles.
7160 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7161                                        const X86Subtarget *Subtarget,
7162                                        SelectionDAG &DAG) {
7163   SDLoc DL(Op);
7164   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7165   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7166   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7167   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7168   ArrayRef<int> Mask = SVOp->getMask();
7169   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7170
7171   SDValue LowV = V1, HighV = V2;
7172   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7173
7174   int NumV2Elements =
7175       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7176
7177   if (NumV2Elements == 0)
7178     // Straight shuffle of a single input vector. We pass the input vector to
7179     // both operands to simulate this with a SHUFPS.
7180     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7181                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7182
7183   if (NumV2Elements == 1) {
7184     int V2Index =
7185         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7186         Mask.begin();
7187     // Compute the index adjacent to V2Index and in the same half by toggling
7188     // the low bit.
7189     int V2AdjIndex = V2Index ^ 1;
7190
7191     if (Mask[V2AdjIndex] == -1) {
7192       // Handles all the cases where we have a single V2 element and an undef.
7193       // This will only ever happen in the high lanes because we commute the
7194       // vector otherwise.
7195       if (V2Index < 2)
7196         std::swap(LowV, HighV);
7197       NewMask[V2Index] -= 4;
7198     } else {
7199       // Handle the case where the V2 element ends up adjacent to a V1 element.
7200       // To make this work, blend them together as the first step.
7201       int V1Index = V2AdjIndex;
7202       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7203       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7204                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7205
7206       // Now proceed to reconstruct the final blend as we have the necessary
7207       // high or low half formed.
7208       if (V2Index < 2) {
7209         LowV = V2;
7210         HighV = V1;
7211       } else {
7212         HighV = V2;
7213       }
7214       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7215       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7216     }
7217   } else if (NumV2Elements == 2) {
7218     if (Mask[0] < 4 && Mask[1] < 4) {
7219       // Handle the easy case where we have V1 in the low lanes and V2 in the
7220       // high lanes. We never see this reversed because we sort the shuffle.
7221       NewMask[2] -= 4;
7222       NewMask[3] -= 4;
7223     } else {
7224       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7225       // trying to place elements directly, just blend them and set up the final
7226       // shuffle to place them.
7227
7228       // The first two blend mask elements are for V1, the second two are for
7229       // V2.
7230       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7231                           Mask[2] < 4 ? Mask[2] : Mask[3],
7232                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7233                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7234       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7235                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7236
7237       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7238       // a blend.
7239       LowV = HighV = V1;
7240       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7241       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7242       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7243       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7244     }
7245   }
7246   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7247                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7248 }
7249
7250 /// \brief Lower 4-lane i32 vector shuffles.
7251 ///
7252 /// We try to handle these with integer-domain shuffles where we can, but for
7253 /// blends we use the floating point domain blend instructions.
7254 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7255                                        const X86Subtarget *Subtarget,
7256                                        SelectionDAG &DAG) {
7257   SDLoc DL(Op);
7258   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7259   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7260   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7261   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7262   ArrayRef<int> Mask = SVOp->getMask();
7263   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7264
7265   if (isSingleInputShuffleMask(Mask))
7266     // Straight shuffle of a single input vector. For everything from SSE2
7267     // onward this has a single fast instruction with no scary immediates.
7268     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7269                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7270
7271   // We implement this with SHUFPS because it can blend from two vectors.
7272   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7273   // up the inputs, bypassing domain shift penalties that we would encur if we
7274   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7275   // relevant.
7276   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7277                      DAG.getVectorShuffle(
7278                          MVT::v4f32, DL,
7279                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7280                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7281 }
7282
7283 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7284 /// shuffle lowering, and the most complex part.
7285 ///
7286 /// The lowering strategy is to try to form pairs of input lanes which are
7287 /// targeted at the same half of the final vector, and then use a dword shuffle
7288 /// to place them onto the right half, and finally unpack the paired lanes into
7289 /// their final position.
7290 ///
7291 /// The exact breakdown of how to form these dword pairs and align them on the
7292 /// correct sides is really tricky. See the comments within the function for
7293 /// more of the details.
7294 static SDValue lowerV8I16SingleInputVectorShuffle(
7295     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7296     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7297   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7298   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7299   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7300
7301   SmallVector<int, 4> LoInputs;
7302   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7303                [](int M) { return M >= 0; });
7304   std::sort(LoInputs.begin(), LoInputs.end());
7305   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7306   SmallVector<int, 4> HiInputs;
7307   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7308                [](int M) { return M >= 0; });
7309   std::sort(HiInputs.begin(), HiInputs.end());
7310   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7311   int NumLToL =
7312       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7313   int NumHToL = LoInputs.size() - NumLToL;
7314   int NumLToH =
7315       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7316   int NumHToH = HiInputs.size() - NumLToH;
7317   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7318   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7319   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7320   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7321
7322   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7323   // such inputs we can swap two of the dwords across the half mark and end up
7324   // with <=2 inputs to each half in each half. Once there, we can fall through
7325   // to the generic code below. For example:
7326   //
7327   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7328   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7329   //
7330   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7331   // and an existing 2-into-2 on the other half. In this case we may have to
7332   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7333   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7334   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7335   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7336   // half than the one we target for fixing) will be fixed when we re-enter this
7337   // path. We will also combine away any sequence of PSHUFD instructions that
7338   // result into a single instruction. Here is an example of the tricky case:
7339   //
7340   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7341   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7342   //
7343   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7344   //
7345   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7346   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7347   //
7348   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7349   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7350   //
7351   // The result is fine to be handled by the generic logic.
7352   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7353                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7354                           int AOffset, int BOffset) {
7355     assert(AToAInputs.size() == 3 || AToAInputs.size() == 1 &&
7356            "Must call this with A having 3 or 1 inputs from the A half.");
7357     assert(BToAInputs.size() == 1 || BToAInputs.size() == 3 &&
7358            "Must call this with B having 1 or 3 inputs from the B half.");
7359     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7360            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7361
7362     // Compute the index of dword with only one word among the three inputs in
7363     // a half by taking the sum of the half with three inputs and subtracting
7364     // the sum of the actual three inputs. The difference is the remaining
7365     // slot.
7366     int ADWord, BDWord;
7367     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7368     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7369     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7370     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7371     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7372     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7373     int TripleNonInputIdx =
7374         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7375     TripleDWord = TripleNonInputIdx / 2;
7376
7377     // We use xor with one to compute the adjacent DWord to whichever one the
7378     // OneInput is in.
7379     OneInputDWord = (OneInput / 2) ^ 1;
7380
7381     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7382     // and BToA inputs. If there is also such a problem with the BToB and AToB
7383     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7384     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7385     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7386     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7387       // Compute how many inputs will be flipped by swapping these DWords. We
7388       // need
7389       // to balance this to ensure we don't form a 3-1 shuffle in the other
7390       // half.
7391       int NumFlippedAToBInputs =
7392           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7393           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7394       int NumFlippedBToBInputs =
7395           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7396           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7397       if ((NumFlippedAToBInputs == 1 &&
7398            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7399           (NumFlippedBToBInputs == 1 &&
7400            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7401         // We choose whether to fix the A half or B half based on whether that
7402         // half has zero flipped inputs. At zero, we may not be able to fix it
7403         // with that half. We also bias towards fixing the B half because that
7404         // will more commonly be the high half, and we have to bias one way.
7405         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7406                                                        ArrayRef<int> Inputs) {
7407           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7408           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7409                                          PinnedIdx ^ 1) != Inputs.end();
7410           // Determine whether the free index is in the flipped dword or the
7411           // unflipped dword based on where the pinned index is. We use this bit
7412           // in an xor to conditionally select the adjacent dword.
7413           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7414           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7415                                              FixFreeIdx) != Inputs.end();
7416           if (IsFixIdxInput == IsFixFreeIdxInput)
7417             FixFreeIdx += 1;
7418           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7419                                         FixFreeIdx) != Inputs.end();
7420           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7421                  "We need to be changing the number of flipped inputs!");
7422           int PSHUFHalfMask[] = {0, 1, 2, 3};
7423           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7424           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7425                           MVT::v8i16, V,
7426                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7427
7428           for (int &M : Mask)
7429             if (M != -1 && M == FixIdx)
7430               M = FixFreeIdx;
7431             else if (M != -1 && M == FixFreeIdx)
7432               M = FixIdx;
7433         };
7434         if (NumFlippedBToBInputs != 0) {
7435           int BPinnedIdx =
7436               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7437           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7438         } else {
7439           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7440           int APinnedIdx =
7441               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7442           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7443         }
7444       }
7445     }
7446
7447     int PSHUFDMask[] = {0, 1, 2, 3};
7448     PSHUFDMask[ADWord] = BDWord;
7449     PSHUFDMask[BDWord] = ADWord;
7450     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7451                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7452                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7453                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7454
7455     // Adjust the mask to match the new locations of A and B.
7456     for (int &M : Mask)
7457       if (M != -1 && M/2 == ADWord)
7458         M = 2 * BDWord + M % 2;
7459       else if (M != -1 && M/2 == BDWord)
7460         M = 2 * ADWord + M % 2;
7461
7462     // Recurse back into this routine to re-compute state now that this isn't
7463     // a 3 and 1 problem.
7464     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7465                                 Mask);
7466   };
7467   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7468     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7469   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7470     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7471
7472   // At this point there are at most two inputs to the low and high halves from
7473   // each half. That means the inputs can always be grouped into dwords and
7474   // those dwords can then be moved to the correct half with a dword shuffle.
7475   // We use at most one low and one high word shuffle to collect these paired
7476   // inputs into dwords, and finally a dword shuffle to place them.
7477   int PSHUFLMask[4] = {-1, -1, -1, -1};
7478   int PSHUFHMask[4] = {-1, -1, -1, -1};
7479   int PSHUFDMask[4] = {-1, -1, -1, -1};
7480
7481   // First fix the masks for all the inputs that are staying in their
7482   // original halves. This will then dictate the targets of the cross-half
7483   // shuffles.
7484   auto fixInPlaceInputs =
7485       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7486                     MutableArrayRef<int> SourceHalfMask,
7487                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7488     if (InPlaceInputs.empty())
7489       return;
7490     if (InPlaceInputs.size() == 1) {
7491       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7492           InPlaceInputs[0] - HalfOffset;
7493       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7494       return;
7495     }
7496     if (IncomingInputs.empty()) {
7497       // Just fix all of the in place inputs.
7498       for (int Input : InPlaceInputs) {
7499         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7500         PSHUFDMask[Input / 2] = Input / 2;
7501       }
7502       return;
7503     }
7504
7505     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7506     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7507         InPlaceInputs[0] - HalfOffset;
7508     // Put the second input next to the first so that they are packed into
7509     // a dword. We find the adjacent index by toggling the low bit.
7510     int AdjIndex = InPlaceInputs[0] ^ 1;
7511     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7512     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7513     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7514   };
7515   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7516   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7517
7518   // Now gather the cross-half inputs and place them into a free dword of
7519   // their target half.
7520   // FIXME: This operation could almost certainly be simplified dramatically to
7521   // look more like the 3-1 fixing operation.
7522   auto moveInputsToRightHalf = [&PSHUFDMask](
7523       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7524       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7525       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7526       int DestOffset) {
7527     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7528       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7529     };
7530     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7531                                                int Word) {
7532       int LowWord = Word & ~1;
7533       int HighWord = Word | 1;
7534       return isWordClobbered(SourceHalfMask, LowWord) ||
7535              isWordClobbered(SourceHalfMask, HighWord);
7536     };
7537
7538     if (IncomingInputs.empty())
7539       return;
7540
7541     if (ExistingInputs.empty()) {
7542       // Map any dwords with inputs from them into the right half.
7543       for (int Input : IncomingInputs) {
7544         // If the source half mask maps over the inputs, turn those into
7545         // swaps and use the swapped lane.
7546         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7547           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7548             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7549                 Input - SourceOffset;
7550             // We have to swap the uses in our half mask in one sweep.
7551             for (int &M : HalfMask)
7552               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7553                 M = Input;
7554               else if (M == Input)
7555                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7556           } else {
7557             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7558                        Input - SourceOffset &&
7559                    "Previous placement doesn't match!");
7560           }
7561           // Note that this correctly re-maps both when we do a swap and when
7562           // we observe the other side of the swap above. We rely on that to
7563           // avoid swapping the members of the input list directly.
7564           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7565         }
7566
7567         // Map the input's dword into the correct half.
7568         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7569           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7570         else
7571           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7572                      Input / 2 &&
7573                  "Previous placement doesn't match!");
7574       }
7575
7576       // And just directly shift any other-half mask elements to be same-half
7577       // as we will have mirrored the dword containing the element into the
7578       // same position within that half.
7579       for (int &M : HalfMask)
7580         if (M >= SourceOffset && M < SourceOffset + 4) {
7581           M = M - SourceOffset + DestOffset;
7582           assert(M >= 0 && "This should never wrap below zero!");
7583         }
7584       return;
7585     }
7586
7587     // Ensure we have the input in a viable dword of its current half. This
7588     // is particularly tricky because the original position may be clobbered
7589     // by inputs being moved and *staying* in that half.
7590     if (IncomingInputs.size() == 1) {
7591       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7592         int InputFixed = std::find(std::begin(SourceHalfMask),
7593                                    std::end(SourceHalfMask), -1) -
7594                          std::begin(SourceHalfMask) + SourceOffset;
7595         SourceHalfMask[InputFixed - SourceOffset] =
7596             IncomingInputs[0] - SourceOffset;
7597         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7598                      InputFixed);
7599         IncomingInputs[0] = InputFixed;
7600       }
7601     } else if (IncomingInputs.size() == 2) {
7602       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7603           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7604         // We have two non-adjacent or clobbered inputs we need to extract from
7605         // the source half. To do this, we need to map them into some adjacent
7606         // dword slot in the source mask.
7607         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7608                               IncomingInputs[1] - SourceOffset};
7609
7610         // If there is a free slot in the source half mask adjacent to one of
7611         // the inputs, place the other input in it. We use (Index XOR 1) to
7612         // compute an adjacent index.
7613         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7614             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7615           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7616           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7617           InputsFixed[1] = InputsFixed[0] ^ 1;
7618         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7619                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7620           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7621           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7622           InputsFixed[0] = InputsFixed[1] ^ 1;
7623         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7624                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7625           // The two inputs are in the same DWord but it is clobbered and the
7626           // adjacent DWord isn't used at all. Move both inputs to the free
7627           // slot.
7628           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7629           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7630           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7631           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7632         } else {
7633           // The only way we hit this point is if there is no clobbering
7634           // (because there are no off-half inputs to this half) and there is no
7635           // free slot adjacent to one of the inputs. In this case, we have to
7636           // swap an input with a non-input.
7637           for (int i = 0; i < 4; ++i)
7638             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7639                    "We can't handle any clobbers here!");
7640           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7641                  "Cannot have adjacent inputs here!");
7642
7643           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7644           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7645
7646           // We also have to update the final source mask in this case because
7647           // it may need to undo the above swap.
7648           for (int &M : FinalSourceHalfMask)
7649             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7650               M = InputsFixed[1] + SourceOffset;
7651             else if (M == InputsFixed[1] + SourceOffset)
7652               M = (InputsFixed[0] ^ 1) + SourceOffset;
7653
7654           InputsFixed[1] = InputsFixed[0] ^ 1;
7655         }
7656
7657         // Point everything at the fixed inputs.
7658         for (int &M : HalfMask)
7659           if (M == IncomingInputs[0])
7660             M = InputsFixed[0] + SourceOffset;
7661           else if (M == IncomingInputs[1])
7662             M = InputsFixed[1] + SourceOffset;
7663
7664         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7665         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7666       }
7667     } else {
7668       llvm_unreachable("Unhandled input size!");
7669     }
7670
7671     // Now hoist the DWord down to the right half.
7672     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7673     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7674     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7675     for (int &M : HalfMask)
7676       for (int Input : IncomingInputs)
7677         if (M == Input)
7678           M = FreeDWord * 2 + Input % 2;
7679   };
7680   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7681                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7682   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7683                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7684
7685   // Now enact all the shuffles we've computed to move the inputs into their
7686   // target half.
7687   if (!isNoopShuffleMask(PSHUFLMask))
7688     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7689                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7690   if (!isNoopShuffleMask(PSHUFHMask))
7691     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7692                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7693   if (!isNoopShuffleMask(PSHUFDMask))
7694     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7695                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7696                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7697                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7698
7699   // At this point, each half should contain all its inputs, and we can then
7700   // just shuffle them into their final position.
7701   assert(std::count_if(LoMask.begin(), LoMask.end(),
7702                        [](int M) { return M >= 4; }) == 0 &&
7703          "Failed to lift all the high half inputs to the low mask!");
7704   assert(std::count_if(HiMask.begin(), HiMask.end(),
7705                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7706          "Failed to lift all the low half inputs to the high mask!");
7707
7708   // Do a half shuffle for the low mask.
7709   if (!isNoopShuffleMask(LoMask))
7710     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7711                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7712
7713   // Do a half shuffle with the high mask after shifting its values down.
7714   for (int &M : HiMask)
7715     if (M >= 0)
7716       M -= 4;
7717   if (!isNoopShuffleMask(HiMask))
7718     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7719                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7720
7721   return V;
7722 }
7723
7724 /// \brief Detect whether the mask pattern should be lowered through
7725 /// interleaving.
7726 ///
7727 /// This essentially tests whether viewing the mask as an interleaving of two
7728 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7729 /// lowering it through interleaving is a significantly better strategy.
7730 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7731   int NumEvenInputs[2] = {0, 0};
7732   int NumOddInputs[2] = {0, 0};
7733   int NumLoInputs[2] = {0, 0};
7734   int NumHiInputs[2] = {0, 0};
7735   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7736     if (Mask[i] < 0)
7737       continue;
7738
7739     int InputIdx = Mask[i] >= Size;
7740
7741     if (i < Size / 2)
7742       ++NumLoInputs[InputIdx];
7743     else
7744       ++NumHiInputs[InputIdx];
7745
7746     if ((i % 2) == 0)
7747       ++NumEvenInputs[InputIdx];
7748     else
7749       ++NumOddInputs[InputIdx];
7750   }
7751
7752   // The minimum number of cross-input results for both the interleaved and
7753   // split cases. If interleaving results in fewer cross-input results, return
7754   // true.
7755   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7756                                     NumEvenInputs[0] + NumOddInputs[1]);
7757   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7758                               NumLoInputs[0] + NumHiInputs[1]);
7759   return InterleavedCrosses < SplitCrosses;
7760 }
7761
7762 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7763 ///
7764 /// This strategy only works when the inputs from each vector fit into a single
7765 /// half of that vector, and generally there are not so many inputs as to leave
7766 /// the in-place shuffles required highly constrained (and thus expensive). It
7767 /// shifts all the inputs into a single side of both input vectors and then
7768 /// uses an unpack to interleave these inputs in a single vector. At that
7769 /// point, we will fall back on the generic single input shuffle lowering.
7770 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7771                                                  SDValue V2,
7772                                                  MutableArrayRef<int> Mask,
7773                                                  const X86Subtarget *Subtarget,
7774                                                  SelectionDAG &DAG) {
7775   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7776   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7777   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7778   for (int i = 0; i < 8; ++i)
7779     if (Mask[i] >= 0 && Mask[i] < 4)
7780       LoV1Inputs.push_back(i);
7781     else if (Mask[i] >= 4 && Mask[i] < 8)
7782       HiV1Inputs.push_back(i);
7783     else if (Mask[i] >= 8 && Mask[i] < 12)
7784       LoV2Inputs.push_back(i);
7785     else if (Mask[i] >= 12)
7786       HiV2Inputs.push_back(i);
7787
7788   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7789   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7790   (void)NumV1Inputs;
7791   (void)NumV2Inputs;
7792   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7793   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7794   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7795
7796   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7797                      HiV1Inputs.size() + HiV2Inputs.size();
7798
7799   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7800                               ArrayRef<int> HiInputs, bool MoveToLo,
7801                               int MaskOffset) {
7802     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7803     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7804     if (BadInputs.empty())
7805       return V;
7806
7807     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7808     int MoveOffset = MoveToLo ? 0 : 4;
7809
7810     if (GoodInputs.empty()) {
7811       for (int BadInput : BadInputs) {
7812         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7813         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7814       }
7815     } else {
7816       if (GoodInputs.size() == 2) {
7817         // If the low inputs are spread across two dwords, pack them into
7818         // a single dword.
7819         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7820         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7821         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7822         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7823       } else {
7824         // Otherwise pin the good inputs.
7825         for (int GoodInput : GoodInputs)
7826           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7827       }
7828
7829       if (BadInputs.size() == 2) {
7830         // If we have two bad inputs then there may be either one or two good
7831         // inputs fixed in place. Find a fixed input, and then find the *other*
7832         // two adjacent indices by using modular arithmetic.
7833         int GoodMaskIdx =
7834             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7835                          [](int M) { return M >= 0; }) -
7836             std::begin(MoveMask);
7837         int MoveMaskIdx =
7838             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
7839         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7840         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7841         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7842         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7843         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7844         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7845       } else {
7846         assert(BadInputs.size() == 1 && "All sizes handled");
7847         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7848                                     std::end(MoveMask), -1) -
7849                           std::begin(MoveMask);
7850         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7851         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7852       }
7853     }
7854
7855     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7856                                 MoveMask);
7857   };
7858   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7859                         /*MaskOffset*/ 0);
7860   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7861                         /*MaskOffset*/ 8);
7862
7863   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7864   // cross-half traffic in the final shuffle.
7865
7866   // Munge the mask to be a single-input mask after the unpack merges the
7867   // results.
7868   for (int &M : Mask)
7869     if (M != -1)
7870       M = 2 * (M % 4) + (M / 8);
7871
7872   return DAG.getVectorShuffle(
7873       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7874                                   DL, MVT::v8i16, V1, V2),
7875       DAG.getUNDEF(MVT::v8i16), Mask);
7876 }
7877
7878 /// \brief Generic lowering of 8-lane i16 shuffles.
7879 ///
7880 /// This handles both single-input shuffles and combined shuffle/blends with
7881 /// two inputs. The single input shuffles are immediately delegated to
7882 /// a dedicated lowering routine.
7883 ///
7884 /// The blends are lowered in one of three fundamental ways. If there are few
7885 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7886 /// of the input is significantly cheaper when lowered as an interleaving of
7887 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7888 /// halves of the inputs separately (making them have relatively few inputs)
7889 /// and then concatenate them.
7890 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7891                                        const X86Subtarget *Subtarget,
7892                                        SelectionDAG &DAG) {
7893   SDLoc DL(Op);
7894   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7895   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7896   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7897   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7898   ArrayRef<int> OrigMask = SVOp->getMask();
7899   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7900                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7901   MutableArrayRef<int> Mask(MaskStorage);
7902
7903   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7904
7905   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7906   auto isV2 = [](int M) { return M >= 8; };
7907
7908   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7909   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7910
7911   if (NumV2Inputs == 0)
7912     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7913
7914   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7915                             "to be V1-input shuffles.");
7916
7917   if (NumV1Inputs + NumV2Inputs <= 4)
7918     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7919
7920   // Check whether an interleaving lowering is likely to be more efficient.
7921   // This isn't perfect but it is a strong heuristic that tends to work well on
7922   // the kinds of shuffles that show up in practice.
7923   //
7924   // FIXME: Handle 1x, 2x, and 4x interleaving.
7925   if (shouldLowerAsInterleaving(Mask)) {
7926     // FIXME: Figure out whether we should pack these into the low or high
7927     // halves.
7928
7929     int EMask[8], OMask[8];
7930     for (int i = 0; i < 4; ++i) {
7931       EMask[i] = Mask[2*i];
7932       OMask[i] = Mask[2*i + 1];
7933       EMask[i + 4] = -1;
7934       OMask[i + 4] = -1;
7935     }
7936
7937     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7938     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7939
7940     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7941   }
7942
7943   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7944   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7945
7946   for (int i = 0; i < 4; ++i) {
7947     LoBlendMask[i] = Mask[i];
7948     HiBlendMask[i] = Mask[i + 4];
7949   }
7950
7951   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7952   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7953   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7954   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7955
7956   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7957                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7958 }
7959
7960 /// \brief Check whether a compaction lowering can be done by dropping even
7961 /// elements and compute how many times even elements must be dropped.
7962 ///
7963 /// This handles shuffles which take every Nth element where N is a power of
7964 /// two. Example shuffle masks:
7965 ///
7966 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
7967 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
7968 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
7969 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
7970 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
7971 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
7972 ///
7973 /// Any of these lanes can of course be undef.
7974 ///
7975 /// This routine only supports N <= 3.
7976 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
7977 /// for larger N.
7978 ///
7979 /// \returns N above, or the number of times even elements must be dropped if
7980 /// there is such a number. Otherwise returns zero.
7981 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
7982   // Figure out whether we're looping over two inputs or just one.
7983   bool IsSingleInput = isSingleInputShuffleMask(Mask);
7984
7985   // The modulus for the shuffle vector entries is based on whether this is
7986   // a single input or not.
7987   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
7988   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
7989          "We should only be called with masks with a power-of-2 size!");
7990
7991   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
7992
7993   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
7994   // and 2^3 simultaneously. This is because we may have ambiguity with
7995   // partially undef inputs.
7996   bool ViableForN[3] = {true, true, true};
7997
7998   for (int i = 0, e = Mask.size(); i < e; ++i) {
7999     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8000     // want.
8001     if (Mask[i] == -1)
8002       continue;
8003
8004     bool IsAnyViable = false;
8005     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8006       if (ViableForN[j]) {
8007         uint64_t N = j + 1;
8008
8009         // The shuffle mask must be equal to (i * 2^N) % M.
8010         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8011           IsAnyViable = true;
8012         else
8013           ViableForN[j] = false;
8014       }
8015     // Early exit if we exhaust the possible powers of two.
8016     if (!IsAnyViable)
8017       break;
8018   }
8019
8020   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8021     if (ViableForN[j])
8022       return j + 1;
8023
8024   // Return 0 as there is no viable power of two.
8025   return 0;
8026 }
8027
8028 /// \brief Generic lowering of v16i8 shuffles.
8029 ///
8030 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8031 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8032 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8033 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8034 /// back together.
8035 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8036                                        const X86Subtarget *Subtarget,
8037                                        SelectionDAG &DAG) {
8038   SDLoc DL(Op);
8039   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8040   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8041   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8042   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8043   ArrayRef<int> OrigMask = SVOp->getMask();
8044   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8045   int MaskStorage[16] = {
8046       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
8047       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
8048       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
8049       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8050   MutableArrayRef<int> Mask(MaskStorage);
8051   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8052   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8053
8054   // For single-input shuffles, there are some nicer lowering tricks we can use.
8055   if (isSingleInputShuffleMask(Mask)) {
8056     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8057     // Notably, this handles splat and partial-splat shuffles more efficiently.
8058     // However, it only makes sense if the pre-duplication shuffle simplifies
8059     // things significantly. Currently, this means we need to be able to
8060     // express the pre-duplication shuffle as an i16 shuffle.
8061     //
8062     // FIXME: We should check for other patterns which can be widened into an
8063     // i16 shuffle as well.
8064     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8065       for (int i = 0; i < 16; i += 2) {
8066         if (Mask[i] != Mask[i + 1])
8067           return false;
8068       }
8069       return true;
8070     };
8071     auto tryToWidenViaDuplication = [&]() -> SDValue {
8072       if (!canWidenViaDuplication(Mask))
8073         return SDValue();
8074       SmallVector<int, 4> LoInputs;
8075       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8076                    [](int M) { return M >= 0 && M < 8; });
8077       std::sort(LoInputs.begin(), LoInputs.end());
8078       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8079                      LoInputs.end());
8080       SmallVector<int, 4> HiInputs;
8081       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8082                    [](int M) { return M >= 8; });
8083       std::sort(HiInputs.begin(), HiInputs.end());
8084       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8085                      HiInputs.end());
8086
8087       bool TargetLo = LoInputs.size() >= HiInputs.size();
8088       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8089       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8090
8091       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8092       SmallDenseMap<int, int, 8> LaneMap;
8093       for (int I : InPlaceInputs) {
8094         PreDupI16Shuffle[I/2] = I/2;
8095         LaneMap[I] = I;
8096       }
8097       int j = TargetLo ? 0 : 4, je = j + 4;
8098       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8099         // Check if j is already a shuffle of this input. This happens when
8100         // there are two adjacent bytes after we move the low one.
8101         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8102           // If we haven't yet mapped the input, search for a slot into which
8103           // we can map it.
8104           while (j < je && PreDupI16Shuffle[j] != -1)
8105             ++j;
8106
8107           if (j == je)
8108             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8109             return SDValue();
8110
8111           // Map this input with the i16 shuffle.
8112           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8113         }
8114
8115         // Update the lane map based on the mapping we ended up with.
8116         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8117       }
8118       V1 = DAG.getNode(
8119           ISD::BITCAST, DL, MVT::v16i8,
8120           DAG.getVectorShuffle(MVT::v8i16, DL,
8121                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8122                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8123
8124       // Unpack the bytes to form the i16s that will be shuffled into place.
8125       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8126                        MVT::v16i8, V1, V1);
8127
8128       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8129       for (int i = 0; i < 16; i += 2) {
8130         if (Mask[i] != -1)
8131           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8132         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8133       }
8134       return DAG.getNode(
8135           ISD::BITCAST, DL, MVT::v16i8,
8136           DAG.getVectorShuffle(MVT::v8i16, DL,
8137                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8138                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8139     };
8140     if (SDValue V = tryToWidenViaDuplication())
8141       return V;
8142   }
8143
8144   // Check whether an interleaving lowering is likely to be more efficient.
8145   // This isn't perfect but it is a strong heuristic that tends to work well on
8146   // the kinds of shuffles that show up in practice.
8147   //
8148   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8149   if (shouldLowerAsInterleaving(Mask)) {
8150     // FIXME: Figure out whether we should pack these into the low or high
8151     // halves.
8152
8153     int EMask[16], OMask[16];
8154     for (int i = 0; i < 8; ++i) {
8155       EMask[i] = Mask[2*i];
8156       OMask[i] = Mask[2*i + 1];
8157       EMask[i + 8] = -1;
8158       OMask[i + 8] = -1;
8159     }
8160
8161     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8162     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8163
8164     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8165   }
8166
8167   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8168   // with PSHUFB. It is important to do this before we attempt to generate any
8169   // blends but after all of the single-input lowerings. If the single input
8170   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8171   // want to preserve that and we can DAG combine any longer sequences into
8172   // a PSHUFB in the end. But once we start blending from multiple inputs,
8173   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8174   // and there are *very* few patterns that would actually be faster than the
8175   // PSHUFB approach because of its ability to zero lanes.
8176   //
8177   // FIXME: The only exceptions to the above are blends which are exact
8178   // interleavings with direct instructions supporting them. We currently don't
8179   // handle those well here.
8180   if (Subtarget->hasSSSE3()) {
8181     SDValue V1Mask[16];
8182     SDValue V2Mask[16];
8183     for (int i = 0; i < 16; ++i)
8184       if (Mask[i] == -1) {
8185         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8186       } else {
8187         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8188         V2Mask[i] =
8189             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8190       }
8191     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8192                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8193     if (isSingleInputShuffleMask(Mask))
8194       return V1; // Single inputs are easy.
8195
8196     // Otherwise, blend the two.
8197     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8198                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8199     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8200   }
8201
8202   // Check whether a compaction lowering can be done. This handles shuffles
8203   // which take every Nth element for some even N. See the helper function for
8204   // details.
8205   //
8206   // We special case these as they can be particularly efficiently handled with
8207   // the PACKUSB instruction on x86 and they show up in common patterns of
8208   // rearranging bytes to truncate wide elements.
8209   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8210     // NumEvenDrops is the power of two stride of the elements. Another way of
8211     // thinking about it is that we need to drop the even elements this many
8212     // times to get the original input.
8213     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8214
8215     // First we need to zero all the dropped bytes.
8216     assert(NumEvenDrops <= 3 &&
8217            "No support for dropping even elements more than 3 times.");
8218     // We use the mask type to pick which bytes are preserved based on how many
8219     // elements are dropped.
8220     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8221     SDValue ByteClearMask =
8222         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8223                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8224     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8225     if (!IsSingleInput)
8226       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8227
8228     // Now pack things back together.
8229     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8230     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8231     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8232     for (int i = 1; i < NumEvenDrops; ++i) {
8233       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8234       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8235     }
8236
8237     return Result;
8238   }
8239
8240   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8241   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8242   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8243   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8244
8245   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8246                             MutableArrayRef<int> V1HalfBlendMask,
8247                             MutableArrayRef<int> V2HalfBlendMask) {
8248     for (int i = 0; i < 8; ++i)
8249       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8250         V1HalfBlendMask[i] = HalfMask[i];
8251         HalfMask[i] = i;
8252       } else if (HalfMask[i] >= 16) {
8253         V2HalfBlendMask[i] = HalfMask[i] - 16;
8254         HalfMask[i] = i + 8;
8255       }
8256   };
8257   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8258   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8259
8260   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8261
8262   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8263                              MutableArrayRef<int> HiBlendMask) {
8264     SDValue V1, V2;
8265     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8266     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8267     // i16s.
8268     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8269                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8270         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8271                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8272       // Use a mask to drop the high bytes.
8273       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8274       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8275                        DAG.getConstant(0x00FF, MVT::v8i16));
8276
8277       // This will be a single vector shuffle instead of a blend so nuke V2.
8278       V2 = DAG.getUNDEF(MVT::v8i16);
8279
8280       // Squash the masks to point directly into V1.
8281       for (int &M : LoBlendMask)
8282         if (M >= 0)
8283           M /= 2;
8284       for (int &M : HiBlendMask)
8285         if (M >= 0)
8286           M /= 2;
8287     } else {
8288       // Otherwise just unpack the low half of V into V1 and the high half into
8289       // V2 so that we can blend them as i16s.
8290       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8291                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8292       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8293                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8294     }
8295
8296     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8297     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8298     return std::make_pair(BlendedLo, BlendedHi);
8299   };
8300   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8301   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8302   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8303
8304   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8305   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8306
8307   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8308 }
8309
8310 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8311 ///
8312 /// This routine breaks down the specific type of 128-bit shuffle and
8313 /// dispatches to the lowering routines accordingly.
8314 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8315                                         MVT VT, const X86Subtarget *Subtarget,
8316                                         SelectionDAG &DAG) {
8317   switch (VT.SimpleTy) {
8318   case MVT::v2i64:
8319     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8320   case MVT::v2f64:
8321     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8322   case MVT::v4i32:
8323     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8324   case MVT::v4f32:
8325     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8326   case MVT::v8i16:
8327     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8328   case MVT::v16i8:
8329     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8330
8331   default:
8332     llvm_unreachable("Unimplemented!");
8333   }
8334 }
8335
8336 /// \brief Tiny helper function to test whether a shuffle mask could be
8337 /// simplified by widening the elements being shuffled.
8338 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8339   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8340     if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8341       return false;
8342
8343   return true;
8344 }
8345
8346 /// \brief Top-level lowering for x86 vector shuffles.
8347 ///
8348 /// This handles decomposition, canonicalization, and lowering of all x86
8349 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8350 /// above in helper routines. The canonicalization attempts to widen shuffles
8351 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8352 /// s.t. only one of the two inputs needs to be tested, etc.
8353 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8354                                   SelectionDAG &DAG) {
8355   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8356   ArrayRef<int> Mask = SVOp->getMask();
8357   SDValue V1 = Op.getOperand(0);
8358   SDValue V2 = Op.getOperand(1);
8359   MVT VT = Op.getSimpleValueType();
8360   int NumElements = VT.getVectorNumElements();
8361   SDLoc dl(Op);
8362
8363   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8364
8365   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8366   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8367   if (V1IsUndef && V2IsUndef)
8368     return DAG.getUNDEF(VT);
8369
8370   // When we create a shuffle node we put the UNDEF node to second operand,
8371   // but in some cases the first operand may be transformed to UNDEF.
8372   // In this case we should just commute the node.
8373   if (V1IsUndef)
8374     return DAG.getCommutedVectorShuffle(*SVOp);
8375
8376   // Check for non-undef masks pointing at an undef vector and make the masks
8377   // undef as well. This makes it easier to match the shuffle based solely on
8378   // the mask.
8379   if (V2IsUndef)
8380     for (int M : Mask)
8381       if (M >= NumElements) {
8382         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8383         for (int &M : NewMask)
8384           if (M >= NumElements)
8385             M = -1;
8386         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8387       }
8388
8389   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8390   // lanes but wider integers. We cap this to not form integers larger than i64
8391   // but it might be interesting to form i128 integers to handle flipping the
8392   // low and high halves of AVX 256-bit vectors.
8393   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8394       canWidenShuffleElements(Mask)) {
8395     SmallVector<int, 8> NewMask;
8396     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8397       NewMask.push_back(Mask[i] / 2);
8398     MVT NewVT =
8399         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8400                          VT.getVectorNumElements() / 2);
8401     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8402     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8403     return DAG.getNode(ISD::BITCAST, dl, VT,
8404                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8405   }
8406
8407   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8408   for (int M : SVOp->getMask())
8409     if (M < 0)
8410       ++NumUndefElements;
8411     else if (M < NumElements)
8412       ++NumV1Elements;
8413     else
8414       ++NumV2Elements;
8415
8416   // Commute the shuffle as needed such that more elements come from V1 than
8417   // V2. This allows us to match the shuffle pattern strictly on how many
8418   // elements come from V1 without handling the symmetric cases.
8419   if (NumV2Elements > NumV1Elements)
8420     return DAG.getCommutedVectorShuffle(*SVOp);
8421
8422   // When the number of V1 and V2 elements are the same, try to minimize the
8423   // number of uses of V2 in the low half of the vector.
8424   if (NumV1Elements == NumV2Elements) {
8425     int LowV1Elements = 0, LowV2Elements = 0;
8426     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8427       if (M >= NumElements)
8428         ++LowV2Elements;
8429       else if (M >= 0)
8430         ++LowV1Elements;
8431     if (LowV2Elements > LowV1Elements)
8432       return DAG.getCommutedVectorShuffle(*SVOp);
8433   }
8434
8435   // For each vector width, delegate to a specialized lowering routine.
8436   if (VT.getSizeInBits() == 128)
8437     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8438
8439   llvm_unreachable("Unimplemented!");
8440 }
8441
8442
8443 //===----------------------------------------------------------------------===//
8444 // Legacy vector shuffle lowering
8445 //
8446 // This code is the legacy code handling vector shuffles until the above
8447 // replaces its functionality and performance.
8448 //===----------------------------------------------------------------------===//
8449
8450 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8451                         bool hasInt256, unsigned *MaskOut = nullptr) {
8452   MVT EltVT = VT.getVectorElementType();
8453
8454   // There is no blend with immediate in AVX-512.
8455   if (VT.is512BitVector())
8456     return false;
8457
8458   if (!hasSSE41 || EltVT == MVT::i8)
8459     return false;
8460   if (!hasInt256 && VT == MVT::v16i16)
8461     return false;
8462
8463   unsigned MaskValue = 0;
8464   unsigned NumElems = VT.getVectorNumElements();
8465   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8466   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8467   unsigned NumElemsInLane = NumElems / NumLanes;
8468
8469   // Blend for v16i16 should be symetric for the both lanes.
8470   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8471
8472     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8473     int EltIdx = MaskVals[i];
8474
8475     if ((EltIdx < 0 || EltIdx == (int)i) &&
8476         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8477       continue;
8478
8479     if (((unsigned)EltIdx == (i + NumElems)) &&
8480         (SndLaneEltIdx < 0 ||
8481          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8482       MaskValue |= (1 << i);
8483     else
8484       return false;
8485   }
8486
8487   if (MaskOut)
8488     *MaskOut = MaskValue;
8489   return true;
8490 }
8491
8492 // Try to lower a shuffle node into a simple blend instruction.
8493 // This function assumes isBlendMask returns true for this
8494 // SuffleVectorSDNode
8495 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8496                                           unsigned MaskValue,
8497                                           const X86Subtarget *Subtarget,
8498                                           SelectionDAG &DAG) {
8499   MVT VT = SVOp->getSimpleValueType(0);
8500   MVT EltVT = VT.getVectorElementType();
8501   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8502                      Subtarget->hasInt256() && "Trying to lower a "
8503                                                "VECTOR_SHUFFLE to a Blend but "
8504                                                "with the wrong mask"));
8505   SDValue V1 = SVOp->getOperand(0);
8506   SDValue V2 = SVOp->getOperand(1);
8507   SDLoc dl(SVOp);
8508   unsigned NumElems = VT.getVectorNumElements();
8509
8510   // Convert i32 vectors to floating point if it is not AVX2.
8511   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8512   MVT BlendVT = VT;
8513   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8514     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8515                                NumElems);
8516     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8517     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8518   }
8519
8520   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8521                             DAG.getConstant(MaskValue, MVT::i32));
8522   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8523 }
8524
8525 /// In vector type \p VT, return true if the element at index \p InputIdx
8526 /// falls on a different 128-bit lane than \p OutputIdx.
8527 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8528                                      unsigned OutputIdx) {
8529   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8530   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8531 }
8532
8533 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8534 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8535 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8536 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8537 /// zero.
8538 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8539                          SelectionDAG &DAG) {
8540   MVT VT = V1.getSimpleValueType();
8541   assert(VT.is128BitVector() || VT.is256BitVector());
8542
8543   MVT EltVT = VT.getVectorElementType();
8544   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8545   unsigned NumElts = VT.getVectorNumElements();
8546
8547   SmallVector<SDValue, 32> PshufbMask;
8548   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8549     int InputIdx = MaskVals[OutputIdx];
8550     unsigned InputByteIdx;
8551
8552     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8553       InputByteIdx = 0x80;
8554     else {
8555       // Cross lane is not allowed.
8556       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8557         return SDValue();
8558       InputByteIdx = InputIdx * EltSizeInBytes;
8559       // Index is an byte offset within the 128-bit lane.
8560       InputByteIdx &= 0xf;
8561     }
8562
8563     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8564       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8565       if (InputByteIdx != 0x80)
8566         ++InputByteIdx;
8567     }
8568   }
8569
8570   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8571   if (ShufVT != VT)
8572     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8573   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8574                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8575 }
8576
8577 // v8i16 shuffles - Prefer shuffles in the following order:
8578 // 1. [all]   pshuflw, pshufhw, optional move
8579 // 2. [ssse3] 1 x pshufb
8580 // 3. [ssse3] 2 x pshufb + 1 x por
8581 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8582 static SDValue
8583 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8584                          SelectionDAG &DAG) {
8585   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8586   SDValue V1 = SVOp->getOperand(0);
8587   SDValue V2 = SVOp->getOperand(1);
8588   SDLoc dl(SVOp);
8589   SmallVector<int, 8> MaskVals;
8590
8591   // Determine if more than 1 of the words in each of the low and high quadwords
8592   // of the result come from the same quadword of one of the two inputs.  Undef
8593   // mask values count as coming from any quadword, for better codegen.
8594   //
8595   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8596   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8597   unsigned LoQuad[] = { 0, 0, 0, 0 };
8598   unsigned HiQuad[] = { 0, 0, 0, 0 };
8599   // Indices of quads used.
8600   std::bitset<4> InputQuads;
8601   for (unsigned i = 0; i < 8; ++i) {
8602     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8603     int EltIdx = SVOp->getMaskElt(i);
8604     MaskVals.push_back(EltIdx);
8605     if (EltIdx < 0) {
8606       ++Quad[0];
8607       ++Quad[1];
8608       ++Quad[2];
8609       ++Quad[3];
8610       continue;
8611     }
8612     ++Quad[EltIdx / 4];
8613     InputQuads.set(EltIdx / 4);
8614   }
8615
8616   int BestLoQuad = -1;
8617   unsigned MaxQuad = 1;
8618   for (unsigned i = 0; i < 4; ++i) {
8619     if (LoQuad[i] > MaxQuad) {
8620       BestLoQuad = i;
8621       MaxQuad = LoQuad[i];
8622     }
8623   }
8624
8625   int BestHiQuad = -1;
8626   MaxQuad = 1;
8627   for (unsigned i = 0; i < 4; ++i) {
8628     if (HiQuad[i] > MaxQuad) {
8629       BestHiQuad = i;
8630       MaxQuad = HiQuad[i];
8631     }
8632   }
8633
8634   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8635   // of the two input vectors, shuffle them into one input vector so only a
8636   // single pshufb instruction is necessary. If there are more than 2 input
8637   // quads, disable the next transformation since it does not help SSSE3.
8638   bool V1Used = InputQuads[0] || InputQuads[1];
8639   bool V2Used = InputQuads[2] || InputQuads[3];
8640   if (Subtarget->hasSSSE3()) {
8641     if (InputQuads.count() == 2 && V1Used && V2Used) {
8642       BestLoQuad = InputQuads[0] ? 0 : 1;
8643       BestHiQuad = InputQuads[2] ? 2 : 3;
8644     }
8645     if (InputQuads.count() > 2) {
8646       BestLoQuad = -1;
8647       BestHiQuad = -1;
8648     }
8649   }
8650
8651   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8652   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8653   // words from all 4 input quadwords.
8654   SDValue NewV;
8655   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8656     int MaskV[] = {
8657       BestLoQuad < 0 ? 0 : BestLoQuad,
8658       BestHiQuad < 0 ? 1 : BestHiQuad
8659     };
8660     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8661                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8662                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8663     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8664
8665     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8666     // source words for the shuffle, to aid later transformations.
8667     bool AllWordsInNewV = true;
8668     bool InOrder[2] = { true, true };
8669     for (unsigned i = 0; i != 8; ++i) {
8670       int idx = MaskVals[i];
8671       if (idx != (int)i)
8672         InOrder[i/4] = false;
8673       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8674         continue;
8675       AllWordsInNewV = false;
8676       break;
8677     }
8678
8679     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8680     if (AllWordsInNewV) {
8681       for (int i = 0; i != 8; ++i) {
8682         int idx = MaskVals[i];
8683         if (idx < 0)
8684           continue;
8685         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8686         if ((idx != i) && idx < 4)
8687           pshufhw = false;
8688         if ((idx != i) && idx > 3)
8689           pshuflw = false;
8690       }
8691       V1 = NewV;
8692       V2Used = false;
8693       BestLoQuad = 0;
8694       BestHiQuad = 1;
8695     }
8696
8697     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8698     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8699     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8700       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8701       unsigned TargetMask = 0;
8702       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8703                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8704       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8705       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8706                              getShufflePSHUFLWImmediate(SVOp);
8707       V1 = NewV.getOperand(0);
8708       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8709     }
8710   }
8711
8712   // Promote splats to a larger type which usually leads to more efficient code.
8713   // FIXME: Is this true if pshufb is available?
8714   if (SVOp->isSplat())
8715     return PromoteSplat(SVOp, DAG);
8716
8717   // If we have SSSE3, and all words of the result are from 1 input vector,
8718   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8719   // is present, fall back to case 4.
8720   if (Subtarget->hasSSSE3()) {
8721     SmallVector<SDValue,16> pshufbMask;
8722
8723     // If we have elements from both input vectors, set the high bit of the
8724     // shuffle mask element to zero out elements that come from V2 in the V1
8725     // mask, and elements that come from V1 in the V2 mask, so that the two
8726     // results can be OR'd together.
8727     bool TwoInputs = V1Used && V2Used;
8728     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8729     if (!TwoInputs)
8730       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8731
8732     // Calculate the shuffle mask for the second input, shuffle it, and
8733     // OR it with the first shuffled input.
8734     CommuteVectorShuffleMask(MaskVals, 8);
8735     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8736     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8737     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8738   }
8739
8740   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8741   // and update MaskVals with new element order.
8742   std::bitset<8> InOrder;
8743   if (BestLoQuad >= 0) {
8744     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8745     for (int i = 0; i != 4; ++i) {
8746       int idx = MaskVals[i];
8747       if (idx < 0) {
8748         InOrder.set(i);
8749       } else if ((idx / 4) == BestLoQuad) {
8750         MaskV[i] = idx & 3;
8751         InOrder.set(i);
8752       }
8753     }
8754     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8755                                 &MaskV[0]);
8756
8757     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8758       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8759       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8760                                   NewV.getOperand(0),
8761                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8762     }
8763   }
8764
8765   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8766   // and update MaskVals with the new element order.
8767   if (BestHiQuad >= 0) {
8768     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8769     for (unsigned i = 4; i != 8; ++i) {
8770       int idx = MaskVals[i];
8771       if (idx < 0) {
8772         InOrder.set(i);
8773       } else if ((idx / 4) == BestHiQuad) {
8774         MaskV[i] = (idx & 3) + 4;
8775         InOrder.set(i);
8776       }
8777     }
8778     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8779                                 &MaskV[0]);
8780
8781     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8782       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8783       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8784                                   NewV.getOperand(0),
8785                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8786     }
8787   }
8788
8789   // In case BestHi & BestLo were both -1, which means each quadword has a word
8790   // from each of the four input quadwords, calculate the InOrder bitvector now
8791   // before falling through to the insert/extract cleanup.
8792   if (BestLoQuad == -1 && BestHiQuad == -1) {
8793     NewV = V1;
8794     for (int i = 0; i != 8; ++i)
8795       if (MaskVals[i] < 0 || MaskVals[i] == i)
8796         InOrder.set(i);
8797   }
8798
8799   // The other elements are put in the right place using pextrw and pinsrw.
8800   for (unsigned i = 0; i != 8; ++i) {
8801     if (InOrder[i])
8802       continue;
8803     int EltIdx = MaskVals[i];
8804     if (EltIdx < 0)
8805       continue;
8806     SDValue ExtOp = (EltIdx < 8) ?
8807       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8808                   DAG.getIntPtrConstant(EltIdx)) :
8809       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8810                   DAG.getIntPtrConstant(EltIdx - 8));
8811     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8812                        DAG.getIntPtrConstant(i));
8813   }
8814   return NewV;
8815 }
8816
8817 /// \brief v16i16 shuffles
8818 ///
8819 /// FIXME: We only support generation of a single pshufb currently.  We can
8820 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8821 /// well (e.g 2 x pshufb + 1 x por).
8822 static SDValue
8823 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8824   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8825   SDValue V1 = SVOp->getOperand(0);
8826   SDValue V2 = SVOp->getOperand(1);
8827   SDLoc dl(SVOp);
8828
8829   if (V2.getOpcode() != ISD::UNDEF)
8830     return SDValue();
8831
8832   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8833   return getPSHUFB(MaskVals, V1, dl, DAG);
8834 }
8835
8836 // v16i8 shuffles - Prefer shuffles in the following order:
8837 // 1. [ssse3] 1 x pshufb
8838 // 2. [ssse3] 2 x pshufb + 1 x por
8839 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8840 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8841                                         const X86Subtarget* Subtarget,
8842                                         SelectionDAG &DAG) {
8843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8844   SDValue V1 = SVOp->getOperand(0);
8845   SDValue V2 = SVOp->getOperand(1);
8846   SDLoc dl(SVOp);
8847   ArrayRef<int> MaskVals = SVOp->getMask();
8848
8849   // Promote splats to a larger type which usually leads to more efficient code.
8850   // FIXME: Is this true if pshufb is available?
8851   if (SVOp->isSplat())
8852     return PromoteSplat(SVOp, DAG);
8853
8854   // If we have SSSE3, case 1 is generated when all result bytes come from
8855   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8856   // present, fall back to case 3.
8857
8858   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8859   if (Subtarget->hasSSSE3()) {
8860     SmallVector<SDValue,16> pshufbMask;
8861
8862     // If all result elements are from one input vector, then only translate
8863     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8864     //
8865     // Otherwise, we have elements from both input vectors, and must zero out
8866     // elements that come from V2 in the first mask, and V1 in the second mask
8867     // so that we can OR them together.
8868     for (unsigned i = 0; i != 16; ++i) {
8869       int EltIdx = MaskVals[i];
8870       if (EltIdx < 0 || EltIdx >= 16)
8871         EltIdx = 0x80;
8872       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8873     }
8874     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8875                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8876                                  MVT::v16i8, pshufbMask));
8877
8878     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8879     // the 2nd operand if it's undefined or zero.
8880     if (V2.getOpcode() == ISD::UNDEF ||
8881         ISD::isBuildVectorAllZeros(V2.getNode()))
8882       return V1;
8883
8884     // Calculate the shuffle mask for the second input, shuffle it, and
8885     // OR it with the first shuffled input.
8886     pshufbMask.clear();
8887     for (unsigned i = 0; i != 16; ++i) {
8888       int EltIdx = MaskVals[i];
8889       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8890       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8891     }
8892     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8893                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8894                                  MVT::v16i8, pshufbMask));
8895     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8896   }
8897
8898   // No SSSE3 - Calculate in place words and then fix all out of place words
8899   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8900   // the 16 different words that comprise the two doublequadword input vectors.
8901   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8902   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8903   SDValue NewV = V1;
8904   for (int i = 0; i != 8; ++i) {
8905     int Elt0 = MaskVals[i*2];
8906     int Elt1 = MaskVals[i*2+1];
8907
8908     // This word of the result is all undef, skip it.
8909     if (Elt0 < 0 && Elt1 < 0)
8910       continue;
8911
8912     // This word of the result is already in the correct place, skip it.
8913     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8914       continue;
8915
8916     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8917     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8918     SDValue InsElt;
8919
8920     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8921     // using a single extract together, load it and store it.
8922     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8923       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8924                            DAG.getIntPtrConstant(Elt1 / 2));
8925       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8926                         DAG.getIntPtrConstant(i));
8927       continue;
8928     }
8929
8930     // If Elt1 is defined, extract it from the appropriate source.  If the
8931     // source byte is not also odd, shift the extracted word left 8 bits
8932     // otherwise clear the bottom 8 bits if we need to do an or.
8933     if (Elt1 >= 0) {
8934       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8935                            DAG.getIntPtrConstant(Elt1 / 2));
8936       if ((Elt1 & 1) == 0)
8937         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8938                              DAG.getConstant(8,
8939                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8940       else if (Elt0 >= 0)
8941         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8942                              DAG.getConstant(0xFF00, MVT::i16));
8943     }
8944     // If Elt0 is defined, extract it from the appropriate source.  If the
8945     // source byte is not also even, shift the extracted word right 8 bits. If
8946     // Elt1 was also defined, OR the extracted values together before
8947     // inserting them in the result.
8948     if (Elt0 >= 0) {
8949       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8950                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8951       if ((Elt0 & 1) != 0)
8952         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8953                               DAG.getConstant(8,
8954                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8955       else if (Elt1 >= 0)
8956         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8957                              DAG.getConstant(0x00FF, MVT::i16));
8958       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8959                          : InsElt0;
8960     }
8961     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8962                        DAG.getIntPtrConstant(i));
8963   }
8964   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8965 }
8966
8967 // v32i8 shuffles - Translate to VPSHUFB if possible.
8968 static
8969 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8970                                  const X86Subtarget *Subtarget,
8971                                  SelectionDAG &DAG) {
8972   MVT VT = SVOp->getSimpleValueType(0);
8973   SDValue V1 = SVOp->getOperand(0);
8974   SDValue V2 = SVOp->getOperand(1);
8975   SDLoc dl(SVOp);
8976   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8977
8978   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8979   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8980   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8981
8982   // VPSHUFB may be generated if
8983   // (1) one of input vector is undefined or zeroinitializer.
8984   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8985   // And (2) the mask indexes don't cross the 128-bit lane.
8986   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8987       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8988     return SDValue();
8989
8990   if (V1IsAllZero && !V2IsAllZero) {
8991     CommuteVectorShuffleMask(MaskVals, 32);
8992     V1 = V2;
8993   }
8994   return getPSHUFB(MaskVals, V1, dl, DAG);
8995 }
8996
8997 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8998 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8999 /// done when every pair / quad of shuffle mask elements point to elements in
9000 /// the right sequence. e.g.
9001 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9002 static
9003 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9004                                  SelectionDAG &DAG) {
9005   MVT VT = SVOp->getSimpleValueType(0);
9006   SDLoc dl(SVOp);
9007   unsigned NumElems = VT.getVectorNumElements();
9008   MVT NewVT;
9009   unsigned Scale;
9010   switch (VT.SimpleTy) {
9011   default: llvm_unreachable("Unexpected!");
9012   case MVT::v2i64:
9013   case MVT::v2f64:
9014            return SDValue(SVOp, 0);
9015   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
9016   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
9017   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
9018   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
9019   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9020   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
9021   }
9022
9023   SmallVector<int, 8> MaskVec;
9024   for (unsigned i = 0; i != NumElems; i += Scale) {
9025     int StartIdx = -1;
9026     for (unsigned j = 0; j != Scale; ++j) {
9027       int EltIdx = SVOp->getMaskElt(i+j);
9028       if (EltIdx < 0)
9029         continue;
9030       if (StartIdx < 0)
9031         StartIdx = (EltIdx / Scale);
9032       if (EltIdx != (int)(StartIdx*Scale + j))
9033         return SDValue();
9034     }
9035     MaskVec.push_back(StartIdx);
9036   }
9037
9038   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9039   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9040   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9041 }
9042
9043 /// getVZextMovL - Return a zero-extending vector move low node.
9044 ///
9045 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9046                             SDValue SrcOp, SelectionDAG &DAG,
9047                             const X86Subtarget *Subtarget, SDLoc dl) {
9048   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9049     LoadSDNode *LD = nullptr;
9050     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9051       LD = dyn_cast<LoadSDNode>(SrcOp);
9052     if (!LD) {
9053       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9054       // instead.
9055       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9056       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9057           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9058           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9059           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9060         // PR2108
9061         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9062         return DAG.getNode(ISD::BITCAST, dl, VT,
9063                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9064                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9065                                                    OpVT,
9066                                                    SrcOp.getOperand(0)
9067                                                           .getOperand(0))));
9068       }
9069     }
9070   }
9071
9072   return DAG.getNode(ISD::BITCAST, dl, VT,
9073                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9074                                  DAG.getNode(ISD::BITCAST, dl,
9075                                              OpVT, SrcOp)));
9076 }
9077
9078 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9079 /// which could not be matched by any known target speficic shuffle
9080 static SDValue
9081 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9082
9083   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9084   if (NewOp.getNode())
9085     return NewOp;
9086
9087   MVT VT = SVOp->getSimpleValueType(0);
9088
9089   unsigned NumElems = VT.getVectorNumElements();
9090   unsigned NumLaneElems = NumElems / 2;
9091
9092   SDLoc dl(SVOp);
9093   MVT EltVT = VT.getVectorElementType();
9094   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9095   SDValue Output[2];
9096
9097   SmallVector<int, 16> Mask;
9098   for (unsigned l = 0; l < 2; ++l) {
9099     // Build a shuffle mask for the output, discovering on the fly which
9100     // input vectors to use as shuffle operands (recorded in InputUsed).
9101     // If building a suitable shuffle vector proves too hard, then bail
9102     // out with UseBuildVector set.
9103     bool UseBuildVector = false;
9104     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9105     unsigned LaneStart = l * NumLaneElems;
9106     for (unsigned i = 0; i != NumLaneElems; ++i) {
9107       // The mask element.  This indexes into the input.
9108       int Idx = SVOp->getMaskElt(i+LaneStart);
9109       if (Idx < 0) {
9110         // the mask element does not index into any input vector.
9111         Mask.push_back(-1);
9112         continue;
9113       }
9114
9115       // The input vector this mask element indexes into.
9116       int Input = Idx / NumLaneElems;
9117
9118       // Turn the index into an offset from the start of the input vector.
9119       Idx -= Input * NumLaneElems;
9120
9121       // Find or create a shuffle vector operand to hold this input.
9122       unsigned OpNo;
9123       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9124         if (InputUsed[OpNo] == Input)
9125           // This input vector is already an operand.
9126           break;
9127         if (InputUsed[OpNo] < 0) {
9128           // Create a new operand for this input vector.
9129           InputUsed[OpNo] = Input;
9130           break;
9131         }
9132       }
9133
9134       if (OpNo >= array_lengthof(InputUsed)) {
9135         // More than two input vectors used!  Give up on trying to create a
9136         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9137         UseBuildVector = true;
9138         break;
9139       }
9140
9141       // Add the mask index for the new shuffle vector.
9142       Mask.push_back(Idx + OpNo * NumLaneElems);
9143     }
9144
9145     if (UseBuildVector) {
9146       SmallVector<SDValue, 16> SVOps;
9147       for (unsigned i = 0; i != NumLaneElems; ++i) {
9148         // The mask element.  This indexes into the input.
9149         int Idx = SVOp->getMaskElt(i+LaneStart);
9150         if (Idx < 0) {
9151           SVOps.push_back(DAG.getUNDEF(EltVT));
9152           continue;
9153         }
9154
9155         // The input vector this mask element indexes into.
9156         int Input = Idx / NumElems;
9157
9158         // Turn the index into an offset from the start of the input vector.
9159         Idx -= Input * NumElems;
9160
9161         // Extract the vector element by hand.
9162         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9163                                     SVOp->getOperand(Input),
9164                                     DAG.getIntPtrConstant(Idx)));
9165       }
9166
9167       // Construct the output using a BUILD_VECTOR.
9168       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9169     } else if (InputUsed[0] < 0) {
9170       // No input vectors were used! The result is undefined.
9171       Output[l] = DAG.getUNDEF(NVT);
9172     } else {
9173       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9174                                         (InputUsed[0] % 2) * NumLaneElems,
9175                                         DAG, dl);
9176       // If only one input was used, use an undefined vector for the other.
9177       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9178         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9179                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9180       // At least one input vector was used. Create a new shuffle vector.
9181       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9182     }
9183
9184     Mask.clear();
9185   }
9186
9187   // Concatenate the result back
9188   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9189 }
9190
9191 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9192 /// 4 elements, and match them with several different shuffle types.
9193 static SDValue
9194 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9195   SDValue V1 = SVOp->getOperand(0);
9196   SDValue V2 = SVOp->getOperand(1);
9197   SDLoc dl(SVOp);
9198   MVT VT = SVOp->getSimpleValueType(0);
9199
9200   assert(VT.is128BitVector() && "Unsupported vector size");
9201
9202   std::pair<int, int> Locs[4];
9203   int Mask1[] = { -1, -1, -1, -1 };
9204   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9205
9206   unsigned NumHi = 0;
9207   unsigned NumLo = 0;
9208   for (unsigned i = 0; i != 4; ++i) {
9209     int Idx = PermMask[i];
9210     if (Idx < 0) {
9211       Locs[i] = std::make_pair(-1, -1);
9212     } else {
9213       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9214       if (Idx < 4) {
9215         Locs[i] = std::make_pair(0, NumLo);
9216         Mask1[NumLo] = Idx;
9217         NumLo++;
9218       } else {
9219         Locs[i] = std::make_pair(1, NumHi);
9220         if (2+NumHi < 4)
9221           Mask1[2+NumHi] = Idx;
9222         NumHi++;
9223       }
9224     }
9225   }
9226
9227   if (NumLo <= 2 && NumHi <= 2) {
9228     // If no more than two elements come from either vector. This can be
9229     // implemented with two shuffles. First shuffle gather the elements.
9230     // The second shuffle, which takes the first shuffle as both of its
9231     // vector operands, put the elements into the right order.
9232     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9233
9234     int Mask2[] = { -1, -1, -1, -1 };
9235
9236     for (unsigned i = 0; i != 4; ++i)
9237       if (Locs[i].first != -1) {
9238         unsigned Idx = (i < 2) ? 0 : 4;
9239         Idx += Locs[i].first * 2 + Locs[i].second;
9240         Mask2[i] = Idx;
9241       }
9242
9243     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9244   }
9245
9246   if (NumLo == 3 || NumHi == 3) {
9247     // Otherwise, we must have three elements from one vector, call it X, and
9248     // one element from the other, call it Y.  First, use a shufps to build an
9249     // intermediate vector with the one element from Y and the element from X
9250     // that will be in the same half in the final destination (the indexes don't
9251     // matter). Then, use a shufps to build the final vector, taking the half
9252     // containing the element from Y from the intermediate, and the other half
9253     // from X.
9254     if (NumHi == 3) {
9255       // Normalize it so the 3 elements come from V1.
9256       CommuteVectorShuffleMask(PermMask, 4);
9257       std::swap(V1, V2);
9258     }
9259
9260     // Find the element from V2.
9261     unsigned HiIndex;
9262     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9263       int Val = PermMask[HiIndex];
9264       if (Val < 0)
9265         continue;
9266       if (Val >= 4)
9267         break;
9268     }
9269
9270     Mask1[0] = PermMask[HiIndex];
9271     Mask1[1] = -1;
9272     Mask1[2] = PermMask[HiIndex^1];
9273     Mask1[3] = -1;
9274     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9275
9276     if (HiIndex >= 2) {
9277       Mask1[0] = PermMask[0];
9278       Mask1[1] = PermMask[1];
9279       Mask1[2] = HiIndex & 1 ? 6 : 4;
9280       Mask1[3] = HiIndex & 1 ? 4 : 6;
9281       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9282     }
9283
9284     Mask1[0] = HiIndex & 1 ? 2 : 0;
9285     Mask1[1] = HiIndex & 1 ? 0 : 2;
9286     Mask1[2] = PermMask[2];
9287     Mask1[3] = PermMask[3];
9288     if (Mask1[2] >= 0)
9289       Mask1[2] += 4;
9290     if (Mask1[3] >= 0)
9291       Mask1[3] += 4;
9292     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9293   }
9294
9295   // Break it into (shuffle shuffle_hi, shuffle_lo).
9296   int LoMask[] = { -1, -1, -1, -1 };
9297   int HiMask[] = { -1, -1, -1, -1 };
9298
9299   int *MaskPtr = LoMask;
9300   unsigned MaskIdx = 0;
9301   unsigned LoIdx = 0;
9302   unsigned HiIdx = 2;
9303   for (unsigned i = 0; i != 4; ++i) {
9304     if (i == 2) {
9305       MaskPtr = HiMask;
9306       MaskIdx = 1;
9307       LoIdx = 0;
9308       HiIdx = 2;
9309     }
9310     int Idx = PermMask[i];
9311     if (Idx < 0) {
9312       Locs[i] = std::make_pair(-1, -1);
9313     } else if (Idx < 4) {
9314       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9315       MaskPtr[LoIdx] = Idx;
9316       LoIdx++;
9317     } else {
9318       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9319       MaskPtr[HiIdx] = Idx;
9320       HiIdx++;
9321     }
9322   }
9323
9324   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9325   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9326   int MaskOps[] = { -1, -1, -1, -1 };
9327   for (unsigned i = 0; i != 4; ++i)
9328     if (Locs[i].first != -1)
9329       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9330   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9331 }
9332
9333 static bool MayFoldVectorLoad(SDValue V) {
9334   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9335     V = V.getOperand(0);
9336
9337   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9338     V = V.getOperand(0);
9339   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9340       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9341     // BUILD_VECTOR (load), undef
9342     V = V.getOperand(0);
9343
9344   return MayFoldLoad(V);
9345 }
9346
9347 static
9348 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9349   MVT VT = Op.getSimpleValueType();
9350
9351   // Canonizalize to v2f64.
9352   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9353   return DAG.getNode(ISD::BITCAST, dl, VT,
9354                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9355                                           V1, DAG));
9356 }
9357
9358 static
9359 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9360                         bool HasSSE2) {
9361   SDValue V1 = Op.getOperand(0);
9362   SDValue V2 = Op.getOperand(1);
9363   MVT VT = Op.getSimpleValueType();
9364
9365   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9366
9367   if (HasSSE2 && VT == MVT::v2f64)
9368     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9369
9370   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9371   return DAG.getNode(ISD::BITCAST, dl, VT,
9372                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9373                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9374                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9375 }
9376
9377 static
9378 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9379   SDValue V1 = Op.getOperand(0);
9380   SDValue V2 = Op.getOperand(1);
9381   MVT VT = Op.getSimpleValueType();
9382
9383   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9384          "unsupported shuffle type");
9385
9386   if (V2.getOpcode() == ISD::UNDEF)
9387     V2 = V1;
9388
9389   // v4i32 or v4f32
9390   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9391 }
9392
9393 static
9394 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9395   SDValue V1 = Op.getOperand(0);
9396   SDValue V2 = Op.getOperand(1);
9397   MVT VT = Op.getSimpleValueType();
9398   unsigned NumElems = VT.getVectorNumElements();
9399
9400   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9401   // operand of these instructions is only memory, so check if there's a
9402   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9403   // same masks.
9404   bool CanFoldLoad = false;
9405
9406   // Trivial case, when V2 comes from a load.
9407   if (MayFoldVectorLoad(V2))
9408     CanFoldLoad = true;
9409
9410   // When V1 is a load, it can be folded later into a store in isel, example:
9411   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9412   //    turns into:
9413   //  (MOVLPSmr addr:$src1, VR128:$src2)
9414   // So, recognize this potential and also use MOVLPS or MOVLPD
9415   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9416     CanFoldLoad = true;
9417
9418   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9419   if (CanFoldLoad) {
9420     if (HasSSE2 && NumElems == 2)
9421       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9422
9423     if (NumElems == 4)
9424       // If we don't care about the second element, proceed to use movss.
9425       if (SVOp->getMaskElt(1) != -1)
9426         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9427   }
9428
9429   // movl and movlp will both match v2i64, but v2i64 is never matched by
9430   // movl earlier because we make it strict to avoid messing with the movlp load
9431   // folding logic (see the code above getMOVLP call). Match it here then,
9432   // this is horrible, but will stay like this until we move all shuffle
9433   // matching to x86 specific nodes. Note that for the 1st condition all
9434   // types are matched with movsd.
9435   if (HasSSE2) {
9436     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9437     // as to remove this logic from here, as much as possible
9438     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9439       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9440     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9441   }
9442
9443   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9444
9445   // Invert the operand order and use SHUFPS to match it.
9446   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9447                               getShuffleSHUFImmediate(SVOp), DAG);
9448 }
9449
9450 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9451                                          SelectionDAG &DAG) {
9452   SDLoc dl(Load);
9453   MVT VT = Load->getSimpleValueType(0);
9454   MVT EVT = VT.getVectorElementType();
9455   SDValue Addr = Load->getOperand(1);
9456   SDValue NewAddr = DAG.getNode(
9457       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9458       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9459
9460   SDValue NewLoad =
9461       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9462                   DAG.getMachineFunction().getMachineMemOperand(
9463                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9464   return NewLoad;
9465 }
9466
9467 // It is only safe to call this function if isINSERTPSMask is true for
9468 // this shufflevector mask.
9469 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9470                            SelectionDAG &DAG) {
9471   // Generate an insertps instruction when inserting an f32 from memory onto a
9472   // v4f32 or when copying a member from one v4f32 to another.
9473   // We also use it for transferring i32 from one register to another,
9474   // since it simply copies the same bits.
9475   // If we're transferring an i32 from memory to a specific element in a
9476   // register, we output a generic DAG that will match the PINSRD
9477   // instruction.
9478   MVT VT = SVOp->getSimpleValueType(0);
9479   MVT EVT = VT.getVectorElementType();
9480   SDValue V1 = SVOp->getOperand(0);
9481   SDValue V2 = SVOp->getOperand(1);
9482   auto Mask = SVOp->getMask();
9483   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9484          "unsupported vector type for insertps/pinsrd");
9485
9486   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9487   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9488   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9489
9490   SDValue From;
9491   SDValue To;
9492   unsigned DestIndex;
9493   if (FromV1 == 1) {
9494     From = V1;
9495     To = V2;
9496     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9497                 Mask.begin();
9498
9499     // If we have 1 element from each vector, we have to check if we're
9500     // changing V1's element's place. If so, we're done. Otherwise, we
9501     // should assume we're changing V2's element's place and behave
9502     // accordingly.
9503     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9504     assert(DestIndex <= INT32_MAX && "truncated destination index");
9505     if (FromV1 == FromV2 &&
9506         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9507       From = V2;
9508       To = V1;
9509       DestIndex =
9510           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9511     }
9512   } else {
9513     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9514            "More than one element from V1 and from V2, or no elements from one "
9515            "of the vectors. This case should not have returned true from "
9516            "isINSERTPSMask");
9517     From = V2;
9518     To = V1;
9519     DestIndex =
9520         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9521   }
9522
9523   // Get an index into the source vector in the range [0,4) (the mask is
9524   // in the range [0,8) because it can address V1 and V2)
9525   unsigned SrcIndex = Mask[DestIndex] % 4;
9526   if (MayFoldLoad(From)) {
9527     // Trivial case, when From comes from a load and is only used by the
9528     // shuffle. Make it use insertps from the vector that we need from that
9529     // load.
9530     SDValue NewLoad =
9531         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9532     if (!NewLoad.getNode())
9533       return SDValue();
9534
9535     if (EVT == MVT::f32) {
9536       // Create this as a scalar to vector to match the instruction pattern.
9537       SDValue LoadScalarToVector =
9538           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9539       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9540       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9541                          InsertpsMask);
9542     } else { // EVT == MVT::i32
9543       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9544       // instruction, to match the PINSRD instruction, which loads an i32 to a
9545       // certain vector element.
9546       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9547                          DAG.getConstant(DestIndex, MVT::i32));
9548     }
9549   }
9550
9551   // Vector-element-to-vector
9552   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9553   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9554 }
9555
9556 // Reduce a vector shuffle to zext.
9557 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9558                                     SelectionDAG &DAG) {
9559   // PMOVZX is only available from SSE41.
9560   if (!Subtarget->hasSSE41())
9561     return SDValue();
9562
9563   MVT VT = Op.getSimpleValueType();
9564
9565   // Only AVX2 support 256-bit vector integer extending.
9566   if (!Subtarget->hasInt256() && VT.is256BitVector())
9567     return SDValue();
9568
9569   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9570   SDLoc DL(Op);
9571   SDValue V1 = Op.getOperand(0);
9572   SDValue V2 = Op.getOperand(1);
9573   unsigned NumElems = VT.getVectorNumElements();
9574
9575   // Extending is an unary operation and the element type of the source vector
9576   // won't be equal to or larger than i64.
9577   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9578       VT.getVectorElementType() == MVT::i64)
9579     return SDValue();
9580
9581   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9582   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9583   while ((1U << Shift) < NumElems) {
9584     if (SVOp->getMaskElt(1U << Shift) == 1)
9585       break;
9586     Shift += 1;
9587     // The maximal ratio is 8, i.e. from i8 to i64.
9588     if (Shift > 3)
9589       return SDValue();
9590   }
9591
9592   // Check the shuffle mask.
9593   unsigned Mask = (1U << Shift) - 1;
9594   for (unsigned i = 0; i != NumElems; ++i) {
9595     int EltIdx = SVOp->getMaskElt(i);
9596     if ((i & Mask) != 0 && EltIdx != -1)
9597       return SDValue();
9598     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9599       return SDValue();
9600   }
9601
9602   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9603   MVT NeVT = MVT::getIntegerVT(NBits);
9604   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9605
9606   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9607     return SDValue();
9608
9609   // Simplify the operand as it's prepared to be fed into shuffle.
9610   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9611   if (V1.getOpcode() == ISD::BITCAST &&
9612       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9613       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9614       V1.getOperand(0).getOperand(0)
9615         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9616     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9617     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9618     ConstantSDNode *CIdx =
9619       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9620     // If it's foldable, i.e. normal load with single use, we will let code
9621     // selection to fold it. Otherwise, we will short the conversion sequence.
9622     if (CIdx && CIdx->getZExtValue() == 0 &&
9623         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9624       MVT FullVT = V.getSimpleValueType();
9625       MVT V1VT = V1.getSimpleValueType();
9626       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9627         // The "ext_vec_elt" node is wider than the result node.
9628         // In this case we should extract subvector from V.
9629         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9630         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9631         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9632                                         FullVT.getVectorNumElements()/Ratio);
9633         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9634                         DAG.getIntPtrConstant(0));
9635       }
9636       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9637     }
9638   }
9639
9640   return DAG.getNode(ISD::BITCAST, DL, VT,
9641                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9642 }
9643
9644 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9645                                       SelectionDAG &DAG) {
9646   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9647   MVT VT = Op.getSimpleValueType();
9648   SDLoc dl(Op);
9649   SDValue V1 = Op.getOperand(0);
9650   SDValue V2 = Op.getOperand(1);
9651
9652   if (isZeroShuffle(SVOp))
9653     return getZeroVector(VT, Subtarget, DAG, dl);
9654
9655   // Handle splat operations
9656   if (SVOp->isSplat()) {
9657     // Use vbroadcast whenever the splat comes from a foldable load
9658     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9659     if (Broadcast.getNode())
9660       return Broadcast;
9661   }
9662
9663   // Check integer expanding shuffles.
9664   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9665   if (NewOp.getNode())
9666     return NewOp;
9667
9668   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9669   // do it!
9670   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9671       VT == MVT::v32i8) {
9672     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9673     if (NewOp.getNode())
9674       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9675   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9676     // FIXME: Figure out a cleaner way to do this.
9677     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9678       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9679       if (NewOp.getNode()) {
9680         MVT NewVT = NewOp.getSimpleValueType();
9681         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9682                                NewVT, true, false))
9683           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9684                               dl);
9685       }
9686     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9687       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9688       if (NewOp.getNode()) {
9689         MVT NewVT = NewOp.getSimpleValueType();
9690         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9691           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9692                               dl);
9693       }
9694     }
9695   }
9696   return SDValue();
9697 }
9698
9699 SDValue
9700 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9701   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9702   SDValue V1 = Op.getOperand(0);
9703   SDValue V2 = Op.getOperand(1);
9704   MVT VT = Op.getSimpleValueType();
9705   SDLoc dl(Op);
9706   unsigned NumElems = VT.getVectorNumElements();
9707   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9708   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9709   bool V1IsSplat = false;
9710   bool V2IsSplat = false;
9711   bool HasSSE2 = Subtarget->hasSSE2();
9712   bool HasFp256    = Subtarget->hasFp256();
9713   bool HasInt256   = Subtarget->hasInt256();
9714   MachineFunction &MF = DAG.getMachineFunction();
9715   bool OptForSize = MF.getFunction()->getAttributes().
9716     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9717
9718   // Check if we should use the experimental vector shuffle lowering. If so,
9719   // delegate completely to that code path.
9720   if (ExperimentalVectorShuffleLowering)
9721     return lowerVectorShuffle(Op, Subtarget, DAG);
9722
9723   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9724
9725   if (V1IsUndef && V2IsUndef)
9726     return DAG.getUNDEF(VT);
9727
9728   // When we create a shuffle node we put the UNDEF node to second operand,
9729   // but in some cases the first operand may be transformed to UNDEF.
9730   // In this case we should just commute the node.
9731   if (V1IsUndef)
9732     return DAG.getCommutedVectorShuffle(*SVOp);
9733
9734   // Vector shuffle lowering takes 3 steps:
9735   //
9736   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9737   //    narrowing and commutation of operands should be handled.
9738   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9739   //    shuffle nodes.
9740   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9741   //    so the shuffle can be broken into other shuffles and the legalizer can
9742   //    try the lowering again.
9743   //
9744   // The general idea is that no vector_shuffle operation should be left to
9745   // be matched during isel, all of them must be converted to a target specific
9746   // node here.
9747
9748   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9749   // narrowing and commutation of operands should be handled. The actual code
9750   // doesn't include all of those, work in progress...
9751   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9752   if (NewOp.getNode())
9753     return NewOp;
9754
9755   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9756
9757   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9758   // unpckh_undef). Only use pshufd if speed is more important than size.
9759   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9760     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9761   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9762     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9763
9764   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9765       V2IsUndef && MayFoldVectorLoad(V1))
9766     return getMOVDDup(Op, dl, V1, DAG);
9767
9768   if (isMOVHLPS_v_undef_Mask(M, VT))
9769     return getMOVHighToLow(Op, dl, DAG);
9770
9771   // Use to match splats
9772   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9773       (VT == MVT::v2f64 || VT == MVT::v2i64))
9774     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9775
9776   if (isPSHUFDMask(M, VT)) {
9777     // The actual implementation will match the mask in the if above and then
9778     // during isel it can match several different instructions, not only pshufd
9779     // as its name says, sad but true, emulate the behavior for now...
9780     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9781       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9782
9783     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9784
9785     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9786       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9787
9788     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9789       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9790                                   DAG);
9791
9792     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9793                                 TargetMask, DAG);
9794   }
9795
9796   if (isPALIGNRMask(M, VT, Subtarget))
9797     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9798                                 getShufflePALIGNRImmediate(SVOp),
9799                                 DAG);
9800
9801   if (isVALIGNMask(M, VT, Subtarget))
9802     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
9803                                 getShuffleVALIGNImmediate(SVOp),
9804                                 DAG);
9805
9806   // Check if this can be converted into a logical shift.
9807   bool isLeft = false;
9808   unsigned ShAmt = 0;
9809   SDValue ShVal;
9810   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9811   if (isShift && ShVal.hasOneUse()) {
9812     // If the shifted value has multiple uses, it may be cheaper to use
9813     // v_set0 + movlhps or movhlps, etc.
9814     MVT EltVT = VT.getVectorElementType();
9815     ShAmt *= EltVT.getSizeInBits();
9816     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9817   }
9818
9819   if (isMOVLMask(M, VT)) {
9820     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9821       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9822     if (!isMOVLPMask(M, VT)) {
9823       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9824         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9825
9826       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9827         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9828     }
9829   }
9830
9831   // FIXME: fold these into legal mask.
9832   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9833     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9834
9835   if (isMOVHLPSMask(M, VT))
9836     return getMOVHighToLow(Op, dl, DAG);
9837
9838   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9839     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9840
9841   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9842     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9843
9844   if (isMOVLPMask(M, VT))
9845     return getMOVLP(Op, dl, DAG, HasSSE2);
9846
9847   if (ShouldXformToMOVHLPS(M, VT) ||
9848       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9849     return DAG.getCommutedVectorShuffle(*SVOp);
9850
9851   if (isShift) {
9852     // No better options. Use a vshldq / vsrldq.
9853     MVT EltVT = VT.getVectorElementType();
9854     ShAmt *= EltVT.getSizeInBits();
9855     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9856   }
9857
9858   bool Commuted = false;
9859   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9860   // 1,1,1,1 -> v8i16 though.
9861   BitVector UndefElements;
9862   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9863     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9864       V1IsSplat = true;
9865   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9866     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9867       V2IsSplat = true;
9868
9869   // Canonicalize the splat or undef, if present, to be on the RHS.
9870   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9871     CommuteVectorShuffleMask(M, NumElems);
9872     std::swap(V1, V2);
9873     std::swap(V1IsSplat, V2IsSplat);
9874     Commuted = true;
9875   }
9876
9877   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9878     // Shuffling low element of v1 into undef, just return v1.
9879     if (V2IsUndef)
9880       return V1;
9881     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9882     // the instruction selector will not match, so get a canonical MOVL with
9883     // swapped operands to undo the commute.
9884     return getMOVL(DAG, dl, VT, V2, V1);
9885   }
9886
9887   if (isUNPCKLMask(M, VT, HasInt256))
9888     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9889
9890   if (isUNPCKHMask(M, VT, HasInt256))
9891     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9892
9893   if (V2IsSplat) {
9894     // Normalize mask so all entries that point to V2 points to its first
9895     // element then try to match unpck{h|l} again. If match, return a
9896     // new vector_shuffle with the corrected mask.p
9897     SmallVector<int, 8> NewMask(M.begin(), M.end());
9898     NormalizeMask(NewMask, NumElems);
9899     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9900       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9901     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9902       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9903   }
9904
9905   if (Commuted) {
9906     // Commute is back and try unpck* again.
9907     // FIXME: this seems wrong.
9908     CommuteVectorShuffleMask(M, NumElems);
9909     std::swap(V1, V2);
9910     std::swap(V1IsSplat, V2IsSplat);
9911
9912     if (isUNPCKLMask(M, VT, HasInt256))
9913       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9914
9915     if (isUNPCKHMask(M, VT, HasInt256))
9916       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9917   }
9918
9919   // Normalize the node to match x86 shuffle ops if needed
9920   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9921     return DAG.getCommutedVectorShuffle(*SVOp);
9922
9923   // The checks below are all present in isShuffleMaskLegal, but they are
9924   // inlined here right now to enable us to directly emit target specific
9925   // nodes, and remove one by one until they don't return Op anymore.
9926
9927   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9928       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9929     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9930       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9931   }
9932
9933   if (isPSHUFHWMask(M, VT, HasInt256))
9934     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9935                                 getShufflePSHUFHWImmediate(SVOp),
9936                                 DAG);
9937
9938   if (isPSHUFLWMask(M, VT, HasInt256))
9939     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9940                                 getShufflePSHUFLWImmediate(SVOp),
9941                                 DAG);
9942
9943   unsigned MaskValue;
9944   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9945                   &MaskValue))
9946     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9947
9948   if (isSHUFPMask(M, VT))
9949     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9950                                 getShuffleSHUFImmediate(SVOp), DAG);
9951
9952   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9953     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9954   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9955     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9956
9957   //===--------------------------------------------------------------------===//
9958   // Generate target specific nodes for 128 or 256-bit shuffles only
9959   // supported in the AVX instruction set.
9960   //
9961
9962   // Handle VMOVDDUPY permutations
9963   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9964     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9965
9966   // Handle VPERMILPS/D* permutations
9967   if (isVPERMILPMask(M, VT)) {
9968     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9969       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9970                                   getShuffleSHUFImmediate(SVOp), DAG);
9971     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9972                                 getShuffleSHUFImmediate(SVOp), DAG);
9973   }
9974
9975   unsigned Idx;
9976   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9977     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9978                               Idx*(NumElems/2), DAG, dl);
9979
9980   // Handle VPERM2F128/VPERM2I128 permutations
9981   if (isVPERM2X128Mask(M, VT, HasFp256))
9982     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9983                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9984
9985   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9986     return getINSERTPS(SVOp, dl, DAG);
9987
9988   unsigned Imm8;
9989   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9990     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9991
9992   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9993       VT.is512BitVector()) {
9994     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9995     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9996     SmallVector<SDValue, 16> permclMask;
9997     for (unsigned i = 0; i != NumElems; ++i) {
9998       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9999     }
10000
10001     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10002     if (V2IsUndef)
10003       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10004       return DAG.getNode(X86ISD::VPERMV, dl, VT,
10005                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10006     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10007                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10008   }
10009
10010   //===--------------------------------------------------------------------===//
10011   // Since no target specific shuffle was selected for this generic one,
10012   // lower it into other known shuffles. FIXME: this isn't true yet, but
10013   // this is the plan.
10014   //
10015
10016   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10017   if (VT == MVT::v8i16) {
10018     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10019     if (NewOp.getNode())
10020       return NewOp;
10021   }
10022
10023   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10024     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10025     if (NewOp.getNode())
10026       return NewOp;
10027   }
10028
10029   if (VT == MVT::v16i8) {
10030     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10031     if (NewOp.getNode())
10032       return NewOp;
10033   }
10034
10035   if (VT == MVT::v32i8) {
10036     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10037     if (NewOp.getNode())
10038       return NewOp;
10039   }
10040
10041   // Handle all 128-bit wide vectors with 4 elements, and match them with
10042   // several different shuffle types.
10043   if (NumElems == 4 && VT.is128BitVector())
10044     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10045
10046   // Handle general 256-bit shuffles
10047   if (VT.is256BitVector())
10048     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10049
10050   return SDValue();
10051 }
10052
10053 // This function assumes its argument is a BUILD_VECTOR of constants or
10054 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10055 // true.
10056 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10057                                     unsigned &MaskValue) {
10058   MaskValue = 0;
10059   unsigned NumElems = BuildVector->getNumOperands();
10060   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10061   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10062   unsigned NumElemsInLane = NumElems / NumLanes;
10063
10064   // Blend for v16i16 should be symetric for the both lanes.
10065   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10066     SDValue EltCond = BuildVector->getOperand(i);
10067     SDValue SndLaneEltCond =
10068         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10069
10070     int Lane1Cond = -1, Lane2Cond = -1;
10071     if (isa<ConstantSDNode>(EltCond))
10072       Lane1Cond = !isZero(EltCond);
10073     if (isa<ConstantSDNode>(SndLaneEltCond))
10074       Lane2Cond = !isZero(SndLaneEltCond);
10075
10076     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10077       // Lane1Cond != 0, means we want the first argument.
10078       // Lane1Cond == 0, means we want the second argument.
10079       // The encoding of this argument is 0 for the first argument, 1
10080       // for the second. Therefore, invert the condition.
10081       MaskValue |= !Lane1Cond << i;
10082     else if (Lane1Cond < 0)
10083       MaskValue |= !Lane2Cond << i;
10084     else
10085       return false;
10086   }
10087   return true;
10088 }
10089
10090 // Try to lower a vselect node into a simple blend instruction.
10091 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10092                                    SelectionDAG &DAG) {
10093   SDValue Cond = Op.getOperand(0);
10094   SDValue LHS = Op.getOperand(1);
10095   SDValue RHS = Op.getOperand(2);
10096   SDLoc dl(Op);
10097   MVT VT = Op.getSimpleValueType();
10098   MVT EltVT = VT.getVectorElementType();
10099   unsigned NumElems = VT.getVectorNumElements();
10100
10101   // There is no blend with immediate in AVX-512.
10102   if (VT.is512BitVector())
10103     return SDValue();
10104
10105   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10106     return SDValue();
10107   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10108     return SDValue();
10109
10110   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10111     return SDValue();
10112
10113   // Check the mask for BLEND and build the value.
10114   unsigned MaskValue = 0;
10115   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10116     return SDValue();
10117
10118   // Convert i32 vectors to floating point if it is not AVX2.
10119   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10120   MVT BlendVT = VT;
10121   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10122     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10123                                NumElems);
10124     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10125     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10126   }
10127
10128   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10129                             DAG.getConstant(MaskValue, MVT::i32));
10130   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10131 }
10132
10133 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10134   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10135   if (BlendOp.getNode())
10136     return BlendOp;
10137
10138   // Some types for vselect were previously set to Expand, not Legal or
10139   // Custom. Return an empty SDValue so we fall-through to Expand, after
10140   // the Custom lowering phase.
10141   MVT VT = Op.getSimpleValueType();
10142   switch (VT.SimpleTy) {
10143   default:
10144     break;
10145   case MVT::v8i16:
10146   case MVT::v16i16:
10147     return SDValue();
10148   }
10149
10150   // We couldn't create a "Blend with immediate" node.
10151   // This node should still be legal, but we'll have to emit a blendv*
10152   // instruction.
10153   return Op;
10154 }
10155
10156 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10157   MVT VT = Op.getSimpleValueType();
10158   SDLoc dl(Op);
10159
10160   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10161     return SDValue();
10162
10163   if (VT.getSizeInBits() == 8) {
10164     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10165                                   Op.getOperand(0), Op.getOperand(1));
10166     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10167                                   DAG.getValueType(VT));
10168     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10169   }
10170
10171   if (VT.getSizeInBits() == 16) {
10172     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10173     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10174     if (Idx == 0)
10175       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10176                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10177                                      DAG.getNode(ISD::BITCAST, dl,
10178                                                  MVT::v4i32,
10179                                                  Op.getOperand(0)),
10180                                      Op.getOperand(1)));
10181     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10182                                   Op.getOperand(0), Op.getOperand(1));
10183     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10184                                   DAG.getValueType(VT));
10185     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10186   }
10187
10188   if (VT == MVT::f32) {
10189     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10190     // the result back to FR32 register. It's only worth matching if the
10191     // result has a single use which is a store or a bitcast to i32.  And in
10192     // the case of a store, it's not worth it if the index is a constant 0,
10193     // because a MOVSSmr can be used instead, which is smaller and faster.
10194     if (!Op.hasOneUse())
10195       return SDValue();
10196     SDNode *User = *Op.getNode()->use_begin();
10197     if ((User->getOpcode() != ISD::STORE ||
10198          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10199           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10200         (User->getOpcode() != ISD::BITCAST ||
10201          User->getValueType(0) != MVT::i32))
10202       return SDValue();
10203     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10204                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10205                                               Op.getOperand(0)),
10206                                               Op.getOperand(1));
10207     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10208   }
10209
10210   if (VT == MVT::i32 || VT == MVT::i64) {
10211     // ExtractPS/pextrq works with constant index.
10212     if (isa<ConstantSDNode>(Op.getOperand(1)))
10213       return Op;
10214   }
10215   return SDValue();
10216 }
10217
10218 /// Extract one bit from mask vector, like v16i1 or v8i1.
10219 /// AVX-512 feature.
10220 SDValue
10221 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10222   SDValue Vec = Op.getOperand(0);
10223   SDLoc dl(Vec);
10224   MVT VecVT = Vec.getSimpleValueType();
10225   SDValue Idx = Op.getOperand(1);
10226   MVT EltVT = Op.getSimpleValueType();
10227
10228   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10229
10230   // variable index can't be handled in mask registers,
10231   // extend vector to VR512
10232   if (!isa<ConstantSDNode>(Idx)) {
10233     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10234     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10235     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10236                               ExtVT.getVectorElementType(), Ext, Idx);
10237     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10238   }
10239
10240   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10241   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10242   unsigned MaxSift = rc->getSize()*8 - 1;
10243   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10244                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10245   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10246                     DAG.getConstant(MaxSift, MVT::i8));
10247   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10248                        DAG.getIntPtrConstant(0));
10249 }
10250
10251 SDValue
10252 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10253                                            SelectionDAG &DAG) const {
10254   SDLoc dl(Op);
10255   SDValue Vec = Op.getOperand(0);
10256   MVT VecVT = Vec.getSimpleValueType();
10257   SDValue Idx = Op.getOperand(1);
10258
10259   if (Op.getSimpleValueType() == MVT::i1)
10260     return ExtractBitFromMaskVector(Op, DAG);
10261
10262   if (!isa<ConstantSDNode>(Idx)) {
10263     if (VecVT.is512BitVector() ||
10264         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10265          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10266
10267       MVT MaskEltVT =
10268         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10269       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10270                                     MaskEltVT.getSizeInBits());
10271
10272       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10273       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10274                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10275                                 Idx, DAG.getConstant(0, getPointerTy()));
10276       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10277       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10278                         Perm, DAG.getConstant(0, getPointerTy()));
10279     }
10280     return SDValue();
10281   }
10282
10283   // If this is a 256-bit vector result, first extract the 128-bit vector and
10284   // then extract the element from the 128-bit vector.
10285   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10286
10287     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10288     // Get the 128-bit vector.
10289     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10290     MVT EltVT = VecVT.getVectorElementType();
10291
10292     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10293
10294     //if (IdxVal >= NumElems/2)
10295     //  IdxVal -= NumElems/2;
10296     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10297     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10298                        DAG.getConstant(IdxVal, MVT::i32));
10299   }
10300
10301   assert(VecVT.is128BitVector() && "Unexpected vector length");
10302
10303   if (Subtarget->hasSSE41()) {
10304     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10305     if (Res.getNode())
10306       return Res;
10307   }
10308
10309   MVT VT = Op.getSimpleValueType();
10310   // TODO: handle v16i8.
10311   if (VT.getSizeInBits() == 16) {
10312     SDValue Vec = Op.getOperand(0);
10313     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10314     if (Idx == 0)
10315       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10316                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10317                                      DAG.getNode(ISD::BITCAST, dl,
10318                                                  MVT::v4i32, Vec),
10319                                      Op.getOperand(1)));
10320     // Transform it so it match pextrw which produces a 32-bit result.
10321     MVT EltVT = MVT::i32;
10322     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10323                                   Op.getOperand(0), Op.getOperand(1));
10324     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10325                                   DAG.getValueType(VT));
10326     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10327   }
10328
10329   if (VT.getSizeInBits() == 32) {
10330     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10331     if (Idx == 0)
10332       return Op;
10333
10334     // SHUFPS the element to the lowest double word, then movss.
10335     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10336     MVT VVT = Op.getOperand(0).getSimpleValueType();
10337     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10338                                        DAG.getUNDEF(VVT), Mask);
10339     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10340                        DAG.getIntPtrConstant(0));
10341   }
10342
10343   if (VT.getSizeInBits() == 64) {
10344     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10345     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10346     //        to match extract_elt for f64.
10347     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10348     if (Idx == 0)
10349       return Op;
10350
10351     // UNPCKHPD the element to the lowest double word, then movsd.
10352     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10353     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10354     int Mask[2] = { 1, -1 };
10355     MVT VVT = Op.getOperand(0).getSimpleValueType();
10356     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10357                                        DAG.getUNDEF(VVT), Mask);
10358     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10359                        DAG.getIntPtrConstant(0));
10360   }
10361
10362   return SDValue();
10363 }
10364
10365 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10366   MVT VT = Op.getSimpleValueType();
10367   MVT EltVT = VT.getVectorElementType();
10368   SDLoc dl(Op);
10369
10370   SDValue N0 = Op.getOperand(0);
10371   SDValue N1 = Op.getOperand(1);
10372   SDValue N2 = Op.getOperand(2);
10373
10374   if (!VT.is128BitVector())
10375     return SDValue();
10376
10377   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10378       isa<ConstantSDNode>(N2)) {
10379     unsigned Opc;
10380     if (VT == MVT::v8i16)
10381       Opc = X86ISD::PINSRW;
10382     else if (VT == MVT::v16i8)
10383       Opc = X86ISD::PINSRB;
10384     else
10385       Opc = X86ISD::PINSRB;
10386
10387     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10388     // argument.
10389     if (N1.getValueType() != MVT::i32)
10390       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10391     if (N2.getValueType() != MVT::i32)
10392       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10393     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10394   }
10395
10396   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10397     // Bits [7:6] of the constant are the source select.  This will always be
10398     //  zero here.  The DAG Combiner may combine an extract_elt index into these
10399     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
10400     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10401     // Bits [5:4] of the constant are the destination select.  This is the
10402     //  value of the incoming immediate.
10403     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10404     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10405     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10406     // Create this as a scalar to vector..
10407     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10408     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10409   }
10410
10411   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10412     // PINSR* works with constant index.
10413     return Op;
10414   }
10415   return SDValue();
10416 }
10417
10418 /// Insert one bit to mask vector, like v16i1 or v8i1.
10419 /// AVX-512 feature.
10420 SDValue 
10421 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10422   SDLoc dl(Op);
10423   SDValue Vec = Op.getOperand(0);
10424   SDValue Elt = Op.getOperand(1);
10425   SDValue Idx = Op.getOperand(2);
10426   MVT VecVT = Vec.getSimpleValueType();
10427
10428   if (!isa<ConstantSDNode>(Idx)) {
10429     // Non constant index. Extend source and destination,
10430     // insert element and then truncate the result.
10431     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10432     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10433     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10434       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10435       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10436     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10437   }
10438
10439   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10440   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10441   if (Vec.getOpcode() == ISD::UNDEF)
10442     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10443                        DAG.getConstant(IdxVal, MVT::i8));
10444   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10445   unsigned MaxSift = rc->getSize()*8 - 1;
10446   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10447                     DAG.getConstant(MaxSift, MVT::i8));
10448   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10449                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10450   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10451 }
10452 SDValue
10453 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10454   MVT VT = Op.getSimpleValueType();
10455   MVT EltVT = VT.getVectorElementType();
10456   
10457   if (EltVT == MVT::i1)
10458     return InsertBitToMaskVector(Op, DAG);
10459
10460   SDLoc dl(Op);
10461   SDValue N0 = Op.getOperand(0);
10462   SDValue N1 = Op.getOperand(1);
10463   SDValue N2 = Op.getOperand(2);
10464
10465   // If this is a 256-bit vector result, first extract the 128-bit vector,
10466   // insert the element into the extracted half and then place it back.
10467   if (VT.is256BitVector() || VT.is512BitVector()) {
10468     if (!isa<ConstantSDNode>(N2))
10469       return SDValue();
10470
10471     // Get the desired 128-bit vector half.
10472     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10473     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10474
10475     // Insert the element into the desired half.
10476     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10477     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10478
10479     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10480                     DAG.getConstant(IdxIn128, MVT::i32));
10481
10482     // Insert the changed part back to the 256-bit vector
10483     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10484   }
10485
10486   if (Subtarget->hasSSE41())
10487     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10488
10489   if (EltVT == MVT::i8)
10490     return SDValue();
10491
10492   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10493     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10494     // as its second argument.
10495     if (N1.getValueType() != MVT::i32)
10496       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10497     if (N2.getValueType() != MVT::i32)
10498       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10499     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10500   }
10501   return SDValue();
10502 }
10503
10504 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10505   SDLoc dl(Op);
10506   MVT OpVT = Op.getSimpleValueType();
10507
10508   // If this is a 256-bit vector result, first insert into a 128-bit
10509   // vector and then insert into the 256-bit vector.
10510   if (!OpVT.is128BitVector()) {
10511     // Insert into a 128-bit vector.
10512     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10513     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10514                                  OpVT.getVectorNumElements() / SizeFactor);
10515
10516     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10517
10518     // Insert the 128-bit vector.
10519     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10520   }
10521
10522   if (OpVT == MVT::v1i64 &&
10523       Op.getOperand(0).getValueType() == MVT::i64)
10524     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10525
10526   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10527   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10528   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10529                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10530 }
10531
10532 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10533 // a simple subregister reference or explicit instructions to grab
10534 // upper bits of a vector.
10535 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10536                                       SelectionDAG &DAG) {
10537   SDLoc dl(Op);
10538   SDValue In =  Op.getOperand(0);
10539   SDValue Idx = Op.getOperand(1);
10540   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10541   MVT ResVT   = Op.getSimpleValueType();
10542   MVT InVT    = In.getSimpleValueType();
10543
10544   if (Subtarget->hasFp256()) {
10545     if (ResVT.is128BitVector() &&
10546         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10547         isa<ConstantSDNode>(Idx)) {
10548       return Extract128BitVector(In, IdxVal, DAG, dl);
10549     }
10550     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10551         isa<ConstantSDNode>(Idx)) {
10552       return Extract256BitVector(In, IdxVal, DAG, dl);
10553     }
10554   }
10555   return SDValue();
10556 }
10557
10558 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10559 // simple superregister reference or explicit instructions to insert
10560 // the upper bits of a vector.
10561 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10562                                      SelectionDAG &DAG) {
10563   if (Subtarget->hasFp256()) {
10564     SDLoc dl(Op.getNode());
10565     SDValue Vec = Op.getNode()->getOperand(0);
10566     SDValue SubVec = Op.getNode()->getOperand(1);
10567     SDValue Idx = Op.getNode()->getOperand(2);
10568
10569     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10570          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10571         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10572         isa<ConstantSDNode>(Idx)) {
10573       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10574       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10575     }
10576
10577     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10578         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10579         isa<ConstantSDNode>(Idx)) {
10580       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10581       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10582     }
10583   }
10584   return SDValue();
10585 }
10586
10587 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10588 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10589 // one of the above mentioned nodes. It has to be wrapped because otherwise
10590 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10591 // be used to form addressing mode. These wrapped nodes will be selected
10592 // into MOV32ri.
10593 SDValue
10594 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10595   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10596
10597   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10598   // global base reg.
10599   unsigned char OpFlag = 0;
10600   unsigned WrapperKind = X86ISD::Wrapper;
10601   CodeModel::Model M = DAG.getTarget().getCodeModel();
10602
10603   if (Subtarget->isPICStyleRIPRel() &&
10604       (M == CodeModel::Small || M == CodeModel::Kernel))
10605     WrapperKind = X86ISD::WrapperRIP;
10606   else if (Subtarget->isPICStyleGOT())
10607     OpFlag = X86II::MO_GOTOFF;
10608   else if (Subtarget->isPICStyleStubPIC())
10609     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10610
10611   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10612                                              CP->getAlignment(),
10613                                              CP->getOffset(), OpFlag);
10614   SDLoc DL(CP);
10615   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10616   // With PIC, the address is actually $g + Offset.
10617   if (OpFlag) {
10618     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10619                          DAG.getNode(X86ISD::GlobalBaseReg,
10620                                      SDLoc(), getPointerTy()),
10621                          Result);
10622   }
10623
10624   return Result;
10625 }
10626
10627 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10628   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10629
10630   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10631   // global base reg.
10632   unsigned char OpFlag = 0;
10633   unsigned WrapperKind = X86ISD::Wrapper;
10634   CodeModel::Model M = DAG.getTarget().getCodeModel();
10635
10636   if (Subtarget->isPICStyleRIPRel() &&
10637       (M == CodeModel::Small || M == CodeModel::Kernel))
10638     WrapperKind = X86ISD::WrapperRIP;
10639   else if (Subtarget->isPICStyleGOT())
10640     OpFlag = X86II::MO_GOTOFF;
10641   else if (Subtarget->isPICStyleStubPIC())
10642     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10643
10644   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10645                                           OpFlag);
10646   SDLoc DL(JT);
10647   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10648
10649   // With PIC, the address is actually $g + Offset.
10650   if (OpFlag)
10651     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10652                          DAG.getNode(X86ISD::GlobalBaseReg,
10653                                      SDLoc(), getPointerTy()),
10654                          Result);
10655
10656   return Result;
10657 }
10658
10659 SDValue
10660 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10661   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10662
10663   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10664   // global base reg.
10665   unsigned char OpFlag = 0;
10666   unsigned WrapperKind = X86ISD::Wrapper;
10667   CodeModel::Model M = DAG.getTarget().getCodeModel();
10668
10669   if (Subtarget->isPICStyleRIPRel() &&
10670       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10671     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10672       OpFlag = X86II::MO_GOTPCREL;
10673     WrapperKind = X86ISD::WrapperRIP;
10674   } else if (Subtarget->isPICStyleGOT()) {
10675     OpFlag = X86II::MO_GOT;
10676   } else if (Subtarget->isPICStyleStubPIC()) {
10677     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10678   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10679     OpFlag = X86II::MO_DARWIN_NONLAZY;
10680   }
10681
10682   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10683
10684   SDLoc DL(Op);
10685   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10686
10687   // With PIC, the address is actually $g + Offset.
10688   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10689       !Subtarget->is64Bit()) {
10690     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10691                          DAG.getNode(X86ISD::GlobalBaseReg,
10692                                      SDLoc(), getPointerTy()),
10693                          Result);
10694   }
10695
10696   // For symbols that require a load from a stub to get the address, emit the
10697   // load.
10698   if (isGlobalStubReference(OpFlag))
10699     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10700                          MachinePointerInfo::getGOT(), false, false, false, 0);
10701
10702   return Result;
10703 }
10704
10705 SDValue
10706 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10707   // Create the TargetBlockAddressAddress node.
10708   unsigned char OpFlags =
10709     Subtarget->ClassifyBlockAddressReference();
10710   CodeModel::Model M = DAG.getTarget().getCodeModel();
10711   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10712   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10713   SDLoc dl(Op);
10714   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10715                                              OpFlags);
10716
10717   if (Subtarget->isPICStyleRIPRel() &&
10718       (M == CodeModel::Small || M == CodeModel::Kernel))
10719     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10720   else
10721     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10722
10723   // With PIC, the address is actually $g + Offset.
10724   if (isGlobalRelativeToPICBase(OpFlags)) {
10725     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10726                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10727                          Result);
10728   }
10729
10730   return Result;
10731 }
10732
10733 SDValue
10734 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10735                                       int64_t Offset, SelectionDAG &DAG) const {
10736   // Create the TargetGlobalAddress node, folding in the constant
10737   // offset if it is legal.
10738   unsigned char OpFlags =
10739       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10740   CodeModel::Model M = DAG.getTarget().getCodeModel();
10741   SDValue Result;
10742   if (OpFlags == X86II::MO_NO_FLAG &&
10743       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10744     // A direct static reference to a global.
10745     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10746     Offset = 0;
10747   } else {
10748     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10749   }
10750
10751   if (Subtarget->isPICStyleRIPRel() &&
10752       (M == CodeModel::Small || M == CodeModel::Kernel))
10753     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10754   else
10755     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10756
10757   // With PIC, the address is actually $g + Offset.
10758   if (isGlobalRelativeToPICBase(OpFlags)) {
10759     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10760                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10761                          Result);
10762   }
10763
10764   // For globals that require a load from a stub to get the address, emit the
10765   // load.
10766   if (isGlobalStubReference(OpFlags))
10767     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10768                          MachinePointerInfo::getGOT(), false, false, false, 0);
10769
10770   // If there was a non-zero offset that we didn't fold, create an explicit
10771   // addition for it.
10772   if (Offset != 0)
10773     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10774                          DAG.getConstant(Offset, getPointerTy()));
10775
10776   return Result;
10777 }
10778
10779 SDValue
10780 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10781   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10782   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10783   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10784 }
10785
10786 static SDValue
10787 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10788            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10789            unsigned char OperandFlags, bool LocalDynamic = false) {
10790   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10791   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10792   SDLoc dl(GA);
10793   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10794                                            GA->getValueType(0),
10795                                            GA->getOffset(),
10796                                            OperandFlags);
10797
10798   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10799                                            : X86ISD::TLSADDR;
10800
10801   if (InFlag) {
10802     SDValue Ops[] = { Chain,  TGA, *InFlag };
10803     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10804   } else {
10805     SDValue Ops[]  = { Chain, TGA };
10806     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10807   }
10808
10809   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10810   MFI->setAdjustsStack(true);
10811
10812   SDValue Flag = Chain.getValue(1);
10813   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10814 }
10815
10816 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10817 static SDValue
10818 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10819                                 const EVT PtrVT) {
10820   SDValue InFlag;
10821   SDLoc dl(GA);  // ? function entry point might be better
10822   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10823                                    DAG.getNode(X86ISD::GlobalBaseReg,
10824                                                SDLoc(), PtrVT), InFlag);
10825   InFlag = Chain.getValue(1);
10826
10827   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10828 }
10829
10830 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10831 static SDValue
10832 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10833                                 const EVT PtrVT) {
10834   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10835                     X86::RAX, X86II::MO_TLSGD);
10836 }
10837
10838 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10839                                            SelectionDAG &DAG,
10840                                            const EVT PtrVT,
10841                                            bool is64Bit) {
10842   SDLoc dl(GA);
10843
10844   // Get the start address of the TLS block for this module.
10845   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10846       .getInfo<X86MachineFunctionInfo>();
10847   MFI->incNumLocalDynamicTLSAccesses();
10848
10849   SDValue Base;
10850   if (is64Bit) {
10851     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10852                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10853   } else {
10854     SDValue InFlag;
10855     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10856         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10857     InFlag = Chain.getValue(1);
10858     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10859                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10860   }
10861
10862   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10863   // of Base.
10864
10865   // Build x@dtpoff.
10866   unsigned char OperandFlags = X86II::MO_DTPOFF;
10867   unsigned WrapperKind = X86ISD::Wrapper;
10868   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10869                                            GA->getValueType(0),
10870                                            GA->getOffset(), OperandFlags);
10871   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10872
10873   // Add x@dtpoff with the base.
10874   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10875 }
10876
10877 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10878 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10879                                    const EVT PtrVT, TLSModel::Model model,
10880                                    bool is64Bit, bool isPIC) {
10881   SDLoc dl(GA);
10882
10883   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10884   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10885                                                          is64Bit ? 257 : 256));
10886
10887   SDValue ThreadPointer =
10888       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10889                   MachinePointerInfo(Ptr), false, false, false, 0);
10890
10891   unsigned char OperandFlags = 0;
10892   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10893   // initialexec.
10894   unsigned WrapperKind = X86ISD::Wrapper;
10895   if (model == TLSModel::LocalExec) {
10896     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10897   } else if (model == TLSModel::InitialExec) {
10898     if (is64Bit) {
10899       OperandFlags = X86II::MO_GOTTPOFF;
10900       WrapperKind = X86ISD::WrapperRIP;
10901     } else {
10902       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10903     }
10904   } else {
10905     llvm_unreachable("Unexpected model");
10906   }
10907
10908   // emit "addl x@ntpoff,%eax" (local exec)
10909   // or "addl x@indntpoff,%eax" (initial exec)
10910   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10911   SDValue TGA =
10912       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10913                                  GA->getOffset(), OperandFlags);
10914   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10915
10916   if (model == TLSModel::InitialExec) {
10917     if (isPIC && !is64Bit) {
10918       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10919                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10920                            Offset);
10921     }
10922
10923     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10924                          MachinePointerInfo::getGOT(), false, false, false, 0);
10925   }
10926
10927   // The address of the thread local variable is the add of the thread
10928   // pointer with the offset of the variable.
10929   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10930 }
10931
10932 SDValue
10933 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10934
10935   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10936   const GlobalValue *GV = GA->getGlobal();
10937
10938   if (Subtarget->isTargetELF()) {
10939     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10940
10941     switch (model) {
10942       case TLSModel::GeneralDynamic:
10943         if (Subtarget->is64Bit())
10944           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10945         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10946       case TLSModel::LocalDynamic:
10947         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10948                                            Subtarget->is64Bit());
10949       case TLSModel::InitialExec:
10950       case TLSModel::LocalExec:
10951         return LowerToTLSExecModel(
10952             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10953             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10954     }
10955     llvm_unreachable("Unknown TLS model.");
10956   }
10957
10958   if (Subtarget->isTargetDarwin()) {
10959     // Darwin only has one model of TLS.  Lower to that.
10960     unsigned char OpFlag = 0;
10961     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10962                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10963
10964     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10965     // global base reg.
10966     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10967                  !Subtarget->is64Bit();
10968     if (PIC32)
10969       OpFlag = X86II::MO_TLVP_PIC_BASE;
10970     else
10971       OpFlag = X86II::MO_TLVP;
10972     SDLoc DL(Op);
10973     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10974                                                 GA->getValueType(0),
10975                                                 GA->getOffset(), OpFlag);
10976     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10977
10978     // With PIC32, the address is actually $g + Offset.
10979     if (PIC32)
10980       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10981                            DAG.getNode(X86ISD::GlobalBaseReg,
10982                                        SDLoc(), getPointerTy()),
10983                            Offset);
10984
10985     // Lowering the machine isd will make sure everything is in the right
10986     // location.
10987     SDValue Chain = DAG.getEntryNode();
10988     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10989     SDValue Args[] = { Chain, Offset };
10990     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10991
10992     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10993     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10994     MFI->setAdjustsStack(true);
10995
10996     // And our return value (tls address) is in the standard call return value
10997     // location.
10998     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10999     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11000                               Chain.getValue(1));
11001   }
11002
11003   if (Subtarget->isTargetKnownWindowsMSVC() ||
11004       Subtarget->isTargetWindowsGNU()) {
11005     // Just use the implicit TLS architecture
11006     // Need to generate someting similar to:
11007     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11008     //                                  ; from TEB
11009     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11010     //   mov     rcx, qword [rdx+rcx*8]
11011     //   mov     eax, .tls$:tlsvar
11012     //   [rax+rcx] contains the address
11013     // Windows 64bit: gs:0x58
11014     // Windows 32bit: fs:__tls_array
11015
11016     SDLoc dl(GA);
11017     SDValue Chain = DAG.getEntryNode();
11018
11019     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11020     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11021     // use its literal value of 0x2C.
11022     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11023                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11024                                                              256)
11025                                         : Type::getInt32PtrTy(*DAG.getContext(),
11026                                                               257));
11027
11028     SDValue TlsArray =
11029         Subtarget->is64Bit()
11030             ? DAG.getIntPtrConstant(0x58)
11031             : (Subtarget->isTargetWindowsGNU()
11032                    ? DAG.getIntPtrConstant(0x2C)
11033                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11034
11035     SDValue ThreadPointer =
11036         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11037                     MachinePointerInfo(Ptr), false, false, false, 0);
11038
11039     // Load the _tls_index variable
11040     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11041     if (Subtarget->is64Bit())
11042       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11043                            IDX, MachinePointerInfo(), MVT::i32,
11044                            false, false, false, 0);
11045     else
11046       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11047                         false, false, false, 0);
11048
11049     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11050                                     getPointerTy());
11051     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11052
11053     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11054     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11055                       false, false, false, 0);
11056
11057     // Get the offset of start of .tls section
11058     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11059                                              GA->getValueType(0),
11060                                              GA->getOffset(), X86II::MO_SECREL);
11061     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11062
11063     // The address of the thread local variable is the add of the thread
11064     // pointer with the offset of the variable.
11065     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11066   }
11067
11068   llvm_unreachable("TLS not implemented for this target.");
11069 }
11070
11071 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11072 /// and take a 2 x i32 value to shift plus a shift amount.
11073 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11074   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11075   MVT VT = Op.getSimpleValueType();
11076   unsigned VTBits = VT.getSizeInBits();
11077   SDLoc dl(Op);
11078   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11079   SDValue ShOpLo = Op.getOperand(0);
11080   SDValue ShOpHi = Op.getOperand(1);
11081   SDValue ShAmt  = Op.getOperand(2);
11082   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11083   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11084   // during isel.
11085   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11086                                   DAG.getConstant(VTBits - 1, MVT::i8));
11087   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11088                                      DAG.getConstant(VTBits - 1, MVT::i8))
11089                        : DAG.getConstant(0, VT);
11090
11091   SDValue Tmp2, Tmp3;
11092   if (Op.getOpcode() == ISD::SHL_PARTS) {
11093     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11094     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11095   } else {
11096     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11097     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11098   }
11099
11100   // If the shift amount is larger or equal than the width of a part we can't
11101   // rely on the results of shld/shrd. Insert a test and select the appropriate
11102   // values for large shift amounts.
11103   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11104                                 DAG.getConstant(VTBits, MVT::i8));
11105   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11106                              AndNode, DAG.getConstant(0, MVT::i8));
11107
11108   SDValue Hi, Lo;
11109   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11110   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11111   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11112
11113   if (Op.getOpcode() == ISD::SHL_PARTS) {
11114     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11115     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11116   } else {
11117     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11118     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11119   }
11120
11121   SDValue Ops[2] = { Lo, Hi };
11122   return DAG.getMergeValues(Ops, dl);
11123 }
11124
11125 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11126                                            SelectionDAG &DAG) const {
11127   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11128
11129   if (SrcVT.isVector())
11130     return SDValue();
11131
11132   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11133          "Unknown SINT_TO_FP to lower!");
11134
11135   // These are really Legal; return the operand so the caller accepts it as
11136   // Legal.
11137   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11138     return Op;
11139   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11140       Subtarget->is64Bit()) {
11141     return Op;
11142   }
11143
11144   SDLoc dl(Op);
11145   unsigned Size = SrcVT.getSizeInBits()/8;
11146   MachineFunction &MF = DAG.getMachineFunction();
11147   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11148   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11149   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11150                                StackSlot,
11151                                MachinePointerInfo::getFixedStack(SSFI),
11152                                false, false, 0);
11153   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11154 }
11155
11156 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11157                                      SDValue StackSlot,
11158                                      SelectionDAG &DAG) const {
11159   // Build the FILD
11160   SDLoc DL(Op);
11161   SDVTList Tys;
11162   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11163   if (useSSE)
11164     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11165   else
11166     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11167
11168   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11169
11170   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11171   MachineMemOperand *MMO;
11172   if (FI) {
11173     int SSFI = FI->getIndex();
11174     MMO =
11175       DAG.getMachineFunction()
11176       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11177                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11178   } else {
11179     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11180     StackSlot = StackSlot.getOperand(1);
11181   }
11182   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11183   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11184                                            X86ISD::FILD, DL,
11185                                            Tys, Ops, SrcVT, MMO);
11186
11187   if (useSSE) {
11188     Chain = Result.getValue(1);
11189     SDValue InFlag = Result.getValue(2);
11190
11191     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11192     // shouldn't be necessary except that RFP cannot be live across
11193     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11194     MachineFunction &MF = DAG.getMachineFunction();
11195     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11196     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11197     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11198     Tys = DAG.getVTList(MVT::Other);
11199     SDValue Ops[] = {
11200       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11201     };
11202     MachineMemOperand *MMO =
11203       DAG.getMachineFunction()
11204       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11205                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11206
11207     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11208                                     Ops, Op.getValueType(), MMO);
11209     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11210                          MachinePointerInfo::getFixedStack(SSFI),
11211                          false, false, false, 0);
11212   }
11213
11214   return Result;
11215 }
11216
11217 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11218 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11219                                                SelectionDAG &DAG) const {
11220   // This algorithm is not obvious. Here it is what we're trying to output:
11221   /*
11222      movq       %rax,  %xmm0
11223      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11224      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11225      #ifdef __SSE3__
11226        haddpd   %xmm0, %xmm0
11227      #else
11228        pshufd   $0x4e, %xmm0, %xmm1
11229        addpd    %xmm1, %xmm0
11230      #endif
11231   */
11232
11233   SDLoc dl(Op);
11234   LLVMContext *Context = DAG.getContext();
11235
11236   // Build some magic constants.
11237   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11238   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11239   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11240
11241   SmallVector<Constant*,2> CV1;
11242   CV1.push_back(
11243     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11244                                       APInt(64, 0x4330000000000000ULL))));
11245   CV1.push_back(
11246     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11247                                       APInt(64, 0x4530000000000000ULL))));
11248   Constant *C1 = ConstantVector::get(CV1);
11249   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11250
11251   // Load the 64-bit value into an XMM register.
11252   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11253                             Op.getOperand(0));
11254   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11255                               MachinePointerInfo::getConstantPool(),
11256                               false, false, false, 16);
11257   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11258                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11259                               CLod0);
11260
11261   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11262                               MachinePointerInfo::getConstantPool(),
11263                               false, false, false, 16);
11264   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11265   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11266   SDValue Result;
11267
11268   if (Subtarget->hasSSE3()) {
11269     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11270     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11271   } else {
11272     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11273     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11274                                            S2F, 0x4E, DAG);
11275     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11276                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11277                          Sub);
11278   }
11279
11280   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11281                      DAG.getIntPtrConstant(0));
11282 }
11283
11284 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11285 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11286                                                SelectionDAG &DAG) const {
11287   SDLoc dl(Op);
11288   // FP constant to bias correct the final result.
11289   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11290                                    MVT::f64);
11291
11292   // Load the 32-bit value into an XMM register.
11293   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11294                              Op.getOperand(0));
11295
11296   // Zero out the upper parts of the register.
11297   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11298
11299   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11300                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11301                      DAG.getIntPtrConstant(0));
11302
11303   // Or the load with the bias.
11304   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11305                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11306                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11307                                                    MVT::v2f64, Load)),
11308                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11309                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11310                                                    MVT::v2f64, Bias)));
11311   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11312                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11313                    DAG.getIntPtrConstant(0));
11314
11315   // Subtract the bias.
11316   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11317
11318   // Handle final rounding.
11319   EVT DestVT = Op.getValueType();
11320
11321   if (DestVT.bitsLT(MVT::f64))
11322     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11323                        DAG.getIntPtrConstant(0));
11324   if (DestVT.bitsGT(MVT::f64))
11325     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11326
11327   // Handle final rounding.
11328   return Sub;
11329 }
11330
11331 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11332                                                SelectionDAG &DAG) const {
11333   SDValue N0 = Op.getOperand(0);
11334   MVT SVT = N0.getSimpleValueType();
11335   SDLoc dl(Op);
11336
11337   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11338           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11339          "Custom UINT_TO_FP is not supported!");
11340
11341   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11342   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11343                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11344 }
11345
11346 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11347                                            SelectionDAG &DAG) const {
11348   SDValue N0 = Op.getOperand(0);
11349   SDLoc dl(Op);
11350
11351   if (Op.getValueType().isVector())
11352     return lowerUINT_TO_FP_vec(Op, DAG);
11353
11354   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11355   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11356   // the optimization here.
11357   if (DAG.SignBitIsZero(N0))
11358     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11359
11360   MVT SrcVT = N0.getSimpleValueType();
11361   MVT DstVT = Op.getSimpleValueType();
11362   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11363     return LowerUINT_TO_FP_i64(Op, DAG);
11364   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11365     return LowerUINT_TO_FP_i32(Op, DAG);
11366   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11367     return SDValue();
11368
11369   // Make a 64-bit buffer, and use it to build an FILD.
11370   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11371   if (SrcVT == MVT::i32) {
11372     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11373     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11374                                      getPointerTy(), StackSlot, WordOff);
11375     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11376                                   StackSlot, MachinePointerInfo(),
11377                                   false, false, 0);
11378     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11379                                   OffsetSlot, MachinePointerInfo(),
11380                                   false, false, 0);
11381     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11382     return Fild;
11383   }
11384
11385   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11386   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11387                                StackSlot, MachinePointerInfo(),
11388                                false, false, 0);
11389   // For i64 source, we need to add the appropriate power of 2 if the input
11390   // was negative.  This is the same as the optimization in
11391   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11392   // we must be careful to do the computation in x87 extended precision, not
11393   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11394   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11395   MachineMemOperand *MMO =
11396     DAG.getMachineFunction()
11397     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11398                           MachineMemOperand::MOLoad, 8, 8);
11399
11400   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11401   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11402   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11403                                          MVT::i64, MMO);
11404
11405   APInt FF(32, 0x5F800000ULL);
11406
11407   // Check whether the sign bit is set.
11408   SDValue SignSet = DAG.getSetCC(dl,
11409                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11410                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11411                                  ISD::SETLT);
11412
11413   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11414   SDValue FudgePtr = DAG.getConstantPool(
11415                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11416                                          getPointerTy());
11417
11418   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11419   SDValue Zero = DAG.getIntPtrConstant(0);
11420   SDValue Four = DAG.getIntPtrConstant(4);
11421   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11422                                Zero, Four);
11423   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11424
11425   // Load the value out, extending it from f32 to f80.
11426   // FIXME: Avoid the extend by constructing the right constant pool?
11427   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11428                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11429                                  MVT::f32, false, false, false, 4);
11430   // Extend everything to 80 bits to force it to be done on x87.
11431   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11432   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11433 }
11434
11435 std::pair<SDValue,SDValue>
11436 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11437                                     bool IsSigned, bool IsReplace) const {
11438   SDLoc DL(Op);
11439
11440   EVT DstTy = Op.getValueType();
11441
11442   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11443     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11444     DstTy = MVT::i64;
11445   }
11446
11447   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11448          DstTy.getSimpleVT() >= MVT::i16 &&
11449          "Unknown FP_TO_INT to lower!");
11450
11451   // These are really Legal.
11452   if (DstTy == MVT::i32 &&
11453       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11454     return std::make_pair(SDValue(), SDValue());
11455   if (Subtarget->is64Bit() &&
11456       DstTy == MVT::i64 &&
11457       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11458     return std::make_pair(SDValue(), SDValue());
11459
11460   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11461   // stack slot, or into the FTOL runtime function.
11462   MachineFunction &MF = DAG.getMachineFunction();
11463   unsigned MemSize = DstTy.getSizeInBits()/8;
11464   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11465   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11466
11467   unsigned Opc;
11468   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11469     Opc = X86ISD::WIN_FTOL;
11470   else
11471     switch (DstTy.getSimpleVT().SimpleTy) {
11472     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11473     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11474     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11475     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11476     }
11477
11478   SDValue Chain = DAG.getEntryNode();
11479   SDValue Value = Op.getOperand(0);
11480   EVT TheVT = Op.getOperand(0).getValueType();
11481   // FIXME This causes a redundant load/store if the SSE-class value is already
11482   // in memory, such as if it is on the callstack.
11483   if (isScalarFPTypeInSSEReg(TheVT)) {
11484     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11485     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11486                          MachinePointerInfo::getFixedStack(SSFI),
11487                          false, false, 0);
11488     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11489     SDValue Ops[] = {
11490       Chain, StackSlot, DAG.getValueType(TheVT)
11491     };
11492
11493     MachineMemOperand *MMO =
11494       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11495                               MachineMemOperand::MOLoad, MemSize, MemSize);
11496     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11497     Chain = Value.getValue(1);
11498     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11499     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11500   }
11501
11502   MachineMemOperand *MMO =
11503     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11504                             MachineMemOperand::MOStore, MemSize, MemSize);
11505
11506   if (Opc != X86ISD::WIN_FTOL) {
11507     // Build the FP_TO_INT*_IN_MEM
11508     SDValue Ops[] = { Chain, Value, StackSlot };
11509     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11510                                            Ops, DstTy, MMO);
11511     return std::make_pair(FIST, StackSlot);
11512   } else {
11513     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11514       DAG.getVTList(MVT::Other, MVT::Glue),
11515       Chain, Value);
11516     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11517       MVT::i32, ftol.getValue(1));
11518     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11519       MVT::i32, eax.getValue(2));
11520     SDValue Ops[] = { eax, edx };
11521     SDValue pair = IsReplace
11522       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11523       : DAG.getMergeValues(Ops, DL);
11524     return std::make_pair(pair, SDValue());
11525   }
11526 }
11527
11528 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11529                               const X86Subtarget *Subtarget) {
11530   MVT VT = Op->getSimpleValueType(0);
11531   SDValue In = Op->getOperand(0);
11532   MVT InVT = In.getSimpleValueType();
11533   SDLoc dl(Op);
11534
11535   // Optimize vectors in AVX mode:
11536   //
11537   //   v8i16 -> v8i32
11538   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11539   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11540   //   Concat upper and lower parts.
11541   //
11542   //   v4i32 -> v4i64
11543   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11544   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11545   //   Concat upper and lower parts.
11546   //
11547
11548   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11549       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11550       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11551     return SDValue();
11552
11553   if (Subtarget->hasInt256())
11554     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11555
11556   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11557   SDValue Undef = DAG.getUNDEF(InVT);
11558   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11559   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11560   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11561
11562   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11563                              VT.getVectorNumElements()/2);
11564
11565   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11566   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11567
11568   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11569 }
11570
11571 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11572                                         SelectionDAG &DAG) {
11573   MVT VT = Op->getSimpleValueType(0);
11574   SDValue In = Op->getOperand(0);
11575   MVT InVT = In.getSimpleValueType();
11576   SDLoc DL(Op);
11577   unsigned int NumElts = VT.getVectorNumElements();
11578   if (NumElts != 8 && NumElts != 16)
11579     return SDValue();
11580
11581   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11582     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11583
11584   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11586   // Now we have only mask extension
11587   assert(InVT.getVectorElementType() == MVT::i1);
11588   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11589   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11590   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11591   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11592   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11593                            MachinePointerInfo::getConstantPool(),
11594                            false, false, false, Alignment);
11595
11596   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11597   if (VT.is512BitVector())
11598     return Brcst;
11599   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11600 }
11601
11602 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11603                                SelectionDAG &DAG) {
11604   if (Subtarget->hasFp256()) {
11605     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11606     if (Res.getNode())
11607       return Res;
11608   }
11609
11610   return SDValue();
11611 }
11612
11613 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11614                                 SelectionDAG &DAG) {
11615   SDLoc DL(Op);
11616   MVT VT = Op.getSimpleValueType();
11617   SDValue In = Op.getOperand(0);
11618   MVT SVT = In.getSimpleValueType();
11619
11620   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11621     return LowerZERO_EXTEND_AVX512(Op, DAG);
11622
11623   if (Subtarget->hasFp256()) {
11624     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11625     if (Res.getNode())
11626       return Res;
11627   }
11628
11629   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11630          VT.getVectorNumElements() != SVT.getVectorNumElements());
11631   return SDValue();
11632 }
11633
11634 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11635   SDLoc DL(Op);
11636   MVT VT = Op.getSimpleValueType();
11637   SDValue In = Op.getOperand(0);
11638   MVT InVT = In.getSimpleValueType();
11639
11640   if (VT == MVT::i1) {
11641     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11642            "Invalid scalar TRUNCATE operation");
11643     if (InVT == MVT::i32)
11644       return SDValue();
11645     if (InVT.getSizeInBits() == 64)
11646       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11647     else if (InVT.getSizeInBits() < 32)
11648       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11649     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11650   }
11651   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11652          "Invalid TRUNCATE operation");
11653
11654   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11655     if (VT.getVectorElementType().getSizeInBits() >=8)
11656       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11657
11658     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11659     unsigned NumElts = InVT.getVectorNumElements();
11660     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11661     if (InVT.getSizeInBits() < 512) {
11662       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11663       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11664       InVT = ExtVT;
11665     }
11666     
11667     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11668     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11669     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11670     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11671     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11672                            MachinePointerInfo::getConstantPool(),
11673                            false, false, false, Alignment);
11674     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11675     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11676     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11677   }
11678
11679   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11680     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11681     if (Subtarget->hasInt256()) {
11682       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11683       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11684       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11685                                 ShufMask);
11686       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11687                          DAG.getIntPtrConstant(0));
11688     }
11689
11690     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11691                                DAG.getIntPtrConstant(0));
11692     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11693                                DAG.getIntPtrConstant(2));
11694     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11695     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11696     static const int ShufMask[] = {0, 2, 4, 6};
11697     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11698   }
11699
11700   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11701     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11702     if (Subtarget->hasInt256()) {
11703       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11704
11705       SmallVector<SDValue,32> pshufbMask;
11706       for (unsigned i = 0; i < 2; ++i) {
11707         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11708         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11709         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11710         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11711         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11712         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11713         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11714         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11715         for (unsigned j = 0; j < 8; ++j)
11716           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11717       }
11718       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11719       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11720       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11721
11722       static const int ShufMask[] = {0,  2,  -1,  -1};
11723       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11724                                 &ShufMask[0]);
11725       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11726                        DAG.getIntPtrConstant(0));
11727       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11728     }
11729
11730     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11731                                DAG.getIntPtrConstant(0));
11732
11733     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11734                                DAG.getIntPtrConstant(4));
11735
11736     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11737     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11738
11739     // The PSHUFB mask:
11740     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11741                                    -1, -1, -1, -1, -1, -1, -1, -1};
11742
11743     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11744     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11745     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11746
11747     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11748     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11749
11750     // The MOVLHPS Mask:
11751     static const int ShufMask2[] = {0, 1, 4, 5};
11752     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11753     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11754   }
11755
11756   // Handle truncation of V256 to V128 using shuffles.
11757   if (!VT.is128BitVector() || !InVT.is256BitVector())
11758     return SDValue();
11759
11760   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11761
11762   unsigned NumElems = VT.getVectorNumElements();
11763   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11764
11765   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11766   // Prepare truncation shuffle mask
11767   for (unsigned i = 0; i != NumElems; ++i)
11768     MaskVec[i] = i * 2;
11769   SDValue V = DAG.getVectorShuffle(NVT, DL,
11770                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11771                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11772   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11773                      DAG.getIntPtrConstant(0));
11774 }
11775
11776 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11777                                            SelectionDAG &DAG) const {
11778   assert(!Op.getSimpleValueType().isVector());
11779
11780   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11781     /*IsSigned=*/ true, /*IsReplace=*/ false);
11782   SDValue FIST = Vals.first, StackSlot = Vals.second;
11783   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11784   if (!FIST.getNode()) return Op;
11785
11786   if (StackSlot.getNode())
11787     // Load the result.
11788     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11789                        FIST, StackSlot, MachinePointerInfo(),
11790                        false, false, false, 0);
11791
11792   // The node is the result.
11793   return FIST;
11794 }
11795
11796 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11797                                            SelectionDAG &DAG) const {
11798   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11799     /*IsSigned=*/ false, /*IsReplace=*/ false);
11800   SDValue FIST = Vals.first, StackSlot = Vals.second;
11801   assert(FIST.getNode() && "Unexpected failure");
11802
11803   if (StackSlot.getNode())
11804     // Load the result.
11805     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11806                        FIST, StackSlot, MachinePointerInfo(),
11807                        false, false, false, 0);
11808
11809   // The node is the result.
11810   return FIST;
11811 }
11812
11813 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11814   SDLoc DL(Op);
11815   MVT VT = Op.getSimpleValueType();
11816   SDValue In = Op.getOperand(0);
11817   MVT SVT = In.getSimpleValueType();
11818
11819   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11820
11821   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11822                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11823                                  In, DAG.getUNDEF(SVT)));
11824 }
11825
11826 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11827   LLVMContext *Context = DAG.getContext();
11828   SDLoc dl(Op);
11829   MVT VT = Op.getSimpleValueType();
11830   MVT EltVT = VT;
11831   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11832   if (VT.isVector()) {
11833     EltVT = VT.getVectorElementType();
11834     NumElts = VT.getVectorNumElements();
11835   }
11836   Constant *C;
11837   if (EltVT == MVT::f64)
11838     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11839                                           APInt(64, ~(1ULL << 63))));
11840   else
11841     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11842                                           APInt(32, ~(1U << 31))));
11843   C = ConstantVector::getSplat(NumElts, C);
11844   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11845   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11846   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11847   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11848                              MachinePointerInfo::getConstantPool(),
11849                              false, false, false, Alignment);
11850   if (VT.isVector()) {
11851     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11852     return DAG.getNode(ISD::BITCAST, dl, VT,
11853                        DAG.getNode(ISD::AND, dl, ANDVT,
11854                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11855                                                Op.getOperand(0)),
11856                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11857   }
11858   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11859 }
11860
11861 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11862   LLVMContext *Context = DAG.getContext();
11863   SDLoc dl(Op);
11864   MVT VT = Op.getSimpleValueType();
11865   MVT EltVT = VT;
11866   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11867   if (VT.isVector()) {
11868     EltVT = VT.getVectorElementType();
11869     NumElts = VT.getVectorNumElements();
11870   }
11871   Constant *C;
11872   if (EltVT == MVT::f64)
11873     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11874                                           APInt(64, 1ULL << 63)));
11875   else
11876     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11877                                           APInt(32, 1U << 31)));
11878   C = ConstantVector::getSplat(NumElts, C);
11879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11880   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11881   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11882   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11883                              MachinePointerInfo::getConstantPool(),
11884                              false, false, false, Alignment);
11885   if (VT.isVector()) {
11886     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11887     return DAG.getNode(ISD::BITCAST, dl, VT,
11888                        DAG.getNode(ISD::XOR, dl, XORVT,
11889                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11890                                                Op.getOperand(0)),
11891                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11892   }
11893
11894   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11895 }
11896
11897 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11898   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11899   LLVMContext *Context = DAG.getContext();
11900   SDValue Op0 = Op.getOperand(0);
11901   SDValue Op1 = Op.getOperand(1);
11902   SDLoc dl(Op);
11903   MVT VT = Op.getSimpleValueType();
11904   MVT SrcVT = Op1.getSimpleValueType();
11905
11906   // If second operand is smaller, extend it first.
11907   if (SrcVT.bitsLT(VT)) {
11908     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11909     SrcVT = VT;
11910   }
11911   // And if it is bigger, shrink it first.
11912   if (SrcVT.bitsGT(VT)) {
11913     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11914     SrcVT = VT;
11915   }
11916
11917   // At this point the operands and the result should have the same
11918   // type, and that won't be f80 since that is not custom lowered.
11919
11920   // First get the sign bit of second operand.
11921   SmallVector<Constant*,4> CV;
11922   if (SrcVT == MVT::f64) {
11923     const fltSemantics &Sem = APFloat::IEEEdouble;
11924     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11925     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11926   } else {
11927     const fltSemantics &Sem = APFloat::IEEEsingle;
11928     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11929     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11930     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11931     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11932   }
11933   Constant *C = ConstantVector::get(CV);
11934   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11935   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11936                               MachinePointerInfo::getConstantPool(),
11937                               false, false, false, 16);
11938   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11939
11940   // Shift sign bit right or left if the two operands have different types.
11941   if (SrcVT.bitsGT(VT)) {
11942     // Op0 is MVT::f32, Op1 is MVT::f64.
11943     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11944     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11945                           DAG.getConstant(32, MVT::i32));
11946     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11947     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11948                           DAG.getIntPtrConstant(0));
11949   }
11950
11951   // Clear first operand sign bit.
11952   CV.clear();
11953   if (VT == MVT::f64) {
11954     const fltSemantics &Sem = APFloat::IEEEdouble;
11955     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11956                                                    APInt(64, ~(1ULL << 63)))));
11957     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11958   } else {
11959     const fltSemantics &Sem = APFloat::IEEEsingle;
11960     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11961                                                    APInt(32, ~(1U << 31)))));
11962     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11963     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11964     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11965   }
11966   C = ConstantVector::get(CV);
11967   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11968   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11969                               MachinePointerInfo::getConstantPool(),
11970                               false, false, false, 16);
11971   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11972
11973   // Or the value with the sign bit.
11974   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11975 }
11976
11977 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11978   SDValue N0 = Op.getOperand(0);
11979   SDLoc dl(Op);
11980   MVT VT = Op.getSimpleValueType();
11981
11982   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11983   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11984                                   DAG.getConstant(1, VT));
11985   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11986 }
11987
11988 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11989 //
11990 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11991                                       SelectionDAG &DAG) {
11992   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11993
11994   if (!Subtarget->hasSSE41())
11995     return SDValue();
11996
11997   if (!Op->hasOneUse())
11998     return SDValue();
11999
12000   SDNode *N = Op.getNode();
12001   SDLoc DL(N);
12002
12003   SmallVector<SDValue, 8> Opnds;
12004   DenseMap<SDValue, unsigned> VecInMap;
12005   SmallVector<SDValue, 8> VecIns;
12006   EVT VT = MVT::Other;
12007
12008   // Recognize a special case where a vector is casted into wide integer to
12009   // test all 0s.
12010   Opnds.push_back(N->getOperand(0));
12011   Opnds.push_back(N->getOperand(1));
12012
12013   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12014     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12015     // BFS traverse all OR'd operands.
12016     if (I->getOpcode() == ISD::OR) {
12017       Opnds.push_back(I->getOperand(0));
12018       Opnds.push_back(I->getOperand(1));
12019       // Re-evaluate the number of nodes to be traversed.
12020       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12021       continue;
12022     }
12023
12024     // Quit if a non-EXTRACT_VECTOR_ELT
12025     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12026       return SDValue();
12027
12028     // Quit if without a constant index.
12029     SDValue Idx = I->getOperand(1);
12030     if (!isa<ConstantSDNode>(Idx))
12031       return SDValue();
12032
12033     SDValue ExtractedFromVec = I->getOperand(0);
12034     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12035     if (M == VecInMap.end()) {
12036       VT = ExtractedFromVec.getValueType();
12037       // Quit if not 128/256-bit vector.
12038       if (!VT.is128BitVector() && !VT.is256BitVector())
12039         return SDValue();
12040       // Quit if not the same type.
12041       if (VecInMap.begin() != VecInMap.end() &&
12042           VT != VecInMap.begin()->first.getValueType())
12043         return SDValue();
12044       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12045       VecIns.push_back(ExtractedFromVec);
12046     }
12047     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12048   }
12049
12050   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12051          "Not extracted from 128-/256-bit vector.");
12052
12053   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12054
12055   for (DenseMap<SDValue, unsigned>::const_iterator
12056         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12057     // Quit if not all elements are used.
12058     if (I->second != FullMask)
12059       return SDValue();
12060   }
12061
12062   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12063
12064   // Cast all vectors into TestVT for PTEST.
12065   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12066     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12067
12068   // If more than one full vectors are evaluated, OR them first before PTEST.
12069   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12070     // Each iteration will OR 2 nodes and append the result until there is only
12071     // 1 node left, i.e. the final OR'd value of all vectors.
12072     SDValue LHS = VecIns[Slot];
12073     SDValue RHS = VecIns[Slot + 1];
12074     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12075   }
12076
12077   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12078                      VecIns.back(), VecIns.back());
12079 }
12080
12081 /// \brief return true if \c Op has a use that doesn't just read flags.
12082 static bool hasNonFlagsUse(SDValue Op) {
12083   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12084        ++UI) {
12085     SDNode *User = *UI;
12086     unsigned UOpNo = UI.getOperandNo();
12087     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12088       // Look pass truncate.
12089       UOpNo = User->use_begin().getOperandNo();
12090       User = *User->use_begin();
12091     }
12092
12093     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12094         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12095       return true;
12096   }
12097   return false;
12098 }
12099
12100 /// Emit nodes that will be selected as "test Op0,Op0", or something
12101 /// equivalent.
12102 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12103                                     SelectionDAG &DAG) const {
12104   if (Op.getValueType() == MVT::i1)
12105     // KORTEST instruction should be selected
12106     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12107                        DAG.getConstant(0, Op.getValueType()));
12108
12109   // CF and OF aren't always set the way we want. Determine which
12110   // of these we need.
12111   bool NeedCF = false;
12112   bool NeedOF = false;
12113   switch (X86CC) {
12114   default: break;
12115   case X86::COND_A: case X86::COND_AE:
12116   case X86::COND_B: case X86::COND_BE:
12117     NeedCF = true;
12118     break;
12119   case X86::COND_G: case X86::COND_GE:
12120   case X86::COND_L: case X86::COND_LE:
12121   case X86::COND_O: case X86::COND_NO: {
12122     // Check if we really need to set the
12123     // Overflow flag. If NoSignedWrap is present
12124     // that is not actually needed.
12125     switch (Op->getOpcode()) {
12126     case ISD::ADD:
12127     case ISD::SUB:
12128     case ISD::MUL:
12129     case ISD::SHL: {
12130       const BinaryWithFlagsSDNode *BinNode =
12131           cast<BinaryWithFlagsSDNode>(Op.getNode());
12132       if (BinNode->hasNoSignedWrap())
12133         break;
12134     }
12135     default:
12136       NeedOF = true;
12137       break;
12138     }
12139     break;
12140   }
12141   }
12142   // See if we can use the EFLAGS value from the operand instead of
12143   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12144   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12145   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12146     // Emit a CMP with 0, which is the TEST pattern.
12147     //if (Op.getValueType() == MVT::i1)
12148     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12149     //                     DAG.getConstant(0, MVT::i1));
12150     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12151                        DAG.getConstant(0, Op.getValueType()));
12152   }
12153   unsigned Opcode = 0;
12154   unsigned NumOperands = 0;
12155
12156   // Truncate operations may prevent the merge of the SETCC instruction
12157   // and the arithmetic instruction before it. Attempt to truncate the operands
12158   // of the arithmetic instruction and use a reduced bit-width instruction.
12159   bool NeedTruncation = false;
12160   SDValue ArithOp = Op;
12161   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12162     SDValue Arith = Op->getOperand(0);
12163     // Both the trunc and the arithmetic op need to have one user each.
12164     if (Arith->hasOneUse())
12165       switch (Arith.getOpcode()) {
12166         default: break;
12167         case ISD::ADD:
12168         case ISD::SUB:
12169         case ISD::AND:
12170         case ISD::OR:
12171         case ISD::XOR: {
12172           NeedTruncation = true;
12173           ArithOp = Arith;
12174         }
12175       }
12176   }
12177
12178   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12179   // which may be the result of a CAST.  We use the variable 'Op', which is the
12180   // non-casted variable when we check for possible users.
12181   switch (ArithOp.getOpcode()) {
12182   case ISD::ADD:
12183     // Due to an isel shortcoming, be conservative if this add is likely to be
12184     // selected as part of a load-modify-store instruction. When the root node
12185     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12186     // uses of other nodes in the match, such as the ADD in this case. This
12187     // leads to the ADD being left around and reselected, with the result being
12188     // two adds in the output.  Alas, even if none our users are stores, that
12189     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12190     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12191     // climbing the DAG back to the root, and it doesn't seem to be worth the
12192     // effort.
12193     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12194          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12195       if (UI->getOpcode() != ISD::CopyToReg &&
12196           UI->getOpcode() != ISD::SETCC &&
12197           UI->getOpcode() != ISD::STORE)
12198         goto default_case;
12199
12200     if (ConstantSDNode *C =
12201         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12202       // An add of one will be selected as an INC.
12203       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12204         Opcode = X86ISD::INC;
12205         NumOperands = 1;
12206         break;
12207       }
12208
12209       // An add of negative one (subtract of one) will be selected as a DEC.
12210       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12211         Opcode = X86ISD::DEC;
12212         NumOperands = 1;
12213         break;
12214       }
12215     }
12216
12217     // Otherwise use a regular EFLAGS-setting add.
12218     Opcode = X86ISD::ADD;
12219     NumOperands = 2;
12220     break;
12221   case ISD::SHL:
12222   case ISD::SRL:
12223     // If we have a constant logical shift that's only used in a comparison
12224     // against zero turn it into an equivalent AND. This allows turning it into
12225     // a TEST instruction later.
12226     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12227         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12228       EVT VT = Op.getValueType();
12229       unsigned BitWidth = VT.getSizeInBits();
12230       unsigned ShAmt = Op->getConstantOperandVal(1);
12231       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12232         break;
12233       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12234                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12235                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12236       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12237         break;
12238       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12239                                 DAG.getConstant(Mask, VT));
12240       DAG.ReplaceAllUsesWith(Op, New);
12241       Op = New;
12242     }
12243     break;
12244
12245   case ISD::AND:
12246     // If the primary and result isn't used, don't bother using X86ISD::AND,
12247     // because a TEST instruction will be better.
12248     if (!hasNonFlagsUse(Op))
12249       break;
12250     // FALL THROUGH
12251   case ISD::SUB:
12252   case ISD::OR:
12253   case ISD::XOR:
12254     // Due to the ISEL shortcoming noted above, be conservative if this op is
12255     // likely to be selected as part of a load-modify-store instruction.
12256     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12257            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12258       if (UI->getOpcode() == ISD::STORE)
12259         goto default_case;
12260
12261     // Otherwise use a regular EFLAGS-setting instruction.
12262     switch (ArithOp.getOpcode()) {
12263     default: llvm_unreachable("unexpected operator!");
12264     case ISD::SUB: Opcode = X86ISD::SUB; break;
12265     case ISD::XOR: Opcode = X86ISD::XOR; break;
12266     case ISD::AND: Opcode = X86ISD::AND; break;
12267     case ISD::OR: {
12268       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12269         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12270         if (EFLAGS.getNode())
12271           return EFLAGS;
12272       }
12273       Opcode = X86ISD::OR;
12274       break;
12275     }
12276     }
12277
12278     NumOperands = 2;
12279     break;
12280   case X86ISD::ADD:
12281   case X86ISD::SUB:
12282   case X86ISD::INC:
12283   case X86ISD::DEC:
12284   case X86ISD::OR:
12285   case X86ISD::XOR:
12286   case X86ISD::AND:
12287     return SDValue(Op.getNode(), 1);
12288   default:
12289   default_case:
12290     break;
12291   }
12292
12293   // If we found that truncation is beneficial, perform the truncation and
12294   // update 'Op'.
12295   if (NeedTruncation) {
12296     EVT VT = Op.getValueType();
12297     SDValue WideVal = Op->getOperand(0);
12298     EVT WideVT = WideVal.getValueType();
12299     unsigned ConvertedOp = 0;
12300     // Use a target machine opcode to prevent further DAGCombine
12301     // optimizations that may separate the arithmetic operations
12302     // from the setcc node.
12303     switch (WideVal.getOpcode()) {
12304       default: break;
12305       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12306       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12307       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12308       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12309       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12310     }
12311
12312     if (ConvertedOp) {
12313       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12314       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12315         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12316         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12317         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12318       }
12319     }
12320   }
12321
12322   if (Opcode == 0)
12323     // Emit a CMP with 0, which is the TEST pattern.
12324     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12325                        DAG.getConstant(0, Op.getValueType()));
12326
12327   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12328   SmallVector<SDValue, 4> Ops;
12329   for (unsigned i = 0; i != NumOperands; ++i)
12330     Ops.push_back(Op.getOperand(i));
12331
12332   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12333   DAG.ReplaceAllUsesWith(Op, New);
12334   return SDValue(New.getNode(), 1);
12335 }
12336
12337 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12338 /// equivalent.
12339 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12340                                    SDLoc dl, SelectionDAG &DAG) const {
12341   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12342     if (C->getAPIntValue() == 0)
12343       return EmitTest(Op0, X86CC, dl, DAG);
12344
12345      if (Op0.getValueType() == MVT::i1)
12346        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12347   }
12348  
12349   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12350        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12351     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12352     // This avoids subregister aliasing issues. Keep the smaller reference 
12353     // if we're optimizing for size, however, as that'll allow better folding 
12354     // of memory operations.
12355     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12356         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12357              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12358         !Subtarget->isAtom()) {
12359       unsigned ExtendOp =
12360           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12361       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12362       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12363     }
12364     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12365     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12366     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12367                               Op0, Op1);
12368     return SDValue(Sub.getNode(), 1);
12369   }
12370   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12371 }
12372
12373 /// Convert a comparison if required by the subtarget.
12374 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12375                                                  SelectionDAG &DAG) const {
12376   // If the subtarget does not support the FUCOMI instruction, floating-point
12377   // comparisons have to be converted.
12378   if (Subtarget->hasCMov() ||
12379       Cmp.getOpcode() != X86ISD::CMP ||
12380       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12381       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12382     return Cmp;
12383
12384   // The instruction selector will select an FUCOM instruction instead of
12385   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12386   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12387   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12388   SDLoc dl(Cmp);
12389   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12390   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12391   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12392                             DAG.getConstant(8, MVT::i8));
12393   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12394   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12395 }
12396
12397 static bool isAllOnes(SDValue V) {
12398   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12399   return C && C->isAllOnesValue();
12400 }
12401
12402 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12403 /// if it's possible.
12404 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12405                                      SDLoc dl, SelectionDAG &DAG) const {
12406   SDValue Op0 = And.getOperand(0);
12407   SDValue Op1 = And.getOperand(1);
12408   if (Op0.getOpcode() == ISD::TRUNCATE)
12409     Op0 = Op0.getOperand(0);
12410   if (Op1.getOpcode() == ISD::TRUNCATE)
12411     Op1 = Op1.getOperand(0);
12412
12413   SDValue LHS, RHS;
12414   if (Op1.getOpcode() == ISD::SHL)
12415     std::swap(Op0, Op1);
12416   if (Op0.getOpcode() == ISD::SHL) {
12417     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12418       if (And00C->getZExtValue() == 1) {
12419         // If we looked past a truncate, check that it's only truncating away
12420         // known zeros.
12421         unsigned BitWidth = Op0.getValueSizeInBits();
12422         unsigned AndBitWidth = And.getValueSizeInBits();
12423         if (BitWidth > AndBitWidth) {
12424           APInt Zeros, Ones;
12425           DAG.computeKnownBits(Op0, Zeros, Ones);
12426           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12427             return SDValue();
12428         }
12429         LHS = Op1;
12430         RHS = Op0.getOperand(1);
12431       }
12432   } else if (Op1.getOpcode() == ISD::Constant) {
12433     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12434     uint64_t AndRHSVal = AndRHS->getZExtValue();
12435     SDValue AndLHS = Op0;
12436
12437     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12438       LHS = AndLHS.getOperand(0);
12439       RHS = AndLHS.getOperand(1);
12440     }
12441
12442     // Use BT if the immediate can't be encoded in a TEST instruction.
12443     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12444       LHS = AndLHS;
12445       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12446     }
12447   }
12448
12449   if (LHS.getNode()) {
12450     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12451     // instruction.  Since the shift amount is in-range-or-undefined, we know
12452     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12453     // the encoding for the i16 version is larger than the i32 version.
12454     // Also promote i16 to i32 for performance / code size reason.
12455     if (LHS.getValueType() == MVT::i8 ||
12456         LHS.getValueType() == MVT::i16)
12457       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12458
12459     // If the operand types disagree, extend the shift amount to match.  Since
12460     // BT ignores high bits (like shifts) we can use anyextend.
12461     if (LHS.getValueType() != RHS.getValueType())
12462       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12463
12464     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12465     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12466     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12467                        DAG.getConstant(Cond, MVT::i8), BT);
12468   }
12469
12470   return SDValue();
12471 }
12472
12473 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12474 /// mask CMPs.
12475 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12476                               SDValue &Op1) {
12477   unsigned SSECC;
12478   bool Swap = false;
12479
12480   // SSE Condition code mapping:
12481   //  0 - EQ
12482   //  1 - LT
12483   //  2 - LE
12484   //  3 - UNORD
12485   //  4 - NEQ
12486   //  5 - NLT
12487   //  6 - NLE
12488   //  7 - ORD
12489   switch (SetCCOpcode) {
12490   default: llvm_unreachable("Unexpected SETCC condition");
12491   case ISD::SETOEQ:
12492   case ISD::SETEQ:  SSECC = 0; break;
12493   case ISD::SETOGT:
12494   case ISD::SETGT:  Swap = true; // Fallthrough
12495   case ISD::SETLT:
12496   case ISD::SETOLT: SSECC = 1; break;
12497   case ISD::SETOGE:
12498   case ISD::SETGE:  Swap = true; // Fallthrough
12499   case ISD::SETLE:
12500   case ISD::SETOLE: SSECC = 2; break;
12501   case ISD::SETUO:  SSECC = 3; break;
12502   case ISD::SETUNE:
12503   case ISD::SETNE:  SSECC = 4; break;
12504   case ISD::SETULE: Swap = true; // Fallthrough
12505   case ISD::SETUGE: SSECC = 5; break;
12506   case ISD::SETULT: Swap = true; // Fallthrough
12507   case ISD::SETUGT: SSECC = 6; break;
12508   case ISD::SETO:   SSECC = 7; break;
12509   case ISD::SETUEQ:
12510   case ISD::SETONE: SSECC = 8; break;
12511   }
12512   if (Swap)
12513     std::swap(Op0, Op1);
12514
12515   return SSECC;
12516 }
12517
12518 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12519 // ones, and then concatenate the result back.
12520 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12521   MVT VT = Op.getSimpleValueType();
12522
12523   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12524          "Unsupported value type for operation");
12525
12526   unsigned NumElems = VT.getVectorNumElements();
12527   SDLoc dl(Op);
12528   SDValue CC = Op.getOperand(2);
12529
12530   // Extract the LHS vectors
12531   SDValue LHS = Op.getOperand(0);
12532   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12533   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12534
12535   // Extract the RHS vectors
12536   SDValue RHS = Op.getOperand(1);
12537   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12538   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12539
12540   // Issue the operation on the smaller types and concatenate the result back
12541   MVT EltVT = VT.getVectorElementType();
12542   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12543   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12544                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12545                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12546 }
12547
12548 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12549                                      const X86Subtarget *Subtarget) {
12550   SDValue Op0 = Op.getOperand(0);
12551   SDValue Op1 = Op.getOperand(1);
12552   SDValue CC = Op.getOperand(2);
12553   MVT VT = Op.getSimpleValueType();
12554   SDLoc dl(Op);
12555
12556   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12557          Op.getValueType().getScalarType() == MVT::i1 &&
12558          "Cannot set masked compare for this operation");
12559
12560   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12561   unsigned  Opc = 0;
12562   bool Unsigned = false;
12563   bool Swap = false;
12564   unsigned SSECC;
12565   switch (SetCCOpcode) {
12566   default: llvm_unreachable("Unexpected SETCC condition");
12567   case ISD::SETNE:  SSECC = 4; break;
12568   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12569   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12570   case ISD::SETLT:  Swap = true; //fall-through
12571   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12572   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12573   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12574   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12575   case ISD::SETULE: Unsigned = true; //fall-through
12576   case ISD::SETLE:  SSECC = 2; break;
12577   }
12578
12579   if (Swap)
12580     std::swap(Op0, Op1);
12581   if (Opc)
12582     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12583   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12584   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12585                      DAG.getConstant(SSECC, MVT::i8));
12586 }
12587
12588 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12589 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12590 /// return an empty value.
12591 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12592 {
12593   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12594   if (!BV)
12595     return SDValue();
12596
12597   MVT VT = Op1.getSimpleValueType();
12598   MVT EVT = VT.getVectorElementType();
12599   unsigned n = VT.getVectorNumElements();
12600   SmallVector<SDValue, 8> ULTOp1;
12601
12602   for (unsigned i = 0; i < n; ++i) {
12603     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12604     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12605       return SDValue();
12606
12607     // Avoid underflow.
12608     APInt Val = Elt->getAPIntValue();
12609     if (Val == 0)
12610       return SDValue();
12611
12612     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12613   }
12614
12615   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12616 }
12617
12618 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12619                            SelectionDAG &DAG) {
12620   SDValue Op0 = Op.getOperand(0);
12621   SDValue Op1 = Op.getOperand(1);
12622   SDValue CC = Op.getOperand(2);
12623   MVT VT = Op.getSimpleValueType();
12624   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12625   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12626   SDLoc dl(Op);
12627
12628   if (isFP) {
12629 #ifndef NDEBUG
12630     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12631     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12632 #endif
12633
12634     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12635     unsigned Opc = X86ISD::CMPP;
12636     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12637       assert(VT.getVectorNumElements() <= 16);
12638       Opc = X86ISD::CMPM;
12639     }
12640     // In the two special cases we can't handle, emit two comparisons.
12641     if (SSECC == 8) {
12642       unsigned CC0, CC1;
12643       unsigned CombineOpc;
12644       if (SetCCOpcode == ISD::SETUEQ) {
12645         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12646       } else {
12647         assert(SetCCOpcode == ISD::SETONE);
12648         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12649       }
12650
12651       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12652                                  DAG.getConstant(CC0, MVT::i8));
12653       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12654                                  DAG.getConstant(CC1, MVT::i8));
12655       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12656     }
12657     // Handle all other FP comparisons here.
12658     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12659                        DAG.getConstant(SSECC, MVT::i8));
12660   }
12661
12662   // Break 256-bit integer vector compare into smaller ones.
12663   if (VT.is256BitVector() && !Subtarget->hasInt256())
12664     return Lower256IntVSETCC(Op, DAG);
12665
12666   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12667   EVT OpVT = Op1.getValueType();
12668   if (Subtarget->hasAVX512()) {
12669     if (Op1.getValueType().is512BitVector() ||
12670         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12671       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12672
12673     // In AVX-512 architecture setcc returns mask with i1 elements,
12674     // But there is no compare instruction for i8 and i16 elements.
12675     // We are not talking about 512-bit operands in this case, these
12676     // types are illegal.
12677     if (MaskResult &&
12678         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12679          OpVT.getVectorElementType().getSizeInBits() >= 8))
12680       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12681                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12682   }
12683
12684   // We are handling one of the integer comparisons here.  Since SSE only has
12685   // GT and EQ comparisons for integer, swapping operands and multiple
12686   // operations may be required for some comparisons.
12687   unsigned Opc;
12688   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12689   bool Subus = false;
12690
12691   switch (SetCCOpcode) {
12692   default: llvm_unreachable("Unexpected SETCC condition");
12693   case ISD::SETNE:  Invert = true;
12694   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12695   case ISD::SETLT:  Swap = true;
12696   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12697   case ISD::SETGE:  Swap = true;
12698   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12699                     Invert = true; break;
12700   case ISD::SETULT: Swap = true;
12701   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12702                     FlipSigns = true; break;
12703   case ISD::SETUGE: Swap = true;
12704   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12705                     FlipSigns = true; Invert = true; break;
12706   }
12707
12708   // Special case: Use min/max operations for SETULE/SETUGE
12709   MVT VET = VT.getVectorElementType();
12710   bool hasMinMax =
12711        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12712     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12713
12714   if (hasMinMax) {
12715     switch (SetCCOpcode) {
12716     default: break;
12717     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12718     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12719     }
12720
12721     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12722   }
12723
12724   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12725   if (!MinMax && hasSubus) {
12726     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12727     // Op0 u<= Op1:
12728     //   t = psubus Op0, Op1
12729     //   pcmpeq t, <0..0>
12730     switch (SetCCOpcode) {
12731     default: break;
12732     case ISD::SETULT: {
12733       // If the comparison is against a constant we can turn this into a
12734       // setule.  With psubus, setule does not require a swap.  This is
12735       // beneficial because the constant in the register is no longer
12736       // destructed as the destination so it can be hoisted out of a loop.
12737       // Only do this pre-AVX since vpcmp* is no longer destructive.
12738       if (Subtarget->hasAVX())
12739         break;
12740       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12741       if (ULEOp1.getNode()) {
12742         Op1 = ULEOp1;
12743         Subus = true; Invert = false; Swap = false;
12744       }
12745       break;
12746     }
12747     // Psubus is better than flip-sign because it requires no inversion.
12748     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12749     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12750     }
12751
12752     if (Subus) {
12753       Opc = X86ISD::SUBUS;
12754       FlipSigns = false;
12755     }
12756   }
12757
12758   if (Swap)
12759     std::swap(Op0, Op1);
12760
12761   // Check that the operation in question is available (most are plain SSE2,
12762   // but PCMPGTQ and PCMPEQQ have different requirements).
12763   if (VT == MVT::v2i64) {
12764     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12765       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12766
12767       // First cast everything to the right type.
12768       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12769       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12770
12771       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12772       // bits of the inputs before performing those operations. The lower
12773       // compare is always unsigned.
12774       SDValue SB;
12775       if (FlipSigns) {
12776         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12777       } else {
12778         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12779         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12780         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12781                          Sign, Zero, Sign, Zero);
12782       }
12783       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12784       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12785
12786       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12787       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12788       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12789
12790       // Create masks for only the low parts/high parts of the 64 bit integers.
12791       static const int MaskHi[] = { 1, 1, 3, 3 };
12792       static const int MaskLo[] = { 0, 0, 2, 2 };
12793       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12794       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12795       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12796
12797       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12798       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12799
12800       if (Invert)
12801         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12802
12803       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12804     }
12805
12806     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12807       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12808       // pcmpeqd + pshufd + pand.
12809       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12810
12811       // First cast everything to the right type.
12812       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12813       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12814
12815       // Do the compare.
12816       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12817
12818       // Make sure the lower and upper halves are both all-ones.
12819       static const int Mask[] = { 1, 0, 3, 2 };
12820       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12821       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12822
12823       if (Invert)
12824         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12825
12826       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12827     }
12828   }
12829
12830   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12831   // bits of the inputs before performing those operations.
12832   if (FlipSigns) {
12833     EVT EltVT = VT.getVectorElementType();
12834     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12835     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12836     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12837   }
12838
12839   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12840
12841   // If the logical-not of the result is required, perform that now.
12842   if (Invert)
12843     Result = DAG.getNOT(dl, Result, VT);
12844
12845   if (MinMax)
12846     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12847
12848   if (Subus)
12849     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12850                          getZeroVector(VT, Subtarget, DAG, dl));
12851
12852   return Result;
12853 }
12854
12855 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12856
12857   MVT VT = Op.getSimpleValueType();
12858
12859   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12860
12861   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12862          && "SetCC type must be 8-bit or 1-bit integer");
12863   SDValue Op0 = Op.getOperand(0);
12864   SDValue Op1 = Op.getOperand(1);
12865   SDLoc dl(Op);
12866   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12867
12868   // Optimize to BT if possible.
12869   // Lower (X & (1 << N)) == 0 to BT(X, N).
12870   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12871   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12872   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12873       Op1.getOpcode() == ISD::Constant &&
12874       cast<ConstantSDNode>(Op1)->isNullValue() &&
12875       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12876     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12877     if (NewSetCC.getNode())
12878       return NewSetCC;
12879   }
12880
12881   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12882   // these.
12883   if (Op1.getOpcode() == ISD::Constant &&
12884       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12885        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12886       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12887
12888     // If the input is a setcc, then reuse the input setcc or use a new one with
12889     // the inverted condition.
12890     if (Op0.getOpcode() == X86ISD::SETCC) {
12891       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12892       bool Invert = (CC == ISD::SETNE) ^
12893         cast<ConstantSDNode>(Op1)->isNullValue();
12894       if (!Invert)
12895         return Op0;
12896
12897       CCode = X86::GetOppositeBranchCondition(CCode);
12898       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12899                                   DAG.getConstant(CCode, MVT::i8),
12900                                   Op0.getOperand(1));
12901       if (VT == MVT::i1)
12902         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12903       return SetCC;
12904     }
12905   }
12906   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12907       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12908       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12909
12910     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12911     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12912   }
12913
12914   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12915   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12916   if (X86CC == X86::COND_INVALID)
12917     return SDValue();
12918
12919   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12920   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12921   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12922                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12923   if (VT == MVT::i1)
12924     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12925   return SetCC;
12926 }
12927
12928 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12929 static bool isX86LogicalCmp(SDValue Op) {
12930   unsigned Opc = Op.getNode()->getOpcode();
12931   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12932       Opc == X86ISD::SAHF)
12933     return true;
12934   if (Op.getResNo() == 1 &&
12935       (Opc == X86ISD::ADD ||
12936        Opc == X86ISD::SUB ||
12937        Opc == X86ISD::ADC ||
12938        Opc == X86ISD::SBB ||
12939        Opc == X86ISD::SMUL ||
12940        Opc == X86ISD::UMUL ||
12941        Opc == X86ISD::INC ||
12942        Opc == X86ISD::DEC ||
12943        Opc == X86ISD::OR ||
12944        Opc == X86ISD::XOR ||
12945        Opc == X86ISD::AND))
12946     return true;
12947
12948   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12949     return true;
12950
12951   return false;
12952 }
12953
12954 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12955   if (V.getOpcode() != ISD::TRUNCATE)
12956     return false;
12957
12958   SDValue VOp0 = V.getOperand(0);
12959   unsigned InBits = VOp0.getValueSizeInBits();
12960   unsigned Bits = V.getValueSizeInBits();
12961   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12962 }
12963
12964 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12965   bool addTest = true;
12966   SDValue Cond  = Op.getOperand(0);
12967   SDValue Op1 = Op.getOperand(1);
12968   SDValue Op2 = Op.getOperand(2);
12969   SDLoc DL(Op);
12970   EVT VT = Op1.getValueType();
12971   SDValue CC;
12972
12973   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12974   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12975   // sequence later on.
12976   if (Cond.getOpcode() == ISD::SETCC &&
12977       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12978        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12979       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12980     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12981     int SSECC = translateX86FSETCC(
12982         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12983
12984     if (SSECC != 8) {
12985       if (Subtarget->hasAVX512()) {
12986         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12987                                   DAG.getConstant(SSECC, MVT::i8));
12988         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12989       }
12990       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12991                                 DAG.getConstant(SSECC, MVT::i8));
12992       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12993       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12994       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12995     }
12996   }
12997
12998   if (Cond.getOpcode() == ISD::SETCC) {
12999     SDValue NewCond = LowerSETCC(Cond, DAG);
13000     if (NewCond.getNode())
13001       Cond = NewCond;
13002   }
13003
13004   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13005   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13006   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13007   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13008   if (Cond.getOpcode() == X86ISD::SETCC &&
13009       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13010       isZero(Cond.getOperand(1).getOperand(1))) {
13011     SDValue Cmp = Cond.getOperand(1);
13012
13013     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13014
13015     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13016         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13017       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13018
13019       SDValue CmpOp0 = Cmp.getOperand(0);
13020       // Apply further optimizations for special cases
13021       // (select (x != 0), -1, 0) -> neg & sbb
13022       // (select (x == 0), 0, -1) -> neg & sbb
13023       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13024         if (YC->isNullValue() &&
13025             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13026           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13027           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13028                                     DAG.getConstant(0, CmpOp0.getValueType()),
13029                                     CmpOp0);
13030           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13031                                     DAG.getConstant(X86::COND_B, MVT::i8),
13032                                     SDValue(Neg.getNode(), 1));
13033           return Res;
13034         }
13035
13036       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13037                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13038       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13039
13040       SDValue Res =   // Res = 0 or -1.
13041         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13042                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13043
13044       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13045         Res = DAG.getNOT(DL, Res, Res.getValueType());
13046
13047       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13048       if (!N2C || !N2C->isNullValue())
13049         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13050       return Res;
13051     }
13052   }
13053
13054   // Look past (and (setcc_carry (cmp ...)), 1).
13055   if (Cond.getOpcode() == ISD::AND &&
13056       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13057     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13058     if (C && C->getAPIntValue() == 1)
13059       Cond = Cond.getOperand(0);
13060   }
13061
13062   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13063   // setting operand in place of the X86ISD::SETCC.
13064   unsigned CondOpcode = Cond.getOpcode();
13065   if (CondOpcode == X86ISD::SETCC ||
13066       CondOpcode == X86ISD::SETCC_CARRY) {
13067     CC = Cond.getOperand(0);
13068
13069     SDValue Cmp = Cond.getOperand(1);
13070     unsigned Opc = Cmp.getOpcode();
13071     MVT VT = Op.getSimpleValueType();
13072
13073     bool IllegalFPCMov = false;
13074     if (VT.isFloatingPoint() && !VT.isVector() &&
13075         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13076       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13077
13078     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13079         Opc == X86ISD::BT) { // FIXME
13080       Cond = Cmp;
13081       addTest = false;
13082     }
13083   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13084              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13085              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13086               Cond.getOperand(0).getValueType() != MVT::i8)) {
13087     SDValue LHS = Cond.getOperand(0);
13088     SDValue RHS = Cond.getOperand(1);
13089     unsigned X86Opcode;
13090     unsigned X86Cond;
13091     SDVTList VTs;
13092     switch (CondOpcode) {
13093     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13094     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13095     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13096     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13097     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13098     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13099     default: llvm_unreachable("unexpected overflowing operator");
13100     }
13101     if (CondOpcode == ISD::UMULO)
13102       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13103                           MVT::i32);
13104     else
13105       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13106
13107     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13108
13109     if (CondOpcode == ISD::UMULO)
13110       Cond = X86Op.getValue(2);
13111     else
13112       Cond = X86Op.getValue(1);
13113
13114     CC = DAG.getConstant(X86Cond, MVT::i8);
13115     addTest = false;
13116   }
13117
13118   if (addTest) {
13119     // Look pass the truncate if the high bits are known zero.
13120     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13121         Cond = Cond.getOperand(0);
13122
13123     // We know the result of AND is compared against zero. Try to match
13124     // it to BT.
13125     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13126       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13127       if (NewSetCC.getNode()) {
13128         CC = NewSetCC.getOperand(0);
13129         Cond = NewSetCC.getOperand(1);
13130         addTest = false;
13131       }
13132     }
13133   }
13134
13135   if (addTest) {
13136     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13137     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13138   }
13139
13140   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13141   // a <  b ?  0 : -1 -> RES = setcc_carry
13142   // a >= b ? -1 :  0 -> RES = setcc_carry
13143   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13144   if (Cond.getOpcode() == X86ISD::SUB) {
13145     Cond = ConvertCmpIfNecessary(Cond, DAG);
13146     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13147
13148     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13149         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13150       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13151                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13152       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13153         return DAG.getNOT(DL, Res, Res.getValueType());
13154       return Res;
13155     }
13156   }
13157
13158   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13159   // widen the cmov and push the truncate through. This avoids introducing a new
13160   // branch during isel and doesn't add any extensions.
13161   if (Op.getValueType() == MVT::i8 &&
13162       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13163     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13164     if (T1.getValueType() == T2.getValueType() &&
13165         // Blacklist CopyFromReg to avoid partial register stalls.
13166         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13167       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13168       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13169       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13170     }
13171   }
13172
13173   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13174   // condition is true.
13175   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13176   SDValue Ops[] = { Op2, Op1, CC, Cond };
13177   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13178 }
13179
13180 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13181   MVT VT = Op->getSimpleValueType(0);
13182   SDValue In = Op->getOperand(0);
13183   MVT InVT = In.getSimpleValueType();
13184   SDLoc dl(Op);
13185
13186   unsigned int NumElts = VT.getVectorNumElements();
13187   if (NumElts != 8 && NumElts != 16)
13188     return SDValue();
13189
13190   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13191     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13192
13193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13194   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13195
13196   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13197   Constant *C = ConstantInt::get(*DAG.getContext(),
13198     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13199
13200   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13201   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13202   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13203                           MachinePointerInfo::getConstantPool(),
13204                           false, false, false, Alignment);
13205   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13206   if (VT.is512BitVector())
13207     return Brcst;
13208   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13209 }
13210
13211 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13212                                 SelectionDAG &DAG) {
13213   MVT VT = Op->getSimpleValueType(0);
13214   SDValue In = Op->getOperand(0);
13215   MVT InVT = In.getSimpleValueType();
13216   SDLoc dl(Op);
13217
13218   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13219     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13220
13221   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13222       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13223       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13224     return SDValue();
13225
13226   if (Subtarget->hasInt256())
13227     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13228
13229   // Optimize vectors in AVX mode
13230   // Sign extend  v8i16 to v8i32 and
13231   //              v4i32 to v4i64
13232   //
13233   // Divide input vector into two parts
13234   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13235   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13236   // concat the vectors to original VT
13237
13238   unsigned NumElems = InVT.getVectorNumElements();
13239   SDValue Undef = DAG.getUNDEF(InVT);
13240
13241   SmallVector<int,8> ShufMask1(NumElems, -1);
13242   for (unsigned i = 0; i != NumElems/2; ++i)
13243     ShufMask1[i] = i;
13244
13245   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13246
13247   SmallVector<int,8> ShufMask2(NumElems, -1);
13248   for (unsigned i = 0; i != NumElems/2; ++i)
13249     ShufMask2[i] = i + NumElems/2;
13250
13251   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13252
13253   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13254                                 VT.getVectorNumElements()/2);
13255
13256   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13257   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13258
13259   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13260 }
13261
13262 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13263 // may emit an illegal shuffle but the expansion is still better than scalar
13264 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13265 // we'll emit a shuffle and a arithmetic shift.
13266 // TODO: It is possible to support ZExt by zeroing the undef values during
13267 // the shuffle phase or after the shuffle.
13268 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13269                                  SelectionDAG &DAG) {
13270   MVT RegVT = Op.getSimpleValueType();
13271   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13272   assert(RegVT.isInteger() &&
13273          "We only custom lower integer vector sext loads.");
13274
13275   // Nothing useful we can do without SSE2 shuffles.
13276   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13277
13278   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13279   SDLoc dl(Ld);
13280   EVT MemVT = Ld->getMemoryVT();
13281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13282   unsigned RegSz = RegVT.getSizeInBits();
13283
13284   ISD::LoadExtType Ext = Ld->getExtensionType();
13285
13286   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13287          && "Only anyext and sext are currently implemented.");
13288   assert(MemVT != RegVT && "Cannot extend to the same type");
13289   assert(MemVT.isVector() && "Must load a vector from memory");
13290
13291   unsigned NumElems = RegVT.getVectorNumElements();
13292   unsigned MemSz = MemVT.getSizeInBits();
13293   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13294
13295   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13296     // The only way in which we have a legal 256-bit vector result but not the
13297     // integer 256-bit operations needed to directly lower a sextload is if we
13298     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13299     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13300     // correctly legalized. We do this late to allow the canonical form of
13301     // sextload to persist throughout the rest of the DAG combiner -- it wants
13302     // to fold together any extensions it can, and so will fuse a sign_extend
13303     // of an sextload into a sextload targeting a wider value.
13304     SDValue Load;
13305     if (MemSz == 128) {
13306       // Just switch this to a normal load.
13307       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13308                                        "it must be a legal 128-bit vector "
13309                                        "type!");
13310       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13311                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13312                   Ld->isInvariant(), Ld->getAlignment());
13313     } else {
13314       assert(MemSz < 128 &&
13315              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13316       // Do an sext load to a 128-bit vector type. We want to use the same
13317       // number of elements, but elements half as wide. This will end up being
13318       // recursively lowered by this routine, but will succeed as we definitely
13319       // have all the necessary features if we're using AVX1.
13320       EVT HalfEltVT =
13321           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13322       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13323       Load =
13324           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13325                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13326                          Ld->isNonTemporal(), Ld->isInvariant(),
13327                          Ld->getAlignment());
13328     }
13329
13330     // Replace chain users with the new chain.
13331     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13332     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13333
13334     // Finally, do a normal sign-extend to the desired register.
13335     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13336   }
13337
13338   // All sizes must be a power of two.
13339   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13340          "Non-power-of-two elements are not custom lowered!");
13341
13342   // Attempt to load the original value using scalar loads.
13343   // Find the largest scalar type that divides the total loaded size.
13344   MVT SclrLoadTy = MVT::i8;
13345   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13346        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13347     MVT Tp = (MVT::SimpleValueType)tp;
13348     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13349       SclrLoadTy = Tp;
13350     }
13351   }
13352
13353   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13354   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13355       (64 <= MemSz))
13356     SclrLoadTy = MVT::f64;
13357
13358   // Calculate the number of scalar loads that we need to perform
13359   // in order to load our vector from memory.
13360   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13361
13362   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13363          "Can only lower sext loads with a single scalar load!");
13364
13365   unsigned loadRegZize = RegSz;
13366   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13367     loadRegZize /= 2;
13368
13369   // Represent our vector as a sequence of elements which are the
13370   // largest scalar that we can load.
13371   EVT LoadUnitVecVT = EVT::getVectorVT(
13372       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13373
13374   // Represent the data using the same element type that is stored in
13375   // memory. In practice, we ''widen'' MemVT.
13376   EVT WideVecVT =
13377       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13378                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13379
13380   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13381          "Invalid vector type");
13382
13383   // We can't shuffle using an illegal type.
13384   assert(TLI.isTypeLegal(WideVecVT) &&
13385          "We only lower types that form legal widened vector types");
13386
13387   SmallVector<SDValue, 8> Chains;
13388   SDValue Ptr = Ld->getBasePtr();
13389   SDValue Increment =
13390       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13391   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13392
13393   for (unsigned i = 0; i < NumLoads; ++i) {
13394     // Perform a single load.
13395     SDValue ScalarLoad =
13396         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13397                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13398                     Ld->getAlignment());
13399     Chains.push_back(ScalarLoad.getValue(1));
13400     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13401     // another round of DAGCombining.
13402     if (i == 0)
13403       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13404     else
13405       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13406                         ScalarLoad, DAG.getIntPtrConstant(i));
13407
13408     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13409   }
13410
13411   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13412
13413   // Bitcast the loaded value to a vector of the original element type, in
13414   // the size of the target vector type.
13415   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13416   unsigned SizeRatio = RegSz / MemSz;
13417
13418   if (Ext == ISD::SEXTLOAD) {
13419     // If we have SSE4.1, we can directly emit a VSEXT node.
13420     if (Subtarget->hasSSE41()) {
13421       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13422       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13423       return Sext;
13424     }
13425
13426     // Otherwise we'll shuffle the small elements in the high bits of the
13427     // larger type and perform an arithmetic shift. If the shift is not legal
13428     // it's better to scalarize.
13429     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13430            "We can't implement a sext load without an arithmetic right shift!");
13431
13432     // Redistribute the loaded elements into the different locations.
13433     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13434     for (unsigned i = 0; i != NumElems; ++i)
13435       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13436
13437     SDValue Shuff = DAG.getVectorShuffle(
13438         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13439
13440     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13441
13442     // Build the arithmetic shift.
13443     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13444                    MemVT.getVectorElementType().getSizeInBits();
13445     Shuff =
13446         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13447
13448     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13449     return Shuff;
13450   }
13451
13452   // Redistribute the loaded elements into the different locations.
13453   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13454   for (unsigned i = 0; i != NumElems; ++i)
13455     ShuffleVec[i * SizeRatio] = i;
13456
13457   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13458                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13459
13460   // Bitcast to the requested type.
13461   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13462   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13463   return Shuff;
13464 }
13465
13466 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13467 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13468 // from the AND / OR.
13469 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13470   Opc = Op.getOpcode();
13471   if (Opc != ISD::OR && Opc != ISD::AND)
13472     return false;
13473   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13474           Op.getOperand(0).hasOneUse() &&
13475           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13476           Op.getOperand(1).hasOneUse());
13477 }
13478
13479 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13480 // 1 and that the SETCC node has a single use.
13481 static bool isXor1OfSetCC(SDValue Op) {
13482   if (Op.getOpcode() != ISD::XOR)
13483     return false;
13484   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13485   if (N1C && N1C->getAPIntValue() == 1) {
13486     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13487       Op.getOperand(0).hasOneUse();
13488   }
13489   return false;
13490 }
13491
13492 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13493   bool addTest = true;
13494   SDValue Chain = Op.getOperand(0);
13495   SDValue Cond  = Op.getOperand(1);
13496   SDValue Dest  = Op.getOperand(2);
13497   SDLoc dl(Op);
13498   SDValue CC;
13499   bool Inverted = false;
13500
13501   if (Cond.getOpcode() == ISD::SETCC) {
13502     // Check for setcc([su]{add,sub,mul}o == 0).
13503     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13504         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13505         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13506         Cond.getOperand(0).getResNo() == 1 &&
13507         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13508          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13509          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13510          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13511          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13512          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13513       Inverted = true;
13514       Cond = Cond.getOperand(0);
13515     } else {
13516       SDValue NewCond = LowerSETCC(Cond, DAG);
13517       if (NewCond.getNode())
13518         Cond = NewCond;
13519     }
13520   }
13521 #if 0
13522   // FIXME: LowerXALUO doesn't handle these!!
13523   else if (Cond.getOpcode() == X86ISD::ADD  ||
13524            Cond.getOpcode() == X86ISD::SUB  ||
13525            Cond.getOpcode() == X86ISD::SMUL ||
13526            Cond.getOpcode() == X86ISD::UMUL)
13527     Cond = LowerXALUO(Cond, DAG);
13528 #endif
13529
13530   // Look pass (and (setcc_carry (cmp ...)), 1).
13531   if (Cond.getOpcode() == ISD::AND &&
13532       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13533     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13534     if (C && C->getAPIntValue() == 1)
13535       Cond = Cond.getOperand(0);
13536   }
13537
13538   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13539   // setting operand in place of the X86ISD::SETCC.
13540   unsigned CondOpcode = Cond.getOpcode();
13541   if (CondOpcode == X86ISD::SETCC ||
13542       CondOpcode == X86ISD::SETCC_CARRY) {
13543     CC = Cond.getOperand(0);
13544
13545     SDValue Cmp = Cond.getOperand(1);
13546     unsigned Opc = Cmp.getOpcode();
13547     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13548     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13549       Cond = Cmp;
13550       addTest = false;
13551     } else {
13552       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13553       default: break;
13554       case X86::COND_O:
13555       case X86::COND_B:
13556         // These can only come from an arithmetic instruction with overflow,
13557         // e.g. SADDO, UADDO.
13558         Cond = Cond.getNode()->getOperand(1);
13559         addTest = false;
13560         break;
13561       }
13562     }
13563   }
13564   CondOpcode = Cond.getOpcode();
13565   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13566       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13567       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13568        Cond.getOperand(0).getValueType() != MVT::i8)) {
13569     SDValue LHS = Cond.getOperand(0);
13570     SDValue RHS = Cond.getOperand(1);
13571     unsigned X86Opcode;
13572     unsigned X86Cond;
13573     SDVTList VTs;
13574     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13575     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13576     // X86ISD::INC).
13577     switch (CondOpcode) {
13578     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13579     case ISD::SADDO:
13580       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13581         if (C->isOne()) {
13582           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13583           break;
13584         }
13585       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13586     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13587     case ISD::SSUBO:
13588       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13589         if (C->isOne()) {
13590           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13591           break;
13592         }
13593       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13594     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13595     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13596     default: llvm_unreachable("unexpected overflowing operator");
13597     }
13598     if (Inverted)
13599       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13600     if (CondOpcode == ISD::UMULO)
13601       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13602                           MVT::i32);
13603     else
13604       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13605
13606     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13607
13608     if (CondOpcode == ISD::UMULO)
13609       Cond = X86Op.getValue(2);
13610     else
13611       Cond = X86Op.getValue(1);
13612
13613     CC = DAG.getConstant(X86Cond, MVT::i8);
13614     addTest = false;
13615   } else {
13616     unsigned CondOpc;
13617     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13618       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13619       if (CondOpc == ISD::OR) {
13620         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13621         // two branches instead of an explicit OR instruction with a
13622         // separate test.
13623         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13624             isX86LogicalCmp(Cmp)) {
13625           CC = Cond.getOperand(0).getOperand(0);
13626           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13627                               Chain, Dest, CC, Cmp);
13628           CC = Cond.getOperand(1).getOperand(0);
13629           Cond = Cmp;
13630           addTest = false;
13631         }
13632       } else { // ISD::AND
13633         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13634         // two branches instead of an explicit AND instruction with a
13635         // separate test. However, we only do this if this block doesn't
13636         // have a fall-through edge, because this requires an explicit
13637         // jmp when the condition is false.
13638         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13639             isX86LogicalCmp(Cmp) &&
13640             Op.getNode()->hasOneUse()) {
13641           X86::CondCode CCode =
13642             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13643           CCode = X86::GetOppositeBranchCondition(CCode);
13644           CC = DAG.getConstant(CCode, MVT::i8);
13645           SDNode *User = *Op.getNode()->use_begin();
13646           // Look for an unconditional branch following this conditional branch.
13647           // We need this because we need to reverse the successors in order
13648           // to implement FCMP_OEQ.
13649           if (User->getOpcode() == ISD::BR) {
13650             SDValue FalseBB = User->getOperand(1);
13651             SDNode *NewBR =
13652               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13653             assert(NewBR == User);
13654             (void)NewBR;
13655             Dest = FalseBB;
13656
13657             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13658                                 Chain, Dest, CC, Cmp);
13659             X86::CondCode CCode =
13660               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13661             CCode = X86::GetOppositeBranchCondition(CCode);
13662             CC = DAG.getConstant(CCode, MVT::i8);
13663             Cond = Cmp;
13664             addTest = false;
13665           }
13666         }
13667       }
13668     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13669       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13670       // It should be transformed during dag combiner except when the condition
13671       // is set by a arithmetics with overflow node.
13672       X86::CondCode CCode =
13673         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13674       CCode = X86::GetOppositeBranchCondition(CCode);
13675       CC = DAG.getConstant(CCode, MVT::i8);
13676       Cond = Cond.getOperand(0).getOperand(1);
13677       addTest = false;
13678     } else if (Cond.getOpcode() == ISD::SETCC &&
13679                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13680       // For FCMP_OEQ, we can emit
13681       // two branches instead of an explicit AND instruction with a
13682       // separate test. However, we only do this if this block doesn't
13683       // have a fall-through edge, because this requires an explicit
13684       // jmp when the condition is false.
13685       if (Op.getNode()->hasOneUse()) {
13686         SDNode *User = *Op.getNode()->use_begin();
13687         // Look for an unconditional branch following this conditional branch.
13688         // We need this because we need to reverse the successors in order
13689         // to implement FCMP_OEQ.
13690         if (User->getOpcode() == ISD::BR) {
13691           SDValue FalseBB = User->getOperand(1);
13692           SDNode *NewBR =
13693             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13694           assert(NewBR == User);
13695           (void)NewBR;
13696           Dest = FalseBB;
13697
13698           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13699                                     Cond.getOperand(0), Cond.getOperand(1));
13700           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13701           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13702           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13703                               Chain, Dest, CC, Cmp);
13704           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13705           Cond = Cmp;
13706           addTest = false;
13707         }
13708       }
13709     } else if (Cond.getOpcode() == ISD::SETCC &&
13710                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13711       // For FCMP_UNE, we can emit
13712       // two branches instead of an explicit AND instruction with a
13713       // separate test. However, we only do this if this block doesn't
13714       // have a fall-through edge, because this requires an explicit
13715       // jmp when the condition is false.
13716       if (Op.getNode()->hasOneUse()) {
13717         SDNode *User = *Op.getNode()->use_begin();
13718         // Look for an unconditional branch following this conditional branch.
13719         // We need this because we need to reverse the successors in order
13720         // to implement FCMP_UNE.
13721         if (User->getOpcode() == ISD::BR) {
13722           SDValue FalseBB = User->getOperand(1);
13723           SDNode *NewBR =
13724             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13725           assert(NewBR == User);
13726           (void)NewBR;
13727
13728           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13729                                     Cond.getOperand(0), Cond.getOperand(1));
13730           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13731           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13732           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13733                               Chain, Dest, CC, Cmp);
13734           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13735           Cond = Cmp;
13736           addTest = false;
13737           Dest = FalseBB;
13738         }
13739       }
13740     }
13741   }
13742
13743   if (addTest) {
13744     // Look pass the truncate if the high bits are known zero.
13745     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13746         Cond = Cond.getOperand(0);
13747
13748     // We know the result of AND is compared against zero. Try to match
13749     // it to BT.
13750     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13751       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13752       if (NewSetCC.getNode()) {
13753         CC = NewSetCC.getOperand(0);
13754         Cond = NewSetCC.getOperand(1);
13755         addTest = false;
13756       }
13757     }
13758   }
13759
13760   if (addTest) {
13761     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13762     CC = DAG.getConstant(X86Cond, MVT::i8);
13763     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13764   }
13765   Cond = ConvertCmpIfNecessary(Cond, DAG);
13766   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13767                      Chain, Dest, CC, Cond);
13768 }
13769
13770 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13771 // Calls to _alloca are needed to probe the stack when allocating more than 4k
13772 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13773 // that the guard pages used by the OS virtual memory manager are allocated in
13774 // correct sequence.
13775 SDValue
13776 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13777                                            SelectionDAG &DAG) const {
13778   MachineFunction &MF = DAG.getMachineFunction();
13779   bool SplitStack = MF.shouldSplitStack();
13780   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13781                SplitStack;
13782   SDLoc dl(Op);
13783
13784   if (!Lower) {
13785     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13786     SDNode* Node = Op.getNode();
13787
13788     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13789     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13790         " not tell us which reg is the stack pointer!");
13791     EVT VT = Node->getValueType(0);
13792     SDValue Tmp1 = SDValue(Node, 0);
13793     SDValue Tmp2 = SDValue(Node, 1);
13794     SDValue Tmp3 = Node->getOperand(2);
13795     SDValue Chain = Tmp1.getOperand(0);
13796
13797     // Chain the dynamic stack allocation so that it doesn't modify the stack
13798     // pointer when other instructions are using the stack.
13799     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13800         SDLoc(Node));
13801
13802     SDValue Size = Tmp2.getOperand(1);
13803     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13804     Chain = SP.getValue(1);
13805     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13806     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
13807     unsigned StackAlign = TFI.getStackAlignment();
13808     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13809     if (Align > StackAlign)
13810       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13811           DAG.getConstant(-(uint64_t)Align, VT));
13812     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13813
13814     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13815         DAG.getIntPtrConstant(0, true), SDValue(),
13816         SDLoc(Node));
13817
13818     SDValue Ops[2] = { Tmp1, Tmp2 };
13819     return DAG.getMergeValues(Ops, dl);
13820   }
13821
13822   // Get the inputs.
13823   SDValue Chain = Op.getOperand(0);
13824   SDValue Size  = Op.getOperand(1);
13825   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13826   EVT VT = Op.getNode()->getValueType(0);
13827
13828   bool Is64Bit = Subtarget->is64Bit();
13829   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13830
13831   if (SplitStack) {
13832     MachineRegisterInfo &MRI = MF.getRegInfo();
13833
13834     if (Is64Bit) {
13835       // The 64 bit implementation of segmented stacks needs to clobber both r10
13836       // r11. This makes it impossible to use it along with nested parameters.
13837       const Function *F = MF.getFunction();
13838
13839       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13840            I != E; ++I)
13841         if (I->hasNestAttr())
13842           report_fatal_error("Cannot use segmented stacks with functions that "
13843                              "have nested arguments.");
13844     }
13845
13846     const TargetRegisterClass *AddrRegClass =
13847       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13848     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13849     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13850     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13851                                 DAG.getRegister(Vreg, SPTy));
13852     SDValue Ops1[2] = { Value, Chain };
13853     return DAG.getMergeValues(Ops1, dl);
13854   } else {
13855     SDValue Flag;
13856     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13857
13858     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13859     Flag = Chain.getValue(1);
13860     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13861
13862     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13863
13864     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
13865         DAG.getSubtarget().getRegisterInfo());
13866     unsigned SPReg = RegInfo->getStackRegister();
13867     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13868     Chain = SP.getValue(1);
13869
13870     if (Align) {
13871       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13872                        DAG.getConstant(-(uint64_t)Align, VT));
13873       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13874     }
13875
13876     SDValue Ops1[2] = { SP, Chain };
13877     return DAG.getMergeValues(Ops1, dl);
13878   }
13879 }
13880
13881 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13882   MachineFunction &MF = DAG.getMachineFunction();
13883   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13884
13885   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13886   SDLoc DL(Op);
13887
13888   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13889     // vastart just stores the address of the VarArgsFrameIndex slot into the
13890     // memory location argument.
13891     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13892                                    getPointerTy());
13893     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13894                         MachinePointerInfo(SV), false, false, 0);
13895   }
13896
13897   // __va_list_tag:
13898   //   gp_offset         (0 - 6 * 8)
13899   //   fp_offset         (48 - 48 + 8 * 16)
13900   //   overflow_arg_area (point to parameters coming in memory).
13901   //   reg_save_area
13902   SmallVector<SDValue, 8> MemOps;
13903   SDValue FIN = Op.getOperand(1);
13904   // Store gp_offset
13905   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13906                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13907                                                MVT::i32),
13908                                FIN, MachinePointerInfo(SV), false, false, 0);
13909   MemOps.push_back(Store);
13910
13911   // Store fp_offset
13912   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13913                     FIN, DAG.getIntPtrConstant(4));
13914   Store = DAG.getStore(Op.getOperand(0), DL,
13915                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13916                                        MVT::i32),
13917                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13918   MemOps.push_back(Store);
13919
13920   // Store ptr to overflow_arg_area
13921   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13922                     FIN, DAG.getIntPtrConstant(4));
13923   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13924                                     getPointerTy());
13925   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13926                        MachinePointerInfo(SV, 8),
13927                        false, false, 0);
13928   MemOps.push_back(Store);
13929
13930   // Store ptr to reg_save_area.
13931   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13932                     FIN, DAG.getIntPtrConstant(8));
13933   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13934                                     getPointerTy());
13935   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13936                        MachinePointerInfo(SV, 16), false, false, 0);
13937   MemOps.push_back(Store);
13938   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13939 }
13940
13941 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13942   assert(Subtarget->is64Bit() &&
13943          "LowerVAARG only handles 64-bit va_arg!");
13944   assert((Subtarget->isTargetLinux() ||
13945           Subtarget->isTargetDarwin()) &&
13946           "Unhandled target in LowerVAARG");
13947   assert(Op.getNode()->getNumOperands() == 4);
13948   SDValue Chain = Op.getOperand(0);
13949   SDValue SrcPtr = Op.getOperand(1);
13950   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13951   unsigned Align = Op.getConstantOperandVal(3);
13952   SDLoc dl(Op);
13953
13954   EVT ArgVT = Op.getNode()->getValueType(0);
13955   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13956   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13957   uint8_t ArgMode;
13958
13959   // Decide which area this value should be read from.
13960   // TODO: Implement the AMD64 ABI in its entirety. This simple
13961   // selection mechanism works only for the basic types.
13962   if (ArgVT == MVT::f80) {
13963     llvm_unreachable("va_arg for f80 not yet implemented");
13964   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13965     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13966   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13967     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13968   } else {
13969     llvm_unreachable("Unhandled argument type in LowerVAARG");
13970   }
13971
13972   if (ArgMode == 2) {
13973     // Sanity Check: Make sure using fp_offset makes sense.
13974     assert(!DAG.getTarget().Options.UseSoftFloat &&
13975            !(DAG.getMachineFunction()
13976                 .getFunction()->getAttributes()
13977                 .hasAttribute(AttributeSet::FunctionIndex,
13978                               Attribute::NoImplicitFloat)) &&
13979            Subtarget->hasSSE1());
13980   }
13981
13982   // Insert VAARG_64 node into the DAG
13983   // VAARG_64 returns two values: Variable Argument Address, Chain
13984   SmallVector<SDValue, 11> InstOps;
13985   InstOps.push_back(Chain);
13986   InstOps.push_back(SrcPtr);
13987   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13988   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13989   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13990   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13991   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13992                                           VTs, InstOps, MVT::i64,
13993                                           MachinePointerInfo(SV),
13994                                           /*Align=*/0,
13995                                           /*Volatile=*/false,
13996                                           /*ReadMem=*/true,
13997                                           /*WriteMem=*/true);
13998   Chain = VAARG.getValue(1);
13999
14000   // Load the next argument and return it
14001   return DAG.getLoad(ArgVT, dl,
14002                      Chain,
14003                      VAARG,
14004                      MachinePointerInfo(),
14005                      false, false, false, 0);
14006 }
14007
14008 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14009                            SelectionDAG &DAG) {
14010   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14011   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14012   SDValue Chain = Op.getOperand(0);
14013   SDValue DstPtr = Op.getOperand(1);
14014   SDValue SrcPtr = Op.getOperand(2);
14015   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14016   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14017   SDLoc DL(Op);
14018
14019   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14020                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14021                        false,
14022                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14023 }
14024
14025 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14026 // amount is a constant. Takes immediate version of shift as input.
14027 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14028                                           SDValue SrcOp, uint64_t ShiftAmt,
14029                                           SelectionDAG &DAG) {
14030   MVT ElementType = VT.getVectorElementType();
14031
14032   // Fold this packed shift into its first operand if ShiftAmt is 0.
14033   if (ShiftAmt == 0)
14034     return SrcOp;
14035
14036   // Check for ShiftAmt >= element width
14037   if (ShiftAmt >= ElementType.getSizeInBits()) {
14038     if (Opc == X86ISD::VSRAI)
14039       ShiftAmt = ElementType.getSizeInBits() - 1;
14040     else
14041       return DAG.getConstant(0, VT);
14042   }
14043
14044   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14045          && "Unknown target vector shift-by-constant node");
14046
14047   // Fold this packed vector shift into a build vector if SrcOp is a
14048   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14049   if (VT == SrcOp.getSimpleValueType() &&
14050       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14051     SmallVector<SDValue, 8> Elts;
14052     unsigned NumElts = SrcOp->getNumOperands();
14053     ConstantSDNode *ND;
14054
14055     switch(Opc) {
14056     default: llvm_unreachable(nullptr);
14057     case X86ISD::VSHLI:
14058       for (unsigned i=0; i!=NumElts; ++i) {
14059         SDValue CurrentOp = SrcOp->getOperand(i);
14060         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14061           Elts.push_back(CurrentOp);
14062           continue;
14063         }
14064         ND = cast<ConstantSDNode>(CurrentOp);
14065         const APInt &C = ND->getAPIntValue();
14066         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14067       }
14068       break;
14069     case X86ISD::VSRLI:
14070       for (unsigned i=0; i!=NumElts; ++i) {
14071         SDValue CurrentOp = SrcOp->getOperand(i);
14072         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14073           Elts.push_back(CurrentOp);
14074           continue;
14075         }
14076         ND = cast<ConstantSDNode>(CurrentOp);
14077         const APInt &C = ND->getAPIntValue();
14078         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14079       }
14080       break;
14081     case X86ISD::VSRAI:
14082       for (unsigned i=0; i!=NumElts; ++i) {
14083         SDValue CurrentOp = SrcOp->getOperand(i);
14084         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14085           Elts.push_back(CurrentOp);
14086           continue;
14087         }
14088         ND = cast<ConstantSDNode>(CurrentOp);
14089         const APInt &C = ND->getAPIntValue();
14090         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14091       }
14092       break;
14093     }
14094
14095     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14096   }
14097
14098   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14099 }
14100
14101 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14102 // may or may not be a constant. Takes immediate version of shift as input.
14103 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14104                                    SDValue SrcOp, SDValue ShAmt,
14105                                    SelectionDAG &DAG) {
14106   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14107
14108   // Catch shift-by-constant.
14109   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14110     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14111                                       CShAmt->getZExtValue(), DAG);
14112
14113   // Change opcode to non-immediate version
14114   switch (Opc) {
14115     default: llvm_unreachable("Unknown target vector shift node");
14116     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14117     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14118     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14119   }
14120
14121   // Need to build a vector containing shift amount
14122   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14123   SDValue ShOps[4];
14124   ShOps[0] = ShAmt;
14125   ShOps[1] = DAG.getConstant(0, MVT::i32);
14126   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14127   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14128
14129   // The return type has to be a 128-bit type with the same element
14130   // type as the input type.
14131   MVT EltVT = VT.getVectorElementType();
14132   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14133
14134   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14135   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14136 }
14137
14138 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14139   SDLoc dl(Op);
14140   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14141   switch (IntNo) {
14142   default: return SDValue();    // Don't custom lower most intrinsics.
14143   // Comparison intrinsics.
14144   case Intrinsic::x86_sse_comieq_ss:
14145   case Intrinsic::x86_sse_comilt_ss:
14146   case Intrinsic::x86_sse_comile_ss:
14147   case Intrinsic::x86_sse_comigt_ss:
14148   case Intrinsic::x86_sse_comige_ss:
14149   case Intrinsic::x86_sse_comineq_ss:
14150   case Intrinsic::x86_sse_ucomieq_ss:
14151   case Intrinsic::x86_sse_ucomilt_ss:
14152   case Intrinsic::x86_sse_ucomile_ss:
14153   case Intrinsic::x86_sse_ucomigt_ss:
14154   case Intrinsic::x86_sse_ucomige_ss:
14155   case Intrinsic::x86_sse_ucomineq_ss:
14156   case Intrinsic::x86_sse2_comieq_sd:
14157   case Intrinsic::x86_sse2_comilt_sd:
14158   case Intrinsic::x86_sse2_comile_sd:
14159   case Intrinsic::x86_sse2_comigt_sd:
14160   case Intrinsic::x86_sse2_comige_sd:
14161   case Intrinsic::x86_sse2_comineq_sd:
14162   case Intrinsic::x86_sse2_ucomieq_sd:
14163   case Intrinsic::x86_sse2_ucomilt_sd:
14164   case Intrinsic::x86_sse2_ucomile_sd:
14165   case Intrinsic::x86_sse2_ucomigt_sd:
14166   case Intrinsic::x86_sse2_ucomige_sd:
14167   case Intrinsic::x86_sse2_ucomineq_sd: {
14168     unsigned Opc;
14169     ISD::CondCode CC;
14170     switch (IntNo) {
14171     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14172     case Intrinsic::x86_sse_comieq_ss:
14173     case Intrinsic::x86_sse2_comieq_sd:
14174       Opc = X86ISD::COMI;
14175       CC = ISD::SETEQ;
14176       break;
14177     case Intrinsic::x86_sse_comilt_ss:
14178     case Intrinsic::x86_sse2_comilt_sd:
14179       Opc = X86ISD::COMI;
14180       CC = ISD::SETLT;
14181       break;
14182     case Intrinsic::x86_sse_comile_ss:
14183     case Intrinsic::x86_sse2_comile_sd:
14184       Opc = X86ISD::COMI;
14185       CC = ISD::SETLE;
14186       break;
14187     case Intrinsic::x86_sse_comigt_ss:
14188     case Intrinsic::x86_sse2_comigt_sd:
14189       Opc = X86ISD::COMI;
14190       CC = ISD::SETGT;
14191       break;
14192     case Intrinsic::x86_sse_comige_ss:
14193     case Intrinsic::x86_sse2_comige_sd:
14194       Opc = X86ISD::COMI;
14195       CC = ISD::SETGE;
14196       break;
14197     case Intrinsic::x86_sse_comineq_ss:
14198     case Intrinsic::x86_sse2_comineq_sd:
14199       Opc = X86ISD::COMI;
14200       CC = ISD::SETNE;
14201       break;
14202     case Intrinsic::x86_sse_ucomieq_ss:
14203     case Intrinsic::x86_sse2_ucomieq_sd:
14204       Opc = X86ISD::UCOMI;
14205       CC = ISD::SETEQ;
14206       break;
14207     case Intrinsic::x86_sse_ucomilt_ss:
14208     case Intrinsic::x86_sse2_ucomilt_sd:
14209       Opc = X86ISD::UCOMI;
14210       CC = ISD::SETLT;
14211       break;
14212     case Intrinsic::x86_sse_ucomile_ss:
14213     case Intrinsic::x86_sse2_ucomile_sd:
14214       Opc = X86ISD::UCOMI;
14215       CC = ISD::SETLE;
14216       break;
14217     case Intrinsic::x86_sse_ucomigt_ss:
14218     case Intrinsic::x86_sse2_ucomigt_sd:
14219       Opc = X86ISD::UCOMI;
14220       CC = ISD::SETGT;
14221       break;
14222     case Intrinsic::x86_sse_ucomige_ss:
14223     case Intrinsic::x86_sse2_ucomige_sd:
14224       Opc = X86ISD::UCOMI;
14225       CC = ISD::SETGE;
14226       break;
14227     case Intrinsic::x86_sse_ucomineq_ss:
14228     case Intrinsic::x86_sse2_ucomineq_sd:
14229       Opc = X86ISD::UCOMI;
14230       CC = ISD::SETNE;
14231       break;
14232     }
14233
14234     SDValue LHS = Op.getOperand(1);
14235     SDValue RHS = Op.getOperand(2);
14236     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14237     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14238     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
14239     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14240                                 DAG.getConstant(X86CC, MVT::i8), Cond);
14241     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14242   }
14243
14244   // Arithmetic intrinsics.
14245   case Intrinsic::x86_sse2_pmulu_dq:
14246   case Intrinsic::x86_avx2_pmulu_dq:
14247     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14248                        Op.getOperand(1), Op.getOperand(2));
14249
14250   case Intrinsic::x86_sse41_pmuldq:
14251   case Intrinsic::x86_avx2_pmul_dq:
14252     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14253                        Op.getOperand(1), Op.getOperand(2));
14254
14255   case Intrinsic::x86_sse2_pmulhu_w:
14256   case Intrinsic::x86_avx2_pmulhu_w:
14257     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14258                        Op.getOperand(1), Op.getOperand(2));
14259
14260   case Intrinsic::x86_sse2_pmulh_w:
14261   case Intrinsic::x86_avx2_pmulh_w:
14262     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14263                        Op.getOperand(1), Op.getOperand(2));
14264
14265   // SSE2/AVX2 sub with unsigned saturation intrinsics
14266   case Intrinsic::x86_sse2_psubus_b:
14267   case Intrinsic::x86_sse2_psubus_w:
14268   case Intrinsic::x86_avx2_psubus_b:
14269   case Intrinsic::x86_avx2_psubus_w:
14270     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
14271                        Op.getOperand(1), Op.getOperand(2));
14272
14273   // SSE3/AVX horizontal add/sub intrinsics
14274   case Intrinsic::x86_sse3_hadd_ps:
14275   case Intrinsic::x86_sse3_hadd_pd:
14276   case Intrinsic::x86_avx_hadd_ps_256:
14277   case Intrinsic::x86_avx_hadd_pd_256:
14278   case Intrinsic::x86_sse3_hsub_ps:
14279   case Intrinsic::x86_sse3_hsub_pd:
14280   case Intrinsic::x86_avx_hsub_ps_256:
14281   case Intrinsic::x86_avx_hsub_pd_256:
14282   case Intrinsic::x86_ssse3_phadd_w_128:
14283   case Intrinsic::x86_ssse3_phadd_d_128:
14284   case Intrinsic::x86_avx2_phadd_w:
14285   case Intrinsic::x86_avx2_phadd_d:
14286   case Intrinsic::x86_ssse3_phsub_w_128:
14287   case Intrinsic::x86_ssse3_phsub_d_128:
14288   case Intrinsic::x86_avx2_phsub_w:
14289   case Intrinsic::x86_avx2_phsub_d: {
14290     unsigned Opcode;
14291     switch (IntNo) {
14292     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14293     case Intrinsic::x86_sse3_hadd_ps:
14294     case Intrinsic::x86_sse3_hadd_pd:
14295     case Intrinsic::x86_avx_hadd_ps_256:
14296     case Intrinsic::x86_avx_hadd_pd_256:
14297       Opcode = X86ISD::FHADD;
14298       break;
14299     case Intrinsic::x86_sse3_hsub_ps:
14300     case Intrinsic::x86_sse3_hsub_pd:
14301     case Intrinsic::x86_avx_hsub_ps_256:
14302     case Intrinsic::x86_avx_hsub_pd_256:
14303       Opcode = X86ISD::FHSUB;
14304       break;
14305     case Intrinsic::x86_ssse3_phadd_w_128:
14306     case Intrinsic::x86_ssse3_phadd_d_128:
14307     case Intrinsic::x86_avx2_phadd_w:
14308     case Intrinsic::x86_avx2_phadd_d:
14309       Opcode = X86ISD::HADD;
14310       break;
14311     case Intrinsic::x86_ssse3_phsub_w_128:
14312     case Intrinsic::x86_ssse3_phsub_d_128:
14313     case Intrinsic::x86_avx2_phsub_w:
14314     case Intrinsic::x86_avx2_phsub_d:
14315       Opcode = X86ISD::HSUB;
14316       break;
14317     }
14318     return DAG.getNode(Opcode, dl, Op.getValueType(),
14319                        Op.getOperand(1), Op.getOperand(2));
14320   }
14321
14322   // SSE2/SSE41/AVX2 integer max/min intrinsics.
14323   case Intrinsic::x86_sse2_pmaxu_b:
14324   case Intrinsic::x86_sse41_pmaxuw:
14325   case Intrinsic::x86_sse41_pmaxud:
14326   case Intrinsic::x86_avx2_pmaxu_b:
14327   case Intrinsic::x86_avx2_pmaxu_w:
14328   case Intrinsic::x86_avx2_pmaxu_d:
14329   case Intrinsic::x86_sse2_pminu_b:
14330   case Intrinsic::x86_sse41_pminuw:
14331   case Intrinsic::x86_sse41_pminud:
14332   case Intrinsic::x86_avx2_pminu_b:
14333   case Intrinsic::x86_avx2_pminu_w:
14334   case Intrinsic::x86_avx2_pminu_d:
14335   case Intrinsic::x86_sse41_pmaxsb:
14336   case Intrinsic::x86_sse2_pmaxs_w:
14337   case Intrinsic::x86_sse41_pmaxsd:
14338   case Intrinsic::x86_avx2_pmaxs_b:
14339   case Intrinsic::x86_avx2_pmaxs_w:
14340   case Intrinsic::x86_avx2_pmaxs_d:
14341   case Intrinsic::x86_sse41_pminsb:
14342   case Intrinsic::x86_sse2_pmins_w:
14343   case Intrinsic::x86_sse41_pminsd:
14344   case Intrinsic::x86_avx2_pmins_b:
14345   case Intrinsic::x86_avx2_pmins_w:
14346   case Intrinsic::x86_avx2_pmins_d: {
14347     unsigned Opcode;
14348     switch (IntNo) {
14349     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14350     case Intrinsic::x86_sse2_pmaxu_b:
14351     case Intrinsic::x86_sse41_pmaxuw:
14352     case Intrinsic::x86_sse41_pmaxud:
14353     case Intrinsic::x86_avx2_pmaxu_b:
14354     case Intrinsic::x86_avx2_pmaxu_w:
14355     case Intrinsic::x86_avx2_pmaxu_d:
14356       Opcode = X86ISD::UMAX;
14357       break;
14358     case Intrinsic::x86_sse2_pminu_b:
14359     case Intrinsic::x86_sse41_pminuw:
14360     case Intrinsic::x86_sse41_pminud:
14361     case Intrinsic::x86_avx2_pminu_b:
14362     case Intrinsic::x86_avx2_pminu_w:
14363     case Intrinsic::x86_avx2_pminu_d:
14364       Opcode = X86ISD::UMIN;
14365       break;
14366     case Intrinsic::x86_sse41_pmaxsb:
14367     case Intrinsic::x86_sse2_pmaxs_w:
14368     case Intrinsic::x86_sse41_pmaxsd:
14369     case Intrinsic::x86_avx2_pmaxs_b:
14370     case Intrinsic::x86_avx2_pmaxs_w:
14371     case Intrinsic::x86_avx2_pmaxs_d:
14372       Opcode = X86ISD::SMAX;
14373       break;
14374     case Intrinsic::x86_sse41_pminsb:
14375     case Intrinsic::x86_sse2_pmins_w:
14376     case Intrinsic::x86_sse41_pminsd:
14377     case Intrinsic::x86_avx2_pmins_b:
14378     case Intrinsic::x86_avx2_pmins_w:
14379     case Intrinsic::x86_avx2_pmins_d:
14380       Opcode = X86ISD::SMIN;
14381       break;
14382     }
14383     return DAG.getNode(Opcode, dl, Op.getValueType(),
14384                        Op.getOperand(1), Op.getOperand(2));
14385   }
14386
14387   // SSE/SSE2/AVX floating point max/min intrinsics.
14388   case Intrinsic::x86_sse_max_ps:
14389   case Intrinsic::x86_sse2_max_pd:
14390   case Intrinsic::x86_avx_max_ps_256:
14391   case Intrinsic::x86_avx_max_pd_256:
14392   case Intrinsic::x86_sse_min_ps:
14393   case Intrinsic::x86_sse2_min_pd:
14394   case Intrinsic::x86_avx_min_ps_256:
14395   case Intrinsic::x86_avx_min_pd_256: {
14396     unsigned Opcode;
14397     switch (IntNo) {
14398     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14399     case Intrinsic::x86_sse_max_ps:
14400     case Intrinsic::x86_sse2_max_pd:
14401     case Intrinsic::x86_avx_max_ps_256:
14402     case Intrinsic::x86_avx_max_pd_256:
14403       Opcode = X86ISD::FMAX;
14404       break;
14405     case Intrinsic::x86_sse_min_ps:
14406     case Intrinsic::x86_sse2_min_pd:
14407     case Intrinsic::x86_avx_min_ps_256:
14408     case Intrinsic::x86_avx_min_pd_256:
14409       Opcode = X86ISD::FMIN;
14410       break;
14411     }
14412     return DAG.getNode(Opcode, dl, Op.getValueType(),
14413                        Op.getOperand(1), Op.getOperand(2));
14414   }
14415
14416   // AVX2 variable shift intrinsics
14417   case Intrinsic::x86_avx2_psllv_d:
14418   case Intrinsic::x86_avx2_psllv_q:
14419   case Intrinsic::x86_avx2_psllv_d_256:
14420   case Intrinsic::x86_avx2_psllv_q_256:
14421   case Intrinsic::x86_avx2_psrlv_d:
14422   case Intrinsic::x86_avx2_psrlv_q:
14423   case Intrinsic::x86_avx2_psrlv_d_256:
14424   case Intrinsic::x86_avx2_psrlv_q_256:
14425   case Intrinsic::x86_avx2_psrav_d:
14426   case Intrinsic::x86_avx2_psrav_d_256: {
14427     unsigned Opcode;
14428     switch (IntNo) {
14429     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14430     case Intrinsic::x86_avx2_psllv_d:
14431     case Intrinsic::x86_avx2_psllv_q:
14432     case Intrinsic::x86_avx2_psllv_d_256:
14433     case Intrinsic::x86_avx2_psllv_q_256:
14434       Opcode = ISD::SHL;
14435       break;
14436     case Intrinsic::x86_avx2_psrlv_d:
14437     case Intrinsic::x86_avx2_psrlv_q:
14438     case Intrinsic::x86_avx2_psrlv_d_256:
14439     case Intrinsic::x86_avx2_psrlv_q_256:
14440       Opcode = ISD::SRL;
14441       break;
14442     case Intrinsic::x86_avx2_psrav_d:
14443     case Intrinsic::x86_avx2_psrav_d_256:
14444       Opcode = ISD::SRA;
14445       break;
14446     }
14447     return DAG.getNode(Opcode, dl, Op.getValueType(),
14448                        Op.getOperand(1), Op.getOperand(2));
14449   }
14450
14451   case Intrinsic::x86_sse2_packssdw_128:
14452   case Intrinsic::x86_sse2_packsswb_128:
14453   case Intrinsic::x86_avx2_packssdw:
14454   case Intrinsic::x86_avx2_packsswb:
14455     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14456                        Op.getOperand(1), Op.getOperand(2));
14457
14458   case Intrinsic::x86_sse2_packuswb_128:
14459   case Intrinsic::x86_sse41_packusdw:
14460   case Intrinsic::x86_avx2_packuswb:
14461   case Intrinsic::x86_avx2_packusdw:
14462     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14463                        Op.getOperand(1), Op.getOperand(2));
14464
14465   case Intrinsic::x86_ssse3_pshuf_b_128:
14466   case Intrinsic::x86_avx2_pshuf_b:
14467     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14468                        Op.getOperand(1), Op.getOperand(2));
14469
14470   case Intrinsic::x86_sse2_pshuf_d:
14471     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14472                        Op.getOperand(1), Op.getOperand(2));
14473
14474   case Intrinsic::x86_sse2_pshufl_w:
14475     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14476                        Op.getOperand(1), Op.getOperand(2));
14477
14478   case Intrinsic::x86_sse2_pshufh_w:
14479     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14480                        Op.getOperand(1), Op.getOperand(2));
14481
14482   case Intrinsic::x86_ssse3_psign_b_128:
14483   case Intrinsic::x86_ssse3_psign_w_128:
14484   case Intrinsic::x86_ssse3_psign_d_128:
14485   case Intrinsic::x86_avx2_psign_b:
14486   case Intrinsic::x86_avx2_psign_w:
14487   case Intrinsic::x86_avx2_psign_d:
14488     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14489                        Op.getOperand(1), Op.getOperand(2));
14490
14491   case Intrinsic::x86_sse41_insertps:
14492     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14493                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14494
14495   case Intrinsic::x86_avx_vperm2f128_ps_256:
14496   case Intrinsic::x86_avx_vperm2f128_pd_256:
14497   case Intrinsic::x86_avx_vperm2f128_si_256:
14498   case Intrinsic::x86_avx2_vperm2i128:
14499     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14500                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14501
14502   case Intrinsic::x86_avx2_permd:
14503   case Intrinsic::x86_avx2_permps:
14504     // Operands intentionally swapped. Mask is last operand to intrinsic,
14505     // but second operand for node/instruction.
14506     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14507                        Op.getOperand(2), Op.getOperand(1));
14508
14509   case Intrinsic::x86_sse_sqrt_ps:
14510   case Intrinsic::x86_sse2_sqrt_pd:
14511   case Intrinsic::x86_avx_sqrt_ps_256:
14512   case Intrinsic::x86_avx_sqrt_pd_256:
14513     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14514
14515   case Intrinsic::x86_avx512_mask_valign_q_512:
14516   case Intrinsic::x86_avx512_mask_valign_d_512: {
14517     EVT VT = Op.getValueType();
14518     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14519                                   MVT::i1, VT.getVectorNumElements());
14520     assert(MaskVT.isSimple() && "invalid valign mask type");
14521     // Vector source operands are swapped.
14522     return DAG.getNode(ISD::VSELECT, dl, VT,
14523                        DAG.getNode(ISD::BITCAST, dl, MaskVT,
14524                                    Op.getOperand(5)),
14525                        DAG.getNode(X86ISD::VALIGN, dl, VT,
14526                                    Op.getOperand(2), Op.getOperand(1),
14527                                    Op.getOperand(3)),
14528                        Op.getOperand(4));
14529   }
14530
14531   // ptest and testp intrinsics. The intrinsic these come from are designed to
14532   // return an integer value, not just an instruction so lower it to the ptest
14533   // or testp pattern and a setcc for the result.
14534   case Intrinsic::x86_sse41_ptestz:
14535   case Intrinsic::x86_sse41_ptestc:
14536   case Intrinsic::x86_sse41_ptestnzc:
14537   case Intrinsic::x86_avx_ptestz_256:
14538   case Intrinsic::x86_avx_ptestc_256:
14539   case Intrinsic::x86_avx_ptestnzc_256:
14540   case Intrinsic::x86_avx_vtestz_ps:
14541   case Intrinsic::x86_avx_vtestc_ps:
14542   case Intrinsic::x86_avx_vtestnzc_ps:
14543   case Intrinsic::x86_avx_vtestz_pd:
14544   case Intrinsic::x86_avx_vtestc_pd:
14545   case Intrinsic::x86_avx_vtestnzc_pd:
14546   case Intrinsic::x86_avx_vtestz_ps_256:
14547   case Intrinsic::x86_avx_vtestc_ps_256:
14548   case Intrinsic::x86_avx_vtestnzc_ps_256:
14549   case Intrinsic::x86_avx_vtestz_pd_256:
14550   case Intrinsic::x86_avx_vtestc_pd_256:
14551   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14552     bool IsTestPacked = false;
14553     unsigned X86CC;
14554     switch (IntNo) {
14555     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14556     case Intrinsic::x86_avx_vtestz_ps:
14557     case Intrinsic::x86_avx_vtestz_pd:
14558     case Intrinsic::x86_avx_vtestz_ps_256:
14559     case Intrinsic::x86_avx_vtestz_pd_256:
14560       IsTestPacked = true; // Fallthrough
14561     case Intrinsic::x86_sse41_ptestz:
14562     case Intrinsic::x86_avx_ptestz_256:
14563       // ZF = 1
14564       X86CC = X86::COND_E;
14565       break;
14566     case Intrinsic::x86_avx_vtestc_ps:
14567     case Intrinsic::x86_avx_vtestc_pd:
14568     case Intrinsic::x86_avx_vtestc_ps_256:
14569     case Intrinsic::x86_avx_vtestc_pd_256:
14570       IsTestPacked = true; // Fallthrough
14571     case Intrinsic::x86_sse41_ptestc:
14572     case Intrinsic::x86_avx_ptestc_256:
14573       // CF = 1
14574       X86CC = X86::COND_B;
14575       break;
14576     case Intrinsic::x86_avx_vtestnzc_ps:
14577     case Intrinsic::x86_avx_vtestnzc_pd:
14578     case Intrinsic::x86_avx_vtestnzc_ps_256:
14579     case Intrinsic::x86_avx_vtestnzc_pd_256:
14580       IsTestPacked = true; // Fallthrough
14581     case Intrinsic::x86_sse41_ptestnzc:
14582     case Intrinsic::x86_avx_ptestnzc_256:
14583       // ZF and CF = 0
14584       X86CC = X86::COND_A;
14585       break;
14586     }
14587
14588     SDValue LHS = Op.getOperand(1);
14589     SDValue RHS = Op.getOperand(2);
14590     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14591     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14592     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14593     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14594     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14595   }
14596   case Intrinsic::x86_avx512_kortestz_w:
14597   case Intrinsic::x86_avx512_kortestc_w: {
14598     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14599     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14600     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14601     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14602     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14603     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14604     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14605   }
14606
14607   // SSE/AVX shift intrinsics
14608   case Intrinsic::x86_sse2_psll_w:
14609   case Intrinsic::x86_sse2_psll_d:
14610   case Intrinsic::x86_sse2_psll_q:
14611   case Intrinsic::x86_avx2_psll_w:
14612   case Intrinsic::x86_avx2_psll_d:
14613   case Intrinsic::x86_avx2_psll_q:
14614   case Intrinsic::x86_sse2_psrl_w:
14615   case Intrinsic::x86_sse2_psrl_d:
14616   case Intrinsic::x86_sse2_psrl_q:
14617   case Intrinsic::x86_avx2_psrl_w:
14618   case Intrinsic::x86_avx2_psrl_d:
14619   case Intrinsic::x86_avx2_psrl_q:
14620   case Intrinsic::x86_sse2_psra_w:
14621   case Intrinsic::x86_sse2_psra_d:
14622   case Intrinsic::x86_avx2_psra_w:
14623   case Intrinsic::x86_avx2_psra_d: {
14624     unsigned Opcode;
14625     switch (IntNo) {
14626     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14627     case Intrinsic::x86_sse2_psll_w:
14628     case Intrinsic::x86_sse2_psll_d:
14629     case Intrinsic::x86_sse2_psll_q:
14630     case Intrinsic::x86_avx2_psll_w:
14631     case Intrinsic::x86_avx2_psll_d:
14632     case Intrinsic::x86_avx2_psll_q:
14633       Opcode = X86ISD::VSHL;
14634       break;
14635     case Intrinsic::x86_sse2_psrl_w:
14636     case Intrinsic::x86_sse2_psrl_d:
14637     case Intrinsic::x86_sse2_psrl_q:
14638     case Intrinsic::x86_avx2_psrl_w:
14639     case Intrinsic::x86_avx2_psrl_d:
14640     case Intrinsic::x86_avx2_psrl_q:
14641       Opcode = X86ISD::VSRL;
14642       break;
14643     case Intrinsic::x86_sse2_psra_w:
14644     case Intrinsic::x86_sse2_psra_d:
14645     case Intrinsic::x86_avx2_psra_w:
14646     case Intrinsic::x86_avx2_psra_d:
14647       Opcode = X86ISD::VSRA;
14648       break;
14649     }
14650     return DAG.getNode(Opcode, dl, Op.getValueType(),
14651                        Op.getOperand(1), Op.getOperand(2));
14652   }
14653
14654   // SSE/AVX immediate shift intrinsics
14655   case Intrinsic::x86_sse2_pslli_w:
14656   case Intrinsic::x86_sse2_pslli_d:
14657   case Intrinsic::x86_sse2_pslli_q:
14658   case Intrinsic::x86_avx2_pslli_w:
14659   case Intrinsic::x86_avx2_pslli_d:
14660   case Intrinsic::x86_avx2_pslli_q:
14661   case Intrinsic::x86_sse2_psrli_w:
14662   case Intrinsic::x86_sse2_psrli_d:
14663   case Intrinsic::x86_sse2_psrli_q:
14664   case Intrinsic::x86_avx2_psrli_w:
14665   case Intrinsic::x86_avx2_psrli_d:
14666   case Intrinsic::x86_avx2_psrli_q:
14667   case Intrinsic::x86_sse2_psrai_w:
14668   case Intrinsic::x86_sse2_psrai_d:
14669   case Intrinsic::x86_avx2_psrai_w:
14670   case Intrinsic::x86_avx2_psrai_d: {
14671     unsigned Opcode;
14672     switch (IntNo) {
14673     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14674     case Intrinsic::x86_sse2_pslli_w:
14675     case Intrinsic::x86_sse2_pslli_d:
14676     case Intrinsic::x86_sse2_pslli_q:
14677     case Intrinsic::x86_avx2_pslli_w:
14678     case Intrinsic::x86_avx2_pslli_d:
14679     case Intrinsic::x86_avx2_pslli_q:
14680       Opcode = X86ISD::VSHLI;
14681       break;
14682     case Intrinsic::x86_sse2_psrli_w:
14683     case Intrinsic::x86_sse2_psrli_d:
14684     case Intrinsic::x86_sse2_psrli_q:
14685     case Intrinsic::x86_avx2_psrli_w:
14686     case Intrinsic::x86_avx2_psrli_d:
14687     case Intrinsic::x86_avx2_psrli_q:
14688       Opcode = X86ISD::VSRLI;
14689       break;
14690     case Intrinsic::x86_sse2_psrai_w:
14691     case Intrinsic::x86_sse2_psrai_d:
14692     case Intrinsic::x86_avx2_psrai_w:
14693     case Intrinsic::x86_avx2_psrai_d:
14694       Opcode = X86ISD::VSRAI;
14695       break;
14696     }
14697     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14698                                Op.getOperand(1), Op.getOperand(2), DAG);
14699   }
14700
14701   case Intrinsic::x86_sse42_pcmpistria128:
14702   case Intrinsic::x86_sse42_pcmpestria128:
14703   case Intrinsic::x86_sse42_pcmpistric128:
14704   case Intrinsic::x86_sse42_pcmpestric128:
14705   case Intrinsic::x86_sse42_pcmpistrio128:
14706   case Intrinsic::x86_sse42_pcmpestrio128:
14707   case Intrinsic::x86_sse42_pcmpistris128:
14708   case Intrinsic::x86_sse42_pcmpestris128:
14709   case Intrinsic::x86_sse42_pcmpistriz128:
14710   case Intrinsic::x86_sse42_pcmpestriz128: {
14711     unsigned Opcode;
14712     unsigned X86CC;
14713     switch (IntNo) {
14714     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14715     case Intrinsic::x86_sse42_pcmpistria128:
14716       Opcode = X86ISD::PCMPISTRI;
14717       X86CC = X86::COND_A;
14718       break;
14719     case Intrinsic::x86_sse42_pcmpestria128:
14720       Opcode = X86ISD::PCMPESTRI;
14721       X86CC = X86::COND_A;
14722       break;
14723     case Intrinsic::x86_sse42_pcmpistric128:
14724       Opcode = X86ISD::PCMPISTRI;
14725       X86CC = X86::COND_B;
14726       break;
14727     case Intrinsic::x86_sse42_pcmpestric128:
14728       Opcode = X86ISD::PCMPESTRI;
14729       X86CC = X86::COND_B;
14730       break;
14731     case Intrinsic::x86_sse42_pcmpistrio128:
14732       Opcode = X86ISD::PCMPISTRI;
14733       X86CC = X86::COND_O;
14734       break;
14735     case Intrinsic::x86_sse42_pcmpestrio128:
14736       Opcode = X86ISD::PCMPESTRI;
14737       X86CC = X86::COND_O;
14738       break;
14739     case Intrinsic::x86_sse42_pcmpistris128:
14740       Opcode = X86ISD::PCMPISTRI;
14741       X86CC = X86::COND_S;
14742       break;
14743     case Intrinsic::x86_sse42_pcmpestris128:
14744       Opcode = X86ISD::PCMPESTRI;
14745       X86CC = X86::COND_S;
14746       break;
14747     case Intrinsic::x86_sse42_pcmpistriz128:
14748       Opcode = X86ISD::PCMPISTRI;
14749       X86CC = X86::COND_E;
14750       break;
14751     case Intrinsic::x86_sse42_pcmpestriz128:
14752       Opcode = X86ISD::PCMPESTRI;
14753       X86CC = X86::COND_E;
14754       break;
14755     }
14756     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14757     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14758     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14759     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14760                                 DAG.getConstant(X86CC, MVT::i8),
14761                                 SDValue(PCMP.getNode(), 1));
14762     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14763   }
14764
14765   case Intrinsic::x86_sse42_pcmpistri128:
14766   case Intrinsic::x86_sse42_pcmpestri128: {
14767     unsigned Opcode;
14768     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14769       Opcode = X86ISD::PCMPISTRI;
14770     else
14771       Opcode = X86ISD::PCMPESTRI;
14772
14773     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14774     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14775     return DAG.getNode(Opcode, dl, VTs, NewOps);
14776   }
14777   case Intrinsic::x86_fma_vfmadd_ps:
14778   case Intrinsic::x86_fma_vfmadd_pd:
14779   case Intrinsic::x86_fma_vfmsub_ps:
14780   case Intrinsic::x86_fma_vfmsub_pd:
14781   case Intrinsic::x86_fma_vfnmadd_ps:
14782   case Intrinsic::x86_fma_vfnmadd_pd:
14783   case Intrinsic::x86_fma_vfnmsub_ps:
14784   case Intrinsic::x86_fma_vfnmsub_pd:
14785   case Intrinsic::x86_fma_vfmaddsub_ps:
14786   case Intrinsic::x86_fma_vfmaddsub_pd:
14787   case Intrinsic::x86_fma_vfmsubadd_ps:
14788   case Intrinsic::x86_fma_vfmsubadd_pd:
14789   case Intrinsic::x86_fma_vfmadd_ps_256:
14790   case Intrinsic::x86_fma_vfmadd_pd_256:
14791   case Intrinsic::x86_fma_vfmsub_ps_256:
14792   case Intrinsic::x86_fma_vfmsub_pd_256:
14793   case Intrinsic::x86_fma_vfnmadd_ps_256:
14794   case Intrinsic::x86_fma_vfnmadd_pd_256:
14795   case Intrinsic::x86_fma_vfnmsub_ps_256:
14796   case Intrinsic::x86_fma_vfnmsub_pd_256:
14797   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14798   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14799   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14800   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14801   case Intrinsic::x86_fma_vfmadd_ps_512:
14802   case Intrinsic::x86_fma_vfmadd_pd_512:
14803   case Intrinsic::x86_fma_vfmsub_ps_512:
14804   case Intrinsic::x86_fma_vfmsub_pd_512:
14805   case Intrinsic::x86_fma_vfnmadd_ps_512:
14806   case Intrinsic::x86_fma_vfnmadd_pd_512:
14807   case Intrinsic::x86_fma_vfnmsub_ps_512:
14808   case Intrinsic::x86_fma_vfnmsub_pd_512:
14809   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14810   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14811   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14812   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14813     unsigned Opc;
14814     switch (IntNo) {
14815     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14816     case Intrinsic::x86_fma_vfmadd_ps:
14817     case Intrinsic::x86_fma_vfmadd_pd:
14818     case Intrinsic::x86_fma_vfmadd_ps_256:
14819     case Intrinsic::x86_fma_vfmadd_pd_256:
14820     case Intrinsic::x86_fma_vfmadd_ps_512:
14821     case Intrinsic::x86_fma_vfmadd_pd_512:
14822       Opc = X86ISD::FMADD;
14823       break;
14824     case Intrinsic::x86_fma_vfmsub_ps:
14825     case Intrinsic::x86_fma_vfmsub_pd:
14826     case Intrinsic::x86_fma_vfmsub_ps_256:
14827     case Intrinsic::x86_fma_vfmsub_pd_256:
14828     case Intrinsic::x86_fma_vfmsub_ps_512:
14829     case Intrinsic::x86_fma_vfmsub_pd_512:
14830       Opc = X86ISD::FMSUB;
14831       break;
14832     case Intrinsic::x86_fma_vfnmadd_ps:
14833     case Intrinsic::x86_fma_vfnmadd_pd:
14834     case Intrinsic::x86_fma_vfnmadd_ps_256:
14835     case Intrinsic::x86_fma_vfnmadd_pd_256:
14836     case Intrinsic::x86_fma_vfnmadd_ps_512:
14837     case Intrinsic::x86_fma_vfnmadd_pd_512:
14838       Opc = X86ISD::FNMADD;
14839       break;
14840     case Intrinsic::x86_fma_vfnmsub_ps:
14841     case Intrinsic::x86_fma_vfnmsub_pd:
14842     case Intrinsic::x86_fma_vfnmsub_ps_256:
14843     case Intrinsic::x86_fma_vfnmsub_pd_256:
14844     case Intrinsic::x86_fma_vfnmsub_ps_512:
14845     case Intrinsic::x86_fma_vfnmsub_pd_512:
14846       Opc = X86ISD::FNMSUB;
14847       break;
14848     case Intrinsic::x86_fma_vfmaddsub_ps:
14849     case Intrinsic::x86_fma_vfmaddsub_pd:
14850     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14851     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14852     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14853     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14854       Opc = X86ISD::FMADDSUB;
14855       break;
14856     case Intrinsic::x86_fma_vfmsubadd_ps:
14857     case Intrinsic::x86_fma_vfmsubadd_pd:
14858     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14859     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14860     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14861     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14862       Opc = X86ISD::FMSUBADD;
14863       break;
14864     }
14865
14866     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14867                        Op.getOperand(2), Op.getOperand(3));
14868   }
14869   }
14870 }
14871
14872 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14873                               SDValue Src, SDValue Mask, SDValue Base,
14874                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14875                               const X86Subtarget * Subtarget) {
14876   SDLoc dl(Op);
14877   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14878   assert(C && "Invalid scale type");
14879   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14880   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14881                              Index.getSimpleValueType().getVectorNumElements());
14882   SDValue MaskInReg;
14883   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14884   if (MaskC)
14885     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14886   else
14887     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14888   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14889   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14890   SDValue Segment = DAG.getRegister(0, MVT::i32);
14891   if (Src.getOpcode() == ISD::UNDEF)
14892     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14893   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14894   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14895   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14896   return DAG.getMergeValues(RetOps, dl);
14897 }
14898
14899 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14900                                SDValue Src, SDValue Mask, SDValue Base,
14901                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14902   SDLoc dl(Op);
14903   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14904   assert(C && "Invalid scale type");
14905   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14906   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14907   SDValue Segment = DAG.getRegister(0, MVT::i32);
14908   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14909                              Index.getSimpleValueType().getVectorNumElements());
14910   SDValue MaskInReg;
14911   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14912   if (MaskC)
14913     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14914   else
14915     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14916   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14917   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14918   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14919   return SDValue(Res, 1);
14920 }
14921
14922 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14923                                SDValue Mask, SDValue Base, SDValue Index,
14924                                SDValue ScaleOp, SDValue Chain) {
14925   SDLoc dl(Op);
14926   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14927   assert(C && "Invalid scale type");
14928   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14929   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14930   SDValue Segment = DAG.getRegister(0, MVT::i32);
14931   EVT MaskVT =
14932     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14933   SDValue MaskInReg;
14934   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14935   if (MaskC)
14936     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14937   else
14938     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14939   //SDVTList VTs = DAG.getVTList(MVT::Other);
14940   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14941   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14942   return SDValue(Res, 0);
14943 }
14944
14945 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14946 // read performance monitor counters (x86_rdpmc).
14947 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14948                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14949                               SmallVectorImpl<SDValue> &Results) {
14950   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14951   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14952   SDValue LO, HI;
14953
14954   // The ECX register is used to select the index of the performance counter
14955   // to read.
14956   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14957                                    N->getOperand(2));
14958   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14959
14960   // Reads the content of a 64-bit performance counter and returns it in the
14961   // registers EDX:EAX.
14962   if (Subtarget->is64Bit()) {
14963     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14964     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14965                             LO.getValue(2));
14966   } else {
14967     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14968     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14969                             LO.getValue(2));
14970   }
14971   Chain = HI.getValue(1);
14972
14973   if (Subtarget->is64Bit()) {
14974     // The EAX register is loaded with the low-order 32 bits. The EDX register
14975     // is loaded with the supported high-order bits of the counter.
14976     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14977                               DAG.getConstant(32, MVT::i8));
14978     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14979     Results.push_back(Chain);
14980     return;
14981   }
14982
14983   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14984   SDValue Ops[] = { LO, HI };
14985   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14986   Results.push_back(Pair);
14987   Results.push_back(Chain);
14988 }
14989
14990 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14991 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14992 // also used to custom lower READCYCLECOUNTER nodes.
14993 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14994                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14995                               SmallVectorImpl<SDValue> &Results) {
14996   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14997   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14998   SDValue LO, HI;
14999
15000   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15001   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15002   // and the EAX register is loaded with the low-order 32 bits.
15003   if (Subtarget->is64Bit()) {
15004     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15005     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15006                             LO.getValue(2));
15007   } else {
15008     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15009     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15010                             LO.getValue(2));
15011   }
15012   SDValue Chain = HI.getValue(1);
15013
15014   if (Opcode == X86ISD::RDTSCP_DAG) {
15015     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15016
15017     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15018     // the ECX register. Add 'ecx' explicitly to the chain.
15019     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15020                                      HI.getValue(2));
15021     // Explicitly store the content of ECX at the location passed in input
15022     // to the 'rdtscp' intrinsic.
15023     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15024                          MachinePointerInfo(), false, false, 0);
15025   }
15026
15027   if (Subtarget->is64Bit()) {
15028     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15029     // the EAX register is loaded with the low-order 32 bits.
15030     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15031                               DAG.getConstant(32, MVT::i8));
15032     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15033     Results.push_back(Chain);
15034     return;
15035   }
15036
15037   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15038   SDValue Ops[] = { LO, HI };
15039   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15040   Results.push_back(Pair);
15041   Results.push_back(Chain);
15042 }
15043
15044 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15045                                      SelectionDAG &DAG) {
15046   SmallVector<SDValue, 2> Results;
15047   SDLoc DL(Op);
15048   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15049                           Results);
15050   return DAG.getMergeValues(Results, DL);
15051 }
15052
15053 enum IntrinsicType {
15054   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
15055 };
15056
15057 struct IntrinsicData {
15058   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
15059     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
15060   IntrinsicType Type;
15061   unsigned      Opc0;
15062   unsigned      Opc1;
15063 };
15064
15065 std::map < unsigned, IntrinsicData> IntrMap;
15066 static void InitIntinsicsMap() {
15067   static bool Initialized = false;
15068   if (Initialized) 
15069     return;
15070   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
15071                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
15072   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
15073                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
15074   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
15075                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
15076   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
15077                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
15078   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
15079                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
15080   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
15081                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
15082   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
15083                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
15084   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
15085                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
15086   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
15087                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
15088
15089   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
15090                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
15091   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
15092                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
15093   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
15094                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
15095   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
15096                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
15097   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
15098                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
15099   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
15100                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
15101   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
15102                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
15103   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
15104                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
15105    
15106   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
15107                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
15108                                                         X86::VGATHERPF1QPSm)));
15109   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
15110                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
15111                                                         X86::VGATHERPF1QPDm)));
15112   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
15113                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
15114                                                         X86::VGATHERPF1DPDm)));
15115   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
15116                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
15117                                                         X86::VGATHERPF1DPSm)));
15118   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
15119                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
15120                                                         X86::VSCATTERPF1QPSm)));
15121   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
15122                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
15123                                                         X86::VSCATTERPF1QPDm)));
15124   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
15125                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
15126                                                         X86::VSCATTERPF1DPDm)));
15127   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
15128                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
15129                                                         X86::VSCATTERPF1DPSm)));
15130   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
15131                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15132   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
15133                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15134   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
15135                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15136   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
15137                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15138   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
15139                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15140   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
15141                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15142   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
15143                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
15144   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
15145                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
15146   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
15147                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
15148   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
15149                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
15150   Initialized = true;
15151 }
15152
15153 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15154                                       SelectionDAG &DAG) {
15155   InitIntinsicsMap();
15156   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15157   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
15158   if (itr == IntrMap.end())
15159     return SDValue();
15160
15161   SDLoc dl(Op);
15162   IntrinsicData Intr = itr->second;
15163   switch(Intr.Type) {
15164   case RDSEED:
15165   case RDRAND: {
15166     // Emit the node with the right value type.
15167     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15168     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
15169
15170     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15171     // Otherwise return the value from Rand, which is always 0, casted to i32.
15172     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15173                       DAG.getConstant(1, Op->getValueType(1)),
15174                       DAG.getConstant(X86::COND_B, MVT::i32),
15175                       SDValue(Result.getNode(), 1) };
15176     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15177                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15178                                   Ops);
15179
15180     // Return { result, isValid, chain }.
15181     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15182                        SDValue(Result.getNode(), 2));
15183   }
15184   case GATHER: {
15185   //gather(v1, mask, index, base, scale);
15186     SDValue Chain = Op.getOperand(0);
15187     SDValue Src   = Op.getOperand(2);
15188     SDValue Base  = Op.getOperand(3);
15189     SDValue Index = Op.getOperand(4);
15190     SDValue Mask  = Op.getOperand(5);
15191     SDValue Scale = Op.getOperand(6);
15192     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15193                           Subtarget);
15194   }
15195   case SCATTER: {
15196   //scatter(base, mask, index, v1, scale);
15197     SDValue Chain = Op.getOperand(0);
15198     SDValue Base  = Op.getOperand(2);
15199     SDValue Mask  = Op.getOperand(3);
15200     SDValue Index = Op.getOperand(4);
15201     SDValue Src   = Op.getOperand(5);
15202     SDValue Scale = Op.getOperand(6);
15203     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15204   }
15205   case PREFETCH: {
15206     SDValue Hint = Op.getOperand(6);
15207     unsigned HintVal;
15208     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15209         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15210       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15211     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
15212     SDValue Chain = Op.getOperand(0);
15213     SDValue Mask  = Op.getOperand(2);
15214     SDValue Index = Op.getOperand(3);
15215     SDValue Base  = Op.getOperand(4);
15216     SDValue Scale = Op.getOperand(5);
15217     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15218   }
15219   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15220   case RDTSC: {
15221     SmallVector<SDValue, 2> Results;
15222     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
15223     return DAG.getMergeValues(Results, dl);
15224   }
15225   // Read Performance Monitoring Counters.
15226   case RDPMC: {
15227     SmallVector<SDValue, 2> Results;
15228     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15229     return DAG.getMergeValues(Results, dl);
15230   }
15231   // XTEST intrinsics.
15232   case XTEST: {
15233     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15234     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15235     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15236                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15237                                 InTrans);
15238     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15239     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15240                        Ret, SDValue(InTrans.getNode(), 1));
15241   }
15242   }
15243   llvm_unreachable("Unknown Intrinsic Type");
15244 }
15245
15246 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15247                                            SelectionDAG &DAG) const {
15248   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15249   MFI->setReturnAddressIsTaken(true);
15250
15251   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15252     return SDValue();
15253
15254   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15255   SDLoc dl(Op);
15256   EVT PtrVT = getPointerTy();
15257
15258   if (Depth > 0) {
15259     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15260     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15261         DAG.getSubtarget().getRegisterInfo());
15262     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15263     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15264                        DAG.getNode(ISD::ADD, dl, PtrVT,
15265                                    FrameAddr, Offset),
15266                        MachinePointerInfo(), false, false, false, 0);
15267   }
15268
15269   // Just load the return address.
15270   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15271   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15272                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15273 }
15274
15275 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15276   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15277   MFI->setFrameAddressIsTaken(true);
15278
15279   EVT VT = Op.getValueType();
15280   SDLoc dl(Op);  // FIXME probably not meaningful
15281   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15282   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15283       DAG.getSubtarget().getRegisterInfo());
15284   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15285   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15286           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15287          "Invalid Frame Register!");
15288   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15289   while (Depth--)
15290     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15291                             MachinePointerInfo(),
15292                             false, false, false, 0);
15293   return FrameAddr;
15294 }
15295
15296 // FIXME? Maybe this could be a TableGen attribute on some registers and
15297 // this table could be generated automatically from RegInfo.
15298 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15299                                               EVT VT) const {
15300   unsigned Reg = StringSwitch<unsigned>(RegName)
15301                        .Case("esp", X86::ESP)
15302                        .Case("rsp", X86::RSP)
15303                        .Default(0);
15304   if (Reg)
15305     return Reg;
15306   report_fatal_error("Invalid register name global variable");
15307 }
15308
15309 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15310                                                      SelectionDAG &DAG) const {
15311   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15312       DAG.getSubtarget().getRegisterInfo());
15313   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15314 }
15315
15316 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15317   SDValue Chain     = Op.getOperand(0);
15318   SDValue Offset    = Op.getOperand(1);
15319   SDValue Handler   = Op.getOperand(2);
15320   SDLoc dl      (Op);
15321
15322   EVT PtrVT = getPointerTy();
15323   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15324       DAG.getSubtarget().getRegisterInfo());
15325   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15326   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15327           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15328          "Invalid Frame Register!");
15329   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15330   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15331
15332   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15333                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15334   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15335   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15336                        false, false, 0);
15337   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15338
15339   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15340                      DAG.getRegister(StoreAddrReg, PtrVT));
15341 }
15342
15343 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15344                                                SelectionDAG &DAG) const {
15345   SDLoc DL(Op);
15346   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15347                      DAG.getVTList(MVT::i32, MVT::Other),
15348                      Op.getOperand(0), Op.getOperand(1));
15349 }
15350
15351 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15352                                                 SelectionDAG &DAG) const {
15353   SDLoc DL(Op);
15354   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15355                      Op.getOperand(0), Op.getOperand(1));
15356 }
15357
15358 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15359   return Op.getOperand(0);
15360 }
15361
15362 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15363                                                 SelectionDAG &DAG) const {
15364   SDValue Root = Op.getOperand(0);
15365   SDValue Trmp = Op.getOperand(1); // trampoline
15366   SDValue FPtr = Op.getOperand(2); // nested function
15367   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15368   SDLoc dl (Op);
15369
15370   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15371   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15372
15373   if (Subtarget->is64Bit()) {
15374     SDValue OutChains[6];
15375
15376     // Large code-model.
15377     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15378     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15379
15380     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15381     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15382
15383     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15384
15385     // Load the pointer to the nested function into R11.
15386     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15387     SDValue Addr = Trmp;
15388     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15389                                 Addr, MachinePointerInfo(TrmpAddr),
15390                                 false, false, 0);
15391
15392     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15393                        DAG.getConstant(2, MVT::i64));
15394     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15395                                 MachinePointerInfo(TrmpAddr, 2),
15396                                 false, false, 2);
15397
15398     // Load the 'nest' parameter value into R10.
15399     // R10 is specified in X86CallingConv.td
15400     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15401     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15402                        DAG.getConstant(10, MVT::i64));
15403     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15404                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15405                                 false, false, 0);
15406
15407     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15408                        DAG.getConstant(12, MVT::i64));
15409     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15410                                 MachinePointerInfo(TrmpAddr, 12),
15411                                 false, false, 2);
15412
15413     // Jump to the nested function.
15414     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15415     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15416                        DAG.getConstant(20, MVT::i64));
15417     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15418                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15419                                 false, false, 0);
15420
15421     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15422     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15423                        DAG.getConstant(22, MVT::i64));
15424     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15425                                 MachinePointerInfo(TrmpAddr, 22),
15426                                 false, false, 0);
15427
15428     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15429   } else {
15430     const Function *Func =
15431       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15432     CallingConv::ID CC = Func->getCallingConv();
15433     unsigned NestReg;
15434
15435     switch (CC) {
15436     default:
15437       llvm_unreachable("Unsupported calling convention");
15438     case CallingConv::C:
15439     case CallingConv::X86_StdCall: {
15440       // Pass 'nest' parameter in ECX.
15441       // Must be kept in sync with X86CallingConv.td
15442       NestReg = X86::ECX;
15443
15444       // Check that ECX wasn't needed by an 'inreg' parameter.
15445       FunctionType *FTy = Func->getFunctionType();
15446       const AttributeSet &Attrs = Func->getAttributes();
15447
15448       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15449         unsigned InRegCount = 0;
15450         unsigned Idx = 1;
15451
15452         for (FunctionType::param_iterator I = FTy->param_begin(),
15453              E = FTy->param_end(); I != E; ++I, ++Idx)
15454           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15455             // FIXME: should only count parameters that are lowered to integers.
15456             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15457
15458         if (InRegCount > 2) {
15459           report_fatal_error("Nest register in use - reduce number of inreg"
15460                              " parameters!");
15461         }
15462       }
15463       break;
15464     }
15465     case CallingConv::X86_FastCall:
15466     case CallingConv::X86_ThisCall:
15467     case CallingConv::Fast:
15468       // Pass 'nest' parameter in EAX.
15469       // Must be kept in sync with X86CallingConv.td
15470       NestReg = X86::EAX;
15471       break;
15472     }
15473
15474     SDValue OutChains[4];
15475     SDValue Addr, Disp;
15476
15477     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15478                        DAG.getConstant(10, MVT::i32));
15479     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15480
15481     // This is storing the opcode for MOV32ri.
15482     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15483     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15484     OutChains[0] = DAG.getStore(Root, dl,
15485                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15486                                 Trmp, MachinePointerInfo(TrmpAddr),
15487                                 false, false, 0);
15488
15489     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15490                        DAG.getConstant(1, MVT::i32));
15491     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15492                                 MachinePointerInfo(TrmpAddr, 1),
15493                                 false, false, 1);
15494
15495     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15496     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15497                        DAG.getConstant(5, MVT::i32));
15498     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15499                                 MachinePointerInfo(TrmpAddr, 5),
15500                                 false, false, 1);
15501
15502     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15503                        DAG.getConstant(6, MVT::i32));
15504     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15505                                 MachinePointerInfo(TrmpAddr, 6),
15506                                 false, false, 1);
15507
15508     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15509   }
15510 }
15511
15512 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15513                                             SelectionDAG &DAG) const {
15514   /*
15515    The rounding mode is in bits 11:10 of FPSR, and has the following
15516    settings:
15517      00 Round to nearest
15518      01 Round to -inf
15519      10 Round to +inf
15520      11 Round to 0
15521
15522   FLT_ROUNDS, on the other hand, expects the following:
15523     -1 Undefined
15524      0 Round to 0
15525      1 Round to nearest
15526      2 Round to +inf
15527      3 Round to -inf
15528
15529   To perform the conversion, we do:
15530     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15531   */
15532
15533   MachineFunction &MF = DAG.getMachineFunction();
15534   const TargetMachine &TM = MF.getTarget();
15535   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15536   unsigned StackAlignment = TFI.getStackAlignment();
15537   MVT VT = Op.getSimpleValueType();
15538   SDLoc DL(Op);
15539
15540   // Save FP Control Word to stack slot
15541   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15542   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15543
15544   MachineMemOperand *MMO =
15545    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15546                            MachineMemOperand::MOStore, 2, 2);
15547
15548   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15549   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15550                                           DAG.getVTList(MVT::Other),
15551                                           Ops, MVT::i16, MMO);
15552
15553   // Load FP Control Word from stack slot
15554   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15555                             MachinePointerInfo(), false, false, false, 0);
15556
15557   // Transform as necessary
15558   SDValue CWD1 =
15559     DAG.getNode(ISD::SRL, DL, MVT::i16,
15560                 DAG.getNode(ISD::AND, DL, MVT::i16,
15561                             CWD, DAG.getConstant(0x800, MVT::i16)),
15562                 DAG.getConstant(11, MVT::i8));
15563   SDValue CWD2 =
15564     DAG.getNode(ISD::SRL, DL, MVT::i16,
15565                 DAG.getNode(ISD::AND, DL, MVT::i16,
15566                             CWD, DAG.getConstant(0x400, MVT::i16)),
15567                 DAG.getConstant(9, MVT::i8));
15568
15569   SDValue RetVal =
15570     DAG.getNode(ISD::AND, DL, MVT::i16,
15571                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15572                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15573                             DAG.getConstant(1, MVT::i16)),
15574                 DAG.getConstant(3, MVT::i16));
15575
15576   return DAG.getNode((VT.getSizeInBits() < 16 ?
15577                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15578 }
15579
15580 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15581   MVT VT = Op.getSimpleValueType();
15582   EVT OpVT = VT;
15583   unsigned NumBits = VT.getSizeInBits();
15584   SDLoc dl(Op);
15585
15586   Op = Op.getOperand(0);
15587   if (VT == MVT::i8) {
15588     // Zero extend to i32 since there is not an i8 bsr.
15589     OpVT = MVT::i32;
15590     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15591   }
15592
15593   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15594   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15595   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15596
15597   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15598   SDValue Ops[] = {
15599     Op,
15600     DAG.getConstant(NumBits+NumBits-1, OpVT),
15601     DAG.getConstant(X86::COND_E, MVT::i8),
15602     Op.getValue(1)
15603   };
15604   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15605
15606   // Finally xor with NumBits-1.
15607   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15608
15609   if (VT == MVT::i8)
15610     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15611   return Op;
15612 }
15613
15614 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15615   MVT VT = Op.getSimpleValueType();
15616   EVT OpVT = VT;
15617   unsigned NumBits = VT.getSizeInBits();
15618   SDLoc dl(Op);
15619
15620   Op = Op.getOperand(0);
15621   if (VT == MVT::i8) {
15622     // Zero extend to i32 since there is not an i8 bsr.
15623     OpVT = MVT::i32;
15624     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15625   }
15626
15627   // Issue a bsr (scan bits in reverse).
15628   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15629   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15630
15631   // And xor with NumBits-1.
15632   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15633
15634   if (VT == MVT::i8)
15635     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15636   return Op;
15637 }
15638
15639 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15640   MVT VT = Op.getSimpleValueType();
15641   unsigned NumBits = VT.getSizeInBits();
15642   SDLoc dl(Op);
15643   Op = Op.getOperand(0);
15644
15645   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15646   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15647   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15648
15649   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15650   SDValue Ops[] = {
15651     Op,
15652     DAG.getConstant(NumBits, VT),
15653     DAG.getConstant(X86::COND_E, MVT::i8),
15654     Op.getValue(1)
15655   };
15656   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15657 }
15658
15659 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15660 // ones, and then concatenate the result back.
15661 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15662   MVT VT = Op.getSimpleValueType();
15663
15664   assert(VT.is256BitVector() && VT.isInteger() &&
15665          "Unsupported value type for operation");
15666
15667   unsigned NumElems = VT.getVectorNumElements();
15668   SDLoc dl(Op);
15669
15670   // Extract the LHS vectors
15671   SDValue LHS = Op.getOperand(0);
15672   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15673   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15674
15675   // Extract the RHS vectors
15676   SDValue RHS = Op.getOperand(1);
15677   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15678   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15679
15680   MVT EltVT = VT.getVectorElementType();
15681   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15682
15683   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15684                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15685                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15686 }
15687
15688 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15689   assert(Op.getSimpleValueType().is256BitVector() &&
15690          Op.getSimpleValueType().isInteger() &&
15691          "Only handle AVX 256-bit vector integer operation");
15692   return Lower256IntArith(Op, DAG);
15693 }
15694
15695 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15696   assert(Op.getSimpleValueType().is256BitVector() &&
15697          Op.getSimpleValueType().isInteger() &&
15698          "Only handle AVX 256-bit vector integer operation");
15699   return Lower256IntArith(Op, DAG);
15700 }
15701
15702 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15703                         SelectionDAG &DAG) {
15704   SDLoc dl(Op);
15705   MVT VT = Op.getSimpleValueType();
15706
15707   // Decompose 256-bit ops into smaller 128-bit ops.
15708   if (VT.is256BitVector() && !Subtarget->hasInt256())
15709     return Lower256IntArith(Op, DAG);
15710
15711   SDValue A = Op.getOperand(0);
15712   SDValue B = Op.getOperand(1);
15713
15714   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15715   if (VT == MVT::v4i32) {
15716     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15717            "Should not custom lower when pmuldq is available!");
15718
15719     // Extract the odd parts.
15720     static const int UnpackMask[] = { 1, -1, 3, -1 };
15721     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15722     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15723
15724     // Multiply the even parts.
15725     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15726     // Now multiply odd parts.
15727     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15728
15729     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15730     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15731
15732     // Merge the two vectors back together with a shuffle. This expands into 2
15733     // shuffles.
15734     static const int ShufMask[] = { 0, 4, 2, 6 };
15735     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15736   }
15737
15738   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15739          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15740
15741   //  Ahi = psrlqi(a, 32);
15742   //  Bhi = psrlqi(b, 32);
15743   //
15744   //  AloBlo = pmuludq(a, b);
15745   //  AloBhi = pmuludq(a, Bhi);
15746   //  AhiBlo = pmuludq(Ahi, b);
15747
15748   //  AloBhi = psllqi(AloBhi, 32);
15749   //  AhiBlo = psllqi(AhiBlo, 32);
15750   //  return AloBlo + AloBhi + AhiBlo;
15751
15752   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15753   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15754
15755   // Bit cast to 32-bit vectors for MULUDQ
15756   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15757                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15758   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15759   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15760   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15761   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15762
15763   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15764   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15765   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15766
15767   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15768   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15769
15770   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15771   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15772 }
15773
15774 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15775   assert(Subtarget->isTargetWin64() && "Unexpected target");
15776   EVT VT = Op.getValueType();
15777   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15778          "Unexpected return type for lowering");
15779
15780   RTLIB::Libcall LC;
15781   bool isSigned;
15782   switch (Op->getOpcode()) {
15783   default: llvm_unreachable("Unexpected request for libcall!");
15784   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15785   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15786   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15787   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15788   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15789   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15790   }
15791
15792   SDLoc dl(Op);
15793   SDValue InChain = DAG.getEntryNode();
15794
15795   TargetLowering::ArgListTy Args;
15796   TargetLowering::ArgListEntry Entry;
15797   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15798     EVT ArgVT = Op->getOperand(i).getValueType();
15799     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15800            "Unexpected argument type for lowering");
15801     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15802     Entry.Node = StackPtr;
15803     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15804                            false, false, 16);
15805     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15806     Entry.Ty = PointerType::get(ArgTy,0);
15807     Entry.isSExt = false;
15808     Entry.isZExt = false;
15809     Args.push_back(Entry);
15810   }
15811
15812   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15813                                          getPointerTy());
15814
15815   TargetLowering::CallLoweringInfo CLI(DAG);
15816   CLI.setDebugLoc(dl).setChain(InChain)
15817     .setCallee(getLibcallCallingConv(LC),
15818                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15819                Callee, std::move(Args), 0)
15820     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15821
15822   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15823   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15824 }
15825
15826 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15827                              SelectionDAG &DAG) {
15828   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15829   EVT VT = Op0.getValueType();
15830   SDLoc dl(Op);
15831
15832   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15833          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15834
15835   // PMULxD operations multiply each even value (starting at 0) of LHS with
15836   // the related value of RHS and produce a widen result.
15837   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15838   // => <2 x i64> <ae|cg>
15839   //
15840   // In other word, to have all the results, we need to perform two PMULxD:
15841   // 1. one with the even values.
15842   // 2. one with the odd values.
15843   // To achieve #2, with need to place the odd values at an even position.
15844   //
15845   // Place the odd value at an even position (basically, shift all values 1
15846   // step to the left):
15847   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15848   // <a|b|c|d> => <b|undef|d|undef>
15849   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15850   // <e|f|g|h> => <f|undef|h|undef>
15851   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15852
15853   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15854   // ints.
15855   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15856   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15857   unsigned Opcode =
15858       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15859   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15860   // => <2 x i64> <ae|cg>
15861   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15862                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15863   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15864   // => <2 x i64> <bf|dh>
15865   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15866                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15867
15868   // Shuffle it back into the right order.
15869   SDValue Highs, Lows;
15870   if (VT == MVT::v8i32) {
15871     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15872     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15873     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15874     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15875   } else {
15876     const int HighMask[] = {1, 5, 3, 7};
15877     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15878     const int LowMask[] = {1, 4, 2, 6};
15879     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15880   }
15881
15882   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15883   // unsigned multiply.
15884   if (IsSigned && !Subtarget->hasSSE41()) {
15885     SDValue ShAmt =
15886         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15887     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15888                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15889     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15890                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15891
15892     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15893     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15894   }
15895
15896   // The first result of MUL_LOHI is actually the low value, followed by the
15897   // high value.
15898   SDValue Ops[] = {Lows, Highs};
15899   return DAG.getMergeValues(Ops, dl);
15900 }
15901
15902 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15903                                          const X86Subtarget *Subtarget) {
15904   MVT VT = Op.getSimpleValueType();
15905   SDLoc dl(Op);
15906   SDValue R = Op.getOperand(0);
15907   SDValue Amt = Op.getOperand(1);
15908
15909   // Optimize shl/srl/sra with constant shift amount.
15910   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15911     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15912       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15913
15914       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15915           (Subtarget->hasInt256() &&
15916            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15917           (Subtarget->hasAVX512() &&
15918            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15919         if (Op.getOpcode() == ISD::SHL)
15920           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15921                                             DAG);
15922         if (Op.getOpcode() == ISD::SRL)
15923           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15924                                             DAG);
15925         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15926           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15927                                             DAG);
15928       }
15929
15930       if (VT == MVT::v16i8) {
15931         if (Op.getOpcode() == ISD::SHL) {
15932           // Make a large shift.
15933           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15934                                                    MVT::v8i16, R, ShiftAmt,
15935                                                    DAG);
15936           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15937           // Zero out the rightmost bits.
15938           SmallVector<SDValue, 16> V(16,
15939                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15940                                                      MVT::i8));
15941           return DAG.getNode(ISD::AND, dl, VT, SHL,
15942                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15943         }
15944         if (Op.getOpcode() == ISD::SRL) {
15945           // Make a large shift.
15946           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15947                                                    MVT::v8i16, R, ShiftAmt,
15948                                                    DAG);
15949           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15950           // Zero out the leftmost bits.
15951           SmallVector<SDValue, 16> V(16,
15952                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15953                                                      MVT::i8));
15954           return DAG.getNode(ISD::AND, dl, VT, SRL,
15955                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15956         }
15957         if (Op.getOpcode() == ISD::SRA) {
15958           if (ShiftAmt == 7) {
15959             // R s>> 7  ===  R s< 0
15960             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15961             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15962           }
15963
15964           // R s>> a === ((R u>> a) ^ m) - m
15965           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15966           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15967                                                          MVT::i8));
15968           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15969           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15970           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15971           return Res;
15972         }
15973         llvm_unreachable("Unknown shift opcode.");
15974       }
15975
15976       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15977         if (Op.getOpcode() == ISD::SHL) {
15978           // Make a large shift.
15979           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15980                                                    MVT::v16i16, R, ShiftAmt,
15981                                                    DAG);
15982           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15983           // Zero out the rightmost bits.
15984           SmallVector<SDValue, 32> V(32,
15985                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15986                                                      MVT::i8));
15987           return DAG.getNode(ISD::AND, dl, VT, SHL,
15988                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15989         }
15990         if (Op.getOpcode() == ISD::SRL) {
15991           // Make a large shift.
15992           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15993                                                    MVT::v16i16, R, ShiftAmt,
15994                                                    DAG);
15995           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15996           // Zero out the leftmost bits.
15997           SmallVector<SDValue, 32> V(32,
15998                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15999                                                      MVT::i8));
16000           return DAG.getNode(ISD::AND, dl, VT, SRL,
16001                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16002         }
16003         if (Op.getOpcode() == ISD::SRA) {
16004           if (ShiftAmt == 7) {
16005             // R s>> 7  ===  R s< 0
16006             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16007             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16008           }
16009
16010           // R s>> a === ((R u>> a) ^ m) - m
16011           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16012           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
16013                                                          MVT::i8));
16014           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16015           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16016           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16017           return Res;
16018         }
16019         llvm_unreachable("Unknown shift opcode.");
16020       }
16021     }
16022   }
16023
16024   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16025   if (!Subtarget->is64Bit() &&
16026       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16027       Amt.getOpcode() == ISD::BITCAST &&
16028       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16029     Amt = Amt.getOperand(0);
16030     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16031                      VT.getVectorNumElements();
16032     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16033     uint64_t ShiftAmt = 0;
16034     for (unsigned i = 0; i != Ratio; ++i) {
16035       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16036       if (!C)
16037         return SDValue();
16038       // 6 == Log2(64)
16039       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16040     }
16041     // Check remaining shift amounts.
16042     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16043       uint64_t ShAmt = 0;
16044       for (unsigned j = 0; j != Ratio; ++j) {
16045         ConstantSDNode *C =
16046           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16047         if (!C)
16048           return SDValue();
16049         // 6 == Log2(64)
16050         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16051       }
16052       if (ShAmt != ShiftAmt)
16053         return SDValue();
16054     }
16055     switch (Op.getOpcode()) {
16056     default:
16057       llvm_unreachable("Unknown shift opcode!");
16058     case ISD::SHL:
16059       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16060                                         DAG);
16061     case ISD::SRL:
16062       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16063                                         DAG);
16064     case ISD::SRA:
16065       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16066                                         DAG);
16067     }
16068   }
16069
16070   return SDValue();
16071 }
16072
16073 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16074                                         const X86Subtarget* Subtarget) {
16075   MVT VT = Op.getSimpleValueType();
16076   SDLoc dl(Op);
16077   SDValue R = Op.getOperand(0);
16078   SDValue Amt = Op.getOperand(1);
16079
16080   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16081       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16082       (Subtarget->hasInt256() &&
16083        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16084         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16085        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16086     SDValue BaseShAmt;
16087     EVT EltVT = VT.getVectorElementType();
16088
16089     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16090       unsigned NumElts = VT.getVectorNumElements();
16091       unsigned i, j;
16092       for (i = 0; i != NumElts; ++i) {
16093         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16094           continue;
16095         break;
16096       }
16097       for (j = i; j != NumElts; ++j) {
16098         SDValue Arg = Amt.getOperand(j);
16099         if (Arg.getOpcode() == ISD::UNDEF) continue;
16100         if (Arg != Amt.getOperand(i))
16101           break;
16102       }
16103       if (i != NumElts && j == NumElts)
16104         BaseShAmt = Amt.getOperand(i);
16105     } else {
16106       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16107         Amt = Amt.getOperand(0);
16108       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16109                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16110         SDValue InVec = Amt.getOperand(0);
16111         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16112           unsigned NumElts = InVec.getValueType().getVectorNumElements();
16113           unsigned i = 0;
16114           for (; i != NumElts; ++i) {
16115             SDValue Arg = InVec.getOperand(i);
16116             if (Arg.getOpcode() == ISD::UNDEF) continue;
16117             BaseShAmt = Arg;
16118             break;
16119           }
16120         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16121            if (ConstantSDNode *C =
16122                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16123              unsigned SplatIdx =
16124                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16125              if (C->getZExtValue() == SplatIdx)
16126                BaseShAmt = InVec.getOperand(1);
16127            }
16128         }
16129         if (!BaseShAmt.getNode())
16130           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16131                                   DAG.getIntPtrConstant(0));
16132       }
16133     }
16134
16135     if (BaseShAmt.getNode()) {
16136       if (EltVT.bitsGT(MVT::i32))
16137         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16138       else if (EltVT.bitsLT(MVT::i32))
16139         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16140
16141       switch (Op.getOpcode()) {
16142       default:
16143         llvm_unreachable("Unknown shift opcode!");
16144       case ISD::SHL:
16145         switch (VT.SimpleTy) {
16146         default: return SDValue();
16147         case MVT::v2i64:
16148         case MVT::v4i32:
16149         case MVT::v8i16:
16150         case MVT::v4i64:
16151         case MVT::v8i32:
16152         case MVT::v16i16:
16153         case MVT::v16i32:
16154         case MVT::v8i64:
16155           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16156         }
16157       case ISD::SRA:
16158         switch (VT.SimpleTy) {
16159         default: return SDValue();
16160         case MVT::v4i32:
16161         case MVT::v8i16:
16162         case MVT::v8i32:
16163         case MVT::v16i16:
16164         case MVT::v16i32:
16165         case MVT::v8i64:
16166           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16167         }
16168       case ISD::SRL:
16169         switch (VT.SimpleTy) {
16170         default: return SDValue();
16171         case MVT::v2i64:
16172         case MVT::v4i32:
16173         case MVT::v8i16:
16174         case MVT::v4i64:
16175         case MVT::v8i32:
16176         case MVT::v16i16:
16177         case MVT::v16i32:
16178         case MVT::v8i64:
16179           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16180         }
16181       }
16182     }
16183   }
16184
16185   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16186   if (!Subtarget->is64Bit() &&
16187       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16188       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16189       Amt.getOpcode() == ISD::BITCAST &&
16190       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16191     Amt = Amt.getOperand(0);
16192     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16193                      VT.getVectorNumElements();
16194     std::vector<SDValue> Vals(Ratio);
16195     for (unsigned i = 0; i != Ratio; ++i)
16196       Vals[i] = Amt.getOperand(i);
16197     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16198       for (unsigned j = 0; j != Ratio; ++j)
16199         if (Vals[j] != Amt.getOperand(i + j))
16200           return SDValue();
16201     }
16202     switch (Op.getOpcode()) {
16203     default:
16204       llvm_unreachable("Unknown shift opcode!");
16205     case ISD::SHL:
16206       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16207     case ISD::SRL:
16208       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16209     case ISD::SRA:
16210       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16211     }
16212   }
16213
16214   return SDValue();
16215 }
16216
16217 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16218                           SelectionDAG &DAG) {
16219   MVT VT = Op.getSimpleValueType();
16220   SDLoc dl(Op);
16221   SDValue R = Op.getOperand(0);
16222   SDValue Amt = Op.getOperand(1);
16223   SDValue V;
16224
16225   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16226   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16227
16228   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16229   if (V.getNode())
16230     return V;
16231
16232   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16233   if (V.getNode())
16234       return V;
16235
16236   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16237     return Op;
16238   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16239   if (Subtarget->hasInt256()) {
16240     if (Op.getOpcode() == ISD::SRL &&
16241         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16242          VT == MVT::v4i64 || VT == MVT::v8i32))
16243       return Op;
16244     if (Op.getOpcode() == ISD::SHL &&
16245         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16246          VT == MVT::v4i64 || VT == MVT::v8i32))
16247       return Op;
16248     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16249       return Op;
16250   }
16251
16252   // If possible, lower this packed shift into a vector multiply instead of
16253   // expanding it into a sequence of scalar shifts.
16254   // Do this only if the vector shift count is a constant build_vector.
16255   if (Op.getOpcode() == ISD::SHL && 
16256       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16257        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16258       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16259     SmallVector<SDValue, 8> Elts;
16260     EVT SVT = VT.getScalarType();
16261     unsigned SVTBits = SVT.getSizeInBits();
16262     const APInt &One = APInt(SVTBits, 1);
16263     unsigned NumElems = VT.getVectorNumElements();
16264
16265     for (unsigned i=0; i !=NumElems; ++i) {
16266       SDValue Op = Amt->getOperand(i);
16267       if (Op->getOpcode() == ISD::UNDEF) {
16268         Elts.push_back(Op);
16269         continue;
16270       }
16271
16272       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16273       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16274       uint64_t ShAmt = C.getZExtValue();
16275       if (ShAmt >= SVTBits) {
16276         Elts.push_back(DAG.getUNDEF(SVT));
16277         continue;
16278       }
16279       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16280     }
16281     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16282     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16283   }
16284
16285   // Lower SHL with variable shift amount.
16286   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16287     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16288
16289     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16290     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16291     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16292     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16293   }
16294
16295   // If possible, lower this shift as a sequence of two shifts by
16296   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16297   // Example:
16298   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16299   //
16300   // Could be rewritten as:
16301   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16302   //
16303   // The advantage is that the two shifts from the example would be
16304   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16305   // the vector shift into four scalar shifts plus four pairs of vector
16306   // insert/extract.
16307   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16308       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16309     unsigned TargetOpcode = X86ISD::MOVSS;
16310     bool CanBeSimplified;
16311     // The splat value for the first packed shift (the 'X' from the example).
16312     SDValue Amt1 = Amt->getOperand(0);
16313     // The splat value for the second packed shift (the 'Y' from the example).
16314     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16315                                         Amt->getOperand(2);
16316
16317     // See if it is possible to replace this node with a sequence of
16318     // two shifts followed by a MOVSS/MOVSD
16319     if (VT == MVT::v4i32) {
16320       // Check if it is legal to use a MOVSS.
16321       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16322                         Amt2 == Amt->getOperand(3);
16323       if (!CanBeSimplified) {
16324         // Otherwise, check if we can still simplify this node using a MOVSD.
16325         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16326                           Amt->getOperand(2) == Amt->getOperand(3);
16327         TargetOpcode = X86ISD::MOVSD;
16328         Amt2 = Amt->getOperand(2);
16329       }
16330     } else {
16331       // Do similar checks for the case where the machine value type
16332       // is MVT::v8i16.
16333       CanBeSimplified = Amt1 == Amt->getOperand(1);
16334       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16335         CanBeSimplified = Amt2 == Amt->getOperand(i);
16336
16337       if (!CanBeSimplified) {
16338         TargetOpcode = X86ISD::MOVSD;
16339         CanBeSimplified = true;
16340         Amt2 = Amt->getOperand(4);
16341         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16342           CanBeSimplified = Amt1 == Amt->getOperand(i);
16343         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16344           CanBeSimplified = Amt2 == Amt->getOperand(j);
16345       }
16346     }
16347     
16348     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16349         isa<ConstantSDNode>(Amt2)) {
16350       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16351       EVT CastVT = MVT::v4i32;
16352       SDValue Splat1 = 
16353         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16354       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16355       SDValue Splat2 = 
16356         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16357       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16358       if (TargetOpcode == X86ISD::MOVSD)
16359         CastVT = MVT::v2i64;
16360       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16361       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16362       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16363                                             BitCast1, DAG);
16364       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16365     }
16366   }
16367
16368   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16369     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16370
16371     // a = a << 5;
16372     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16373     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16374
16375     // Turn 'a' into a mask suitable for VSELECT
16376     SDValue VSelM = DAG.getConstant(0x80, VT);
16377     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16378     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16379
16380     SDValue CM1 = DAG.getConstant(0x0f, VT);
16381     SDValue CM2 = DAG.getConstant(0x3f, VT);
16382
16383     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16384     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16385     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16386     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16387     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16388
16389     // a += a
16390     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16391     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16392     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16393
16394     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16395     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16396     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16397     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16398     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16399
16400     // a += a
16401     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16402     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16403     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16404
16405     // return VSELECT(r, r+r, a);
16406     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16407                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16408     return R;
16409   }
16410
16411   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16412   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16413   // solution better.
16414   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16415     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16416     unsigned ExtOpc =
16417         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16418     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16419     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16420     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16421                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16422     }
16423
16424   // Decompose 256-bit shifts into smaller 128-bit shifts.
16425   if (VT.is256BitVector()) {
16426     unsigned NumElems = VT.getVectorNumElements();
16427     MVT EltVT = VT.getVectorElementType();
16428     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16429
16430     // Extract the two vectors
16431     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16432     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16433
16434     // Recreate the shift amount vectors
16435     SDValue Amt1, Amt2;
16436     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16437       // Constant shift amount
16438       SmallVector<SDValue, 4> Amt1Csts;
16439       SmallVector<SDValue, 4> Amt2Csts;
16440       for (unsigned i = 0; i != NumElems/2; ++i)
16441         Amt1Csts.push_back(Amt->getOperand(i));
16442       for (unsigned i = NumElems/2; i != NumElems; ++i)
16443         Amt2Csts.push_back(Amt->getOperand(i));
16444
16445       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16446       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16447     } else {
16448       // Variable shift amount
16449       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16450       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16451     }
16452
16453     // Issue new vector shifts for the smaller types
16454     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16455     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16456
16457     // Concatenate the result back
16458     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16459   }
16460
16461   return SDValue();
16462 }
16463
16464 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16465   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16466   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16467   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16468   // has only one use.
16469   SDNode *N = Op.getNode();
16470   SDValue LHS = N->getOperand(0);
16471   SDValue RHS = N->getOperand(1);
16472   unsigned BaseOp = 0;
16473   unsigned Cond = 0;
16474   SDLoc DL(Op);
16475   switch (Op.getOpcode()) {
16476   default: llvm_unreachable("Unknown ovf instruction!");
16477   case ISD::SADDO:
16478     // A subtract of one will be selected as a INC. Note that INC doesn't
16479     // set CF, so we can't do this for UADDO.
16480     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16481       if (C->isOne()) {
16482         BaseOp = X86ISD::INC;
16483         Cond = X86::COND_O;
16484         break;
16485       }
16486     BaseOp = X86ISD::ADD;
16487     Cond = X86::COND_O;
16488     break;
16489   case ISD::UADDO:
16490     BaseOp = X86ISD::ADD;
16491     Cond = X86::COND_B;
16492     break;
16493   case ISD::SSUBO:
16494     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16495     // set CF, so we can't do this for USUBO.
16496     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16497       if (C->isOne()) {
16498         BaseOp = X86ISD::DEC;
16499         Cond = X86::COND_O;
16500         break;
16501       }
16502     BaseOp = X86ISD::SUB;
16503     Cond = X86::COND_O;
16504     break;
16505   case ISD::USUBO:
16506     BaseOp = X86ISD::SUB;
16507     Cond = X86::COND_B;
16508     break;
16509   case ISD::SMULO:
16510     BaseOp = X86ISD::SMUL;
16511     Cond = X86::COND_O;
16512     break;
16513   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16514     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16515                                  MVT::i32);
16516     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16517
16518     SDValue SetCC =
16519       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16520                   DAG.getConstant(X86::COND_O, MVT::i32),
16521                   SDValue(Sum.getNode(), 2));
16522
16523     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16524   }
16525   }
16526
16527   // Also sets EFLAGS.
16528   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16529   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16530
16531   SDValue SetCC =
16532     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16533                 DAG.getConstant(Cond, MVT::i32),
16534                 SDValue(Sum.getNode(), 1));
16535
16536   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16537 }
16538
16539 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16540                                                   SelectionDAG &DAG) const {
16541   SDLoc dl(Op);
16542   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16543   MVT VT = Op.getSimpleValueType();
16544
16545   if (!Subtarget->hasSSE2() || !VT.isVector())
16546     return SDValue();
16547
16548   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16549                       ExtraVT.getScalarType().getSizeInBits();
16550
16551   switch (VT.SimpleTy) {
16552     default: return SDValue();
16553     case MVT::v8i32:
16554     case MVT::v16i16:
16555       if (!Subtarget->hasFp256())
16556         return SDValue();
16557       if (!Subtarget->hasInt256()) {
16558         // needs to be split
16559         unsigned NumElems = VT.getVectorNumElements();
16560
16561         // Extract the LHS vectors
16562         SDValue LHS = Op.getOperand(0);
16563         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16564         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16565
16566         MVT EltVT = VT.getVectorElementType();
16567         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16568
16569         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16570         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16571         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16572                                    ExtraNumElems/2);
16573         SDValue Extra = DAG.getValueType(ExtraVT);
16574
16575         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16576         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16577
16578         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16579       }
16580       // fall through
16581     case MVT::v4i32:
16582     case MVT::v8i16: {
16583       SDValue Op0 = Op.getOperand(0);
16584       SDValue Op00 = Op0.getOperand(0);
16585       SDValue Tmp1;
16586       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16587       if (Op0.getOpcode() == ISD::BITCAST &&
16588           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16589         // (sext (vzext x)) -> (vsext x)
16590         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16591         if (Tmp1.getNode()) {
16592           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16593           // This folding is only valid when the in-reg type is a vector of i8,
16594           // i16, or i32.
16595           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16596               ExtraEltVT == MVT::i32) {
16597             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16598             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16599                    "This optimization is invalid without a VZEXT.");
16600             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16601           }
16602           Op0 = Tmp1;
16603         }
16604       }
16605
16606       // If the above didn't work, then just use Shift-Left + Shift-Right.
16607       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16608                                         DAG);
16609       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16610                                         DAG);
16611     }
16612   }
16613 }
16614
16615 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16616                                  SelectionDAG &DAG) {
16617   SDLoc dl(Op);
16618   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16619     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16620   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16621     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16622
16623   // The only fence that needs an instruction is a sequentially-consistent
16624   // cross-thread fence.
16625   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16626     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16627     // no-sse2). There isn't any reason to disable it if the target processor
16628     // supports it.
16629     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16630       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16631
16632     SDValue Chain = Op.getOperand(0);
16633     SDValue Zero = DAG.getConstant(0, MVT::i32);
16634     SDValue Ops[] = {
16635       DAG.getRegister(X86::ESP, MVT::i32), // Base
16636       DAG.getTargetConstant(1, MVT::i8),   // Scale
16637       DAG.getRegister(0, MVT::i32),        // Index
16638       DAG.getTargetConstant(0, MVT::i32),  // Disp
16639       DAG.getRegister(0, MVT::i32),        // Segment.
16640       Zero,
16641       Chain
16642     };
16643     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16644     return SDValue(Res, 0);
16645   }
16646
16647   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16648   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16649 }
16650
16651 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16652                              SelectionDAG &DAG) {
16653   MVT T = Op.getSimpleValueType();
16654   SDLoc DL(Op);
16655   unsigned Reg = 0;
16656   unsigned size = 0;
16657   switch(T.SimpleTy) {
16658   default: llvm_unreachable("Invalid value type!");
16659   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16660   case MVT::i16: Reg = X86::AX;  size = 2; break;
16661   case MVT::i32: Reg = X86::EAX; size = 4; break;
16662   case MVT::i64:
16663     assert(Subtarget->is64Bit() && "Node not type legal!");
16664     Reg = X86::RAX; size = 8;
16665     break;
16666   }
16667   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16668                                   Op.getOperand(2), SDValue());
16669   SDValue Ops[] = { cpIn.getValue(0),
16670                     Op.getOperand(1),
16671                     Op.getOperand(3),
16672                     DAG.getTargetConstant(size, MVT::i8),
16673                     cpIn.getValue(1) };
16674   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16675   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16676   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16677                                            Ops, T, MMO);
16678
16679   SDValue cpOut =
16680     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16681   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16682                                       MVT::i32, cpOut.getValue(2));
16683   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16684                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16685
16686   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16687   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16688   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16689   return SDValue();
16690 }
16691
16692 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16693                             SelectionDAG &DAG) {
16694   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16695   MVT DstVT = Op.getSimpleValueType();
16696
16697   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16698     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16699     if (DstVT != MVT::f64)
16700       // This conversion needs to be expanded.
16701       return SDValue();
16702
16703     SDValue InVec = Op->getOperand(0);
16704     SDLoc dl(Op);
16705     unsigned NumElts = SrcVT.getVectorNumElements();
16706     EVT SVT = SrcVT.getVectorElementType();
16707
16708     // Widen the vector in input in the case of MVT::v2i32.
16709     // Example: from MVT::v2i32 to MVT::v4i32.
16710     SmallVector<SDValue, 16> Elts;
16711     for (unsigned i = 0, e = NumElts; i != e; ++i)
16712       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16713                                  DAG.getIntPtrConstant(i)));
16714
16715     // Explicitly mark the extra elements as Undef.
16716     SDValue Undef = DAG.getUNDEF(SVT);
16717     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16718       Elts.push_back(Undef);
16719
16720     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16721     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16722     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16723     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16724                        DAG.getIntPtrConstant(0));
16725   }
16726
16727   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16728          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16729   assert((DstVT == MVT::i64 ||
16730           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16731          "Unexpected custom BITCAST");
16732   // i64 <=> MMX conversions are Legal.
16733   if (SrcVT==MVT::i64 && DstVT.isVector())
16734     return Op;
16735   if (DstVT==MVT::i64 && SrcVT.isVector())
16736     return Op;
16737   // MMX <=> MMX conversions are Legal.
16738   if (SrcVT.isVector() && DstVT.isVector())
16739     return Op;
16740   // All other conversions need to be expanded.
16741   return SDValue();
16742 }
16743
16744 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16745   SDNode *Node = Op.getNode();
16746   SDLoc dl(Node);
16747   EVT T = Node->getValueType(0);
16748   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16749                               DAG.getConstant(0, T), Node->getOperand(2));
16750   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16751                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16752                        Node->getOperand(0),
16753                        Node->getOperand(1), negOp,
16754                        cast<AtomicSDNode>(Node)->getMemOperand(),
16755                        cast<AtomicSDNode>(Node)->getOrdering(),
16756                        cast<AtomicSDNode>(Node)->getSynchScope());
16757 }
16758
16759 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16760   SDNode *Node = Op.getNode();
16761   SDLoc dl(Node);
16762   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16763
16764   // Convert seq_cst store -> xchg
16765   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16766   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16767   //        (The only way to get a 16-byte store is cmpxchg16b)
16768   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16769   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16770       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16771     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16772                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16773                                  Node->getOperand(0),
16774                                  Node->getOperand(1), Node->getOperand(2),
16775                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16776                                  cast<AtomicSDNode>(Node)->getOrdering(),
16777                                  cast<AtomicSDNode>(Node)->getSynchScope());
16778     return Swap.getValue(1);
16779   }
16780   // Other atomic stores have a simple pattern.
16781   return Op;
16782 }
16783
16784 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16785   EVT VT = Op.getNode()->getSimpleValueType(0);
16786
16787   // Let legalize expand this if it isn't a legal type yet.
16788   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16789     return SDValue();
16790
16791   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16792
16793   unsigned Opc;
16794   bool ExtraOp = false;
16795   switch (Op.getOpcode()) {
16796   default: llvm_unreachable("Invalid code");
16797   case ISD::ADDC: Opc = X86ISD::ADD; break;
16798   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16799   case ISD::SUBC: Opc = X86ISD::SUB; break;
16800   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16801   }
16802
16803   if (!ExtraOp)
16804     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16805                        Op.getOperand(1));
16806   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16807                      Op.getOperand(1), Op.getOperand(2));
16808 }
16809
16810 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16811                             SelectionDAG &DAG) {
16812   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16813
16814   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16815   // which returns the values as { float, float } (in XMM0) or
16816   // { double, double } (which is returned in XMM0, XMM1).
16817   SDLoc dl(Op);
16818   SDValue Arg = Op.getOperand(0);
16819   EVT ArgVT = Arg.getValueType();
16820   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16821
16822   TargetLowering::ArgListTy Args;
16823   TargetLowering::ArgListEntry Entry;
16824
16825   Entry.Node = Arg;
16826   Entry.Ty = ArgTy;
16827   Entry.isSExt = false;
16828   Entry.isZExt = false;
16829   Args.push_back(Entry);
16830
16831   bool isF64 = ArgVT == MVT::f64;
16832   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16833   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16834   // the results are returned via SRet in memory.
16835   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16836   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16837   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16838
16839   Type *RetTy = isF64
16840     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16841     : (Type*)VectorType::get(ArgTy, 4);
16842
16843   TargetLowering::CallLoweringInfo CLI(DAG);
16844   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16845     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16846
16847   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16848
16849   if (isF64)
16850     // Returned in xmm0 and xmm1.
16851     return CallResult.first;
16852
16853   // Returned in bits 0:31 and 32:64 xmm0.
16854   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16855                                CallResult.first, DAG.getIntPtrConstant(0));
16856   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16857                                CallResult.first, DAG.getIntPtrConstant(1));
16858   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16859   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16860 }
16861
16862 /// LowerOperation - Provide custom lowering hooks for some operations.
16863 ///
16864 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16865   switch (Op.getOpcode()) {
16866   default: llvm_unreachable("Should not custom lower this!");
16867   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16868   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16869   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16870     return LowerCMP_SWAP(Op, Subtarget, DAG);
16871   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16872   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16873   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16874   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16875   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16876   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16877   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16878   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16879   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16880   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16881   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16882   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16883   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16884   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16885   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16886   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16887   case ISD::SHL_PARTS:
16888   case ISD::SRA_PARTS:
16889   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16890   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16891   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16892   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16893   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16894   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16895   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16896   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16897   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16898   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16899   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16900   case ISD::FABS:               return LowerFABS(Op, DAG);
16901   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16902   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16903   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16904   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16905   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16906   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16907   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16908   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16909   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16910   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16911   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16912   case ISD::INTRINSIC_VOID:
16913   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16914   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16915   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16916   case ISD::FRAME_TO_ARGS_OFFSET:
16917                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16918   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16919   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16920   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16921   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16922   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16923   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16924   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16925   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16926   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16927   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16928   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16929   case ISD::UMUL_LOHI:
16930   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16931   case ISD::SRA:
16932   case ISD::SRL:
16933   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16934   case ISD::SADDO:
16935   case ISD::UADDO:
16936   case ISD::SSUBO:
16937   case ISD::USUBO:
16938   case ISD::SMULO:
16939   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16940   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16941   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16942   case ISD::ADDC:
16943   case ISD::ADDE:
16944   case ISD::SUBC:
16945   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16946   case ISD::ADD:                return LowerADD(Op, DAG);
16947   case ISD::SUB:                return LowerSUB(Op, DAG);
16948   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16949   }
16950 }
16951
16952 static void ReplaceATOMIC_LOAD(SDNode *Node,
16953                                SmallVectorImpl<SDValue> &Results,
16954                                SelectionDAG &DAG) {
16955   SDLoc dl(Node);
16956   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16957
16958   // Convert wide load -> cmpxchg8b/cmpxchg16b
16959   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16960   //        (The only way to get a 16-byte load is cmpxchg16b)
16961   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16962   SDValue Zero = DAG.getConstant(0, VT);
16963   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16964   SDValue Swap =
16965       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16966                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16967                            cast<AtomicSDNode>(Node)->getMemOperand(),
16968                            cast<AtomicSDNode>(Node)->getOrdering(),
16969                            cast<AtomicSDNode>(Node)->getOrdering(),
16970                            cast<AtomicSDNode>(Node)->getSynchScope());
16971   Results.push_back(Swap.getValue(0));
16972   Results.push_back(Swap.getValue(2));
16973 }
16974
16975 /// ReplaceNodeResults - Replace a node with an illegal result type
16976 /// with a new node built out of custom code.
16977 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16978                                            SmallVectorImpl<SDValue>&Results,
16979                                            SelectionDAG &DAG) const {
16980   SDLoc dl(N);
16981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16982   switch (N->getOpcode()) {
16983   default:
16984     llvm_unreachable("Do not know how to custom type legalize this operation!");
16985   case ISD::SIGN_EXTEND_INREG:
16986   case ISD::ADDC:
16987   case ISD::ADDE:
16988   case ISD::SUBC:
16989   case ISD::SUBE:
16990     // We don't want to expand or promote these.
16991     return;
16992   case ISD::SDIV:
16993   case ISD::UDIV:
16994   case ISD::SREM:
16995   case ISD::UREM:
16996   case ISD::SDIVREM:
16997   case ISD::UDIVREM: {
16998     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16999     Results.push_back(V);
17000     return;
17001   }
17002   case ISD::FP_TO_SINT:
17003   case ISD::FP_TO_UINT: {
17004     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17005
17006     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17007       return;
17008
17009     std::pair<SDValue,SDValue> Vals =
17010         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17011     SDValue FIST = Vals.first, StackSlot = Vals.second;
17012     if (FIST.getNode()) {
17013       EVT VT = N->getValueType(0);
17014       // Return a load from the stack slot.
17015       if (StackSlot.getNode())
17016         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17017                                       MachinePointerInfo(),
17018                                       false, false, false, 0));
17019       else
17020         Results.push_back(FIST);
17021     }
17022     return;
17023   }
17024   case ISD::UINT_TO_FP: {
17025     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17026     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17027         N->getValueType(0) != MVT::v2f32)
17028       return;
17029     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17030                                  N->getOperand(0));
17031     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17032                                      MVT::f64);
17033     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17034     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17035                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17036     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17037     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17038     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17039     return;
17040   }
17041   case ISD::FP_ROUND: {
17042     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17043         return;
17044     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17045     Results.push_back(V);
17046     return;
17047   }
17048   case ISD::INTRINSIC_W_CHAIN: {
17049     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17050     switch (IntNo) {
17051     default : llvm_unreachable("Do not know how to custom type "
17052                                "legalize this intrinsic operation!");
17053     case Intrinsic::x86_rdtsc:
17054       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17055                                      Results);
17056     case Intrinsic::x86_rdtscp:
17057       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17058                                      Results);
17059     case Intrinsic::x86_rdpmc:
17060       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17061     }
17062   }
17063   case ISD::READCYCLECOUNTER: {
17064     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17065                                    Results);
17066   }
17067   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17068     EVT T = N->getValueType(0);
17069     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17070     bool Regs64bit = T == MVT::i128;
17071     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17072     SDValue cpInL, cpInH;
17073     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17074                         DAG.getConstant(0, HalfT));
17075     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17076                         DAG.getConstant(1, HalfT));
17077     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17078                              Regs64bit ? X86::RAX : X86::EAX,
17079                              cpInL, SDValue());
17080     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17081                              Regs64bit ? X86::RDX : X86::EDX,
17082                              cpInH, cpInL.getValue(1));
17083     SDValue swapInL, swapInH;
17084     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17085                           DAG.getConstant(0, HalfT));
17086     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17087                           DAG.getConstant(1, HalfT));
17088     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17089                                Regs64bit ? X86::RBX : X86::EBX,
17090                                swapInL, cpInH.getValue(1));
17091     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17092                                Regs64bit ? X86::RCX : X86::ECX,
17093                                swapInH, swapInL.getValue(1));
17094     SDValue Ops[] = { swapInH.getValue(0),
17095                       N->getOperand(1),
17096                       swapInH.getValue(1) };
17097     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17098     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17099     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17100                                   X86ISD::LCMPXCHG8_DAG;
17101     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17102     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17103                                         Regs64bit ? X86::RAX : X86::EAX,
17104                                         HalfT, Result.getValue(1));
17105     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17106                                         Regs64bit ? X86::RDX : X86::EDX,
17107                                         HalfT, cpOutL.getValue(2));
17108     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17109
17110     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17111                                         MVT::i32, cpOutH.getValue(2));
17112     SDValue Success =
17113         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17114                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17115     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17116
17117     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17118     Results.push_back(Success);
17119     Results.push_back(EFLAGS.getValue(1));
17120     return;
17121   }
17122   case ISD::ATOMIC_SWAP:
17123   case ISD::ATOMIC_LOAD_ADD:
17124   case ISD::ATOMIC_LOAD_SUB:
17125   case ISD::ATOMIC_LOAD_AND:
17126   case ISD::ATOMIC_LOAD_OR:
17127   case ISD::ATOMIC_LOAD_XOR:
17128   case ISD::ATOMIC_LOAD_NAND:
17129   case ISD::ATOMIC_LOAD_MIN:
17130   case ISD::ATOMIC_LOAD_MAX:
17131   case ISD::ATOMIC_LOAD_UMIN:
17132   case ISD::ATOMIC_LOAD_UMAX:
17133     // Delegate to generic TypeLegalization. Situations we can really handle
17134     // should have already been dealt with by X86AtomicExpandPass.cpp.
17135     break;
17136   case ISD::ATOMIC_LOAD: {
17137     ReplaceATOMIC_LOAD(N, Results, DAG);
17138     return;
17139   }
17140   case ISD::BITCAST: {
17141     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17142     EVT DstVT = N->getValueType(0);
17143     EVT SrcVT = N->getOperand(0)->getValueType(0);
17144
17145     if (SrcVT != MVT::f64 ||
17146         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17147       return;
17148
17149     unsigned NumElts = DstVT.getVectorNumElements();
17150     EVT SVT = DstVT.getVectorElementType();
17151     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17152     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17153                                    MVT::v2f64, N->getOperand(0));
17154     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17155
17156     if (ExperimentalVectorWideningLegalization) {
17157       // If we are legalizing vectors by widening, we already have the desired
17158       // legal vector type, just return it.
17159       Results.push_back(ToVecInt);
17160       return;
17161     }
17162
17163     SmallVector<SDValue, 8> Elts;
17164     for (unsigned i = 0, e = NumElts; i != e; ++i)
17165       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17166                                    ToVecInt, DAG.getIntPtrConstant(i)));
17167
17168     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17169   }
17170   }
17171 }
17172
17173 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17174   switch (Opcode) {
17175   default: return nullptr;
17176   case X86ISD::BSF:                return "X86ISD::BSF";
17177   case X86ISD::BSR:                return "X86ISD::BSR";
17178   case X86ISD::SHLD:               return "X86ISD::SHLD";
17179   case X86ISD::SHRD:               return "X86ISD::SHRD";
17180   case X86ISD::FAND:               return "X86ISD::FAND";
17181   case X86ISD::FANDN:              return "X86ISD::FANDN";
17182   case X86ISD::FOR:                return "X86ISD::FOR";
17183   case X86ISD::FXOR:               return "X86ISD::FXOR";
17184   case X86ISD::FSRL:               return "X86ISD::FSRL";
17185   case X86ISD::FILD:               return "X86ISD::FILD";
17186   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17187   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17188   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17189   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17190   case X86ISD::FLD:                return "X86ISD::FLD";
17191   case X86ISD::FST:                return "X86ISD::FST";
17192   case X86ISD::CALL:               return "X86ISD::CALL";
17193   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17194   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17195   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17196   case X86ISD::BT:                 return "X86ISD::BT";
17197   case X86ISD::CMP:                return "X86ISD::CMP";
17198   case X86ISD::COMI:               return "X86ISD::COMI";
17199   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17200   case X86ISD::CMPM:               return "X86ISD::CMPM";
17201   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17202   case X86ISD::SETCC:              return "X86ISD::SETCC";
17203   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17204   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17205   case X86ISD::CMOV:               return "X86ISD::CMOV";
17206   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17207   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17208   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17209   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17210   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17211   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17212   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17213   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17214   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17215   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17216   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17217   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17218   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17219   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17220   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17221   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17222   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17223   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17224   case X86ISD::HADD:               return "X86ISD::HADD";
17225   case X86ISD::HSUB:               return "X86ISD::HSUB";
17226   case X86ISD::FHADD:              return "X86ISD::FHADD";
17227   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17228   case X86ISD::UMAX:               return "X86ISD::UMAX";
17229   case X86ISD::UMIN:               return "X86ISD::UMIN";
17230   case X86ISD::SMAX:               return "X86ISD::SMAX";
17231   case X86ISD::SMIN:               return "X86ISD::SMIN";
17232   case X86ISD::FMAX:               return "X86ISD::FMAX";
17233   case X86ISD::FMIN:               return "X86ISD::FMIN";
17234   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17235   case X86ISD::FMINC:              return "X86ISD::FMINC";
17236   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17237   case X86ISD::FRCP:               return "X86ISD::FRCP";
17238   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17239   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17240   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17241   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17242   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17243   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17244   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17245   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17246   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17247   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17248   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17249   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17250   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17251   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17252   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17253   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17254   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17255   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17256   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17257   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17258   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17259   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17260   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17261   case X86ISD::VSHL:               return "X86ISD::VSHL";
17262   case X86ISD::VSRL:               return "X86ISD::VSRL";
17263   case X86ISD::VSRA:               return "X86ISD::VSRA";
17264   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17265   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17266   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17267   case X86ISD::CMPP:               return "X86ISD::CMPP";
17268   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17269   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17270   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17271   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17272   case X86ISD::ADD:                return "X86ISD::ADD";
17273   case X86ISD::SUB:                return "X86ISD::SUB";
17274   case X86ISD::ADC:                return "X86ISD::ADC";
17275   case X86ISD::SBB:                return "X86ISD::SBB";
17276   case X86ISD::SMUL:               return "X86ISD::SMUL";
17277   case X86ISD::UMUL:               return "X86ISD::UMUL";
17278   case X86ISD::INC:                return "X86ISD::INC";
17279   case X86ISD::DEC:                return "X86ISD::DEC";
17280   case X86ISD::OR:                 return "X86ISD::OR";
17281   case X86ISD::XOR:                return "X86ISD::XOR";
17282   case X86ISD::AND:                return "X86ISD::AND";
17283   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17284   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17285   case X86ISD::PTEST:              return "X86ISD::PTEST";
17286   case X86ISD::TESTP:              return "X86ISD::TESTP";
17287   case X86ISD::TESTM:              return "X86ISD::TESTM";
17288   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17289   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17290   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17291   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17292   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17293   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17294   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17295   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17296   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17297   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17298   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17299   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17300   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17301   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17302   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17303   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17304   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17305   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17306   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17307   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17308   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17309   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17310   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17311   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17312   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17313   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17314   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17315   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17316   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17317   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17318   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17319   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17320   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17321   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17322   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17323   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17324   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17325   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17326   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17327   case X86ISD::SAHF:               return "X86ISD::SAHF";
17328   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17329   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17330   case X86ISD::FMADD:              return "X86ISD::FMADD";
17331   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17332   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17333   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17334   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17335   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17336   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17337   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17338   case X86ISD::XTEST:              return "X86ISD::XTEST";
17339   }
17340 }
17341
17342 // isLegalAddressingMode - Return true if the addressing mode represented
17343 // by AM is legal for this target, for a load/store of the specified type.
17344 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17345                                               Type *Ty) const {
17346   // X86 supports extremely general addressing modes.
17347   CodeModel::Model M = getTargetMachine().getCodeModel();
17348   Reloc::Model R = getTargetMachine().getRelocationModel();
17349
17350   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17351   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17352     return false;
17353
17354   if (AM.BaseGV) {
17355     unsigned GVFlags =
17356       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17357
17358     // If a reference to this global requires an extra load, we can't fold it.
17359     if (isGlobalStubReference(GVFlags))
17360       return false;
17361
17362     // If BaseGV requires a register for the PIC base, we cannot also have a
17363     // BaseReg specified.
17364     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17365       return false;
17366
17367     // If lower 4G is not available, then we must use rip-relative addressing.
17368     if ((M != CodeModel::Small || R != Reloc::Static) &&
17369         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17370       return false;
17371   }
17372
17373   switch (AM.Scale) {
17374   case 0:
17375   case 1:
17376   case 2:
17377   case 4:
17378   case 8:
17379     // These scales always work.
17380     break;
17381   case 3:
17382   case 5:
17383   case 9:
17384     // These scales are formed with basereg+scalereg.  Only accept if there is
17385     // no basereg yet.
17386     if (AM.HasBaseReg)
17387       return false;
17388     break;
17389   default:  // Other stuff never works.
17390     return false;
17391   }
17392
17393   return true;
17394 }
17395
17396 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17397   unsigned Bits = Ty->getScalarSizeInBits();
17398
17399   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17400   // particularly cheaper than those without.
17401   if (Bits == 8)
17402     return false;
17403
17404   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17405   // variable shifts just as cheap as scalar ones.
17406   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17407     return false;
17408
17409   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17410   // fully general vector.
17411   return true;
17412 }
17413
17414 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17415   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17416     return false;
17417   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17418   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17419   return NumBits1 > NumBits2;
17420 }
17421
17422 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17423   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17424     return false;
17425
17426   if (!isTypeLegal(EVT::getEVT(Ty1)))
17427     return false;
17428
17429   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17430
17431   // Assuming the caller doesn't have a zeroext or signext return parameter,
17432   // truncation all the way down to i1 is valid.
17433   return true;
17434 }
17435
17436 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17437   return isInt<32>(Imm);
17438 }
17439
17440 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17441   // Can also use sub to handle negated immediates.
17442   return isInt<32>(Imm);
17443 }
17444
17445 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17446   if (!VT1.isInteger() || !VT2.isInteger())
17447     return false;
17448   unsigned NumBits1 = VT1.getSizeInBits();
17449   unsigned NumBits2 = VT2.getSizeInBits();
17450   return NumBits1 > NumBits2;
17451 }
17452
17453 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17454   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17455   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17456 }
17457
17458 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17459   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17460   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17461 }
17462
17463 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17464   EVT VT1 = Val.getValueType();
17465   if (isZExtFree(VT1, VT2))
17466     return true;
17467
17468   if (Val.getOpcode() != ISD::LOAD)
17469     return false;
17470
17471   if (!VT1.isSimple() || !VT1.isInteger() ||
17472       !VT2.isSimple() || !VT2.isInteger())
17473     return false;
17474
17475   switch (VT1.getSimpleVT().SimpleTy) {
17476   default: break;
17477   case MVT::i8:
17478   case MVT::i16:
17479   case MVT::i32:
17480     // X86 has 8, 16, and 32-bit zero-extending loads.
17481     return true;
17482   }
17483
17484   return false;
17485 }
17486
17487 bool
17488 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17489   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17490     return false;
17491
17492   VT = VT.getScalarType();
17493
17494   if (!VT.isSimple())
17495     return false;
17496
17497   switch (VT.getSimpleVT().SimpleTy) {
17498   case MVT::f32:
17499   case MVT::f64:
17500     return true;
17501   default:
17502     break;
17503   }
17504
17505   return false;
17506 }
17507
17508 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17509   // i16 instructions are longer (0x66 prefix) and potentially slower.
17510   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17511 }
17512
17513 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17514 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17515 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17516 /// are assumed to be legal.
17517 bool
17518 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17519                                       EVT VT) const {
17520   if (!VT.isSimple())
17521     return false;
17522
17523   MVT SVT = VT.getSimpleVT();
17524
17525   // Very little shuffling can be done for 64-bit vectors right now.
17526   if (VT.getSizeInBits() == 64)
17527     return false;
17528
17529   // If this is a single-input shuffle with no 128 bit lane crossings we can
17530   // lower it into pshufb.
17531   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17532       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17533     bool isLegal = true;
17534     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17535       if (M[I] >= (int)SVT.getVectorNumElements() ||
17536           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17537         isLegal = false;
17538         break;
17539       }
17540     }
17541     if (isLegal)
17542       return true;
17543   }
17544
17545   // FIXME: blends, shifts.
17546   return (SVT.getVectorNumElements() == 2 ||
17547           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17548           isMOVLMask(M, SVT) ||
17549           isMOVHLPSMask(M, SVT) ||
17550           isSHUFPMask(M, SVT) ||
17551           isPSHUFDMask(M, SVT) ||
17552           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17553           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17554           isPALIGNRMask(M, SVT, Subtarget) ||
17555           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17556           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17557           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17558           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17559           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17560 }
17561
17562 bool
17563 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17564                                           EVT VT) const {
17565   if (!VT.isSimple())
17566     return false;
17567
17568   MVT SVT = VT.getSimpleVT();
17569   unsigned NumElts = SVT.getVectorNumElements();
17570   // FIXME: This collection of masks seems suspect.
17571   if (NumElts == 2)
17572     return true;
17573   if (NumElts == 4 && SVT.is128BitVector()) {
17574     return (isMOVLMask(Mask, SVT)  ||
17575             isCommutedMOVLMask(Mask, SVT, true) ||
17576             isSHUFPMask(Mask, SVT) ||
17577             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17578   }
17579   return false;
17580 }
17581
17582 //===----------------------------------------------------------------------===//
17583 //                           X86 Scheduler Hooks
17584 //===----------------------------------------------------------------------===//
17585
17586 /// Utility function to emit xbegin specifying the start of an RTM region.
17587 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17588                                      const TargetInstrInfo *TII) {
17589   DebugLoc DL = MI->getDebugLoc();
17590
17591   const BasicBlock *BB = MBB->getBasicBlock();
17592   MachineFunction::iterator I = MBB;
17593   ++I;
17594
17595   // For the v = xbegin(), we generate
17596   //
17597   // thisMBB:
17598   //  xbegin sinkMBB
17599   //
17600   // mainMBB:
17601   //  eax = -1
17602   //
17603   // sinkMBB:
17604   //  v = eax
17605
17606   MachineBasicBlock *thisMBB = MBB;
17607   MachineFunction *MF = MBB->getParent();
17608   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17609   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17610   MF->insert(I, mainMBB);
17611   MF->insert(I, sinkMBB);
17612
17613   // Transfer the remainder of BB and its successor edges to sinkMBB.
17614   sinkMBB->splice(sinkMBB->begin(), MBB,
17615                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17616   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17617
17618   // thisMBB:
17619   //  xbegin sinkMBB
17620   //  # fallthrough to mainMBB
17621   //  # abortion to sinkMBB
17622   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17623   thisMBB->addSuccessor(mainMBB);
17624   thisMBB->addSuccessor(sinkMBB);
17625
17626   // mainMBB:
17627   //  EAX = -1
17628   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17629   mainMBB->addSuccessor(sinkMBB);
17630
17631   // sinkMBB:
17632   // EAX is live into the sinkMBB
17633   sinkMBB->addLiveIn(X86::EAX);
17634   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17635           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17636     .addReg(X86::EAX);
17637
17638   MI->eraseFromParent();
17639   return sinkMBB;
17640 }
17641
17642 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17643 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17644 // in the .td file.
17645 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17646                                        const TargetInstrInfo *TII) {
17647   unsigned Opc;
17648   switch (MI->getOpcode()) {
17649   default: llvm_unreachable("illegal opcode!");
17650   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17651   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17652   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17653   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17654   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17655   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17656   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17657   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17658   }
17659
17660   DebugLoc dl = MI->getDebugLoc();
17661   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17662
17663   unsigned NumArgs = MI->getNumOperands();
17664   for (unsigned i = 1; i < NumArgs; ++i) {
17665     MachineOperand &Op = MI->getOperand(i);
17666     if (!(Op.isReg() && Op.isImplicit()))
17667       MIB.addOperand(Op);
17668   }
17669   if (MI->hasOneMemOperand())
17670     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17671
17672   BuildMI(*BB, MI, dl,
17673     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17674     .addReg(X86::XMM0);
17675
17676   MI->eraseFromParent();
17677   return BB;
17678 }
17679
17680 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17681 // defs in an instruction pattern
17682 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17683                                        const TargetInstrInfo *TII) {
17684   unsigned Opc;
17685   switch (MI->getOpcode()) {
17686   default: llvm_unreachable("illegal opcode!");
17687   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17688   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17689   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17690   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17691   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17692   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17693   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17694   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17695   }
17696
17697   DebugLoc dl = MI->getDebugLoc();
17698   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17699
17700   unsigned NumArgs = MI->getNumOperands(); // remove the results
17701   for (unsigned i = 1; i < NumArgs; ++i) {
17702     MachineOperand &Op = MI->getOperand(i);
17703     if (!(Op.isReg() && Op.isImplicit()))
17704       MIB.addOperand(Op);
17705   }
17706   if (MI->hasOneMemOperand())
17707     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17708
17709   BuildMI(*BB, MI, dl,
17710     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17711     .addReg(X86::ECX);
17712
17713   MI->eraseFromParent();
17714   return BB;
17715 }
17716
17717 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17718                                        const TargetInstrInfo *TII,
17719                                        const X86Subtarget* Subtarget) {
17720   DebugLoc dl = MI->getDebugLoc();
17721
17722   // Address into RAX/EAX, other two args into ECX, EDX.
17723   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17724   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17725   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17726   for (int i = 0; i < X86::AddrNumOperands; ++i)
17727     MIB.addOperand(MI->getOperand(i));
17728
17729   unsigned ValOps = X86::AddrNumOperands;
17730   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17731     .addReg(MI->getOperand(ValOps).getReg());
17732   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17733     .addReg(MI->getOperand(ValOps+1).getReg());
17734
17735   // The instruction doesn't actually take any operands though.
17736   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17737
17738   MI->eraseFromParent(); // The pseudo is gone now.
17739   return BB;
17740 }
17741
17742 MachineBasicBlock *
17743 X86TargetLowering::EmitVAARG64WithCustomInserter(
17744                    MachineInstr *MI,
17745                    MachineBasicBlock *MBB) const {
17746   // Emit va_arg instruction on X86-64.
17747
17748   // Operands to this pseudo-instruction:
17749   // 0  ) Output        : destination address (reg)
17750   // 1-5) Input         : va_list address (addr, i64mem)
17751   // 6  ) ArgSize       : Size (in bytes) of vararg type
17752   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17753   // 8  ) Align         : Alignment of type
17754   // 9  ) EFLAGS (implicit-def)
17755
17756   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17757   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17758
17759   unsigned DestReg = MI->getOperand(0).getReg();
17760   MachineOperand &Base = MI->getOperand(1);
17761   MachineOperand &Scale = MI->getOperand(2);
17762   MachineOperand &Index = MI->getOperand(3);
17763   MachineOperand &Disp = MI->getOperand(4);
17764   MachineOperand &Segment = MI->getOperand(5);
17765   unsigned ArgSize = MI->getOperand(6).getImm();
17766   unsigned ArgMode = MI->getOperand(7).getImm();
17767   unsigned Align = MI->getOperand(8).getImm();
17768
17769   // Memory Reference
17770   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17771   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17772   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17773
17774   // Machine Information
17775   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17776   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17777   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17778   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17779   DebugLoc DL = MI->getDebugLoc();
17780
17781   // struct va_list {
17782   //   i32   gp_offset
17783   //   i32   fp_offset
17784   //   i64   overflow_area (address)
17785   //   i64   reg_save_area (address)
17786   // }
17787   // sizeof(va_list) = 24
17788   // alignment(va_list) = 8
17789
17790   unsigned TotalNumIntRegs = 6;
17791   unsigned TotalNumXMMRegs = 8;
17792   bool UseGPOffset = (ArgMode == 1);
17793   bool UseFPOffset = (ArgMode == 2);
17794   unsigned MaxOffset = TotalNumIntRegs * 8 +
17795                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17796
17797   /* Align ArgSize to a multiple of 8 */
17798   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17799   bool NeedsAlign = (Align > 8);
17800
17801   MachineBasicBlock *thisMBB = MBB;
17802   MachineBasicBlock *overflowMBB;
17803   MachineBasicBlock *offsetMBB;
17804   MachineBasicBlock *endMBB;
17805
17806   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17807   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17808   unsigned OffsetReg = 0;
17809
17810   if (!UseGPOffset && !UseFPOffset) {
17811     // If we only pull from the overflow region, we don't create a branch.
17812     // We don't need to alter control flow.
17813     OffsetDestReg = 0; // unused
17814     OverflowDestReg = DestReg;
17815
17816     offsetMBB = nullptr;
17817     overflowMBB = thisMBB;
17818     endMBB = thisMBB;
17819   } else {
17820     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17821     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17822     // If not, pull from overflow_area. (branch to overflowMBB)
17823     //
17824     //       thisMBB
17825     //         |     .
17826     //         |        .
17827     //     offsetMBB   overflowMBB
17828     //         |        .
17829     //         |     .
17830     //        endMBB
17831
17832     // Registers for the PHI in endMBB
17833     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17834     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17835
17836     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17837     MachineFunction *MF = MBB->getParent();
17838     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17839     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17840     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17841
17842     MachineFunction::iterator MBBIter = MBB;
17843     ++MBBIter;
17844
17845     // Insert the new basic blocks
17846     MF->insert(MBBIter, offsetMBB);
17847     MF->insert(MBBIter, overflowMBB);
17848     MF->insert(MBBIter, endMBB);
17849
17850     // Transfer the remainder of MBB and its successor edges to endMBB.
17851     endMBB->splice(endMBB->begin(), thisMBB,
17852                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17853     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17854
17855     // Make offsetMBB and overflowMBB successors of thisMBB
17856     thisMBB->addSuccessor(offsetMBB);
17857     thisMBB->addSuccessor(overflowMBB);
17858
17859     // endMBB is a successor of both offsetMBB and overflowMBB
17860     offsetMBB->addSuccessor(endMBB);
17861     overflowMBB->addSuccessor(endMBB);
17862
17863     // Load the offset value into a register
17864     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17865     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17866       .addOperand(Base)
17867       .addOperand(Scale)
17868       .addOperand(Index)
17869       .addDisp(Disp, UseFPOffset ? 4 : 0)
17870       .addOperand(Segment)
17871       .setMemRefs(MMOBegin, MMOEnd);
17872
17873     // Check if there is enough room left to pull this argument.
17874     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17875       .addReg(OffsetReg)
17876       .addImm(MaxOffset + 8 - ArgSizeA8);
17877
17878     // Branch to "overflowMBB" if offset >= max
17879     // Fall through to "offsetMBB" otherwise
17880     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17881       .addMBB(overflowMBB);
17882   }
17883
17884   // In offsetMBB, emit code to use the reg_save_area.
17885   if (offsetMBB) {
17886     assert(OffsetReg != 0);
17887
17888     // Read the reg_save_area address.
17889     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17890     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17891       .addOperand(Base)
17892       .addOperand(Scale)
17893       .addOperand(Index)
17894       .addDisp(Disp, 16)
17895       .addOperand(Segment)
17896       .setMemRefs(MMOBegin, MMOEnd);
17897
17898     // Zero-extend the offset
17899     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17900       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17901         .addImm(0)
17902         .addReg(OffsetReg)
17903         .addImm(X86::sub_32bit);
17904
17905     // Add the offset to the reg_save_area to get the final address.
17906     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17907       .addReg(OffsetReg64)
17908       .addReg(RegSaveReg);
17909
17910     // Compute the offset for the next argument
17911     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17912     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17913       .addReg(OffsetReg)
17914       .addImm(UseFPOffset ? 16 : 8);
17915
17916     // Store it back into the va_list.
17917     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17918       .addOperand(Base)
17919       .addOperand(Scale)
17920       .addOperand(Index)
17921       .addDisp(Disp, UseFPOffset ? 4 : 0)
17922       .addOperand(Segment)
17923       .addReg(NextOffsetReg)
17924       .setMemRefs(MMOBegin, MMOEnd);
17925
17926     // Jump to endMBB
17927     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17928       .addMBB(endMBB);
17929   }
17930
17931   //
17932   // Emit code to use overflow area
17933   //
17934
17935   // Load the overflow_area address into a register.
17936   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17937   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17938     .addOperand(Base)
17939     .addOperand(Scale)
17940     .addOperand(Index)
17941     .addDisp(Disp, 8)
17942     .addOperand(Segment)
17943     .setMemRefs(MMOBegin, MMOEnd);
17944
17945   // If we need to align it, do so. Otherwise, just copy the address
17946   // to OverflowDestReg.
17947   if (NeedsAlign) {
17948     // Align the overflow address
17949     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17950     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17951
17952     // aligned_addr = (addr + (align-1)) & ~(align-1)
17953     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17954       .addReg(OverflowAddrReg)
17955       .addImm(Align-1);
17956
17957     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17958       .addReg(TmpReg)
17959       .addImm(~(uint64_t)(Align-1));
17960   } else {
17961     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17962       .addReg(OverflowAddrReg);
17963   }
17964
17965   // Compute the next overflow address after this argument.
17966   // (the overflow address should be kept 8-byte aligned)
17967   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17968   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17969     .addReg(OverflowDestReg)
17970     .addImm(ArgSizeA8);
17971
17972   // Store the new overflow address.
17973   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17974     .addOperand(Base)
17975     .addOperand(Scale)
17976     .addOperand(Index)
17977     .addDisp(Disp, 8)
17978     .addOperand(Segment)
17979     .addReg(NextAddrReg)
17980     .setMemRefs(MMOBegin, MMOEnd);
17981
17982   // If we branched, emit the PHI to the front of endMBB.
17983   if (offsetMBB) {
17984     BuildMI(*endMBB, endMBB->begin(), DL,
17985             TII->get(X86::PHI), DestReg)
17986       .addReg(OffsetDestReg).addMBB(offsetMBB)
17987       .addReg(OverflowDestReg).addMBB(overflowMBB);
17988   }
17989
17990   // Erase the pseudo instruction
17991   MI->eraseFromParent();
17992
17993   return endMBB;
17994 }
17995
17996 MachineBasicBlock *
17997 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17998                                                  MachineInstr *MI,
17999                                                  MachineBasicBlock *MBB) const {
18000   // Emit code to save XMM registers to the stack. The ABI says that the
18001   // number of registers to save is given in %al, so it's theoretically
18002   // possible to do an indirect jump trick to avoid saving all of them,
18003   // however this code takes a simpler approach and just executes all
18004   // of the stores if %al is non-zero. It's less code, and it's probably
18005   // easier on the hardware branch predictor, and stores aren't all that
18006   // expensive anyway.
18007
18008   // Create the new basic blocks. One block contains all the XMM stores,
18009   // and one block is the final destination regardless of whether any
18010   // stores were performed.
18011   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18012   MachineFunction *F = MBB->getParent();
18013   MachineFunction::iterator MBBIter = MBB;
18014   ++MBBIter;
18015   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18016   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18017   F->insert(MBBIter, XMMSaveMBB);
18018   F->insert(MBBIter, EndMBB);
18019
18020   // Transfer the remainder of MBB and its successor edges to EndMBB.
18021   EndMBB->splice(EndMBB->begin(), MBB,
18022                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18023   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18024
18025   // The original block will now fall through to the XMM save block.
18026   MBB->addSuccessor(XMMSaveMBB);
18027   // The XMMSaveMBB will fall through to the end block.
18028   XMMSaveMBB->addSuccessor(EndMBB);
18029
18030   // Now add the instructions.
18031   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18032   DebugLoc DL = MI->getDebugLoc();
18033
18034   unsigned CountReg = MI->getOperand(0).getReg();
18035   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18036   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18037
18038   if (!Subtarget->isTargetWin64()) {
18039     // If %al is 0, branch around the XMM save block.
18040     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18041     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18042     MBB->addSuccessor(EndMBB);
18043   }
18044
18045   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18046   // that was just emitted, but clearly shouldn't be "saved".
18047   assert((MI->getNumOperands() <= 3 ||
18048           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18049           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18050          && "Expected last argument to be EFLAGS");
18051   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18052   // In the XMM save block, save all the XMM argument registers.
18053   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18054     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18055     MachineMemOperand *MMO =
18056       F->getMachineMemOperand(
18057           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18058         MachineMemOperand::MOStore,
18059         /*Size=*/16, /*Align=*/16);
18060     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18061       .addFrameIndex(RegSaveFrameIndex)
18062       .addImm(/*Scale=*/1)
18063       .addReg(/*IndexReg=*/0)
18064       .addImm(/*Disp=*/Offset)
18065       .addReg(/*Segment=*/0)
18066       .addReg(MI->getOperand(i).getReg())
18067       .addMemOperand(MMO);
18068   }
18069
18070   MI->eraseFromParent();   // The pseudo instruction is gone now.
18071
18072   return EndMBB;
18073 }
18074
18075 // The EFLAGS operand of SelectItr might be missing a kill marker
18076 // because there were multiple uses of EFLAGS, and ISel didn't know
18077 // which to mark. Figure out whether SelectItr should have had a
18078 // kill marker, and set it if it should. Returns the correct kill
18079 // marker value.
18080 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18081                                      MachineBasicBlock* BB,
18082                                      const TargetRegisterInfo* TRI) {
18083   // Scan forward through BB for a use/def of EFLAGS.
18084   MachineBasicBlock::iterator miI(std::next(SelectItr));
18085   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18086     const MachineInstr& mi = *miI;
18087     if (mi.readsRegister(X86::EFLAGS))
18088       return false;
18089     if (mi.definesRegister(X86::EFLAGS))
18090       break; // Should have kill-flag - update below.
18091   }
18092
18093   // If we hit the end of the block, check whether EFLAGS is live into a
18094   // successor.
18095   if (miI == BB->end()) {
18096     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18097                                           sEnd = BB->succ_end();
18098          sItr != sEnd; ++sItr) {
18099       MachineBasicBlock* succ = *sItr;
18100       if (succ->isLiveIn(X86::EFLAGS))
18101         return false;
18102     }
18103   }
18104
18105   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18106   // out. SelectMI should have a kill flag on EFLAGS.
18107   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18108   return true;
18109 }
18110
18111 MachineBasicBlock *
18112 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18113                                      MachineBasicBlock *BB) const {
18114   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18115   DebugLoc DL = MI->getDebugLoc();
18116
18117   // To "insert" a SELECT_CC instruction, we actually have to insert the
18118   // diamond control-flow pattern.  The incoming instruction knows the
18119   // destination vreg to set, the condition code register to branch on, the
18120   // true/false values to select between, and a branch opcode to use.
18121   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18122   MachineFunction::iterator It = BB;
18123   ++It;
18124
18125   //  thisMBB:
18126   //  ...
18127   //   TrueVal = ...
18128   //   cmpTY ccX, r1, r2
18129   //   bCC copy1MBB
18130   //   fallthrough --> copy0MBB
18131   MachineBasicBlock *thisMBB = BB;
18132   MachineFunction *F = BB->getParent();
18133   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18134   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18135   F->insert(It, copy0MBB);
18136   F->insert(It, sinkMBB);
18137
18138   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18139   // live into the sink and copy blocks.
18140   const TargetRegisterInfo *TRI =
18141       BB->getParent()->getSubtarget().getRegisterInfo();
18142   if (!MI->killsRegister(X86::EFLAGS) &&
18143       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18144     copy0MBB->addLiveIn(X86::EFLAGS);
18145     sinkMBB->addLiveIn(X86::EFLAGS);
18146   }
18147
18148   // Transfer the remainder of BB and its successor edges to sinkMBB.
18149   sinkMBB->splice(sinkMBB->begin(), BB,
18150                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18151   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18152
18153   // Add the true and fallthrough blocks as its successors.
18154   BB->addSuccessor(copy0MBB);
18155   BB->addSuccessor(sinkMBB);
18156
18157   // Create the conditional branch instruction.
18158   unsigned Opc =
18159     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18160   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18161
18162   //  copy0MBB:
18163   //   %FalseValue = ...
18164   //   # fallthrough to sinkMBB
18165   copy0MBB->addSuccessor(sinkMBB);
18166
18167   //  sinkMBB:
18168   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18169   //  ...
18170   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18171           TII->get(X86::PHI), MI->getOperand(0).getReg())
18172     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18173     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18174
18175   MI->eraseFromParent();   // The pseudo instruction is gone now.
18176   return sinkMBB;
18177 }
18178
18179 MachineBasicBlock *
18180 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18181                                         bool Is64Bit) const {
18182   MachineFunction *MF = BB->getParent();
18183   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18184   DebugLoc DL = MI->getDebugLoc();
18185   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18186
18187   assert(MF->shouldSplitStack());
18188
18189   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18190   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18191
18192   // BB:
18193   //  ... [Till the alloca]
18194   // If stacklet is not large enough, jump to mallocMBB
18195   //
18196   // bumpMBB:
18197   //  Allocate by subtracting from RSP
18198   //  Jump to continueMBB
18199   //
18200   // mallocMBB:
18201   //  Allocate by call to runtime
18202   //
18203   // continueMBB:
18204   //  ...
18205   //  [rest of original BB]
18206   //
18207
18208   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18209   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18210   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18211
18212   MachineRegisterInfo &MRI = MF->getRegInfo();
18213   const TargetRegisterClass *AddrRegClass =
18214     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18215
18216   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18217     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18218     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18219     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18220     sizeVReg = MI->getOperand(1).getReg(),
18221     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18222
18223   MachineFunction::iterator MBBIter = BB;
18224   ++MBBIter;
18225
18226   MF->insert(MBBIter, bumpMBB);
18227   MF->insert(MBBIter, mallocMBB);
18228   MF->insert(MBBIter, continueMBB);
18229
18230   continueMBB->splice(continueMBB->begin(), BB,
18231                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18232   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18233
18234   // Add code to the main basic block to check if the stack limit has been hit,
18235   // and if so, jump to mallocMBB otherwise to bumpMBB.
18236   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18237   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18238     .addReg(tmpSPVReg).addReg(sizeVReg);
18239   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18240     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18241     .addReg(SPLimitVReg);
18242   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18243
18244   // bumpMBB simply decreases the stack pointer, since we know the current
18245   // stacklet has enough space.
18246   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18247     .addReg(SPLimitVReg);
18248   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18249     .addReg(SPLimitVReg);
18250   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18251
18252   // Calls into a routine in libgcc to allocate more space from the heap.
18253   const uint32_t *RegMask = MF->getTarget()
18254                                 .getSubtargetImpl()
18255                                 ->getRegisterInfo()
18256                                 ->getCallPreservedMask(CallingConv::C);
18257   if (Is64Bit) {
18258     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18259       .addReg(sizeVReg);
18260     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18261       .addExternalSymbol("__morestack_allocate_stack_space")
18262       .addRegMask(RegMask)
18263       .addReg(X86::RDI, RegState::Implicit)
18264       .addReg(X86::RAX, RegState::ImplicitDefine);
18265   } else {
18266     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18267       .addImm(12);
18268     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18269     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18270       .addExternalSymbol("__morestack_allocate_stack_space")
18271       .addRegMask(RegMask)
18272       .addReg(X86::EAX, RegState::ImplicitDefine);
18273   }
18274
18275   if (!Is64Bit)
18276     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18277       .addImm(16);
18278
18279   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18280     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18281   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18282
18283   // Set up the CFG correctly.
18284   BB->addSuccessor(bumpMBB);
18285   BB->addSuccessor(mallocMBB);
18286   mallocMBB->addSuccessor(continueMBB);
18287   bumpMBB->addSuccessor(continueMBB);
18288
18289   // Take care of the PHI nodes.
18290   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18291           MI->getOperand(0).getReg())
18292     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18293     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18294
18295   // Delete the original pseudo instruction.
18296   MI->eraseFromParent();
18297
18298   // And we're done.
18299   return continueMBB;
18300 }
18301
18302 MachineBasicBlock *
18303 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18304                                         MachineBasicBlock *BB) const {
18305   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18306   DebugLoc DL = MI->getDebugLoc();
18307
18308   assert(!Subtarget->isTargetMacho());
18309
18310   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18311   // non-trivial part is impdef of ESP.
18312
18313   if (Subtarget->isTargetWin64()) {
18314     if (Subtarget->isTargetCygMing()) {
18315       // ___chkstk(Mingw64):
18316       // Clobbers R10, R11, RAX and EFLAGS.
18317       // Updates RSP.
18318       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18319         .addExternalSymbol("___chkstk")
18320         .addReg(X86::RAX, RegState::Implicit)
18321         .addReg(X86::RSP, RegState::Implicit)
18322         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18323         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18324         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18325     } else {
18326       // __chkstk(MSVCRT): does not update stack pointer.
18327       // Clobbers R10, R11 and EFLAGS.
18328       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18329         .addExternalSymbol("__chkstk")
18330         .addReg(X86::RAX, RegState::Implicit)
18331         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18332       // RAX has the offset to be subtracted from RSP.
18333       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18334         .addReg(X86::RSP)
18335         .addReg(X86::RAX);
18336     }
18337   } else {
18338     const char *StackProbeSymbol =
18339       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18340
18341     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18342       .addExternalSymbol(StackProbeSymbol)
18343       .addReg(X86::EAX, RegState::Implicit)
18344       .addReg(X86::ESP, RegState::Implicit)
18345       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18346       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18347       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18348   }
18349
18350   MI->eraseFromParent();   // The pseudo instruction is gone now.
18351   return BB;
18352 }
18353
18354 MachineBasicBlock *
18355 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18356                                       MachineBasicBlock *BB) const {
18357   // This is pretty easy.  We're taking the value that we received from
18358   // our load from the relocation, sticking it in either RDI (x86-64)
18359   // or EAX and doing an indirect call.  The return value will then
18360   // be in the normal return register.
18361   MachineFunction *F = BB->getParent();
18362   const X86InstrInfo *TII =
18363       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18364   DebugLoc DL = MI->getDebugLoc();
18365
18366   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18367   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18368
18369   // Get a register mask for the lowered call.
18370   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18371   // proper register mask.
18372   const uint32_t *RegMask = F->getTarget()
18373                                 .getSubtargetImpl()
18374                                 ->getRegisterInfo()
18375                                 ->getCallPreservedMask(CallingConv::C);
18376   if (Subtarget->is64Bit()) {
18377     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18378                                       TII->get(X86::MOV64rm), X86::RDI)
18379     .addReg(X86::RIP)
18380     .addImm(0).addReg(0)
18381     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18382                       MI->getOperand(3).getTargetFlags())
18383     .addReg(0);
18384     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18385     addDirectMem(MIB, X86::RDI);
18386     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18387   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18388     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18389                                       TII->get(X86::MOV32rm), X86::EAX)
18390     .addReg(0)
18391     .addImm(0).addReg(0)
18392     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18393                       MI->getOperand(3).getTargetFlags())
18394     .addReg(0);
18395     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18396     addDirectMem(MIB, X86::EAX);
18397     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18398   } else {
18399     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18400                                       TII->get(X86::MOV32rm), X86::EAX)
18401     .addReg(TII->getGlobalBaseReg(F))
18402     .addImm(0).addReg(0)
18403     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18404                       MI->getOperand(3).getTargetFlags())
18405     .addReg(0);
18406     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18407     addDirectMem(MIB, X86::EAX);
18408     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18409   }
18410
18411   MI->eraseFromParent(); // The pseudo instruction is gone now.
18412   return BB;
18413 }
18414
18415 MachineBasicBlock *
18416 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18417                                     MachineBasicBlock *MBB) const {
18418   DebugLoc DL = MI->getDebugLoc();
18419   MachineFunction *MF = MBB->getParent();
18420   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18421   MachineRegisterInfo &MRI = MF->getRegInfo();
18422
18423   const BasicBlock *BB = MBB->getBasicBlock();
18424   MachineFunction::iterator I = MBB;
18425   ++I;
18426
18427   // Memory Reference
18428   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18429   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18430
18431   unsigned DstReg;
18432   unsigned MemOpndSlot = 0;
18433
18434   unsigned CurOp = 0;
18435
18436   DstReg = MI->getOperand(CurOp++).getReg();
18437   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18438   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18439   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18440   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18441
18442   MemOpndSlot = CurOp;
18443
18444   MVT PVT = getPointerTy();
18445   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18446          "Invalid Pointer Size!");
18447
18448   // For v = setjmp(buf), we generate
18449   //
18450   // thisMBB:
18451   //  buf[LabelOffset] = restoreMBB
18452   //  SjLjSetup restoreMBB
18453   //
18454   // mainMBB:
18455   //  v_main = 0
18456   //
18457   // sinkMBB:
18458   //  v = phi(main, restore)
18459   //
18460   // restoreMBB:
18461   //  v_restore = 1
18462
18463   MachineBasicBlock *thisMBB = MBB;
18464   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18465   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18466   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18467   MF->insert(I, mainMBB);
18468   MF->insert(I, sinkMBB);
18469   MF->push_back(restoreMBB);
18470
18471   MachineInstrBuilder MIB;
18472
18473   // Transfer the remainder of BB and its successor edges to sinkMBB.
18474   sinkMBB->splice(sinkMBB->begin(), MBB,
18475                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18476   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18477
18478   // thisMBB:
18479   unsigned PtrStoreOpc = 0;
18480   unsigned LabelReg = 0;
18481   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18482   Reloc::Model RM = MF->getTarget().getRelocationModel();
18483   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18484                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18485
18486   // Prepare IP either in reg or imm.
18487   if (!UseImmLabel) {
18488     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18489     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18490     LabelReg = MRI.createVirtualRegister(PtrRC);
18491     if (Subtarget->is64Bit()) {
18492       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18493               .addReg(X86::RIP)
18494               .addImm(0)
18495               .addReg(0)
18496               .addMBB(restoreMBB)
18497               .addReg(0);
18498     } else {
18499       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18500       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18501               .addReg(XII->getGlobalBaseReg(MF))
18502               .addImm(0)
18503               .addReg(0)
18504               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18505               .addReg(0);
18506     }
18507   } else
18508     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18509   // Store IP
18510   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18511   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18512     if (i == X86::AddrDisp)
18513       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18514     else
18515       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18516   }
18517   if (!UseImmLabel)
18518     MIB.addReg(LabelReg);
18519   else
18520     MIB.addMBB(restoreMBB);
18521   MIB.setMemRefs(MMOBegin, MMOEnd);
18522   // Setup
18523   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18524           .addMBB(restoreMBB);
18525
18526   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18527       MF->getSubtarget().getRegisterInfo());
18528   MIB.addRegMask(RegInfo->getNoPreservedMask());
18529   thisMBB->addSuccessor(mainMBB);
18530   thisMBB->addSuccessor(restoreMBB);
18531
18532   // mainMBB:
18533   //  EAX = 0
18534   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18535   mainMBB->addSuccessor(sinkMBB);
18536
18537   // sinkMBB:
18538   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18539           TII->get(X86::PHI), DstReg)
18540     .addReg(mainDstReg).addMBB(mainMBB)
18541     .addReg(restoreDstReg).addMBB(restoreMBB);
18542
18543   // restoreMBB:
18544   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18545   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18546   restoreMBB->addSuccessor(sinkMBB);
18547
18548   MI->eraseFromParent();
18549   return sinkMBB;
18550 }
18551
18552 MachineBasicBlock *
18553 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18554                                      MachineBasicBlock *MBB) const {
18555   DebugLoc DL = MI->getDebugLoc();
18556   MachineFunction *MF = MBB->getParent();
18557   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18558   MachineRegisterInfo &MRI = MF->getRegInfo();
18559
18560   // Memory Reference
18561   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18562   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18563
18564   MVT PVT = getPointerTy();
18565   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18566          "Invalid Pointer Size!");
18567
18568   const TargetRegisterClass *RC =
18569     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18570   unsigned Tmp = MRI.createVirtualRegister(RC);
18571   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18572   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18573       MF->getSubtarget().getRegisterInfo());
18574   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18575   unsigned SP = RegInfo->getStackRegister();
18576
18577   MachineInstrBuilder MIB;
18578
18579   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18580   const int64_t SPOffset = 2 * PVT.getStoreSize();
18581
18582   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18583   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18584
18585   // Reload FP
18586   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18587   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18588     MIB.addOperand(MI->getOperand(i));
18589   MIB.setMemRefs(MMOBegin, MMOEnd);
18590   // Reload IP
18591   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18592   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18593     if (i == X86::AddrDisp)
18594       MIB.addDisp(MI->getOperand(i), LabelOffset);
18595     else
18596       MIB.addOperand(MI->getOperand(i));
18597   }
18598   MIB.setMemRefs(MMOBegin, MMOEnd);
18599   // Reload SP
18600   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18601   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18602     if (i == X86::AddrDisp)
18603       MIB.addDisp(MI->getOperand(i), SPOffset);
18604     else
18605       MIB.addOperand(MI->getOperand(i));
18606   }
18607   MIB.setMemRefs(MMOBegin, MMOEnd);
18608   // Jump
18609   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18610
18611   MI->eraseFromParent();
18612   return MBB;
18613 }
18614
18615 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18616 // accumulator loops. Writing back to the accumulator allows the coalescer
18617 // to remove extra copies in the loop.   
18618 MachineBasicBlock *
18619 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18620                                  MachineBasicBlock *MBB) const {
18621   MachineOperand &AddendOp = MI->getOperand(3);
18622
18623   // Bail out early if the addend isn't a register - we can't switch these.
18624   if (!AddendOp.isReg())
18625     return MBB;
18626
18627   MachineFunction &MF = *MBB->getParent();
18628   MachineRegisterInfo &MRI = MF.getRegInfo();
18629
18630   // Check whether the addend is defined by a PHI:
18631   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18632   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18633   if (!AddendDef.isPHI())
18634     return MBB;
18635
18636   // Look for the following pattern:
18637   // loop:
18638   //   %addend = phi [%entry, 0], [%loop, %result]
18639   //   ...
18640   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18641
18642   // Replace with:
18643   //   loop:
18644   //   %addend = phi [%entry, 0], [%loop, %result]
18645   //   ...
18646   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18647
18648   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18649     assert(AddendDef.getOperand(i).isReg());
18650     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18651     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18652     if (&PHISrcInst == MI) {
18653       // Found a matching instruction.
18654       unsigned NewFMAOpc = 0;
18655       switch (MI->getOpcode()) {
18656         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18657         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18658         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18659         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18660         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18661         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18662         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18663         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18664         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18665         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18666         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18667         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18668         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18669         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18670         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18671         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18672         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18673         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18674         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18675         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18676         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18677         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18678         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18679         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18680         default: llvm_unreachable("Unrecognized FMA variant.");
18681       }
18682
18683       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18684       MachineInstrBuilder MIB =
18685         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18686         .addOperand(MI->getOperand(0))
18687         .addOperand(MI->getOperand(3))
18688         .addOperand(MI->getOperand(2))
18689         .addOperand(MI->getOperand(1));
18690       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18691       MI->eraseFromParent();
18692     }
18693   }
18694
18695   return MBB;
18696 }
18697
18698 MachineBasicBlock *
18699 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18700                                                MachineBasicBlock *BB) const {
18701   switch (MI->getOpcode()) {
18702   default: llvm_unreachable("Unexpected instr type to insert");
18703   case X86::TAILJMPd64:
18704   case X86::TAILJMPr64:
18705   case X86::TAILJMPm64:
18706     llvm_unreachable("TAILJMP64 would not be touched here.");
18707   case X86::TCRETURNdi64:
18708   case X86::TCRETURNri64:
18709   case X86::TCRETURNmi64:
18710     return BB;
18711   case X86::WIN_ALLOCA:
18712     return EmitLoweredWinAlloca(MI, BB);
18713   case X86::SEG_ALLOCA_32:
18714     return EmitLoweredSegAlloca(MI, BB, false);
18715   case X86::SEG_ALLOCA_64:
18716     return EmitLoweredSegAlloca(MI, BB, true);
18717   case X86::TLSCall_32:
18718   case X86::TLSCall_64:
18719     return EmitLoweredTLSCall(MI, BB);
18720   case X86::CMOV_GR8:
18721   case X86::CMOV_FR32:
18722   case X86::CMOV_FR64:
18723   case X86::CMOV_V4F32:
18724   case X86::CMOV_V2F64:
18725   case X86::CMOV_V2I64:
18726   case X86::CMOV_V8F32:
18727   case X86::CMOV_V4F64:
18728   case X86::CMOV_V4I64:
18729   case X86::CMOV_V16F32:
18730   case X86::CMOV_V8F64:
18731   case X86::CMOV_V8I64:
18732   case X86::CMOV_GR16:
18733   case X86::CMOV_GR32:
18734   case X86::CMOV_RFP32:
18735   case X86::CMOV_RFP64:
18736   case X86::CMOV_RFP80:
18737     return EmitLoweredSelect(MI, BB);
18738
18739   case X86::FP32_TO_INT16_IN_MEM:
18740   case X86::FP32_TO_INT32_IN_MEM:
18741   case X86::FP32_TO_INT64_IN_MEM:
18742   case X86::FP64_TO_INT16_IN_MEM:
18743   case X86::FP64_TO_INT32_IN_MEM:
18744   case X86::FP64_TO_INT64_IN_MEM:
18745   case X86::FP80_TO_INT16_IN_MEM:
18746   case X86::FP80_TO_INT32_IN_MEM:
18747   case X86::FP80_TO_INT64_IN_MEM: {
18748     MachineFunction *F = BB->getParent();
18749     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18750     DebugLoc DL = MI->getDebugLoc();
18751
18752     // Change the floating point control register to use "round towards zero"
18753     // mode when truncating to an integer value.
18754     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18755     addFrameReference(BuildMI(*BB, MI, DL,
18756                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18757
18758     // Load the old value of the high byte of the control word...
18759     unsigned OldCW =
18760       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18761     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18762                       CWFrameIdx);
18763
18764     // Set the high part to be round to zero...
18765     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18766       .addImm(0xC7F);
18767
18768     // Reload the modified control word now...
18769     addFrameReference(BuildMI(*BB, MI, DL,
18770                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18771
18772     // Restore the memory image of control word to original value
18773     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18774       .addReg(OldCW);
18775
18776     // Get the X86 opcode to use.
18777     unsigned Opc;
18778     switch (MI->getOpcode()) {
18779     default: llvm_unreachable("illegal opcode!");
18780     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18781     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18782     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18783     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18784     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18785     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18786     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18787     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18788     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18789     }
18790
18791     X86AddressMode AM;
18792     MachineOperand &Op = MI->getOperand(0);
18793     if (Op.isReg()) {
18794       AM.BaseType = X86AddressMode::RegBase;
18795       AM.Base.Reg = Op.getReg();
18796     } else {
18797       AM.BaseType = X86AddressMode::FrameIndexBase;
18798       AM.Base.FrameIndex = Op.getIndex();
18799     }
18800     Op = MI->getOperand(1);
18801     if (Op.isImm())
18802       AM.Scale = Op.getImm();
18803     Op = MI->getOperand(2);
18804     if (Op.isImm())
18805       AM.IndexReg = Op.getImm();
18806     Op = MI->getOperand(3);
18807     if (Op.isGlobal()) {
18808       AM.GV = Op.getGlobal();
18809     } else {
18810       AM.Disp = Op.getImm();
18811     }
18812     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18813                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18814
18815     // Reload the original control word now.
18816     addFrameReference(BuildMI(*BB, MI, DL,
18817                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18818
18819     MI->eraseFromParent();   // The pseudo instruction is gone now.
18820     return BB;
18821   }
18822     // String/text processing lowering.
18823   case X86::PCMPISTRM128REG:
18824   case X86::VPCMPISTRM128REG:
18825   case X86::PCMPISTRM128MEM:
18826   case X86::VPCMPISTRM128MEM:
18827   case X86::PCMPESTRM128REG:
18828   case X86::VPCMPESTRM128REG:
18829   case X86::PCMPESTRM128MEM:
18830   case X86::VPCMPESTRM128MEM:
18831     assert(Subtarget->hasSSE42() &&
18832            "Target must have SSE4.2 or AVX features enabled");
18833     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18834
18835   // String/text processing lowering.
18836   case X86::PCMPISTRIREG:
18837   case X86::VPCMPISTRIREG:
18838   case X86::PCMPISTRIMEM:
18839   case X86::VPCMPISTRIMEM:
18840   case X86::PCMPESTRIREG:
18841   case X86::VPCMPESTRIREG:
18842   case X86::PCMPESTRIMEM:
18843   case X86::VPCMPESTRIMEM:
18844     assert(Subtarget->hasSSE42() &&
18845            "Target must have SSE4.2 or AVX features enabled");
18846     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18847
18848   // Thread synchronization.
18849   case X86::MONITOR:
18850     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18851                        Subtarget);
18852
18853   // xbegin
18854   case X86::XBEGIN:
18855     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18856
18857   case X86::VASTART_SAVE_XMM_REGS:
18858     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18859
18860   case X86::VAARG_64:
18861     return EmitVAARG64WithCustomInserter(MI, BB);
18862
18863   case X86::EH_SjLj_SetJmp32:
18864   case X86::EH_SjLj_SetJmp64:
18865     return emitEHSjLjSetJmp(MI, BB);
18866
18867   case X86::EH_SjLj_LongJmp32:
18868   case X86::EH_SjLj_LongJmp64:
18869     return emitEHSjLjLongJmp(MI, BB);
18870
18871   case TargetOpcode::STACKMAP:
18872   case TargetOpcode::PATCHPOINT:
18873     return emitPatchPoint(MI, BB);
18874
18875   case X86::VFMADDPDr213r:
18876   case X86::VFMADDPSr213r:
18877   case X86::VFMADDSDr213r:
18878   case X86::VFMADDSSr213r:
18879   case X86::VFMSUBPDr213r:
18880   case X86::VFMSUBPSr213r:
18881   case X86::VFMSUBSDr213r:
18882   case X86::VFMSUBSSr213r:
18883   case X86::VFNMADDPDr213r:
18884   case X86::VFNMADDPSr213r:
18885   case X86::VFNMADDSDr213r:
18886   case X86::VFNMADDSSr213r:
18887   case X86::VFNMSUBPDr213r:
18888   case X86::VFNMSUBPSr213r:
18889   case X86::VFNMSUBSDr213r:
18890   case X86::VFNMSUBSSr213r:
18891   case X86::VFMADDPDr213rY:
18892   case X86::VFMADDPSr213rY:
18893   case X86::VFMSUBPDr213rY:
18894   case X86::VFMSUBPSr213rY:
18895   case X86::VFNMADDPDr213rY:
18896   case X86::VFNMADDPSr213rY:
18897   case X86::VFNMSUBPDr213rY:
18898   case X86::VFNMSUBPSr213rY:
18899     return emitFMA3Instr(MI, BB);
18900   }
18901 }
18902
18903 //===----------------------------------------------------------------------===//
18904 //                           X86 Optimization Hooks
18905 //===----------------------------------------------------------------------===//
18906
18907 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18908                                                       APInt &KnownZero,
18909                                                       APInt &KnownOne,
18910                                                       const SelectionDAG &DAG,
18911                                                       unsigned Depth) const {
18912   unsigned BitWidth = KnownZero.getBitWidth();
18913   unsigned Opc = Op.getOpcode();
18914   assert((Opc >= ISD::BUILTIN_OP_END ||
18915           Opc == ISD::INTRINSIC_WO_CHAIN ||
18916           Opc == ISD::INTRINSIC_W_CHAIN ||
18917           Opc == ISD::INTRINSIC_VOID) &&
18918          "Should use MaskedValueIsZero if you don't know whether Op"
18919          " is a target node!");
18920
18921   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18922   switch (Opc) {
18923   default: break;
18924   case X86ISD::ADD:
18925   case X86ISD::SUB:
18926   case X86ISD::ADC:
18927   case X86ISD::SBB:
18928   case X86ISD::SMUL:
18929   case X86ISD::UMUL:
18930   case X86ISD::INC:
18931   case X86ISD::DEC:
18932   case X86ISD::OR:
18933   case X86ISD::XOR:
18934   case X86ISD::AND:
18935     // These nodes' second result is a boolean.
18936     if (Op.getResNo() == 0)
18937       break;
18938     // Fallthrough
18939   case X86ISD::SETCC:
18940     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18941     break;
18942   case ISD::INTRINSIC_WO_CHAIN: {
18943     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18944     unsigned NumLoBits = 0;
18945     switch (IntId) {
18946     default: break;
18947     case Intrinsic::x86_sse_movmsk_ps:
18948     case Intrinsic::x86_avx_movmsk_ps_256:
18949     case Intrinsic::x86_sse2_movmsk_pd:
18950     case Intrinsic::x86_avx_movmsk_pd_256:
18951     case Intrinsic::x86_mmx_pmovmskb:
18952     case Intrinsic::x86_sse2_pmovmskb_128:
18953     case Intrinsic::x86_avx2_pmovmskb: {
18954       // High bits of movmskp{s|d}, pmovmskb are known zero.
18955       switch (IntId) {
18956         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18957         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18958         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18959         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18960         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18961         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18962         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18963         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18964       }
18965       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18966       break;
18967     }
18968     }
18969     break;
18970   }
18971   }
18972 }
18973
18974 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18975   SDValue Op,
18976   const SelectionDAG &,
18977   unsigned Depth) const {
18978   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18979   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18980     return Op.getValueType().getScalarType().getSizeInBits();
18981
18982   // Fallback case.
18983   return 1;
18984 }
18985
18986 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18987 /// node is a GlobalAddress + offset.
18988 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18989                                        const GlobalValue* &GA,
18990                                        int64_t &Offset) const {
18991   if (N->getOpcode() == X86ISD::Wrapper) {
18992     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18993       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18994       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18995       return true;
18996     }
18997   }
18998   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18999 }
19000
19001 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19002 /// same as extracting the high 128-bit part of 256-bit vector and then
19003 /// inserting the result into the low part of a new 256-bit vector
19004 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19005   EVT VT = SVOp->getValueType(0);
19006   unsigned NumElems = VT.getVectorNumElements();
19007
19008   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19009   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19010     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19011         SVOp->getMaskElt(j) >= 0)
19012       return false;
19013
19014   return true;
19015 }
19016
19017 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19018 /// same as extracting the low 128-bit part of 256-bit vector and then
19019 /// inserting the result into the high part of a new 256-bit vector
19020 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19021   EVT VT = SVOp->getValueType(0);
19022   unsigned NumElems = VT.getVectorNumElements();
19023
19024   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19025   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19026     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19027         SVOp->getMaskElt(j) >= 0)
19028       return false;
19029
19030   return true;
19031 }
19032
19033 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19034 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19035                                         TargetLowering::DAGCombinerInfo &DCI,
19036                                         const X86Subtarget* Subtarget) {
19037   SDLoc dl(N);
19038   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19039   SDValue V1 = SVOp->getOperand(0);
19040   SDValue V2 = SVOp->getOperand(1);
19041   EVT VT = SVOp->getValueType(0);
19042   unsigned NumElems = VT.getVectorNumElements();
19043
19044   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19045       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19046     //
19047     //                   0,0,0,...
19048     //                      |
19049     //    V      UNDEF    BUILD_VECTOR    UNDEF
19050     //     \      /           \           /
19051     //  CONCAT_VECTOR         CONCAT_VECTOR
19052     //         \                  /
19053     //          \                /
19054     //          RESULT: V + zero extended
19055     //
19056     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19057         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19058         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19059       return SDValue();
19060
19061     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19062       return SDValue();
19063
19064     // To match the shuffle mask, the first half of the mask should
19065     // be exactly the first vector, and all the rest a splat with the
19066     // first element of the second one.
19067     for (unsigned i = 0; i != NumElems/2; ++i)
19068       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19069           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19070         return SDValue();
19071
19072     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19073     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19074       if (Ld->hasNUsesOfValue(1, 0)) {
19075         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19076         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19077         SDValue ResNode =
19078           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19079                                   Ld->getMemoryVT(),
19080                                   Ld->getPointerInfo(),
19081                                   Ld->getAlignment(),
19082                                   false/*isVolatile*/, true/*ReadMem*/,
19083                                   false/*WriteMem*/);
19084
19085         // Make sure the newly-created LOAD is in the same position as Ld in
19086         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19087         // and update uses of Ld's output chain to use the TokenFactor.
19088         if (Ld->hasAnyUseOfValue(1)) {
19089           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19090                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19091           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19092           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19093                                  SDValue(ResNode.getNode(), 1));
19094         }
19095
19096         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19097       }
19098     }
19099
19100     // Emit a zeroed vector and insert the desired subvector on its
19101     // first half.
19102     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19103     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19104     return DCI.CombineTo(N, InsV);
19105   }
19106
19107   //===--------------------------------------------------------------------===//
19108   // Combine some shuffles into subvector extracts and inserts:
19109   //
19110
19111   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19112   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19113     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19114     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19115     return DCI.CombineTo(N, InsV);
19116   }
19117
19118   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19119   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19120     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19121     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19122     return DCI.CombineTo(N, InsV);
19123   }
19124
19125   return SDValue();
19126 }
19127
19128 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19129 /// possible.
19130 ///
19131 /// This is the leaf of the recursive combinine below. When we have found some
19132 /// chain of single-use x86 shuffle instructions and accumulated the combined
19133 /// shuffle mask represented by them, this will try to pattern match that mask
19134 /// into either a single instruction if there is a special purpose instruction
19135 /// for this operation, or into a PSHUFB instruction which is a fully general
19136 /// instruction but should only be used to replace chains over a certain depth.
19137 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19138                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19139                                    TargetLowering::DAGCombinerInfo &DCI,
19140                                    const X86Subtarget *Subtarget) {
19141   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19142
19143   // Find the operand that enters the chain. Note that multiple uses are OK
19144   // here, we're not going to remove the operand we find.
19145   SDValue Input = Op.getOperand(0);
19146   while (Input.getOpcode() == ISD::BITCAST)
19147     Input = Input.getOperand(0);
19148
19149   MVT VT = Input.getSimpleValueType();
19150   MVT RootVT = Root.getSimpleValueType();
19151   SDLoc DL(Root);
19152
19153   // Just remove no-op shuffle masks.
19154   if (Mask.size() == 1) {
19155     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19156                   /*AddTo*/ true);
19157     return true;
19158   }
19159
19160   // Use the float domain if the operand type is a floating point type.
19161   bool FloatDomain = VT.isFloatingPoint();
19162
19163   // If we don't have access to VEX encodings, the generic PSHUF instructions
19164   // are preferable to some of the specialized forms despite requiring one more
19165   // byte to encode because they can implicitly copy.
19166   //
19167   // IF we *do* have VEX encodings, than we can use shorter, more specific
19168   // shuffle instructions freely as they can copy due to the extra register
19169   // operand.
19170   if (Subtarget->hasAVX()) {
19171     // We have both floating point and integer variants of shuffles that dup
19172     // either the low or high half of the vector.
19173     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19174       bool Lo = Mask.equals(0, 0);
19175       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19176                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19177       if (Depth == 1 && Root->getOpcode() == Shuffle)
19178         return false; // Nothing to do!
19179       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19180       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19181       DCI.AddToWorklist(Op.getNode());
19182       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19183       DCI.AddToWorklist(Op.getNode());
19184       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19185                     /*AddTo*/ true);
19186       return true;
19187     }
19188
19189     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19190
19191     // For the integer domain we have specialized instructions for duplicating
19192     // any element size from the low or high half.
19193     if (!FloatDomain &&
19194         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19195          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19196          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19197          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19198          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19199                      15))) {
19200       bool Lo = Mask[0] == 0;
19201       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19202       if (Depth == 1 && Root->getOpcode() == Shuffle)
19203         return false; // Nothing to do!
19204       MVT ShuffleVT;
19205       switch (Mask.size()) {
19206       case 4: ShuffleVT = MVT::v4i32; break;
19207       case 8: ShuffleVT = MVT::v8i16; break;
19208       case 16: ShuffleVT = MVT::v16i8; break;
19209       };
19210       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19211       DCI.AddToWorklist(Op.getNode());
19212       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19213       DCI.AddToWorklist(Op.getNode());
19214       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19215                     /*AddTo*/ true);
19216       return true;
19217     }
19218   }
19219
19220   // Don't try to re-form single instruction chains under any circumstances now
19221   // that we've done encoding canonicalization for them.
19222   if (Depth < 2)
19223     return false;
19224
19225   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19226   // can replace them with a single PSHUFB instruction profitably. Intel's
19227   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19228   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19229   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19230     SmallVector<SDValue, 16> PSHUFBMask;
19231     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19232     int Ratio = 16 / Mask.size();
19233     for (unsigned i = 0; i < 16; ++i) {
19234       int M = Ratio * Mask[i / Ratio] + i % Ratio;
19235       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19236     }
19237     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19238     DCI.AddToWorklist(Op.getNode());
19239     SDValue PSHUFBMaskOp =
19240         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19241     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19242     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19243     DCI.AddToWorklist(Op.getNode());
19244     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19245                   /*AddTo*/ true);
19246     return true;
19247   }
19248
19249   // Failed to find any combines.
19250   return false;
19251 }
19252
19253 /// \brief Fully generic combining of x86 shuffle instructions.
19254 ///
19255 /// This should be the last combine run over the x86 shuffle instructions. Once
19256 /// they have been fully optimized, this will recursively consider all chains
19257 /// of single-use shuffle instructions, build a generic model of the cumulative
19258 /// shuffle operation, and check for simpler instructions which implement this
19259 /// operation. We use this primarily for two purposes:
19260 ///
19261 /// 1) Collapse generic shuffles to specialized single instructions when
19262 ///    equivalent. In most cases, this is just an encoding size win, but
19263 ///    sometimes we will collapse multiple generic shuffles into a single
19264 ///    special-purpose shuffle.
19265 /// 2) Look for sequences of shuffle instructions with 3 or more total
19266 ///    instructions, and replace them with the slightly more expensive SSSE3
19267 ///    PSHUFB instruction if available. We do this as the last combining step
19268 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19269 ///    a suitable short sequence of other instructions. The PHUFB will either
19270 ///    use a register or have to read from memory and so is slightly (but only
19271 ///    slightly) more expensive than the other shuffle instructions.
19272 ///
19273 /// Because this is inherently a quadratic operation (for each shuffle in
19274 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19275 /// This should never be an issue in practice as the shuffle lowering doesn't
19276 /// produce sequences of more than 8 instructions.
19277 ///
19278 /// FIXME: We will currently miss some cases where the redundant shuffling
19279 /// would simplify under the threshold for PSHUFB formation because of
19280 /// combine-ordering. To fix this, we should do the redundant instruction
19281 /// combining in this recursive walk.
19282 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19283                                           ArrayRef<int> IncomingMask, int Depth,
19284                                           bool HasPSHUFB, SelectionDAG &DAG,
19285                                           TargetLowering::DAGCombinerInfo &DCI,
19286                                           const X86Subtarget *Subtarget) {
19287   // Bound the depth of our recursive combine because this is ultimately
19288   // quadratic in nature.
19289   if (Depth > 8)
19290     return false;
19291
19292   // Directly rip through bitcasts to find the underlying operand.
19293   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19294     Op = Op.getOperand(0);
19295
19296   MVT VT = Op.getSimpleValueType();
19297   if (!VT.isVector())
19298     return false; // Bail if we hit a non-vector.
19299   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19300   // version should be added.
19301   if (VT.getSizeInBits() != 128)
19302     return false;
19303
19304   assert(Root.getSimpleValueType().isVector() &&
19305          "Shuffles operate on vector types!");
19306   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19307          "Can only combine shuffles of the same vector register size.");
19308
19309   if (!isTargetShuffle(Op.getOpcode()))
19310     return false;
19311   SmallVector<int, 16> OpMask;
19312   bool IsUnary;
19313   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19314   // We only can combine unary shuffles which we can decode the mask for.
19315   if (!HaveMask || !IsUnary)
19316     return false;
19317
19318   assert(VT.getVectorNumElements() == OpMask.size() &&
19319          "Different mask size from vector size!");
19320
19321   SmallVector<int, 16> Mask;
19322   Mask.reserve(std::max(OpMask.size(), IncomingMask.size()));
19323
19324   // Merge this shuffle operation's mask into our accumulated mask. This is
19325   // a bit tricky as the shuffle may have a different size from the root.
19326   if (OpMask.size() == IncomingMask.size()) {
19327     for (int M : IncomingMask)
19328       Mask.push_back(OpMask[M]);
19329   } else if (OpMask.size() < IncomingMask.size()) {
19330     assert(IncomingMask.size() % OpMask.size() == 0 &&
19331            "The smaller number of elements must divide the larger.");
19332     int Ratio = IncomingMask.size() / OpMask.size();
19333     for (int M : IncomingMask)
19334       Mask.push_back(Ratio * OpMask[M / Ratio] + M % Ratio);
19335   } else {
19336     assert(OpMask.size() > IncomingMask.size() && "All other cases handled!");
19337     assert(OpMask.size() % IncomingMask.size() == 0 &&
19338            "The smaller number of elements must divide the larger.");
19339     int Ratio = OpMask.size() / IncomingMask.size();
19340     for (int i = 0, e = OpMask.size(); i < e; ++i)
19341       Mask.push_back(OpMask[Ratio * IncomingMask[i / Ratio] + i % Ratio]);
19342   }
19343
19344   // See if we can recurse into the operand to combine more things.
19345   switch (Op.getOpcode()) {
19346     case X86ISD::PSHUFB:
19347       HasPSHUFB = true;
19348     case X86ISD::PSHUFD:
19349     case X86ISD::PSHUFHW:
19350     case X86ISD::PSHUFLW:
19351       if (Op.getOperand(0).hasOneUse() &&
19352           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19353                                         HasPSHUFB, DAG, DCI, Subtarget))
19354         return true;
19355       break;
19356
19357     case X86ISD::UNPCKL:
19358     case X86ISD::UNPCKH:
19359       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19360       // We can't check for single use, we have to check that this shuffle is the only user.
19361       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19362           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19363                                         HasPSHUFB, DAG, DCI, Subtarget))
19364           return true;
19365       break;
19366   }
19367
19368   // Minor canonicalization of the accumulated shuffle mask to make it easier
19369   // to match below. All this does is detect masks with squential pairs of
19370   // elements, and shrink them to the half-width mask. It does this in a loop
19371   // so it will reduce the size of the mask to the minimal width mask which
19372   // performs an equivalent shuffle.
19373   while (Mask.size() > 1) {
19374     SmallVector<int, 16> NewMask;
19375     for (int i = 0, e = Mask.size()/2; i < e; ++i) {
19376       if (Mask[2*i] % 2 != 0 || Mask[2*i] != Mask[2*i + 1] + 1) {
19377         NewMask.clear();
19378         break;
19379       }
19380       NewMask.push_back(Mask[2*i] / 2);
19381     }
19382     if (NewMask.empty())
19383       break;
19384     Mask.swap(NewMask);
19385   }
19386
19387   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19388                                 Subtarget);
19389 }
19390
19391 /// \brief Get the PSHUF-style mask from PSHUF node.
19392 ///
19393 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19394 /// PSHUF-style masks that can be reused with such instructions.
19395 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19396   SmallVector<int, 4> Mask;
19397   bool IsUnary;
19398   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19399   (void)HaveMask;
19400   assert(HaveMask);
19401
19402   switch (N.getOpcode()) {
19403   case X86ISD::PSHUFD:
19404     return Mask;
19405   case X86ISD::PSHUFLW:
19406     Mask.resize(4);
19407     return Mask;
19408   case X86ISD::PSHUFHW:
19409     Mask.erase(Mask.begin(), Mask.begin() + 4);
19410     for (int &M : Mask)
19411       M -= 4;
19412     return Mask;
19413   default:
19414     llvm_unreachable("No valid shuffle instruction found!");
19415   }
19416 }
19417
19418 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19419 ///
19420 /// We walk up the chain and look for a combinable shuffle, skipping over
19421 /// shuffles that we could hoist this shuffle's transformation past without
19422 /// altering anything.
19423 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19424                                          SelectionDAG &DAG,
19425                                          TargetLowering::DAGCombinerInfo &DCI) {
19426   assert(N.getOpcode() == X86ISD::PSHUFD &&
19427          "Called with something other than an x86 128-bit half shuffle!");
19428   SDLoc DL(N);
19429
19430   // Walk up a single-use chain looking for a combinable shuffle.
19431   SDValue V = N.getOperand(0);
19432   for (; V.hasOneUse(); V = V.getOperand(0)) {
19433     switch (V.getOpcode()) {
19434     default:
19435       return false; // Nothing combined!
19436
19437     case ISD::BITCAST:
19438       // Skip bitcasts as we always know the type for the target specific
19439       // instructions.
19440       continue;
19441
19442     case X86ISD::PSHUFD:
19443       // Found another dword shuffle.
19444       break;
19445
19446     case X86ISD::PSHUFLW:
19447       // Check that the low words (being shuffled) are the identity in the
19448       // dword shuffle, and the high words are self-contained.
19449       if (Mask[0] != 0 || Mask[1] != 1 ||
19450           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19451         return false;
19452
19453       continue;
19454
19455     case X86ISD::PSHUFHW:
19456       // Check that the high words (being shuffled) are the identity in the
19457       // dword shuffle, and the low words are self-contained.
19458       if (Mask[2] != 2 || Mask[3] != 3 ||
19459           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19460         return false;
19461
19462       continue;
19463
19464     case X86ISD::UNPCKL:
19465     case X86ISD::UNPCKH:
19466       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19467       // shuffle into a preceding word shuffle.
19468       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19469         return false;
19470
19471       // Search for a half-shuffle which we can combine with.
19472       unsigned CombineOp =
19473           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19474       if (V.getOperand(0) != V.getOperand(1) ||
19475           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19476         return false;
19477       V = V.getOperand(0);
19478       do {
19479         switch (V.getOpcode()) {
19480         default:
19481           return false; // Nothing to combine.
19482
19483         case X86ISD::PSHUFLW:
19484         case X86ISD::PSHUFHW:
19485           if (V.getOpcode() == CombineOp)
19486             break;
19487
19488           // Fallthrough!
19489         case ISD::BITCAST:
19490           V = V.getOperand(0);
19491           continue;
19492         }
19493         break;
19494       } while (V.hasOneUse());
19495       break;
19496     }
19497     // Break out of the loop if we break out of the switch.
19498     break;
19499   }
19500
19501   if (!V.hasOneUse())
19502     // We fell out of the loop without finding a viable combining instruction.
19503     return false;
19504
19505   // Record the old value to use in RAUW-ing.
19506   SDValue Old = V;
19507
19508   // Merge this node's mask and our incoming mask.
19509   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19510   for (int &M : Mask)
19511     M = VMask[M];
19512   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19513                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19514
19515   // It is possible that one of the combinable shuffles was completely absorbed
19516   // by the other, just replace it and revisit all users in that case.
19517   if (Old.getNode() == V.getNode()) {
19518     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19519     return true;
19520   }
19521
19522   // Replace N with its operand as we're going to combine that shuffle away.
19523   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19524
19525   // Replace the combinable shuffle with the combined one, updating all users
19526   // so that we re-evaluate the chain here.
19527   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19528   return true;
19529 }
19530
19531 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19532 ///
19533 /// We walk up the chain, skipping shuffles of the other half and looking
19534 /// through shuffles which switch halves trying to find a shuffle of the same
19535 /// pair of dwords.
19536 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19537                                         SelectionDAG &DAG,
19538                                         TargetLowering::DAGCombinerInfo &DCI) {
19539   assert(
19540       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19541       "Called with something other than an x86 128-bit half shuffle!");
19542   SDLoc DL(N);
19543   unsigned CombineOpcode = N.getOpcode();
19544
19545   // Walk up a single-use chain looking for a combinable shuffle.
19546   SDValue V = N.getOperand(0);
19547   for (; V.hasOneUse(); V = V.getOperand(0)) {
19548     switch (V.getOpcode()) {
19549     default:
19550       return false; // Nothing combined!
19551
19552     case ISD::BITCAST:
19553       // Skip bitcasts as we always know the type for the target specific
19554       // instructions.
19555       continue;
19556
19557     case X86ISD::PSHUFLW:
19558     case X86ISD::PSHUFHW:
19559       if (V.getOpcode() == CombineOpcode)
19560         break;
19561
19562       // Other-half shuffles are no-ops.
19563       continue;
19564     }
19565     // Break out of the loop if we break out of the switch.
19566     break;
19567   }
19568
19569   if (!V.hasOneUse())
19570     // We fell out of the loop without finding a viable combining instruction.
19571     return false;
19572
19573   // Combine away the bottom node as its shuffle will be accumulated into
19574   // a preceding shuffle.
19575   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19576
19577   // Record the old value.
19578   SDValue Old = V;
19579
19580   // Merge this node's mask and our incoming mask (adjusted to account for all
19581   // the pshufd instructions encountered).
19582   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19583   for (int &M : Mask)
19584     M = VMask[M];
19585   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19586                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19587
19588   // Check that the shuffles didn't cancel each other out. If not, we need to
19589   // combine to the new one.
19590   if (Old != V)
19591     // Replace the combinable shuffle with the combined one, updating all users
19592     // so that we re-evaluate the chain here.
19593     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19594
19595   return true;
19596 }
19597
19598 /// \brief Try to combine x86 target specific shuffles.
19599 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19600                                            TargetLowering::DAGCombinerInfo &DCI,
19601                                            const X86Subtarget *Subtarget) {
19602   SDLoc DL(N);
19603   MVT VT = N.getSimpleValueType();
19604   SmallVector<int, 4> Mask;
19605
19606   switch (N.getOpcode()) {
19607   case X86ISD::PSHUFD:
19608   case X86ISD::PSHUFLW:
19609   case X86ISD::PSHUFHW:
19610     Mask = getPSHUFShuffleMask(N);
19611     assert(Mask.size() == 4);
19612     break;
19613   default:
19614     return SDValue();
19615   }
19616
19617   // Nuke no-op shuffles that show up after combining.
19618   if (isNoopShuffleMask(Mask))
19619     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19620
19621   // Look for simplifications involving one or two shuffle instructions.
19622   SDValue V = N.getOperand(0);
19623   switch (N.getOpcode()) {
19624   default:
19625     break;
19626   case X86ISD::PSHUFLW:
19627   case X86ISD::PSHUFHW:
19628     assert(VT == MVT::v8i16);
19629     (void)VT;
19630
19631     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19632       return SDValue(); // We combined away this shuffle, so we're done.
19633
19634     // See if this reduces to a PSHUFD which is no more expensive and can
19635     // combine with more operations.
19636     if (canWidenShuffleElements(Mask)) {
19637       int DMask[] = {-1, -1, -1, -1};
19638       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19639       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19640       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19641       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19642       DCI.AddToWorklist(V.getNode());
19643       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19644                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19645       DCI.AddToWorklist(V.getNode());
19646       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19647     }
19648
19649     // Look for shuffle patterns which can be implemented as a single unpack.
19650     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19651     // only works when we have a PSHUFD followed by two half-shuffles.
19652     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19653         (V.getOpcode() == X86ISD::PSHUFLW ||
19654          V.getOpcode() == X86ISD::PSHUFHW) &&
19655         V.getOpcode() != N.getOpcode() &&
19656         V.hasOneUse()) {
19657       SDValue D = V.getOperand(0);
19658       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19659         D = D.getOperand(0);
19660       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19661         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19662         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19663         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19664         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19665         int WordMask[8];
19666         for (int i = 0; i < 4; ++i) {
19667           WordMask[i + NOffset] = Mask[i] + NOffset;
19668           WordMask[i + VOffset] = VMask[i] + VOffset;
19669         }
19670         // Map the word mask through the DWord mask.
19671         int MappedMask[8];
19672         for (int i = 0; i < 8; ++i)
19673           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19674         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19675         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19676         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19677                        std::begin(UnpackLoMask)) ||
19678             std::equal(std::begin(MappedMask), std::end(MappedMask),
19679                        std::begin(UnpackHiMask))) {
19680           // We can replace all three shuffles with an unpack.
19681           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19682           DCI.AddToWorklist(V.getNode());
19683           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19684                                                 : X86ISD::UNPCKH,
19685                              DL, MVT::v8i16, V, V);
19686         }
19687       }
19688     }
19689
19690     break;
19691
19692   case X86ISD::PSHUFD:
19693     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19694       return SDValue(); // We combined away this shuffle.
19695
19696     break;
19697   }
19698
19699   return SDValue();
19700 }
19701
19702 /// PerformShuffleCombine - Performs several different shuffle combines.
19703 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19704                                      TargetLowering::DAGCombinerInfo &DCI,
19705                                      const X86Subtarget *Subtarget) {
19706   SDLoc dl(N);
19707   SDValue N0 = N->getOperand(0);
19708   SDValue N1 = N->getOperand(1);
19709   EVT VT = N->getValueType(0);
19710
19711   // Don't create instructions with illegal types after legalize types has run.
19712   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19713   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19714     return SDValue();
19715
19716   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19717   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19718       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19719     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19720
19721   // During Type Legalization, when promoting illegal vector types,
19722   // the backend might introduce new shuffle dag nodes and bitcasts.
19723   //
19724   // This code performs the following transformation:
19725   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19726   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19727   //
19728   // We do this only if both the bitcast and the BINOP dag nodes have
19729   // one use. Also, perform this transformation only if the new binary
19730   // operation is legal. This is to avoid introducing dag nodes that
19731   // potentially need to be further expanded (or custom lowered) into a
19732   // less optimal sequence of dag nodes.
19733   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19734       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19735       N0.getOpcode() == ISD::BITCAST) {
19736     SDValue BC0 = N0.getOperand(0);
19737     EVT SVT = BC0.getValueType();
19738     unsigned Opcode = BC0.getOpcode();
19739     unsigned NumElts = VT.getVectorNumElements();
19740     
19741     if (BC0.hasOneUse() && SVT.isVector() &&
19742         SVT.getVectorNumElements() * 2 == NumElts &&
19743         TLI.isOperationLegal(Opcode, VT)) {
19744       bool CanFold = false;
19745       switch (Opcode) {
19746       default : break;
19747       case ISD::ADD :
19748       case ISD::FADD :
19749       case ISD::SUB :
19750       case ISD::FSUB :
19751       case ISD::MUL :
19752       case ISD::FMUL :
19753         CanFold = true;
19754       }
19755
19756       unsigned SVTNumElts = SVT.getVectorNumElements();
19757       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19758       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19759         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19760       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19761         CanFold = SVOp->getMaskElt(i) < 0;
19762
19763       if (CanFold) {
19764         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19765         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19766         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19767         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19768       }
19769     }
19770   }
19771
19772   // Only handle 128 wide vector from here on.
19773   if (!VT.is128BitVector())
19774     return SDValue();
19775
19776   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19777   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19778   // consecutive, non-overlapping, and in the right order.
19779   SmallVector<SDValue, 16> Elts;
19780   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19781     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19782
19783   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19784   if (LD.getNode())
19785     return LD;
19786
19787   if (isTargetShuffle(N->getOpcode())) {
19788     SDValue Shuffle =
19789         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19790     if (Shuffle.getNode())
19791       return Shuffle;
19792
19793     // Try recursively combining arbitrary sequences of x86 shuffle
19794     // instructions into higher-order shuffles. We do this after combining
19795     // specific PSHUF instruction sequences into their minimal form so that we
19796     // can evaluate how many specialized shuffle instructions are involved in
19797     // a particular chain.
19798     SmallVector<int, 1> NonceMask; // Just a placeholder.
19799     NonceMask.push_back(0);
19800     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19801                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19802                                       DCI, Subtarget))
19803       return SDValue(); // This routine will use CombineTo to replace N.
19804   }
19805
19806   return SDValue();
19807 }
19808
19809 /// PerformTruncateCombine - Converts truncate operation to
19810 /// a sequence of vector shuffle operations.
19811 /// It is possible when we truncate 256-bit vector to 128-bit vector
19812 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19813                                       TargetLowering::DAGCombinerInfo &DCI,
19814                                       const X86Subtarget *Subtarget)  {
19815   return SDValue();
19816 }
19817
19818 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19819 /// specific shuffle of a load can be folded into a single element load.
19820 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19821 /// shuffles have been customed lowered so we need to handle those here.
19822 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19823                                          TargetLowering::DAGCombinerInfo &DCI) {
19824   if (DCI.isBeforeLegalizeOps())
19825     return SDValue();
19826
19827   SDValue InVec = N->getOperand(0);
19828   SDValue EltNo = N->getOperand(1);
19829
19830   if (!isa<ConstantSDNode>(EltNo))
19831     return SDValue();
19832
19833   EVT VT = InVec.getValueType();
19834
19835   bool HasShuffleIntoBitcast = false;
19836   if (InVec.getOpcode() == ISD::BITCAST) {
19837     // Don't duplicate a load with other uses.
19838     if (!InVec.hasOneUse())
19839       return SDValue();
19840     EVT BCVT = InVec.getOperand(0).getValueType();
19841     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19842       return SDValue();
19843     InVec = InVec.getOperand(0);
19844     HasShuffleIntoBitcast = true;
19845   }
19846
19847   if (!isTargetShuffle(InVec.getOpcode()))
19848     return SDValue();
19849
19850   // Don't duplicate a load with other uses.
19851   if (!InVec.hasOneUse())
19852     return SDValue();
19853
19854   SmallVector<int, 16> ShuffleMask;
19855   bool UnaryShuffle;
19856   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19857                             UnaryShuffle))
19858     return SDValue();
19859
19860   // Select the input vector, guarding against out of range extract vector.
19861   unsigned NumElems = VT.getVectorNumElements();
19862   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19863   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19864   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19865                                          : InVec.getOperand(1);
19866
19867   // If inputs to shuffle are the same for both ops, then allow 2 uses
19868   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19869
19870   if (LdNode.getOpcode() == ISD::BITCAST) {
19871     // Don't duplicate a load with other uses.
19872     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19873       return SDValue();
19874
19875     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19876     LdNode = LdNode.getOperand(0);
19877   }
19878
19879   if (!ISD::isNormalLoad(LdNode.getNode()))
19880     return SDValue();
19881
19882   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19883
19884   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19885     return SDValue();
19886
19887   if (HasShuffleIntoBitcast) {
19888     // If there's a bitcast before the shuffle, check if the load type and
19889     // alignment is valid.
19890     unsigned Align = LN0->getAlignment();
19891     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19892     unsigned NewAlign = TLI.getDataLayout()->
19893       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19894
19895     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19896       return SDValue();
19897   }
19898
19899   // All checks match so transform back to vector_shuffle so that DAG combiner
19900   // can finish the job
19901   SDLoc dl(N);
19902
19903   // Create shuffle node taking into account the case that its a unary shuffle
19904   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19905   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19906                                  InVec.getOperand(0), Shuffle,
19907                                  &ShuffleMask[0]);
19908   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19909   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19910                      EltNo);
19911 }
19912
19913 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19914 /// generation and convert it from being a bunch of shuffles and extracts
19915 /// to a simple store and scalar loads to extract the elements.
19916 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19917                                          TargetLowering::DAGCombinerInfo &DCI) {
19918   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19919   if (NewOp.getNode())
19920     return NewOp;
19921
19922   SDValue InputVector = N->getOperand(0);
19923
19924   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19925   // from mmx to v2i32 has a single usage.
19926   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19927       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19928       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19929     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19930                        N->getValueType(0),
19931                        InputVector.getNode()->getOperand(0));
19932
19933   // Only operate on vectors of 4 elements, where the alternative shuffling
19934   // gets to be more expensive.
19935   if (InputVector.getValueType() != MVT::v4i32)
19936     return SDValue();
19937
19938   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19939   // single use which is a sign-extend or zero-extend, and all elements are
19940   // used.
19941   SmallVector<SDNode *, 4> Uses;
19942   unsigned ExtractedElements = 0;
19943   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19944        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19945     if (UI.getUse().getResNo() != InputVector.getResNo())
19946       return SDValue();
19947
19948     SDNode *Extract = *UI;
19949     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19950       return SDValue();
19951
19952     if (Extract->getValueType(0) != MVT::i32)
19953       return SDValue();
19954     if (!Extract->hasOneUse())
19955       return SDValue();
19956     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19957         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19958       return SDValue();
19959     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19960       return SDValue();
19961
19962     // Record which element was extracted.
19963     ExtractedElements |=
19964       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19965
19966     Uses.push_back(Extract);
19967   }
19968
19969   // If not all the elements were used, this may not be worthwhile.
19970   if (ExtractedElements != 15)
19971     return SDValue();
19972
19973   // Ok, we've now decided to do the transformation.
19974   SDLoc dl(InputVector);
19975
19976   // Store the value to a temporary stack slot.
19977   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19978   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19979                             MachinePointerInfo(), false, false, 0);
19980
19981   // Replace each use (extract) with a load of the appropriate element.
19982   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19983        UE = Uses.end(); UI != UE; ++UI) {
19984     SDNode *Extract = *UI;
19985
19986     // cOMpute the element's address.
19987     SDValue Idx = Extract->getOperand(1);
19988     unsigned EltSize =
19989         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19990     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19991     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19992     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19993
19994     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19995                                      StackPtr, OffsetVal);
19996
19997     // Load the scalar.
19998     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19999                                      ScalarAddr, MachinePointerInfo(),
20000                                      false, false, false, 0);
20001
20002     // Replace the exact with the load.
20003     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
20004   }
20005
20006   // The replacement was made in place; don't return anything.
20007   return SDValue();
20008 }
20009
20010 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20011 static std::pair<unsigned, bool>
20012 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20013                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20014   if (!VT.isVector())
20015     return std::make_pair(0, false);
20016
20017   bool NeedSplit = false;
20018   switch (VT.getSimpleVT().SimpleTy) {
20019   default: return std::make_pair(0, false);
20020   case MVT::v32i8:
20021   case MVT::v16i16:
20022   case MVT::v8i32:
20023     if (!Subtarget->hasAVX2())
20024       NeedSplit = true;
20025     if (!Subtarget->hasAVX())
20026       return std::make_pair(0, false);
20027     break;
20028   case MVT::v16i8:
20029   case MVT::v8i16:
20030   case MVT::v4i32:
20031     if (!Subtarget->hasSSE2())
20032       return std::make_pair(0, false);
20033   }
20034
20035   // SSE2 has only a small subset of the operations.
20036   bool hasUnsigned = Subtarget->hasSSE41() ||
20037                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20038   bool hasSigned = Subtarget->hasSSE41() ||
20039                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20040
20041   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20042
20043   unsigned Opc = 0;
20044   // Check for x CC y ? x : y.
20045   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20046       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20047     switch (CC) {
20048     default: break;
20049     case ISD::SETULT:
20050     case ISD::SETULE:
20051       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20052     case ISD::SETUGT:
20053     case ISD::SETUGE:
20054       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20055     case ISD::SETLT:
20056     case ISD::SETLE:
20057       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20058     case ISD::SETGT:
20059     case ISD::SETGE:
20060       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20061     }
20062   // Check for x CC y ? y : x -- a min/max with reversed arms.
20063   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20064              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20065     switch (CC) {
20066     default: break;
20067     case ISD::SETULT:
20068     case ISD::SETULE:
20069       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20070     case ISD::SETUGT:
20071     case ISD::SETUGE:
20072       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20073     case ISD::SETLT:
20074     case ISD::SETLE:
20075       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20076     case ISD::SETGT:
20077     case ISD::SETGE:
20078       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20079     }
20080   }
20081
20082   return std::make_pair(Opc, NeedSplit);
20083 }
20084
20085 static SDValue
20086 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20087                                       const X86Subtarget *Subtarget) {
20088   SDLoc dl(N);
20089   SDValue Cond = N->getOperand(0);
20090   SDValue LHS = N->getOperand(1);
20091   SDValue RHS = N->getOperand(2);
20092
20093   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20094     SDValue CondSrc = Cond->getOperand(0);
20095     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20096       Cond = CondSrc->getOperand(0);
20097   }
20098
20099   MVT VT = N->getSimpleValueType(0);
20100   MVT EltVT = VT.getVectorElementType();
20101   unsigned NumElems = VT.getVectorNumElements();
20102   // There is no blend with immediate in AVX-512.
20103   if (VT.is512BitVector())
20104     return SDValue();
20105
20106   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20107     return SDValue();
20108   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20109     return SDValue();
20110
20111   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20112     return SDValue();
20113
20114   unsigned MaskValue = 0;
20115   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20116     return SDValue();
20117
20118   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20119   for (unsigned i = 0; i < NumElems; ++i) {
20120     // Be sure we emit undef where we can.
20121     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20122       ShuffleMask[i] = -1;
20123     else
20124       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20125   }
20126
20127   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20128 }
20129
20130 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20131 /// nodes.
20132 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20133                                     TargetLowering::DAGCombinerInfo &DCI,
20134                                     const X86Subtarget *Subtarget) {
20135   SDLoc DL(N);
20136   SDValue Cond = N->getOperand(0);
20137   // Get the LHS/RHS of the select.
20138   SDValue LHS = N->getOperand(1);
20139   SDValue RHS = N->getOperand(2);
20140   EVT VT = LHS.getValueType();
20141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20142
20143   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20144   // instructions match the semantics of the common C idiom x<y?x:y but not
20145   // x<=y?x:y, because of how they handle negative zero (which can be
20146   // ignored in unsafe-math mode).
20147   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20148       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20149       (Subtarget->hasSSE2() ||
20150        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20151     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20152
20153     unsigned Opcode = 0;
20154     // Check for x CC y ? x : y.
20155     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20156         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20157       switch (CC) {
20158       default: break;
20159       case ISD::SETULT:
20160         // Converting this to a min would handle NaNs incorrectly, and swapping
20161         // the operands would cause it to handle comparisons between positive
20162         // and negative zero incorrectly.
20163         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20164           if (!DAG.getTarget().Options.UnsafeFPMath &&
20165               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20166             break;
20167           std::swap(LHS, RHS);
20168         }
20169         Opcode = X86ISD::FMIN;
20170         break;
20171       case ISD::SETOLE:
20172         // Converting this to a min would handle comparisons between positive
20173         // and negative zero incorrectly.
20174         if (!DAG.getTarget().Options.UnsafeFPMath &&
20175             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20176           break;
20177         Opcode = X86ISD::FMIN;
20178         break;
20179       case ISD::SETULE:
20180         // Converting this to a min would handle both negative zeros and NaNs
20181         // incorrectly, but we can swap the operands to fix both.
20182         std::swap(LHS, RHS);
20183       case ISD::SETOLT:
20184       case ISD::SETLT:
20185       case ISD::SETLE:
20186         Opcode = X86ISD::FMIN;
20187         break;
20188
20189       case ISD::SETOGE:
20190         // Converting this to a max would handle comparisons between positive
20191         // and negative zero incorrectly.
20192         if (!DAG.getTarget().Options.UnsafeFPMath &&
20193             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20194           break;
20195         Opcode = X86ISD::FMAX;
20196         break;
20197       case ISD::SETUGT:
20198         // Converting this to a max would handle NaNs incorrectly, and swapping
20199         // the operands would cause it to handle comparisons between positive
20200         // and negative zero incorrectly.
20201         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20202           if (!DAG.getTarget().Options.UnsafeFPMath &&
20203               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20204             break;
20205           std::swap(LHS, RHS);
20206         }
20207         Opcode = X86ISD::FMAX;
20208         break;
20209       case ISD::SETUGE:
20210         // Converting this to a max would handle both negative zeros and NaNs
20211         // incorrectly, but we can swap the operands to fix both.
20212         std::swap(LHS, RHS);
20213       case ISD::SETOGT:
20214       case ISD::SETGT:
20215       case ISD::SETGE:
20216         Opcode = X86ISD::FMAX;
20217         break;
20218       }
20219     // Check for x CC y ? y : x -- a min/max with reversed arms.
20220     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20221                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20222       switch (CC) {
20223       default: break;
20224       case ISD::SETOGE:
20225         // Converting this to a min would handle comparisons between positive
20226         // and negative zero incorrectly, and swapping the operands would
20227         // cause it to handle NaNs incorrectly.
20228         if (!DAG.getTarget().Options.UnsafeFPMath &&
20229             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20230           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20231             break;
20232           std::swap(LHS, RHS);
20233         }
20234         Opcode = X86ISD::FMIN;
20235         break;
20236       case ISD::SETUGT:
20237         // Converting this to a min would handle NaNs incorrectly.
20238         if (!DAG.getTarget().Options.UnsafeFPMath &&
20239             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20240           break;
20241         Opcode = X86ISD::FMIN;
20242         break;
20243       case ISD::SETUGE:
20244         // Converting this to a min would handle both negative zeros and NaNs
20245         // incorrectly, but we can swap the operands to fix both.
20246         std::swap(LHS, RHS);
20247       case ISD::SETOGT:
20248       case ISD::SETGT:
20249       case ISD::SETGE:
20250         Opcode = X86ISD::FMIN;
20251         break;
20252
20253       case ISD::SETULT:
20254         // Converting this to a max would handle NaNs incorrectly.
20255         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20256           break;
20257         Opcode = X86ISD::FMAX;
20258         break;
20259       case ISD::SETOLE:
20260         // Converting this to a max would handle comparisons between positive
20261         // and negative zero incorrectly, and swapping the operands would
20262         // cause it to handle NaNs incorrectly.
20263         if (!DAG.getTarget().Options.UnsafeFPMath &&
20264             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20265           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20266             break;
20267           std::swap(LHS, RHS);
20268         }
20269         Opcode = X86ISD::FMAX;
20270         break;
20271       case ISD::SETULE:
20272         // Converting this to a max would handle both negative zeros and NaNs
20273         // incorrectly, but we can swap the operands to fix both.
20274         std::swap(LHS, RHS);
20275       case ISD::SETOLT:
20276       case ISD::SETLT:
20277       case ISD::SETLE:
20278         Opcode = X86ISD::FMAX;
20279         break;
20280       }
20281     }
20282
20283     if (Opcode)
20284       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20285   }
20286
20287   EVT CondVT = Cond.getValueType();
20288   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20289       CondVT.getVectorElementType() == MVT::i1) {
20290     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20291     // lowering on AVX-512. In this case we convert it to
20292     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20293     // The same situation for all 128 and 256-bit vectors of i8 and i16
20294     EVT OpVT = LHS.getValueType();
20295     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20296         (OpVT.getVectorElementType() == MVT::i8 ||
20297          OpVT.getVectorElementType() == MVT::i16)) {
20298       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20299       DCI.AddToWorklist(Cond.getNode());
20300       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20301     }
20302   }
20303   // If this is a select between two integer constants, try to do some
20304   // optimizations.
20305   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20306     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20307       // Don't do this for crazy integer types.
20308       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20309         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20310         // so that TrueC (the true value) is larger than FalseC.
20311         bool NeedsCondInvert = false;
20312
20313         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20314             // Efficiently invertible.
20315             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20316              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20317               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20318           NeedsCondInvert = true;
20319           std::swap(TrueC, FalseC);
20320         }
20321
20322         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20323         if (FalseC->getAPIntValue() == 0 &&
20324             TrueC->getAPIntValue().isPowerOf2()) {
20325           if (NeedsCondInvert) // Invert the condition if needed.
20326             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20327                                DAG.getConstant(1, Cond.getValueType()));
20328
20329           // Zero extend the condition if needed.
20330           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20331
20332           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20333           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20334                              DAG.getConstant(ShAmt, MVT::i8));
20335         }
20336
20337         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20338         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20339           if (NeedsCondInvert) // Invert the condition if needed.
20340             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20341                                DAG.getConstant(1, Cond.getValueType()));
20342
20343           // Zero extend the condition if needed.
20344           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20345                              FalseC->getValueType(0), Cond);
20346           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20347                              SDValue(FalseC, 0));
20348         }
20349
20350         // Optimize cases that will turn into an LEA instruction.  This requires
20351         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20352         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20353           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20354           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20355
20356           bool isFastMultiplier = false;
20357           if (Diff < 10) {
20358             switch ((unsigned char)Diff) {
20359               default: break;
20360               case 1:  // result = add base, cond
20361               case 2:  // result = lea base(    , cond*2)
20362               case 3:  // result = lea base(cond, cond*2)
20363               case 4:  // result = lea base(    , cond*4)
20364               case 5:  // result = lea base(cond, cond*4)
20365               case 8:  // result = lea base(    , cond*8)
20366               case 9:  // result = lea base(cond, cond*8)
20367                 isFastMultiplier = true;
20368                 break;
20369             }
20370           }
20371
20372           if (isFastMultiplier) {
20373             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20374             if (NeedsCondInvert) // Invert the condition if needed.
20375               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20376                                  DAG.getConstant(1, Cond.getValueType()));
20377
20378             // Zero extend the condition if needed.
20379             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20380                                Cond);
20381             // Scale the condition by the difference.
20382             if (Diff != 1)
20383               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20384                                  DAG.getConstant(Diff, Cond.getValueType()));
20385
20386             // Add the base if non-zero.
20387             if (FalseC->getAPIntValue() != 0)
20388               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20389                                  SDValue(FalseC, 0));
20390             return Cond;
20391           }
20392         }
20393       }
20394   }
20395
20396   // Canonicalize max and min:
20397   // (x > y) ? x : y -> (x >= y) ? x : y
20398   // (x < y) ? x : y -> (x <= y) ? x : y
20399   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20400   // the need for an extra compare
20401   // against zero. e.g.
20402   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20403   // subl   %esi, %edi
20404   // testl  %edi, %edi
20405   // movl   $0, %eax
20406   // cmovgl %edi, %eax
20407   // =>
20408   // xorl   %eax, %eax
20409   // subl   %esi, $edi
20410   // cmovsl %eax, %edi
20411   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20412       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20413       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20414     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20415     switch (CC) {
20416     default: break;
20417     case ISD::SETLT:
20418     case ISD::SETGT: {
20419       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20420       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20421                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20422       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20423     }
20424     }
20425   }
20426
20427   // Early exit check
20428   if (!TLI.isTypeLegal(VT))
20429     return SDValue();
20430
20431   // Match VSELECTs into subs with unsigned saturation.
20432   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20433       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20434       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20435        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20436     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20437
20438     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20439     // left side invert the predicate to simplify logic below.
20440     SDValue Other;
20441     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20442       Other = RHS;
20443       CC = ISD::getSetCCInverse(CC, true);
20444     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20445       Other = LHS;
20446     }
20447
20448     if (Other.getNode() && Other->getNumOperands() == 2 &&
20449         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20450       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20451       SDValue CondRHS = Cond->getOperand(1);
20452
20453       // Look for a general sub with unsigned saturation first.
20454       // x >= y ? x-y : 0 --> subus x, y
20455       // x >  y ? x-y : 0 --> subus x, y
20456       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20457           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20458         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20459
20460       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20461         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20462           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20463             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20464               // If the RHS is a constant we have to reverse the const
20465               // canonicalization.
20466               // x > C-1 ? x+-C : 0 --> subus x, C
20467               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20468                   CondRHSConst->getAPIntValue() ==
20469                       (-OpRHSConst->getAPIntValue() - 1))
20470                 return DAG.getNode(
20471                     X86ISD::SUBUS, DL, VT, OpLHS,
20472                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20473
20474           // Another special case: If C was a sign bit, the sub has been
20475           // canonicalized into a xor.
20476           // FIXME: Would it be better to use computeKnownBits to determine
20477           //        whether it's safe to decanonicalize the xor?
20478           // x s< 0 ? x^C : 0 --> subus x, C
20479           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20480               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20481               OpRHSConst->getAPIntValue().isSignBit())
20482             // Note that we have to rebuild the RHS constant here to ensure we
20483             // don't rely on particular values of undef lanes.
20484             return DAG.getNode(
20485                 X86ISD::SUBUS, DL, VT, OpLHS,
20486                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20487         }
20488     }
20489   }
20490
20491   // Try to match a min/max vector operation.
20492   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20493     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20494     unsigned Opc = ret.first;
20495     bool NeedSplit = ret.second;
20496
20497     if (Opc && NeedSplit) {
20498       unsigned NumElems = VT.getVectorNumElements();
20499       // Extract the LHS vectors
20500       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20501       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20502
20503       // Extract the RHS vectors
20504       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20505       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20506
20507       // Create min/max for each subvector
20508       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20509       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20510
20511       // Merge the result
20512       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20513     } else if (Opc)
20514       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20515   }
20516
20517   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20518   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20519       // Check if SETCC has already been promoted
20520       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20521       // Check that condition value type matches vselect operand type
20522       CondVT == VT) { 
20523
20524     assert(Cond.getValueType().isVector() &&
20525            "vector select expects a vector selector!");
20526
20527     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20528     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20529
20530     if (!TValIsAllOnes && !FValIsAllZeros) {
20531       // Try invert the condition if true value is not all 1s and false value
20532       // is not all 0s.
20533       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20534       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20535
20536       if (TValIsAllZeros || FValIsAllOnes) {
20537         SDValue CC = Cond.getOperand(2);
20538         ISD::CondCode NewCC =
20539           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20540                                Cond.getOperand(0).getValueType().isInteger());
20541         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20542         std::swap(LHS, RHS);
20543         TValIsAllOnes = FValIsAllOnes;
20544         FValIsAllZeros = TValIsAllZeros;
20545       }
20546     }
20547
20548     if (TValIsAllOnes || FValIsAllZeros) {
20549       SDValue Ret;
20550
20551       if (TValIsAllOnes && FValIsAllZeros)
20552         Ret = Cond;
20553       else if (TValIsAllOnes)
20554         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20555                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20556       else if (FValIsAllZeros)
20557         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20558                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20559
20560       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20561     }
20562   }
20563
20564   // Try to fold this VSELECT into a MOVSS/MOVSD
20565   if (N->getOpcode() == ISD::VSELECT &&
20566       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20567     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20568         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20569       bool CanFold = false;
20570       unsigned NumElems = Cond.getNumOperands();
20571       SDValue A = LHS;
20572       SDValue B = RHS;
20573       
20574       if (isZero(Cond.getOperand(0))) {
20575         CanFold = true;
20576
20577         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20578         // fold (vselect <0,-1> -> (movsd A, B)
20579         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20580           CanFold = isAllOnes(Cond.getOperand(i));
20581       } else if (isAllOnes(Cond.getOperand(0))) {
20582         CanFold = true;
20583         std::swap(A, B);
20584
20585         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20586         // fold (vselect <-1,0> -> (movsd B, A)
20587         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20588           CanFold = isZero(Cond.getOperand(i));
20589       }
20590
20591       if (CanFold) {
20592         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20593           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20594         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20595       }
20596
20597       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20598         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20599         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20600         //                             (v2i64 (bitcast B)))))
20601         //
20602         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20603         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20604         //                             (v2f64 (bitcast B)))))
20605         //
20606         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20607         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20608         //                             (v2i64 (bitcast A)))))
20609         //
20610         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20611         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20612         //                             (v2f64 (bitcast A)))))
20613
20614         CanFold = (isZero(Cond.getOperand(0)) &&
20615                    isZero(Cond.getOperand(1)) &&
20616                    isAllOnes(Cond.getOperand(2)) &&
20617                    isAllOnes(Cond.getOperand(3)));
20618
20619         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20620             isAllOnes(Cond.getOperand(1)) &&
20621             isZero(Cond.getOperand(2)) &&
20622             isZero(Cond.getOperand(3))) {
20623           CanFold = true;
20624           std::swap(LHS, RHS);
20625         }
20626
20627         if (CanFold) {
20628           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20629           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20630           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20631           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20632                                                 NewB, DAG);
20633           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20634         }
20635       }
20636     }
20637   }
20638
20639   // If we know that this node is legal then we know that it is going to be
20640   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20641   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20642   // to simplify previous instructions.
20643   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20644       !DCI.isBeforeLegalize() &&
20645       // We explicitly check against v8i16 and v16i16 because, although
20646       // they're marked as Custom, they might only be legal when Cond is a
20647       // build_vector of constants. This will be taken care in a later
20648       // condition.
20649       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20650        VT != MVT::v8i16)) {
20651     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20652
20653     // Don't optimize vector selects that map to mask-registers.
20654     if (BitWidth == 1)
20655       return SDValue();
20656
20657     // Check all uses of that condition operand to check whether it will be
20658     // consumed by non-BLEND instructions, which may depend on all bits are set
20659     // properly.
20660     for (SDNode::use_iterator I = Cond->use_begin(),
20661                               E = Cond->use_end(); I != E; ++I)
20662       if (I->getOpcode() != ISD::VSELECT)
20663         // TODO: Add other opcodes eventually lowered into BLEND.
20664         return SDValue();
20665
20666     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20667     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20668
20669     APInt KnownZero, KnownOne;
20670     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20671                                           DCI.isBeforeLegalizeOps());
20672     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20673         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20674       DCI.CommitTargetLoweringOpt(TLO);
20675   }
20676
20677   // We should generate an X86ISD::BLENDI from a vselect if its argument
20678   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20679   // constants. This specific pattern gets generated when we split a
20680   // selector for a 512 bit vector in a machine without AVX512 (but with
20681   // 256-bit vectors), during legalization:
20682   //
20683   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20684   //
20685   // Iff we find this pattern and the build_vectors are built from
20686   // constants, we translate the vselect into a shuffle_vector that we
20687   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20688   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20689     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20690     if (Shuffle.getNode())
20691       return Shuffle;
20692   }
20693
20694   return SDValue();
20695 }
20696
20697 // Check whether a boolean test is testing a boolean value generated by
20698 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20699 // code.
20700 //
20701 // Simplify the following patterns:
20702 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20703 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20704 // to (Op EFLAGS Cond)
20705 //
20706 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20707 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20708 // to (Op EFLAGS !Cond)
20709 //
20710 // where Op could be BRCOND or CMOV.
20711 //
20712 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20713   // Quit if not CMP and SUB with its value result used.
20714   if (Cmp.getOpcode() != X86ISD::CMP &&
20715       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20716       return SDValue();
20717
20718   // Quit if not used as a boolean value.
20719   if (CC != X86::COND_E && CC != X86::COND_NE)
20720     return SDValue();
20721
20722   // Check CMP operands. One of them should be 0 or 1 and the other should be
20723   // an SetCC or extended from it.
20724   SDValue Op1 = Cmp.getOperand(0);
20725   SDValue Op2 = Cmp.getOperand(1);
20726
20727   SDValue SetCC;
20728   const ConstantSDNode* C = nullptr;
20729   bool needOppositeCond = (CC == X86::COND_E);
20730   bool checkAgainstTrue = false; // Is it a comparison against 1?
20731
20732   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20733     SetCC = Op2;
20734   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20735     SetCC = Op1;
20736   else // Quit if all operands are not constants.
20737     return SDValue();
20738
20739   if (C->getZExtValue() == 1) {
20740     needOppositeCond = !needOppositeCond;
20741     checkAgainstTrue = true;
20742   } else if (C->getZExtValue() != 0)
20743     // Quit if the constant is neither 0 or 1.
20744     return SDValue();
20745
20746   bool truncatedToBoolWithAnd = false;
20747   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20748   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20749          SetCC.getOpcode() == ISD::TRUNCATE ||
20750          SetCC.getOpcode() == ISD::AND) {
20751     if (SetCC.getOpcode() == ISD::AND) {
20752       int OpIdx = -1;
20753       ConstantSDNode *CS;
20754       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20755           CS->getZExtValue() == 1)
20756         OpIdx = 1;
20757       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20758           CS->getZExtValue() == 1)
20759         OpIdx = 0;
20760       if (OpIdx == -1)
20761         break;
20762       SetCC = SetCC.getOperand(OpIdx);
20763       truncatedToBoolWithAnd = true;
20764     } else
20765       SetCC = SetCC.getOperand(0);
20766   }
20767
20768   switch (SetCC.getOpcode()) {
20769   case X86ISD::SETCC_CARRY:
20770     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20771     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20772     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20773     // truncated to i1 using 'and'.
20774     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20775       break;
20776     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20777            "Invalid use of SETCC_CARRY!");
20778     // FALL THROUGH
20779   case X86ISD::SETCC:
20780     // Set the condition code or opposite one if necessary.
20781     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20782     if (needOppositeCond)
20783       CC = X86::GetOppositeBranchCondition(CC);
20784     return SetCC.getOperand(1);
20785   case X86ISD::CMOV: {
20786     // Check whether false/true value has canonical one, i.e. 0 or 1.
20787     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20788     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20789     // Quit if true value is not a constant.
20790     if (!TVal)
20791       return SDValue();
20792     // Quit if false value is not a constant.
20793     if (!FVal) {
20794       SDValue Op = SetCC.getOperand(0);
20795       // Skip 'zext' or 'trunc' node.
20796       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20797           Op.getOpcode() == ISD::TRUNCATE)
20798         Op = Op.getOperand(0);
20799       // A special case for rdrand/rdseed, where 0 is set if false cond is
20800       // found.
20801       if ((Op.getOpcode() != X86ISD::RDRAND &&
20802            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20803         return SDValue();
20804     }
20805     // Quit if false value is not the constant 0 or 1.
20806     bool FValIsFalse = true;
20807     if (FVal && FVal->getZExtValue() != 0) {
20808       if (FVal->getZExtValue() != 1)
20809         return SDValue();
20810       // If FVal is 1, opposite cond is needed.
20811       needOppositeCond = !needOppositeCond;
20812       FValIsFalse = false;
20813     }
20814     // Quit if TVal is not the constant opposite of FVal.
20815     if (FValIsFalse && TVal->getZExtValue() != 1)
20816       return SDValue();
20817     if (!FValIsFalse && TVal->getZExtValue() != 0)
20818       return SDValue();
20819     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20820     if (needOppositeCond)
20821       CC = X86::GetOppositeBranchCondition(CC);
20822     return SetCC.getOperand(3);
20823   }
20824   }
20825
20826   return SDValue();
20827 }
20828
20829 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20830 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20831                                   TargetLowering::DAGCombinerInfo &DCI,
20832                                   const X86Subtarget *Subtarget) {
20833   SDLoc DL(N);
20834
20835   // If the flag operand isn't dead, don't touch this CMOV.
20836   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20837     return SDValue();
20838
20839   SDValue FalseOp = N->getOperand(0);
20840   SDValue TrueOp = N->getOperand(1);
20841   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20842   SDValue Cond = N->getOperand(3);
20843
20844   if (CC == X86::COND_E || CC == X86::COND_NE) {
20845     switch (Cond.getOpcode()) {
20846     default: break;
20847     case X86ISD::BSR:
20848     case X86ISD::BSF:
20849       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20850       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20851         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20852     }
20853   }
20854
20855   SDValue Flags;
20856
20857   Flags = checkBoolTestSetCCCombine(Cond, CC);
20858   if (Flags.getNode() &&
20859       // Extra check as FCMOV only supports a subset of X86 cond.
20860       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20861     SDValue Ops[] = { FalseOp, TrueOp,
20862                       DAG.getConstant(CC, MVT::i8), Flags };
20863     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20864   }
20865
20866   // If this is a select between two integer constants, try to do some
20867   // optimizations.  Note that the operands are ordered the opposite of SELECT
20868   // operands.
20869   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20870     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20871       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20872       // larger than FalseC (the false value).
20873       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20874         CC = X86::GetOppositeBranchCondition(CC);
20875         std::swap(TrueC, FalseC);
20876         std::swap(TrueOp, FalseOp);
20877       }
20878
20879       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20880       // This is efficient for any integer data type (including i8/i16) and
20881       // shift amount.
20882       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20883         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20884                            DAG.getConstant(CC, MVT::i8), Cond);
20885
20886         // Zero extend the condition if needed.
20887         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20888
20889         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20890         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20891                            DAG.getConstant(ShAmt, MVT::i8));
20892         if (N->getNumValues() == 2)  // Dead flag value?
20893           return DCI.CombineTo(N, Cond, SDValue());
20894         return Cond;
20895       }
20896
20897       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20898       // for any integer data type, including i8/i16.
20899       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20900         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20901                            DAG.getConstant(CC, MVT::i8), Cond);
20902
20903         // Zero extend the condition if needed.
20904         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20905                            FalseC->getValueType(0), Cond);
20906         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20907                            SDValue(FalseC, 0));
20908
20909         if (N->getNumValues() == 2)  // Dead flag value?
20910           return DCI.CombineTo(N, Cond, SDValue());
20911         return Cond;
20912       }
20913
20914       // Optimize cases that will turn into an LEA instruction.  This requires
20915       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20916       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20917         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20918         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20919
20920         bool isFastMultiplier = false;
20921         if (Diff < 10) {
20922           switch ((unsigned char)Diff) {
20923           default: break;
20924           case 1:  // result = add base, cond
20925           case 2:  // result = lea base(    , cond*2)
20926           case 3:  // result = lea base(cond, cond*2)
20927           case 4:  // result = lea base(    , cond*4)
20928           case 5:  // result = lea base(cond, cond*4)
20929           case 8:  // result = lea base(    , cond*8)
20930           case 9:  // result = lea base(cond, cond*8)
20931             isFastMultiplier = true;
20932             break;
20933           }
20934         }
20935
20936         if (isFastMultiplier) {
20937           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20938           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20939                              DAG.getConstant(CC, MVT::i8), Cond);
20940           // Zero extend the condition if needed.
20941           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20942                              Cond);
20943           // Scale the condition by the difference.
20944           if (Diff != 1)
20945             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20946                                DAG.getConstant(Diff, Cond.getValueType()));
20947
20948           // Add the base if non-zero.
20949           if (FalseC->getAPIntValue() != 0)
20950             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20951                                SDValue(FalseC, 0));
20952           if (N->getNumValues() == 2)  // Dead flag value?
20953             return DCI.CombineTo(N, Cond, SDValue());
20954           return Cond;
20955         }
20956       }
20957     }
20958   }
20959
20960   // Handle these cases:
20961   //   (select (x != c), e, c) -> select (x != c), e, x),
20962   //   (select (x == c), c, e) -> select (x == c), x, e)
20963   // where the c is an integer constant, and the "select" is the combination
20964   // of CMOV and CMP.
20965   //
20966   // The rationale for this change is that the conditional-move from a constant
20967   // needs two instructions, however, conditional-move from a register needs
20968   // only one instruction.
20969   //
20970   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20971   //  some instruction-combining opportunities. This opt needs to be
20972   //  postponed as late as possible.
20973   //
20974   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20975     // the DCI.xxxx conditions are provided to postpone the optimization as
20976     // late as possible.
20977
20978     ConstantSDNode *CmpAgainst = nullptr;
20979     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20980         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20981         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20982
20983       if (CC == X86::COND_NE &&
20984           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20985         CC = X86::GetOppositeBranchCondition(CC);
20986         std::swap(TrueOp, FalseOp);
20987       }
20988
20989       if (CC == X86::COND_E &&
20990           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20991         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20992                           DAG.getConstant(CC, MVT::i8), Cond };
20993         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20994       }
20995     }
20996   }
20997
20998   return SDValue();
20999 }
21000
21001 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21002                                                 const X86Subtarget *Subtarget) {
21003   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21004   switch (IntNo) {
21005   default: return SDValue();
21006   // SSE/AVX/AVX2 blend intrinsics.
21007   case Intrinsic::x86_avx2_pblendvb:
21008   case Intrinsic::x86_avx2_pblendw:
21009   case Intrinsic::x86_avx2_pblendd_128:
21010   case Intrinsic::x86_avx2_pblendd_256:
21011     // Don't try to simplify this intrinsic if we don't have AVX2.
21012     if (!Subtarget->hasAVX2())
21013       return SDValue();
21014     // FALL-THROUGH
21015   case Intrinsic::x86_avx_blend_pd_256:
21016   case Intrinsic::x86_avx_blend_ps_256:
21017   case Intrinsic::x86_avx_blendv_pd_256:
21018   case Intrinsic::x86_avx_blendv_ps_256:
21019     // Don't try to simplify this intrinsic if we don't have AVX.
21020     if (!Subtarget->hasAVX())
21021       return SDValue();
21022     // FALL-THROUGH
21023   case Intrinsic::x86_sse41_pblendw:
21024   case Intrinsic::x86_sse41_blendpd:
21025   case Intrinsic::x86_sse41_blendps:
21026   case Intrinsic::x86_sse41_blendvps:
21027   case Intrinsic::x86_sse41_blendvpd:
21028   case Intrinsic::x86_sse41_pblendvb: {
21029     SDValue Op0 = N->getOperand(1);
21030     SDValue Op1 = N->getOperand(2);
21031     SDValue Mask = N->getOperand(3);
21032
21033     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21034     if (!Subtarget->hasSSE41())
21035       return SDValue();
21036
21037     // fold (blend A, A, Mask) -> A
21038     if (Op0 == Op1)
21039       return Op0;
21040     // fold (blend A, B, allZeros) -> A
21041     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21042       return Op0;
21043     // fold (blend A, B, allOnes) -> B
21044     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21045       return Op1;
21046     
21047     // Simplify the case where the mask is a constant i32 value.
21048     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21049       if (C->isNullValue())
21050         return Op0;
21051       if (C->isAllOnesValue())
21052         return Op1;
21053     }
21054
21055     return SDValue();
21056   }
21057
21058   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21059   case Intrinsic::x86_sse2_psrai_w:
21060   case Intrinsic::x86_sse2_psrai_d:
21061   case Intrinsic::x86_avx2_psrai_w:
21062   case Intrinsic::x86_avx2_psrai_d:
21063   case Intrinsic::x86_sse2_psra_w:
21064   case Intrinsic::x86_sse2_psra_d:
21065   case Intrinsic::x86_avx2_psra_w:
21066   case Intrinsic::x86_avx2_psra_d: {
21067     SDValue Op0 = N->getOperand(1);
21068     SDValue Op1 = N->getOperand(2);
21069     EVT VT = Op0.getValueType();
21070     assert(VT.isVector() && "Expected a vector type!");
21071
21072     if (isa<BuildVectorSDNode>(Op1))
21073       Op1 = Op1.getOperand(0);
21074
21075     if (!isa<ConstantSDNode>(Op1))
21076       return SDValue();
21077
21078     EVT SVT = VT.getVectorElementType();
21079     unsigned SVTBits = SVT.getSizeInBits();
21080
21081     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21082     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21083     uint64_t ShAmt = C.getZExtValue();
21084
21085     // Don't try to convert this shift into a ISD::SRA if the shift
21086     // count is bigger than or equal to the element size.
21087     if (ShAmt >= SVTBits)
21088       return SDValue();
21089
21090     // Trivial case: if the shift count is zero, then fold this
21091     // into the first operand.
21092     if (ShAmt == 0)
21093       return Op0;
21094
21095     // Replace this packed shift intrinsic with a target independent
21096     // shift dag node.
21097     SDValue Splat = DAG.getConstant(C, VT);
21098     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21099   }
21100   }
21101 }
21102
21103 /// PerformMulCombine - Optimize a single multiply with constant into two
21104 /// in order to implement it with two cheaper instructions, e.g.
21105 /// LEA + SHL, LEA + LEA.
21106 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21107                                  TargetLowering::DAGCombinerInfo &DCI) {
21108   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21109     return SDValue();
21110
21111   EVT VT = N->getValueType(0);
21112   if (VT != MVT::i64)
21113     return SDValue();
21114
21115   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21116   if (!C)
21117     return SDValue();
21118   uint64_t MulAmt = C->getZExtValue();
21119   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21120     return SDValue();
21121
21122   uint64_t MulAmt1 = 0;
21123   uint64_t MulAmt2 = 0;
21124   if ((MulAmt % 9) == 0) {
21125     MulAmt1 = 9;
21126     MulAmt2 = MulAmt / 9;
21127   } else if ((MulAmt % 5) == 0) {
21128     MulAmt1 = 5;
21129     MulAmt2 = MulAmt / 5;
21130   } else if ((MulAmt % 3) == 0) {
21131     MulAmt1 = 3;
21132     MulAmt2 = MulAmt / 3;
21133   }
21134   if (MulAmt2 &&
21135       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21136     SDLoc DL(N);
21137
21138     if (isPowerOf2_64(MulAmt2) &&
21139         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21140       // If second multiplifer is pow2, issue it first. We want the multiply by
21141       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21142       // is an add.
21143       std::swap(MulAmt1, MulAmt2);
21144
21145     SDValue NewMul;
21146     if (isPowerOf2_64(MulAmt1))
21147       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21148                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21149     else
21150       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21151                            DAG.getConstant(MulAmt1, VT));
21152
21153     if (isPowerOf2_64(MulAmt2))
21154       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21155                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21156     else
21157       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21158                            DAG.getConstant(MulAmt2, VT));
21159
21160     // Do not add new nodes to DAG combiner worklist.
21161     DCI.CombineTo(N, NewMul, false);
21162   }
21163   return SDValue();
21164 }
21165
21166 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21167   SDValue N0 = N->getOperand(0);
21168   SDValue N1 = N->getOperand(1);
21169   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21170   EVT VT = N0.getValueType();
21171
21172   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21173   // since the result of setcc_c is all zero's or all ones.
21174   if (VT.isInteger() && !VT.isVector() &&
21175       N1C && N0.getOpcode() == ISD::AND &&
21176       N0.getOperand(1).getOpcode() == ISD::Constant) {
21177     SDValue N00 = N0.getOperand(0);
21178     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21179         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21180           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21181          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21182       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21183       APInt ShAmt = N1C->getAPIntValue();
21184       Mask = Mask.shl(ShAmt);
21185       if (Mask != 0)
21186         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21187                            N00, DAG.getConstant(Mask, VT));
21188     }
21189   }
21190
21191   // Hardware support for vector shifts is sparse which makes us scalarize the
21192   // vector operations in many cases. Also, on sandybridge ADD is faster than
21193   // shl.
21194   // (shl V, 1) -> add V,V
21195   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21196     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21197       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21198       // We shift all of the values by one. In many cases we do not have
21199       // hardware support for this operation. This is better expressed as an ADD
21200       // of two values.
21201       if (N1SplatC->getZExtValue() == 1)
21202         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21203     }
21204
21205   return SDValue();
21206 }
21207
21208 /// \brief Returns a vector of 0s if the node in input is a vector logical
21209 /// shift by a constant amount which is known to be bigger than or equal
21210 /// to the vector element size in bits.
21211 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21212                                       const X86Subtarget *Subtarget) {
21213   EVT VT = N->getValueType(0);
21214
21215   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21216       (!Subtarget->hasInt256() ||
21217        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21218     return SDValue();
21219
21220   SDValue Amt = N->getOperand(1);
21221   SDLoc DL(N);
21222   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21223     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21224       APInt ShiftAmt = AmtSplat->getAPIntValue();
21225       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21226
21227       // SSE2/AVX2 logical shifts always return a vector of 0s
21228       // if the shift amount is bigger than or equal to
21229       // the element size. The constant shift amount will be
21230       // encoded as a 8-bit immediate.
21231       if (ShiftAmt.trunc(8).uge(MaxAmount))
21232         return getZeroVector(VT, Subtarget, DAG, DL);
21233     }
21234
21235   return SDValue();
21236 }
21237
21238 /// PerformShiftCombine - Combine shifts.
21239 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21240                                    TargetLowering::DAGCombinerInfo &DCI,
21241                                    const X86Subtarget *Subtarget) {
21242   if (N->getOpcode() == ISD::SHL) {
21243     SDValue V = PerformSHLCombine(N, DAG);
21244     if (V.getNode()) return V;
21245   }
21246
21247   if (N->getOpcode() != ISD::SRA) {
21248     // Try to fold this logical shift into a zero vector.
21249     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21250     if (V.getNode()) return V;
21251   }
21252
21253   return SDValue();
21254 }
21255
21256 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21257 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21258 // and friends.  Likewise for OR -> CMPNEQSS.
21259 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21260                             TargetLowering::DAGCombinerInfo &DCI,
21261                             const X86Subtarget *Subtarget) {
21262   unsigned opcode;
21263
21264   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21265   // we're requiring SSE2 for both.
21266   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21267     SDValue N0 = N->getOperand(0);
21268     SDValue N1 = N->getOperand(1);
21269     SDValue CMP0 = N0->getOperand(1);
21270     SDValue CMP1 = N1->getOperand(1);
21271     SDLoc DL(N);
21272
21273     // The SETCCs should both refer to the same CMP.
21274     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21275       return SDValue();
21276
21277     SDValue CMP00 = CMP0->getOperand(0);
21278     SDValue CMP01 = CMP0->getOperand(1);
21279     EVT     VT    = CMP00.getValueType();
21280
21281     if (VT == MVT::f32 || VT == MVT::f64) {
21282       bool ExpectingFlags = false;
21283       // Check for any users that want flags:
21284       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21285            !ExpectingFlags && UI != UE; ++UI)
21286         switch (UI->getOpcode()) {
21287         default:
21288         case ISD::BR_CC:
21289         case ISD::BRCOND:
21290         case ISD::SELECT:
21291           ExpectingFlags = true;
21292           break;
21293         case ISD::CopyToReg:
21294         case ISD::SIGN_EXTEND:
21295         case ISD::ZERO_EXTEND:
21296         case ISD::ANY_EXTEND:
21297           break;
21298         }
21299
21300       if (!ExpectingFlags) {
21301         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21302         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21303
21304         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21305           X86::CondCode tmp = cc0;
21306           cc0 = cc1;
21307           cc1 = tmp;
21308         }
21309
21310         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21311             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21312           // FIXME: need symbolic constants for these magic numbers.
21313           // See X86ATTInstPrinter.cpp:printSSECC().
21314           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21315           if (Subtarget->hasAVX512()) {
21316             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21317                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21318             if (N->getValueType(0) != MVT::i1)
21319               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21320                                  FSetCC);
21321             return FSetCC;
21322           }
21323           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21324                                               CMP00.getValueType(), CMP00, CMP01,
21325                                               DAG.getConstant(x86cc, MVT::i8));
21326
21327           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21328           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21329
21330           if (is64BitFP && !Subtarget->is64Bit()) {
21331             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21332             // 64-bit integer, since that's not a legal type. Since
21333             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21334             // bits, but can do this little dance to extract the lowest 32 bits
21335             // and work with those going forward.
21336             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21337                                            OnesOrZeroesF);
21338             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21339                                            Vector64);
21340             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21341                                         Vector32, DAG.getIntPtrConstant(0));
21342             IntVT = MVT::i32;
21343           }
21344
21345           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21346           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21347                                       DAG.getConstant(1, IntVT));
21348           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21349           return OneBitOfTruth;
21350         }
21351       }
21352     }
21353   }
21354   return SDValue();
21355 }
21356
21357 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21358 /// so it can be folded inside ANDNP.
21359 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21360   EVT VT = N->getValueType(0);
21361
21362   // Match direct AllOnes for 128 and 256-bit vectors
21363   if (ISD::isBuildVectorAllOnes(N))
21364     return true;
21365
21366   // Look through a bit convert.
21367   if (N->getOpcode() == ISD::BITCAST)
21368     N = N->getOperand(0).getNode();
21369
21370   // Sometimes the operand may come from a insert_subvector building a 256-bit
21371   // allones vector
21372   if (VT.is256BitVector() &&
21373       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21374     SDValue V1 = N->getOperand(0);
21375     SDValue V2 = N->getOperand(1);
21376
21377     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21378         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21379         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21380         ISD::isBuildVectorAllOnes(V2.getNode()))
21381       return true;
21382   }
21383
21384   return false;
21385 }
21386
21387 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21388 // register. In most cases we actually compare or select YMM-sized registers
21389 // and mixing the two types creates horrible code. This method optimizes
21390 // some of the transition sequences.
21391 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21392                                  TargetLowering::DAGCombinerInfo &DCI,
21393                                  const X86Subtarget *Subtarget) {
21394   EVT VT = N->getValueType(0);
21395   if (!VT.is256BitVector())
21396     return SDValue();
21397
21398   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21399           N->getOpcode() == ISD::ZERO_EXTEND ||
21400           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21401
21402   SDValue Narrow = N->getOperand(0);
21403   EVT NarrowVT = Narrow->getValueType(0);
21404   if (!NarrowVT.is128BitVector())
21405     return SDValue();
21406
21407   if (Narrow->getOpcode() != ISD::XOR &&
21408       Narrow->getOpcode() != ISD::AND &&
21409       Narrow->getOpcode() != ISD::OR)
21410     return SDValue();
21411
21412   SDValue N0  = Narrow->getOperand(0);
21413   SDValue N1  = Narrow->getOperand(1);
21414   SDLoc DL(Narrow);
21415
21416   // The Left side has to be a trunc.
21417   if (N0.getOpcode() != ISD::TRUNCATE)
21418     return SDValue();
21419
21420   // The type of the truncated inputs.
21421   EVT WideVT = N0->getOperand(0)->getValueType(0);
21422   if (WideVT != VT)
21423     return SDValue();
21424
21425   // The right side has to be a 'trunc' or a constant vector.
21426   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21427   ConstantSDNode *RHSConstSplat = nullptr;
21428   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21429     RHSConstSplat = RHSBV->getConstantSplatNode();
21430   if (!RHSTrunc && !RHSConstSplat)
21431     return SDValue();
21432
21433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21434
21435   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21436     return SDValue();
21437
21438   // Set N0 and N1 to hold the inputs to the new wide operation.
21439   N0 = N0->getOperand(0);
21440   if (RHSConstSplat) {
21441     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21442                      SDValue(RHSConstSplat, 0));
21443     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21444     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21445   } else if (RHSTrunc) {
21446     N1 = N1->getOperand(0);
21447   }
21448
21449   // Generate the wide operation.
21450   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21451   unsigned Opcode = N->getOpcode();
21452   switch (Opcode) {
21453   case ISD::ANY_EXTEND:
21454     return Op;
21455   case ISD::ZERO_EXTEND: {
21456     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21457     APInt Mask = APInt::getAllOnesValue(InBits);
21458     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21459     return DAG.getNode(ISD::AND, DL, VT,
21460                        Op, DAG.getConstant(Mask, VT));
21461   }
21462   case ISD::SIGN_EXTEND:
21463     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21464                        Op, DAG.getValueType(NarrowVT));
21465   default:
21466     llvm_unreachable("Unexpected opcode");
21467   }
21468 }
21469
21470 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21471                                  TargetLowering::DAGCombinerInfo &DCI,
21472                                  const X86Subtarget *Subtarget) {
21473   EVT VT = N->getValueType(0);
21474   if (DCI.isBeforeLegalizeOps())
21475     return SDValue();
21476
21477   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21478   if (R.getNode())
21479     return R;
21480
21481   // Create BEXTR instructions
21482   // BEXTR is ((X >> imm) & (2**size-1))
21483   if (VT == MVT::i32 || VT == MVT::i64) {
21484     SDValue N0 = N->getOperand(0);
21485     SDValue N1 = N->getOperand(1);
21486     SDLoc DL(N);
21487
21488     // Check for BEXTR.
21489     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21490         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21491       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21492       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21493       if (MaskNode && ShiftNode) {
21494         uint64_t Mask = MaskNode->getZExtValue();
21495         uint64_t Shift = ShiftNode->getZExtValue();
21496         if (isMask_64(Mask)) {
21497           uint64_t MaskSize = CountPopulation_64(Mask);
21498           if (Shift + MaskSize <= VT.getSizeInBits())
21499             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21500                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21501         }
21502       }
21503     } // BEXTR
21504
21505     return SDValue();
21506   }
21507
21508   // Want to form ANDNP nodes:
21509   // 1) In the hopes of then easily combining them with OR and AND nodes
21510   //    to form PBLEND/PSIGN.
21511   // 2) To match ANDN packed intrinsics
21512   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21513     return SDValue();
21514
21515   SDValue N0 = N->getOperand(0);
21516   SDValue N1 = N->getOperand(1);
21517   SDLoc DL(N);
21518
21519   // Check LHS for vnot
21520   if (N0.getOpcode() == ISD::XOR &&
21521       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21522       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21523     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21524
21525   // Check RHS for vnot
21526   if (N1.getOpcode() == ISD::XOR &&
21527       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21528       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21529     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21530
21531   return SDValue();
21532 }
21533
21534 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21535                                 TargetLowering::DAGCombinerInfo &DCI,
21536                                 const X86Subtarget *Subtarget) {
21537   if (DCI.isBeforeLegalizeOps())
21538     return SDValue();
21539
21540   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21541   if (R.getNode())
21542     return R;
21543
21544   SDValue N0 = N->getOperand(0);
21545   SDValue N1 = N->getOperand(1);
21546   EVT VT = N->getValueType(0);
21547
21548   // look for psign/blend
21549   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21550     if (!Subtarget->hasSSSE3() ||
21551         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21552       return SDValue();
21553
21554     // Canonicalize pandn to RHS
21555     if (N0.getOpcode() == X86ISD::ANDNP)
21556       std::swap(N0, N1);
21557     // or (and (m, y), (pandn m, x))
21558     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21559       SDValue Mask = N1.getOperand(0);
21560       SDValue X    = N1.getOperand(1);
21561       SDValue Y;
21562       if (N0.getOperand(0) == Mask)
21563         Y = N0.getOperand(1);
21564       if (N0.getOperand(1) == Mask)
21565         Y = N0.getOperand(0);
21566
21567       // Check to see if the mask appeared in both the AND and ANDNP and
21568       if (!Y.getNode())
21569         return SDValue();
21570
21571       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21572       // Look through mask bitcast.
21573       if (Mask.getOpcode() == ISD::BITCAST)
21574         Mask = Mask.getOperand(0);
21575       if (X.getOpcode() == ISD::BITCAST)
21576         X = X.getOperand(0);
21577       if (Y.getOpcode() == ISD::BITCAST)
21578         Y = Y.getOperand(0);
21579
21580       EVT MaskVT = Mask.getValueType();
21581
21582       // Validate that the Mask operand is a vector sra node.
21583       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21584       // there is no psrai.b
21585       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21586       unsigned SraAmt = ~0;
21587       if (Mask.getOpcode() == ISD::SRA) {
21588         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21589           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21590             SraAmt = AmtConst->getZExtValue();
21591       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21592         SDValue SraC = Mask.getOperand(1);
21593         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21594       }
21595       if ((SraAmt + 1) != EltBits)
21596         return SDValue();
21597
21598       SDLoc DL(N);
21599
21600       // Now we know we at least have a plendvb with the mask val.  See if
21601       // we can form a psignb/w/d.
21602       // psign = x.type == y.type == mask.type && y = sub(0, x);
21603       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21604           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21605           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21606         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21607                "Unsupported VT for PSIGN");
21608         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21609         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21610       }
21611       // PBLENDVB only available on SSE 4.1
21612       if (!Subtarget->hasSSE41())
21613         return SDValue();
21614
21615       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21616
21617       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21618       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21619       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21620       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21621       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21622     }
21623   }
21624
21625   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21626     return SDValue();
21627
21628   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21629   MachineFunction &MF = DAG.getMachineFunction();
21630   bool OptForSize = MF.getFunction()->getAttributes().
21631     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21632
21633   // SHLD/SHRD instructions have lower register pressure, but on some
21634   // platforms they have higher latency than the equivalent
21635   // series of shifts/or that would otherwise be generated.
21636   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21637   // have higher latencies and we are not optimizing for size.
21638   if (!OptForSize && Subtarget->isSHLDSlow())
21639     return SDValue();
21640
21641   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21642     std::swap(N0, N1);
21643   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21644     return SDValue();
21645   if (!N0.hasOneUse() || !N1.hasOneUse())
21646     return SDValue();
21647
21648   SDValue ShAmt0 = N0.getOperand(1);
21649   if (ShAmt0.getValueType() != MVT::i8)
21650     return SDValue();
21651   SDValue ShAmt1 = N1.getOperand(1);
21652   if (ShAmt1.getValueType() != MVT::i8)
21653     return SDValue();
21654   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21655     ShAmt0 = ShAmt0.getOperand(0);
21656   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21657     ShAmt1 = ShAmt1.getOperand(0);
21658
21659   SDLoc DL(N);
21660   unsigned Opc = X86ISD::SHLD;
21661   SDValue Op0 = N0.getOperand(0);
21662   SDValue Op1 = N1.getOperand(0);
21663   if (ShAmt0.getOpcode() == ISD::SUB) {
21664     Opc = X86ISD::SHRD;
21665     std::swap(Op0, Op1);
21666     std::swap(ShAmt0, ShAmt1);
21667   }
21668
21669   unsigned Bits = VT.getSizeInBits();
21670   if (ShAmt1.getOpcode() == ISD::SUB) {
21671     SDValue Sum = ShAmt1.getOperand(0);
21672     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21673       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21674       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21675         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21676       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21677         return DAG.getNode(Opc, DL, VT,
21678                            Op0, Op1,
21679                            DAG.getNode(ISD::TRUNCATE, DL,
21680                                        MVT::i8, ShAmt0));
21681     }
21682   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21683     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21684     if (ShAmt0C &&
21685         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21686       return DAG.getNode(Opc, DL, VT,
21687                          N0.getOperand(0), N1.getOperand(0),
21688                          DAG.getNode(ISD::TRUNCATE, DL,
21689                                        MVT::i8, ShAmt0));
21690   }
21691
21692   return SDValue();
21693 }
21694
21695 // Generate NEG and CMOV for integer abs.
21696 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21697   EVT VT = N->getValueType(0);
21698
21699   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21700   // 8-bit integer abs to NEG and CMOV.
21701   if (VT.isInteger() && VT.getSizeInBits() == 8)
21702     return SDValue();
21703
21704   SDValue N0 = N->getOperand(0);
21705   SDValue N1 = N->getOperand(1);
21706   SDLoc DL(N);
21707
21708   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21709   // and change it to SUB and CMOV.
21710   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21711       N0.getOpcode() == ISD::ADD &&
21712       N0.getOperand(1) == N1 &&
21713       N1.getOpcode() == ISD::SRA &&
21714       N1.getOperand(0) == N0.getOperand(0))
21715     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21716       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21717         // Generate SUB & CMOV.
21718         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21719                                   DAG.getConstant(0, VT), N0.getOperand(0));
21720
21721         SDValue Ops[] = { N0.getOperand(0), Neg,
21722                           DAG.getConstant(X86::COND_GE, MVT::i8),
21723                           SDValue(Neg.getNode(), 1) };
21724         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21725       }
21726   return SDValue();
21727 }
21728
21729 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21730 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21731                                  TargetLowering::DAGCombinerInfo &DCI,
21732                                  const X86Subtarget *Subtarget) {
21733   if (DCI.isBeforeLegalizeOps())
21734     return SDValue();
21735
21736   if (Subtarget->hasCMov()) {
21737     SDValue RV = performIntegerAbsCombine(N, DAG);
21738     if (RV.getNode())
21739       return RV;
21740   }
21741
21742   return SDValue();
21743 }
21744
21745 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21746 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21747                                   TargetLowering::DAGCombinerInfo &DCI,
21748                                   const X86Subtarget *Subtarget) {
21749   LoadSDNode *Ld = cast<LoadSDNode>(N);
21750   EVT RegVT = Ld->getValueType(0);
21751   EVT MemVT = Ld->getMemoryVT();
21752   SDLoc dl(Ld);
21753   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21754
21755   // On Sandybridge unaligned 256bit loads are inefficient.
21756   ISD::LoadExtType Ext = Ld->getExtensionType();
21757   unsigned Alignment = Ld->getAlignment();
21758   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21759   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21760       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21761     unsigned NumElems = RegVT.getVectorNumElements();
21762     if (NumElems < 2)
21763       return SDValue();
21764
21765     SDValue Ptr = Ld->getBasePtr();
21766     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21767
21768     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21769                                   NumElems/2);
21770     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21771                                 Ld->getPointerInfo(), Ld->isVolatile(),
21772                                 Ld->isNonTemporal(), Ld->isInvariant(),
21773                                 Alignment);
21774     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21775     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21776                                 Ld->getPointerInfo(), Ld->isVolatile(),
21777                                 Ld->isNonTemporal(), Ld->isInvariant(),
21778                                 std::min(16U, Alignment));
21779     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21780                              Load1.getValue(1),
21781                              Load2.getValue(1));
21782
21783     SDValue NewVec = DAG.getUNDEF(RegVT);
21784     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21785     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21786     return DCI.CombineTo(N, NewVec, TF, true);
21787   }
21788
21789   return SDValue();
21790 }
21791
21792 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21793 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21794                                    const X86Subtarget *Subtarget) {
21795   StoreSDNode *St = cast<StoreSDNode>(N);
21796   EVT VT = St->getValue().getValueType();
21797   EVT StVT = St->getMemoryVT();
21798   SDLoc dl(St);
21799   SDValue StoredVal = St->getOperand(1);
21800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21801
21802   // If we are saving a concatenation of two XMM registers, perform two stores.
21803   // On Sandy Bridge, 256-bit memory operations are executed by two
21804   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21805   // memory  operation.
21806   unsigned Alignment = St->getAlignment();
21807   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21808   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21809       StVT == VT && !IsAligned) {
21810     unsigned NumElems = VT.getVectorNumElements();
21811     if (NumElems < 2)
21812       return SDValue();
21813
21814     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21815     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21816
21817     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21818     SDValue Ptr0 = St->getBasePtr();
21819     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21820
21821     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21822                                 St->getPointerInfo(), St->isVolatile(),
21823                                 St->isNonTemporal(), Alignment);
21824     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21825                                 St->getPointerInfo(), St->isVolatile(),
21826                                 St->isNonTemporal(),
21827                                 std::min(16U, Alignment));
21828     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21829   }
21830
21831   // Optimize trunc store (of multiple scalars) to shuffle and store.
21832   // First, pack all of the elements in one place. Next, store to memory
21833   // in fewer chunks.
21834   if (St->isTruncatingStore() && VT.isVector()) {
21835     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21836     unsigned NumElems = VT.getVectorNumElements();
21837     assert(StVT != VT && "Cannot truncate to the same type");
21838     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21839     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21840
21841     // From, To sizes and ElemCount must be pow of two
21842     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21843     // We are going to use the original vector elt for storing.
21844     // Accumulated smaller vector elements must be a multiple of the store size.
21845     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21846
21847     unsigned SizeRatio  = FromSz / ToSz;
21848
21849     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21850
21851     // Create a type on which we perform the shuffle
21852     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21853             StVT.getScalarType(), NumElems*SizeRatio);
21854
21855     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21856
21857     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21858     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21859     for (unsigned i = 0; i != NumElems; ++i)
21860       ShuffleVec[i] = i * SizeRatio;
21861
21862     // Can't shuffle using an illegal type.
21863     if (!TLI.isTypeLegal(WideVecVT))
21864       return SDValue();
21865
21866     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21867                                          DAG.getUNDEF(WideVecVT),
21868                                          &ShuffleVec[0]);
21869     // At this point all of the data is stored at the bottom of the
21870     // register. We now need to save it to mem.
21871
21872     // Find the largest store unit
21873     MVT StoreType = MVT::i8;
21874     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21875          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21876       MVT Tp = (MVT::SimpleValueType)tp;
21877       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21878         StoreType = Tp;
21879     }
21880
21881     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21882     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21883         (64 <= NumElems * ToSz))
21884       StoreType = MVT::f64;
21885
21886     // Bitcast the original vector into a vector of store-size units
21887     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21888             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21889     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21890     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21891     SmallVector<SDValue, 8> Chains;
21892     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21893                                         TLI.getPointerTy());
21894     SDValue Ptr = St->getBasePtr();
21895
21896     // Perform one or more big stores into memory.
21897     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21898       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21899                                    StoreType, ShuffWide,
21900                                    DAG.getIntPtrConstant(i));
21901       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21902                                 St->getPointerInfo(), St->isVolatile(),
21903                                 St->isNonTemporal(), St->getAlignment());
21904       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21905       Chains.push_back(Ch);
21906     }
21907
21908     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21909   }
21910
21911   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21912   // the FP state in cases where an emms may be missing.
21913   // A preferable solution to the general problem is to figure out the right
21914   // places to insert EMMS.  This qualifies as a quick hack.
21915
21916   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21917   if (VT.getSizeInBits() != 64)
21918     return SDValue();
21919
21920   const Function *F = DAG.getMachineFunction().getFunction();
21921   bool NoImplicitFloatOps = F->getAttributes().
21922     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21923   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21924                      && Subtarget->hasSSE2();
21925   if ((VT.isVector() ||
21926        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21927       isa<LoadSDNode>(St->getValue()) &&
21928       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21929       St->getChain().hasOneUse() && !St->isVolatile()) {
21930     SDNode* LdVal = St->getValue().getNode();
21931     LoadSDNode *Ld = nullptr;
21932     int TokenFactorIndex = -1;
21933     SmallVector<SDValue, 8> Ops;
21934     SDNode* ChainVal = St->getChain().getNode();
21935     // Must be a store of a load.  We currently handle two cases:  the load
21936     // is a direct child, and it's under an intervening TokenFactor.  It is
21937     // possible to dig deeper under nested TokenFactors.
21938     if (ChainVal == LdVal)
21939       Ld = cast<LoadSDNode>(St->getChain());
21940     else if (St->getValue().hasOneUse() &&
21941              ChainVal->getOpcode() == ISD::TokenFactor) {
21942       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21943         if (ChainVal->getOperand(i).getNode() == LdVal) {
21944           TokenFactorIndex = i;
21945           Ld = cast<LoadSDNode>(St->getValue());
21946         } else
21947           Ops.push_back(ChainVal->getOperand(i));
21948       }
21949     }
21950
21951     if (!Ld || !ISD::isNormalLoad(Ld))
21952       return SDValue();
21953
21954     // If this is not the MMX case, i.e. we are just turning i64 load/store
21955     // into f64 load/store, avoid the transformation if there are multiple
21956     // uses of the loaded value.
21957     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21958       return SDValue();
21959
21960     SDLoc LdDL(Ld);
21961     SDLoc StDL(N);
21962     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21963     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21964     // pair instead.
21965     if (Subtarget->is64Bit() || F64IsLegal) {
21966       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21967       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21968                                   Ld->getPointerInfo(), Ld->isVolatile(),
21969                                   Ld->isNonTemporal(), Ld->isInvariant(),
21970                                   Ld->getAlignment());
21971       SDValue NewChain = NewLd.getValue(1);
21972       if (TokenFactorIndex != -1) {
21973         Ops.push_back(NewChain);
21974         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21975       }
21976       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21977                           St->getPointerInfo(),
21978                           St->isVolatile(), St->isNonTemporal(),
21979                           St->getAlignment());
21980     }
21981
21982     // Otherwise, lower to two pairs of 32-bit loads / stores.
21983     SDValue LoAddr = Ld->getBasePtr();
21984     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21985                                  DAG.getConstant(4, MVT::i32));
21986
21987     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21988                                Ld->getPointerInfo(),
21989                                Ld->isVolatile(), Ld->isNonTemporal(),
21990                                Ld->isInvariant(), Ld->getAlignment());
21991     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21992                                Ld->getPointerInfo().getWithOffset(4),
21993                                Ld->isVolatile(), Ld->isNonTemporal(),
21994                                Ld->isInvariant(),
21995                                MinAlign(Ld->getAlignment(), 4));
21996
21997     SDValue NewChain = LoLd.getValue(1);
21998     if (TokenFactorIndex != -1) {
21999       Ops.push_back(LoLd);
22000       Ops.push_back(HiLd);
22001       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22002     }
22003
22004     LoAddr = St->getBasePtr();
22005     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22006                          DAG.getConstant(4, MVT::i32));
22007
22008     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22009                                 St->getPointerInfo(),
22010                                 St->isVolatile(), St->isNonTemporal(),
22011                                 St->getAlignment());
22012     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22013                                 St->getPointerInfo().getWithOffset(4),
22014                                 St->isVolatile(),
22015                                 St->isNonTemporal(),
22016                                 MinAlign(St->getAlignment(), 4));
22017     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22018   }
22019   return SDValue();
22020 }
22021
22022 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22023 /// and return the operands for the horizontal operation in LHS and RHS.  A
22024 /// horizontal operation performs the binary operation on successive elements
22025 /// of its first operand, then on successive elements of its second operand,
22026 /// returning the resulting values in a vector.  For example, if
22027 ///   A = < float a0, float a1, float a2, float a3 >
22028 /// and
22029 ///   B = < float b0, float b1, float b2, float b3 >
22030 /// then the result of doing a horizontal operation on A and B is
22031 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22032 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22033 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22034 /// set to A, RHS to B, and the routine returns 'true'.
22035 /// Note that the binary operation should have the property that if one of the
22036 /// operands is UNDEF then the result is UNDEF.
22037 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22038   // Look for the following pattern: if
22039   //   A = < float a0, float a1, float a2, float a3 >
22040   //   B = < float b0, float b1, float b2, float b3 >
22041   // and
22042   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22043   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22044   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22045   // which is A horizontal-op B.
22046
22047   // At least one of the operands should be a vector shuffle.
22048   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22049       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22050     return false;
22051
22052   MVT VT = LHS.getSimpleValueType();
22053
22054   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22055          "Unsupported vector type for horizontal add/sub");
22056
22057   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22058   // operate independently on 128-bit lanes.
22059   unsigned NumElts = VT.getVectorNumElements();
22060   unsigned NumLanes = VT.getSizeInBits()/128;
22061   unsigned NumLaneElts = NumElts / NumLanes;
22062   assert((NumLaneElts % 2 == 0) &&
22063          "Vector type should have an even number of elements in each lane");
22064   unsigned HalfLaneElts = NumLaneElts/2;
22065
22066   // View LHS in the form
22067   //   LHS = VECTOR_SHUFFLE A, B, LMask
22068   // If LHS is not a shuffle then pretend it is the shuffle
22069   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22070   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22071   // type VT.
22072   SDValue A, B;
22073   SmallVector<int, 16> LMask(NumElts);
22074   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22075     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22076       A = LHS.getOperand(0);
22077     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22078       B = LHS.getOperand(1);
22079     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22080     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22081   } else {
22082     if (LHS.getOpcode() != ISD::UNDEF)
22083       A = LHS;
22084     for (unsigned i = 0; i != NumElts; ++i)
22085       LMask[i] = i;
22086   }
22087
22088   // Likewise, view RHS in the form
22089   //   RHS = VECTOR_SHUFFLE C, D, RMask
22090   SDValue C, D;
22091   SmallVector<int, 16> RMask(NumElts);
22092   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22093     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22094       C = RHS.getOperand(0);
22095     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22096       D = RHS.getOperand(1);
22097     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22098     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22099   } else {
22100     if (RHS.getOpcode() != ISD::UNDEF)
22101       C = RHS;
22102     for (unsigned i = 0; i != NumElts; ++i)
22103       RMask[i] = i;
22104   }
22105
22106   // Check that the shuffles are both shuffling the same vectors.
22107   if (!(A == C && B == D) && !(A == D && B == C))
22108     return false;
22109
22110   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22111   if (!A.getNode() && !B.getNode())
22112     return false;
22113
22114   // If A and B occur in reverse order in RHS, then "swap" them (which means
22115   // rewriting the mask).
22116   if (A != C)
22117     CommuteVectorShuffleMask(RMask, NumElts);
22118
22119   // At this point LHS and RHS are equivalent to
22120   //   LHS = VECTOR_SHUFFLE A, B, LMask
22121   //   RHS = VECTOR_SHUFFLE A, B, RMask
22122   // Check that the masks correspond to performing a horizontal operation.
22123   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22124     for (unsigned i = 0; i != NumLaneElts; ++i) {
22125       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22126
22127       // Ignore any UNDEF components.
22128       if (LIdx < 0 || RIdx < 0 ||
22129           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22130           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22131         continue;
22132
22133       // Check that successive elements are being operated on.  If not, this is
22134       // not a horizontal operation.
22135       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22136       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22137       if (!(LIdx == Index && RIdx == Index + 1) &&
22138           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22139         return false;
22140     }
22141   }
22142
22143   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22144   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22145   return true;
22146 }
22147
22148 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22149 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22150                                   const X86Subtarget *Subtarget) {
22151   EVT VT = N->getValueType(0);
22152   SDValue LHS = N->getOperand(0);
22153   SDValue RHS = N->getOperand(1);
22154
22155   // Try to synthesize horizontal adds from adds of shuffles.
22156   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22157        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22158       isHorizontalBinOp(LHS, RHS, true))
22159     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22160   return SDValue();
22161 }
22162
22163 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22164 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22165                                   const X86Subtarget *Subtarget) {
22166   EVT VT = N->getValueType(0);
22167   SDValue LHS = N->getOperand(0);
22168   SDValue RHS = N->getOperand(1);
22169
22170   // Try to synthesize horizontal subs from subs of shuffles.
22171   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22172        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22173       isHorizontalBinOp(LHS, RHS, false))
22174     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22175   return SDValue();
22176 }
22177
22178 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22179 /// X86ISD::FXOR nodes.
22180 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22181   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22182   // F[X]OR(0.0, x) -> x
22183   // F[X]OR(x, 0.0) -> x
22184   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22185     if (C->getValueAPF().isPosZero())
22186       return N->getOperand(1);
22187   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22188     if (C->getValueAPF().isPosZero())
22189       return N->getOperand(0);
22190   return SDValue();
22191 }
22192
22193 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22194 /// X86ISD::FMAX nodes.
22195 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22196   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22197
22198   // Only perform optimizations if UnsafeMath is used.
22199   if (!DAG.getTarget().Options.UnsafeFPMath)
22200     return SDValue();
22201
22202   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22203   // into FMINC and FMAXC, which are Commutative operations.
22204   unsigned NewOp = 0;
22205   switch (N->getOpcode()) {
22206     default: llvm_unreachable("unknown opcode");
22207     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22208     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22209   }
22210
22211   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22212                      N->getOperand(0), N->getOperand(1));
22213 }
22214
22215 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22216 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22217   // FAND(0.0, x) -> 0.0
22218   // FAND(x, 0.0) -> 0.0
22219   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22220     if (C->getValueAPF().isPosZero())
22221       return N->getOperand(0);
22222   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22223     if (C->getValueAPF().isPosZero())
22224       return N->getOperand(1);
22225   return SDValue();
22226 }
22227
22228 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22229 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22230   // FANDN(x, 0.0) -> 0.0
22231   // FANDN(0.0, x) -> x
22232   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22233     if (C->getValueAPF().isPosZero())
22234       return N->getOperand(1);
22235   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22236     if (C->getValueAPF().isPosZero())
22237       return N->getOperand(1);
22238   return SDValue();
22239 }
22240
22241 static SDValue PerformBTCombine(SDNode *N,
22242                                 SelectionDAG &DAG,
22243                                 TargetLowering::DAGCombinerInfo &DCI) {
22244   // BT ignores high bits in the bit index operand.
22245   SDValue Op1 = N->getOperand(1);
22246   if (Op1.hasOneUse()) {
22247     unsigned BitWidth = Op1.getValueSizeInBits();
22248     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22249     APInt KnownZero, KnownOne;
22250     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22251                                           !DCI.isBeforeLegalizeOps());
22252     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22253     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22254         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22255       DCI.CommitTargetLoweringOpt(TLO);
22256   }
22257   return SDValue();
22258 }
22259
22260 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22261   SDValue Op = N->getOperand(0);
22262   if (Op.getOpcode() == ISD::BITCAST)
22263     Op = Op.getOperand(0);
22264   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22265   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22266       VT.getVectorElementType().getSizeInBits() ==
22267       OpVT.getVectorElementType().getSizeInBits()) {
22268     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22269   }
22270   return SDValue();
22271 }
22272
22273 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22274                                                const X86Subtarget *Subtarget) {
22275   EVT VT = N->getValueType(0);
22276   if (!VT.isVector())
22277     return SDValue();
22278
22279   SDValue N0 = N->getOperand(0);
22280   SDValue N1 = N->getOperand(1);
22281   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22282   SDLoc dl(N);
22283
22284   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22285   // both SSE and AVX2 since there is no sign-extended shift right
22286   // operation on a vector with 64-bit elements.
22287   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22288   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22289   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22290       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22291     SDValue N00 = N0.getOperand(0);
22292
22293     // EXTLOAD has a better solution on AVX2,
22294     // it may be replaced with X86ISD::VSEXT node.
22295     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22296       if (!ISD::isNormalLoad(N00.getNode()))
22297         return SDValue();
22298
22299     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22300         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22301                                   N00, N1);
22302       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22303     }
22304   }
22305   return SDValue();
22306 }
22307
22308 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22309                                   TargetLowering::DAGCombinerInfo &DCI,
22310                                   const X86Subtarget *Subtarget) {
22311   if (!DCI.isBeforeLegalizeOps())
22312     return SDValue();
22313
22314   if (!Subtarget->hasFp256())
22315     return SDValue();
22316
22317   EVT VT = N->getValueType(0);
22318   if (VT.isVector() && VT.getSizeInBits() == 256) {
22319     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22320     if (R.getNode())
22321       return R;
22322   }
22323
22324   return SDValue();
22325 }
22326
22327 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22328                                  const X86Subtarget* Subtarget) {
22329   SDLoc dl(N);
22330   EVT VT = N->getValueType(0);
22331
22332   // Let legalize expand this if it isn't a legal type yet.
22333   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22334     return SDValue();
22335
22336   EVT ScalarVT = VT.getScalarType();
22337   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22338       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22339     return SDValue();
22340
22341   SDValue A = N->getOperand(0);
22342   SDValue B = N->getOperand(1);
22343   SDValue C = N->getOperand(2);
22344
22345   bool NegA = (A.getOpcode() == ISD::FNEG);
22346   bool NegB = (B.getOpcode() == ISD::FNEG);
22347   bool NegC = (C.getOpcode() == ISD::FNEG);
22348
22349   // Negative multiplication when NegA xor NegB
22350   bool NegMul = (NegA != NegB);
22351   if (NegA)
22352     A = A.getOperand(0);
22353   if (NegB)
22354     B = B.getOperand(0);
22355   if (NegC)
22356     C = C.getOperand(0);
22357
22358   unsigned Opcode;
22359   if (!NegMul)
22360     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22361   else
22362     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22363
22364   return DAG.getNode(Opcode, dl, VT, A, B, C);
22365 }
22366
22367 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22368                                   TargetLowering::DAGCombinerInfo &DCI,
22369                                   const X86Subtarget *Subtarget) {
22370   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22371   //           (and (i32 x86isd::setcc_carry), 1)
22372   // This eliminates the zext. This transformation is necessary because
22373   // ISD::SETCC is always legalized to i8.
22374   SDLoc dl(N);
22375   SDValue N0 = N->getOperand(0);
22376   EVT VT = N->getValueType(0);
22377
22378   if (N0.getOpcode() == ISD::AND &&
22379       N0.hasOneUse() &&
22380       N0.getOperand(0).hasOneUse()) {
22381     SDValue N00 = N0.getOperand(0);
22382     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22383       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22384       if (!C || C->getZExtValue() != 1)
22385         return SDValue();
22386       return DAG.getNode(ISD::AND, dl, VT,
22387                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22388                                      N00.getOperand(0), N00.getOperand(1)),
22389                          DAG.getConstant(1, VT));
22390     }
22391   }
22392
22393   if (N0.getOpcode() == ISD::TRUNCATE &&
22394       N0.hasOneUse() &&
22395       N0.getOperand(0).hasOneUse()) {
22396     SDValue N00 = N0.getOperand(0);
22397     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22398       return DAG.getNode(ISD::AND, dl, VT,
22399                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22400                                      N00.getOperand(0), N00.getOperand(1)),
22401                          DAG.getConstant(1, VT));
22402     }
22403   }
22404   if (VT.is256BitVector()) {
22405     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22406     if (R.getNode())
22407       return R;
22408   }
22409
22410   return SDValue();
22411 }
22412
22413 // Optimize x == -y --> x+y == 0
22414 //          x != -y --> x+y != 0
22415 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22416                                       const X86Subtarget* Subtarget) {
22417   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22418   SDValue LHS = N->getOperand(0);
22419   SDValue RHS = N->getOperand(1);
22420   EVT VT = N->getValueType(0);
22421   SDLoc DL(N);
22422
22423   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22424     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22425       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22426         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22427                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22428         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22429                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22430       }
22431   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22432     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22433       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22434         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22435                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22436         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22437                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22438       }
22439
22440   if (VT.getScalarType() == MVT::i1) {
22441     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22442       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22443     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22444     if (!IsSEXT0 && !IsVZero0)
22445       return SDValue();
22446     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22447       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22448     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22449
22450     if (!IsSEXT1 && !IsVZero1)
22451       return SDValue();
22452
22453     if (IsSEXT0 && IsVZero1) {
22454       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22455       if (CC == ISD::SETEQ)
22456         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22457       return LHS.getOperand(0);
22458     }
22459     if (IsSEXT1 && IsVZero0) {
22460       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22461       if (CC == ISD::SETEQ)
22462         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22463       return RHS.getOperand(0);
22464     }
22465   }
22466
22467   return SDValue();
22468 }
22469
22470 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22471                                       const X86Subtarget *Subtarget) {
22472   SDLoc dl(N);
22473   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22474   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22475          "X86insertps is only defined for v4x32");
22476
22477   SDValue Ld = N->getOperand(1);
22478   if (MayFoldLoad(Ld)) {
22479     // Extract the countS bits from the immediate so we can get the proper
22480     // address when narrowing the vector load to a specific element.
22481     // When the second source op is a memory address, interps doesn't use
22482     // countS and just gets an f32 from that address.
22483     unsigned DestIndex =
22484         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22485     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22486   } else
22487     return SDValue();
22488
22489   // Create this as a scalar to vector to match the instruction pattern.
22490   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22491   // countS bits are ignored when loading from memory on insertps, which
22492   // means we don't need to explicitly set them to 0.
22493   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22494                      LoadScalarToVector, N->getOperand(2));
22495 }
22496
22497 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22498 // as "sbb reg,reg", since it can be extended without zext and produces
22499 // an all-ones bit which is more useful than 0/1 in some cases.
22500 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22501                                MVT VT) {
22502   if (VT == MVT::i8)
22503     return DAG.getNode(ISD::AND, DL, VT,
22504                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22505                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22506                        DAG.getConstant(1, VT));
22507   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22508   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22509                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22510                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22511 }
22512
22513 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22514 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22515                                    TargetLowering::DAGCombinerInfo &DCI,
22516                                    const X86Subtarget *Subtarget) {
22517   SDLoc DL(N);
22518   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22519   SDValue EFLAGS = N->getOperand(1);
22520
22521   if (CC == X86::COND_A) {
22522     // Try to convert COND_A into COND_B in an attempt to facilitate
22523     // materializing "setb reg".
22524     //
22525     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22526     // cannot take an immediate as its first operand.
22527     //
22528     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22529         EFLAGS.getValueType().isInteger() &&
22530         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22531       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22532                                    EFLAGS.getNode()->getVTList(),
22533                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22534       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22535       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22536     }
22537   }
22538
22539   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22540   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22541   // cases.
22542   if (CC == X86::COND_B)
22543     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22544
22545   SDValue Flags;
22546
22547   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22548   if (Flags.getNode()) {
22549     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22550     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22551   }
22552
22553   return SDValue();
22554 }
22555
22556 // Optimize branch condition evaluation.
22557 //
22558 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22559                                     TargetLowering::DAGCombinerInfo &DCI,
22560                                     const X86Subtarget *Subtarget) {
22561   SDLoc DL(N);
22562   SDValue Chain = N->getOperand(0);
22563   SDValue Dest = N->getOperand(1);
22564   SDValue EFLAGS = N->getOperand(3);
22565   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22566
22567   SDValue Flags;
22568
22569   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22570   if (Flags.getNode()) {
22571     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22572     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22573                        Flags);
22574   }
22575
22576   return SDValue();
22577 }
22578
22579 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22580                                                          SelectionDAG &DAG) {
22581   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22582   // optimize away operation when it's from a constant.
22583   //
22584   // The general transformation is:
22585   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22586   //       AND(VECTOR_CMP(x,y), constant2)
22587   //    constant2 = UNARYOP(constant)
22588
22589   // Early exit if this isn't a vector operation, the operand of the
22590   // unary operation isn't a bitwise AND, or if the sizes of the operations
22591   // aren't the same.
22592   EVT VT = N->getValueType(0);
22593   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22594       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22595       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22596     return SDValue();
22597
22598   // Now check that the other operand of the AND is a constant. We could
22599   // make the transformation for non-constant splats as well, but it's unclear
22600   // that would be a benefit as it would not eliminate any operations, just
22601   // perform one more step in scalar code before moving to the vector unit.
22602   if (BuildVectorSDNode *BV =
22603           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22604     // Bail out if the vector isn't a constant.
22605     if (!BV->isConstant())
22606       return SDValue();
22607
22608     // Everything checks out. Build up the new and improved node.
22609     SDLoc DL(N);
22610     EVT IntVT = BV->getValueType(0);
22611     // Create a new constant of the appropriate type for the transformed
22612     // DAG.
22613     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22614     // The AND node needs bitcasts to/from an integer vector type around it.
22615     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22616     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22617                                  N->getOperand(0)->getOperand(0), MaskConst);
22618     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22619     return Res;
22620   }
22621
22622   return SDValue();
22623 }
22624
22625 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22626                                         const X86TargetLowering *XTLI) {
22627   // First try to optimize away the conversion entirely when it's
22628   // conditionally from a constant. Vectors only.
22629   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22630   if (Res != SDValue())
22631     return Res;
22632
22633   // Now move on to more general possibilities.
22634   SDValue Op0 = N->getOperand(0);
22635   EVT InVT = Op0->getValueType(0);
22636
22637   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22638   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22639     SDLoc dl(N);
22640     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22641     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22642     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22643   }
22644
22645   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22646   // a 32-bit target where SSE doesn't support i64->FP operations.
22647   if (Op0.getOpcode() == ISD::LOAD) {
22648     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22649     EVT VT = Ld->getValueType(0);
22650     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22651         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22652         !XTLI->getSubtarget()->is64Bit() &&
22653         VT == MVT::i64) {
22654       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22655                                           Ld->getChain(), Op0, DAG);
22656       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22657       return FILDChain;
22658     }
22659   }
22660   return SDValue();
22661 }
22662
22663 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22664 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22665                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22666   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22667   // the result is either zero or one (depending on the input carry bit).
22668   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22669   if (X86::isZeroNode(N->getOperand(0)) &&
22670       X86::isZeroNode(N->getOperand(1)) &&
22671       // We don't have a good way to replace an EFLAGS use, so only do this when
22672       // dead right now.
22673       SDValue(N, 1).use_empty()) {
22674     SDLoc DL(N);
22675     EVT VT = N->getValueType(0);
22676     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22677     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22678                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22679                                            DAG.getConstant(X86::COND_B,MVT::i8),
22680                                            N->getOperand(2)),
22681                                DAG.getConstant(1, VT));
22682     return DCI.CombineTo(N, Res1, CarryOut);
22683   }
22684
22685   return SDValue();
22686 }
22687
22688 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22689 //      (add Y, (setne X, 0)) -> sbb -1, Y
22690 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22691 //      (sub (setne X, 0), Y) -> adc -1, Y
22692 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22693   SDLoc DL(N);
22694
22695   // Look through ZExts.
22696   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22697   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22698     return SDValue();
22699
22700   SDValue SetCC = Ext.getOperand(0);
22701   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22702     return SDValue();
22703
22704   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22705   if (CC != X86::COND_E && CC != X86::COND_NE)
22706     return SDValue();
22707
22708   SDValue Cmp = SetCC.getOperand(1);
22709   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22710       !X86::isZeroNode(Cmp.getOperand(1)) ||
22711       !Cmp.getOperand(0).getValueType().isInteger())
22712     return SDValue();
22713
22714   SDValue CmpOp0 = Cmp.getOperand(0);
22715   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22716                                DAG.getConstant(1, CmpOp0.getValueType()));
22717
22718   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22719   if (CC == X86::COND_NE)
22720     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22721                        DL, OtherVal.getValueType(), OtherVal,
22722                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22723   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22724                      DL, OtherVal.getValueType(), OtherVal,
22725                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22726 }
22727
22728 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22729 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22730                                  const X86Subtarget *Subtarget) {
22731   EVT VT = N->getValueType(0);
22732   SDValue Op0 = N->getOperand(0);
22733   SDValue Op1 = N->getOperand(1);
22734
22735   // Try to synthesize horizontal adds from adds of shuffles.
22736   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22737        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22738       isHorizontalBinOp(Op0, Op1, true))
22739     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22740
22741   return OptimizeConditionalInDecrement(N, DAG);
22742 }
22743
22744 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22745                                  const X86Subtarget *Subtarget) {
22746   SDValue Op0 = N->getOperand(0);
22747   SDValue Op1 = N->getOperand(1);
22748
22749   // X86 can't encode an immediate LHS of a sub. See if we can push the
22750   // negation into a preceding instruction.
22751   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22752     // If the RHS of the sub is a XOR with one use and a constant, invert the
22753     // immediate. Then add one to the LHS of the sub so we can turn
22754     // X-Y -> X+~Y+1, saving one register.
22755     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22756         isa<ConstantSDNode>(Op1.getOperand(1))) {
22757       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22758       EVT VT = Op0.getValueType();
22759       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22760                                    Op1.getOperand(0),
22761                                    DAG.getConstant(~XorC, VT));
22762       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22763                          DAG.getConstant(C->getAPIntValue()+1, VT));
22764     }
22765   }
22766
22767   // Try to synthesize horizontal adds from adds of shuffles.
22768   EVT VT = N->getValueType(0);
22769   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22770        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22771       isHorizontalBinOp(Op0, Op1, true))
22772     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22773
22774   return OptimizeConditionalInDecrement(N, DAG);
22775 }
22776
22777 /// performVZEXTCombine - Performs build vector combines
22778 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22779                                         TargetLowering::DAGCombinerInfo &DCI,
22780                                         const X86Subtarget *Subtarget) {
22781   // (vzext (bitcast (vzext (x)) -> (vzext x)
22782   SDValue In = N->getOperand(0);
22783   while (In.getOpcode() == ISD::BITCAST)
22784     In = In.getOperand(0);
22785
22786   if (In.getOpcode() != X86ISD::VZEXT)
22787     return SDValue();
22788
22789   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22790                      In.getOperand(0));
22791 }
22792
22793 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22794                                              DAGCombinerInfo &DCI) const {
22795   SelectionDAG &DAG = DCI.DAG;
22796   switch (N->getOpcode()) {
22797   default: break;
22798   case ISD::EXTRACT_VECTOR_ELT:
22799     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22800   case ISD::VSELECT:
22801   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22802   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22803   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22804   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22805   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22806   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22807   case ISD::SHL:
22808   case ISD::SRA:
22809   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22810   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22811   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22812   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22813   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22814   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22815   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22816   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22817   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22818   case X86ISD::FXOR:
22819   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22820   case X86ISD::FMIN:
22821   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22822   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22823   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22824   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22825   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22826   case ISD::ANY_EXTEND:
22827   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22828   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22829   case ISD::SIGN_EXTEND_INREG:
22830     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22831   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22832   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22833   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22834   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22835   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22836   case X86ISD::SHUFP:       // Handle all target specific shuffles
22837   case X86ISD::PALIGNR:
22838   case X86ISD::UNPCKH:
22839   case X86ISD::UNPCKL:
22840   case X86ISD::MOVHLPS:
22841   case X86ISD::MOVLHPS:
22842   case X86ISD::PSHUFB:
22843   case X86ISD::PSHUFD:
22844   case X86ISD::PSHUFHW:
22845   case X86ISD::PSHUFLW:
22846   case X86ISD::MOVSS:
22847   case X86ISD::MOVSD:
22848   case X86ISD::VPERMILP:
22849   case X86ISD::VPERM2X128:
22850   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22851   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22852   case ISD::INTRINSIC_WO_CHAIN:
22853     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22854   case X86ISD::INSERTPS:
22855     return PerformINSERTPSCombine(N, DAG, Subtarget);
22856   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22857   }
22858
22859   return SDValue();
22860 }
22861
22862 /// isTypeDesirableForOp - Return true if the target has native support for
22863 /// the specified value type and it is 'desirable' to use the type for the
22864 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22865 /// instruction encodings are longer and some i16 instructions are slow.
22866 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22867   if (!isTypeLegal(VT))
22868     return false;
22869   if (VT != MVT::i16)
22870     return true;
22871
22872   switch (Opc) {
22873   default:
22874     return true;
22875   case ISD::LOAD:
22876   case ISD::SIGN_EXTEND:
22877   case ISD::ZERO_EXTEND:
22878   case ISD::ANY_EXTEND:
22879   case ISD::SHL:
22880   case ISD::SRL:
22881   case ISD::SUB:
22882   case ISD::ADD:
22883   case ISD::MUL:
22884   case ISD::AND:
22885   case ISD::OR:
22886   case ISD::XOR:
22887     return false;
22888   }
22889 }
22890
22891 /// IsDesirableToPromoteOp - This method query the target whether it is
22892 /// beneficial for dag combiner to promote the specified node. If true, it
22893 /// should return the desired promotion type by reference.
22894 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22895   EVT VT = Op.getValueType();
22896   if (VT != MVT::i16)
22897     return false;
22898
22899   bool Promote = false;
22900   bool Commute = false;
22901   switch (Op.getOpcode()) {
22902   default: break;
22903   case ISD::LOAD: {
22904     LoadSDNode *LD = cast<LoadSDNode>(Op);
22905     // If the non-extending load has a single use and it's not live out, then it
22906     // might be folded.
22907     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22908                                                      Op.hasOneUse()*/) {
22909       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22910              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22911         // The only case where we'd want to promote LOAD (rather then it being
22912         // promoted as an operand is when it's only use is liveout.
22913         if (UI->getOpcode() != ISD::CopyToReg)
22914           return false;
22915       }
22916     }
22917     Promote = true;
22918     break;
22919   }
22920   case ISD::SIGN_EXTEND:
22921   case ISD::ZERO_EXTEND:
22922   case ISD::ANY_EXTEND:
22923     Promote = true;
22924     break;
22925   case ISD::SHL:
22926   case ISD::SRL: {
22927     SDValue N0 = Op.getOperand(0);
22928     // Look out for (store (shl (load), x)).
22929     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22930       return false;
22931     Promote = true;
22932     break;
22933   }
22934   case ISD::ADD:
22935   case ISD::MUL:
22936   case ISD::AND:
22937   case ISD::OR:
22938   case ISD::XOR:
22939     Commute = true;
22940     // fallthrough
22941   case ISD::SUB: {
22942     SDValue N0 = Op.getOperand(0);
22943     SDValue N1 = Op.getOperand(1);
22944     if (!Commute && MayFoldLoad(N1))
22945       return false;
22946     // Avoid disabling potential load folding opportunities.
22947     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22948       return false;
22949     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22950       return false;
22951     Promote = true;
22952   }
22953   }
22954
22955   PVT = MVT::i32;
22956   return Promote;
22957 }
22958
22959 //===----------------------------------------------------------------------===//
22960 //                           X86 Inline Assembly Support
22961 //===----------------------------------------------------------------------===//
22962
22963 namespace {
22964   // Helper to match a string separated by whitespace.
22965   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22966     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22967
22968     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22969       StringRef piece(*args[i]);
22970       if (!s.startswith(piece)) // Check if the piece matches.
22971         return false;
22972
22973       s = s.substr(piece.size());
22974       StringRef::size_type pos = s.find_first_not_of(" \t");
22975       if (pos == 0) // We matched a prefix.
22976         return false;
22977
22978       s = s.substr(pos);
22979     }
22980
22981     return s.empty();
22982   }
22983   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22984 }
22985
22986 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22987
22988   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22989     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22990         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22991         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22992
22993       if (AsmPieces.size() == 3)
22994         return true;
22995       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22996         return true;
22997     }
22998   }
22999   return false;
23000 }
23001
23002 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23003   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23004
23005   std::string AsmStr = IA->getAsmString();
23006
23007   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23008   if (!Ty || Ty->getBitWidth() % 16 != 0)
23009     return false;
23010
23011   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23012   SmallVector<StringRef, 4> AsmPieces;
23013   SplitString(AsmStr, AsmPieces, ";\n");
23014
23015   switch (AsmPieces.size()) {
23016   default: return false;
23017   case 1:
23018     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23019     // we will turn this bswap into something that will be lowered to logical
23020     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23021     // lower so don't worry about this.
23022     // bswap $0
23023     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23024         matchAsm(AsmPieces[0], "bswapl", "$0") ||
23025         matchAsm(AsmPieces[0], "bswapq", "$0") ||
23026         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23027         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23028         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23029       // No need to check constraints, nothing other than the equivalent of
23030       // "=r,0" would be valid here.
23031       return IntrinsicLowering::LowerToByteSwap(CI);
23032     }
23033
23034     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23035     if (CI->getType()->isIntegerTy(16) &&
23036         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23037         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23038          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23039       AsmPieces.clear();
23040       const std::string &ConstraintsStr = IA->getConstraintString();
23041       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23042       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23043       if (clobbersFlagRegisters(AsmPieces))
23044         return IntrinsicLowering::LowerToByteSwap(CI);
23045     }
23046     break;
23047   case 3:
23048     if (CI->getType()->isIntegerTy(32) &&
23049         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23050         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23051         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23052         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23053       AsmPieces.clear();
23054       const std::string &ConstraintsStr = IA->getConstraintString();
23055       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23056       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23057       if (clobbersFlagRegisters(AsmPieces))
23058         return IntrinsicLowering::LowerToByteSwap(CI);
23059     }
23060
23061     if (CI->getType()->isIntegerTy(64)) {
23062       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23063       if (Constraints.size() >= 2 &&
23064           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23065           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23066         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23067         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23068             matchAsm(AsmPieces[1], "bswap", "%edx") &&
23069             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23070           return IntrinsicLowering::LowerToByteSwap(CI);
23071       }
23072     }
23073     break;
23074   }
23075   return false;
23076 }
23077
23078 /// getConstraintType - Given a constraint letter, return the type of
23079 /// constraint it is for this target.
23080 X86TargetLowering::ConstraintType
23081 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23082   if (Constraint.size() == 1) {
23083     switch (Constraint[0]) {
23084     case 'R':
23085     case 'q':
23086     case 'Q':
23087     case 'f':
23088     case 't':
23089     case 'u':
23090     case 'y':
23091     case 'x':
23092     case 'Y':
23093     case 'l':
23094       return C_RegisterClass;
23095     case 'a':
23096     case 'b':
23097     case 'c':
23098     case 'd':
23099     case 'S':
23100     case 'D':
23101     case 'A':
23102       return C_Register;
23103     case 'I':
23104     case 'J':
23105     case 'K':
23106     case 'L':
23107     case 'M':
23108     case 'N':
23109     case 'G':
23110     case 'C':
23111     case 'e':
23112     case 'Z':
23113       return C_Other;
23114     default:
23115       break;
23116     }
23117   }
23118   return TargetLowering::getConstraintType(Constraint);
23119 }
23120
23121 /// Examine constraint type and operand type and determine a weight value.
23122 /// This object must already have been set up with the operand type
23123 /// and the current alternative constraint selected.
23124 TargetLowering::ConstraintWeight
23125   X86TargetLowering::getSingleConstraintMatchWeight(
23126     AsmOperandInfo &info, const char *constraint) const {
23127   ConstraintWeight weight = CW_Invalid;
23128   Value *CallOperandVal = info.CallOperandVal;
23129     // If we don't have a value, we can't do a match,
23130     // but allow it at the lowest weight.
23131   if (!CallOperandVal)
23132     return CW_Default;
23133   Type *type = CallOperandVal->getType();
23134   // Look at the constraint type.
23135   switch (*constraint) {
23136   default:
23137     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23138   case 'R':
23139   case 'q':
23140   case 'Q':
23141   case 'a':
23142   case 'b':
23143   case 'c':
23144   case 'd':
23145   case 'S':
23146   case 'D':
23147   case 'A':
23148     if (CallOperandVal->getType()->isIntegerTy())
23149       weight = CW_SpecificReg;
23150     break;
23151   case 'f':
23152   case 't':
23153   case 'u':
23154     if (type->isFloatingPointTy())
23155       weight = CW_SpecificReg;
23156     break;
23157   case 'y':
23158     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23159       weight = CW_SpecificReg;
23160     break;
23161   case 'x':
23162   case 'Y':
23163     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23164         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23165       weight = CW_Register;
23166     break;
23167   case 'I':
23168     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23169       if (C->getZExtValue() <= 31)
23170         weight = CW_Constant;
23171     }
23172     break;
23173   case 'J':
23174     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23175       if (C->getZExtValue() <= 63)
23176         weight = CW_Constant;
23177     }
23178     break;
23179   case 'K':
23180     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23181       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23182         weight = CW_Constant;
23183     }
23184     break;
23185   case 'L':
23186     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23187       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23188         weight = CW_Constant;
23189     }
23190     break;
23191   case 'M':
23192     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23193       if (C->getZExtValue() <= 3)
23194         weight = CW_Constant;
23195     }
23196     break;
23197   case 'N':
23198     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23199       if (C->getZExtValue() <= 0xff)
23200         weight = CW_Constant;
23201     }
23202     break;
23203   case 'G':
23204   case 'C':
23205     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23206       weight = CW_Constant;
23207     }
23208     break;
23209   case 'e':
23210     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23211       if ((C->getSExtValue() >= -0x80000000LL) &&
23212           (C->getSExtValue() <= 0x7fffffffLL))
23213         weight = CW_Constant;
23214     }
23215     break;
23216   case 'Z':
23217     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23218       if (C->getZExtValue() <= 0xffffffff)
23219         weight = CW_Constant;
23220     }
23221     break;
23222   }
23223   return weight;
23224 }
23225
23226 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23227 /// with another that has more specific requirements based on the type of the
23228 /// corresponding operand.
23229 const char *X86TargetLowering::
23230 LowerXConstraint(EVT ConstraintVT) const {
23231   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23232   // 'f' like normal targets.
23233   if (ConstraintVT.isFloatingPoint()) {
23234     if (Subtarget->hasSSE2())
23235       return "Y";
23236     if (Subtarget->hasSSE1())
23237       return "x";
23238   }
23239
23240   return TargetLowering::LowerXConstraint(ConstraintVT);
23241 }
23242
23243 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23244 /// vector.  If it is invalid, don't add anything to Ops.
23245 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23246                                                      std::string &Constraint,
23247                                                      std::vector<SDValue>&Ops,
23248                                                      SelectionDAG &DAG) const {
23249   SDValue Result;
23250
23251   // Only support length 1 constraints for now.
23252   if (Constraint.length() > 1) return;
23253
23254   char ConstraintLetter = Constraint[0];
23255   switch (ConstraintLetter) {
23256   default: break;
23257   case 'I':
23258     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23259       if (C->getZExtValue() <= 31) {
23260         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23261         break;
23262       }
23263     }
23264     return;
23265   case 'J':
23266     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23267       if (C->getZExtValue() <= 63) {
23268         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23269         break;
23270       }
23271     }
23272     return;
23273   case 'K':
23274     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23275       if (isInt<8>(C->getSExtValue())) {
23276         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23277         break;
23278       }
23279     }
23280     return;
23281   case 'N':
23282     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23283       if (C->getZExtValue() <= 255) {
23284         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23285         break;
23286       }
23287     }
23288     return;
23289   case 'e': {
23290     // 32-bit signed value
23291     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23292       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23293                                            C->getSExtValue())) {
23294         // Widen to 64 bits here to get it sign extended.
23295         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23296         break;
23297       }
23298     // FIXME gcc accepts some relocatable values here too, but only in certain
23299     // memory models; it's complicated.
23300     }
23301     return;
23302   }
23303   case 'Z': {
23304     // 32-bit unsigned value
23305     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23306       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23307                                            C->getZExtValue())) {
23308         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23309         break;
23310       }
23311     }
23312     // FIXME gcc accepts some relocatable values here too, but only in certain
23313     // memory models; it's complicated.
23314     return;
23315   }
23316   case 'i': {
23317     // Literal immediates are always ok.
23318     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23319       // Widen to 64 bits here to get it sign extended.
23320       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23321       break;
23322     }
23323
23324     // In any sort of PIC mode addresses need to be computed at runtime by
23325     // adding in a register or some sort of table lookup.  These can't
23326     // be used as immediates.
23327     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23328       return;
23329
23330     // If we are in non-pic codegen mode, we allow the address of a global (with
23331     // an optional displacement) to be used with 'i'.
23332     GlobalAddressSDNode *GA = nullptr;
23333     int64_t Offset = 0;
23334
23335     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23336     while (1) {
23337       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23338         Offset += GA->getOffset();
23339         break;
23340       } else if (Op.getOpcode() == ISD::ADD) {
23341         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23342           Offset += C->getZExtValue();
23343           Op = Op.getOperand(0);
23344           continue;
23345         }
23346       } else if (Op.getOpcode() == ISD::SUB) {
23347         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23348           Offset += -C->getZExtValue();
23349           Op = Op.getOperand(0);
23350           continue;
23351         }
23352       }
23353
23354       // Otherwise, this isn't something we can handle, reject it.
23355       return;
23356     }
23357
23358     const GlobalValue *GV = GA->getGlobal();
23359     // If we require an extra load to get this address, as in PIC mode, we
23360     // can't accept it.
23361     if (isGlobalStubReference(
23362             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23363       return;
23364
23365     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23366                                         GA->getValueType(0), Offset);
23367     break;
23368   }
23369   }
23370
23371   if (Result.getNode()) {
23372     Ops.push_back(Result);
23373     return;
23374   }
23375   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23376 }
23377
23378 std::pair<unsigned, const TargetRegisterClass*>
23379 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23380                                                 MVT VT) const {
23381   // First, see if this is a constraint that directly corresponds to an LLVM
23382   // register class.
23383   if (Constraint.size() == 1) {
23384     // GCC Constraint Letters
23385     switch (Constraint[0]) {
23386     default: break;
23387       // TODO: Slight differences here in allocation order and leaving
23388       // RIP in the class. Do they matter any more here than they do
23389       // in the normal allocation?
23390     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23391       if (Subtarget->is64Bit()) {
23392         if (VT == MVT::i32 || VT == MVT::f32)
23393           return std::make_pair(0U, &X86::GR32RegClass);
23394         if (VT == MVT::i16)
23395           return std::make_pair(0U, &X86::GR16RegClass);
23396         if (VT == MVT::i8 || VT == MVT::i1)
23397           return std::make_pair(0U, &X86::GR8RegClass);
23398         if (VT == MVT::i64 || VT == MVT::f64)
23399           return std::make_pair(0U, &X86::GR64RegClass);
23400         break;
23401       }
23402       // 32-bit fallthrough
23403     case 'Q':   // Q_REGS
23404       if (VT == MVT::i32 || VT == MVT::f32)
23405         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23406       if (VT == MVT::i16)
23407         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23408       if (VT == MVT::i8 || VT == MVT::i1)
23409         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23410       if (VT == MVT::i64)
23411         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23412       break;
23413     case 'r':   // GENERAL_REGS
23414     case 'l':   // INDEX_REGS
23415       if (VT == MVT::i8 || VT == MVT::i1)
23416         return std::make_pair(0U, &X86::GR8RegClass);
23417       if (VT == MVT::i16)
23418         return std::make_pair(0U, &X86::GR16RegClass);
23419       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23420         return std::make_pair(0U, &X86::GR32RegClass);
23421       return std::make_pair(0U, &X86::GR64RegClass);
23422     case 'R':   // LEGACY_REGS
23423       if (VT == MVT::i8 || VT == MVT::i1)
23424         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23425       if (VT == MVT::i16)
23426         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23427       if (VT == MVT::i32 || !Subtarget->is64Bit())
23428         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23429       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23430     case 'f':  // FP Stack registers.
23431       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23432       // value to the correct fpstack register class.
23433       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23434         return std::make_pair(0U, &X86::RFP32RegClass);
23435       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23436         return std::make_pair(0U, &X86::RFP64RegClass);
23437       return std::make_pair(0U, &X86::RFP80RegClass);
23438     case 'y':   // MMX_REGS if MMX allowed.
23439       if (!Subtarget->hasMMX()) break;
23440       return std::make_pair(0U, &X86::VR64RegClass);
23441     case 'Y':   // SSE_REGS if SSE2 allowed
23442       if (!Subtarget->hasSSE2()) break;
23443       // FALL THROUGH.
23444     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23445       if (!Subtarget->hasSSE1()) break;
23446
23447       switch (VT.SimpleTy) {
23448       default: break;
23449       // Scalar SSE types.
23450       case MVT::f32:
23451       case MVT::i32:
23452         return std::make_pair(0U, &X86::FR32RegClass);
23453       case MVT::f64:
23454       case MVT::i64:
23455         return std::make_pair(0U, &X86::FR64RegClass);
23456       // Vector types.
23457       case MVT::v16i8:
23458       case MVT::v8i16:
23459       case MVT::v4i32:
23460       case MVT::v2i64:
23461       case MVT::v4f32:
23462       case MVT::v2f64:
23463         return std::make_pair(0U, &X86::VR128RegClass);
23464       // AVX types.
23465       case MVT::v32i8:
23466       case MVT::v16i16:
23467       case MVT::v8i32:
23468       case MVT::v4i64:
23469       case MVT::v8f32:
23470       case MVT::v4f64:
23471         return std::make_pair(0U, &X86::VR256RegClass);
23472       case MVT::v8f64:
23473       case MVT::v16f32:
23474       case MVT::v16i32:
23475       case MVT::v8i64:
23476         return std::make_pair(0U, &X86::VR512RegClass);
23477       }
23478       break;
23479     }
23480   }
23481
23482   // Use the default implementation in TargetLowering to convert the register
23483   // constraint into a member of a register class.
23484   std::pair<unsigned, const TargetRegisterClass*> Res;
23485   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23486
23487   // Not found as a standard register?
23488   if (!Res.second) {
23489     // Map st(0) -> st(7) -> ST0
23490     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23491         tolower(Constraint[1]) == 's' &&
23492         tolower(Constraint[2]) == 't' &&
23493         Constraint[3] == '(' &&
23494         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23495         Constraint[5] == ')' &&
23496         Constraint[6] == '}') {
23497
23498       Res.first = X86::FP0+Constraint[4]-'0';
23499       Res.second = &X86::RFP80RegClass;
23500       return Res;
23501     }
23502
23503     // GCC allows "st(0)" to be called just plain "st".
23504     if (StringRef("{st}").equals_lower(Constraint)) {
23505       Res.first = X86::FP0;
23506       Res.second = &X86::RFP80RegClass;
23507       return Res;
23508     }
23509
23510     // flags -> EFLAGS
23511     if (StringRef("{flags}").equals_lower(Constraint)) {
23512       Res.first = X86::EFLAGS;
23513       Res.second = &X86::CCRRegClass;
23514       return Res;
23515     }
23516
23517     // 'A' means EAX + EDX.
23518     if (Constraint == "A") {
23519       Res.first = X86::EAX;
23520       Res.second = &X86::GR32_ADRegClass;
23521       return Res;
23522     }
23523     return Res;
23524   }
23525
23526   // Otherwise, check to see if this is a register class of the wrong value
23527   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23528   // turn into {ax},{dx}.
23529   if (Res.second->hasType(VT))
23530     return Res;   // Correct type already, nothing to do.
23531
23532   // All of the single-register GCC register classes map their values onto
23533   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23534   // really want an 8-bit or 32-bit register, map to the appropriate register
23535   // class and return the appropriate register.
23536   if (Res.second == &X86::GR16RegClass) {
23537     if (VT == MVT::i8 || VT == MVT::i1) {
23538       unsigned DestReg = 0;
23539       switch (Res.first) {
23540       default: break;
23541       case X86::AX: DestReg = X86::AL; break;
23542       case X86::DX: DestReg = X86::DL; break;
23543       case X86::CX: DestReg = X86::CL; break;
23544       case X86::BX: DestReg = X86::BL; break;
23545       }
23546       if (DestReg) {
23547         Res.first = DestReg;
23548         Res.second = &X86::GR8RegClass;
23549       }
23550     } else if (VT == MVT::i32 || VT == MVT::f32) {
23551       unsigned DestReg = 0;
23552       switch (Res.first) {
23553       default: break;
23554       case X86::AX: DestReg = X86::EAX; break;
23555       case X86::DX: DestReg = X86::EDX; break;
23556       case X86::CX: DestReg = X86::ECX; break;
23557       case X86::BX: DestReg = X86::EBX; break;
23558       case X86::SI: DestReg = X86::ESI; break;
23559       case X86::DI: DestReg = X86::EDI; break;
23560       case X86::BP: DestReg = X86::EBP; break;
23561       case X86::SP: DestReg = X86::ESP; break;
23562       }
23563       if (DestReg) {
23564         Res.first = DestReg;
23565         Res.second = &X86::GR32RegClass;
23566       }
23567     } else if (VT == MVT::i64 || VT == MVT::f64) {
23568       unsigned DestReg = 0;
23569       switch (Res.first) {
23570       default: break;
23571       case X86::AX: DestReg = X86::RAX; break;
23572       case X86::DX: DestReg = X86::RDX; break;
23573       case X86::CX: DestReg = X86::RCX; break;
23574       case X86::BX: DestReg = X86::RBX; break;
23575       case X86::SI: DestReg = X86::RSI; break;
23576       case X86::DI: DestReg = X86::RDI; break;
23577       case X86::BP: DestReg = X86::RBP; break;
23578       case X86::SP: DestReg = X86::RSP; break;
23579       }
23580       if (DestReg) {
23581         Res.first = DestReg;
23582         Res.second = &X86::GR64RegClass;
23583       }
23584     }
23585   } else if (Res.second == &X86::FR32RegClass ||
23586              Res.second == &X86::FR64RegClass ||
23587              Res.second == &X86::VR128RegClass ||
23588              Res.second == &X86::VR256RegClass ||
23589              Res.second == &X86::FR32XRegClass ||
23590              Res.second == &X86::FR64XRegClass ||
23591              Res.second == &X86::VR128XRegClass ||
23592              Res.second == &X86::VR256XRegClass ||
23593              Res.second == &X86::VR512RegClass) {
23594     // Handle references to XMM physical registers that got mapped into the
23595     // wrong class.  This can happen with constraints like {xmm0} where the
23596     // target independent register mapper will just pick the first match it can
23597     // find, ignoring the required type.
23598
23599     if (VT == MVT::f32 || VT == MVT::i32)
23600       Res.second = &X86::FR32RegClass;
23601     else if (VT == MVT::f64 || VT == MVT::i64)
23602       Res.second = &X86::FR64RegClass;
23603     else if (X86::VR128RegClass.hasType(VT))
23604       Res.second = &X86::VR128RegClass;
23605     else if (X86::VR256RegClass.hasType(VT))
23606       Res.second = &X86::VR256RegClass;
23607     else if (X86::VR512RegClass.hasType(VT))
23608       Res.second = &X86::VR512RegClass;
23609   }
23610
23611   return Res;
23612 }
23613
23614 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23615                                             Type *Ty) const {
23616   // Scaling factors are not free at all.
23617   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23618   // will take 2 allocations in the out of order engine instead of 1
23619   // for plain addressing mode, i.e. inst (reg1).
23620   // E.g.,
23621   // vaddps (%rsi,%drx), %ymm0, %ymm1
23622   // Requires two allocations (one for the load, one for the computation)
23623   // whereas:
23624   // vaddps (%rsi), %ymm0, %ymm1
23625   // Requires just 1 allocation, i.e., freeing allocations for other operations
23626   // and having less micro operations to execute.
23627   //
23628   // For some X86 architectures, this is even worse because for instance for
23629   // stores, the complex addressing mode forces the instruction to use the
23630   // "load" ports instead of the dedicated "store" port.
23631   // E.g., on Haswell:
23632   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23633   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23634   if (isLegalAddressingMode(AM, Ty))
23635     // Scale represents reg2 * scale, thus account for 1
23636     // as soon as we use a second register.
23637     return AM.Scale != 0;
23638   return -1;
23639 }
23640
23641 bool X86TargetLowering::isTargetFTOL() const {
23642   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23643 }