0f16f809ba1b2492ec882084a1538eb3f7ebf057
[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/SmallBitVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/VariadicFunction.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
54 #include <bitset>
55 #include <numeric>
56 #include <cctype>
57 using namespace llvm;
58
59 #define DEBUG_TYPE "x86-isel"
60
61 STATISTIC(NumTailCalls, "Number of tail calls");
62
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64     "x86-experimental-vector-widening-legalization", cl::init(false),
65     cl::desc("Enable an experimental vector type legalization through widening "
66              "rather than promotion."),
67     cl::Hidden);
68
69 static cl::opt<bool> ExperimentalVectorShuffleLowering(
70     "x86-experimental-vector-shuffle-lowering", cl::init(true),
71     cl::desc("Enable an experimental vector shuffle lowering code path."),
72     cl::Hidden);
73
74 static cl::opt<int> ReciprocalEstimateRefinementSteps(
75     "x86-recip-refinement-steps", cl::init(1),
76     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
77              "result of the hardware reciprocal estimate instruction."),
78     cl::NotHidden);
79
80 // Forward declarations.
81 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
82                        SDValue V2);
83
84 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
85                                 SelectionDAG &DAG, SDLoc dl,
86                                 unsigned vectorWidth) {
87   assert((vectorWidth == 128 || vectorWidth == 256) &&
88          "Unsupported vector width");
89   EVT VT = Vec.getValueType();
90   EVT ElVT = VT.getVectorElementType();
91   unsigned Factor = VT.getSizeInBits()/vectorWidth;
92   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
93                                   VT.getVectorNumElements()/Factor);
94
95   // Extract from UNDEF is UNDEF.
96   if (Vec.getOpcode() == ISD::UNDEF)
97     return DAG.getUNDEF(ResultVT);
98
99   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
100   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
101
102   // This is the index of the first element of the vectorWidth-bit chunk
103   // we want.
104   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
105                                * ElemsPerChunk);
106
107   // If the input is a buildvector just emit a smaller one.
108   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
109     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
110                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
111                                     ElemsPerChunk));
112
113   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
114   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
115                                VecIdx);
116
117   return Result;
118
119 }
120 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
121 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
122 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
123 /// instructions or a simple subregister reference. Idx is an index in the
124 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
125 /// lowering EXTRACT_VECTOR_ELT operations easier.
126 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert((Vec.getValueType().is256BitVector() ||
129           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
130   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
131 }
132
133 /// Generate a DAG to grab 256-bits from a 512-bit vector.
134 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
135                                    SelectionDAG &DAG, SDLoc dl) {
136   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
137   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
138 }
139
140 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
141                                unsigned IdxVal, SelectionDAG &DAG,
142                                SDLoc dl, unsigned vectorWidth) {
143   assert((vectorWidth == 128 || vectorWidth == 256) &&
144          "Unsupported vector width");
145   // Inserting UNDEF is Result
146   if (Vec.getOpcode() == ISD::UNDEF)
147     return Result;
148   EVT VT = Vec.getValueType();
149   EVT ElVT = VT.getVectorElementType();
150   EVT ResultVT = Result.getValueType();
151
152   // Insert the relevant vectorWidth bits.
153   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
154
155   // This is the index of the first element of the vectorWidth-bit chunk
156   // we want.
157   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
158                                * ElemsPerChunk);
159
160   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
161   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
162                      VecIdx);
163 }
164 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
165 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
166 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
167 /// simple superregister reference.  Idx is an index in the 128 bits
168 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
169 /// lowering INSERT_VECTOR_ELT operations easier.
170 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
171                                   unsigned IdxVal, SelectionDAG &DAG,
172                                   SDLoc dl) {
173   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
174   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
175 }
176
177 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
178                                   unsigned IdxVal, SelectionDAG &DAG,
179                                   SDLoc dl) {
180   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
181   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
182 }
183
184 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
185 /// instructions. This is used because creating CONCAT_VECTOR nodes of
186 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
187 /// large BUILD_VECTORS.
188 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
189                                    unsigned NumElems, SelectionDAG &DAG,
190                                    SDLoc dl) {
191   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
192   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
193 }
194
195 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
196                                    unsigned NumElems, SelectionDAG &DAG,
197                                    SDLoc dl) {
198   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
199   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
200 }
201
202 // FIXME: This should stop caching the target machine as soon as
203 // we can remove resetOperationActions et al.
204 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM)
205     : TargetLowering(TM, TM.getObjFileLowering()) {
206   Subtarget = &TM.getSubtarget<X86Subtarget>();
207   X86ScalarSSEf64 = Subtarget->hasSSE2();
208   X86ScalarSSEf32 = Subtarget->hasSSE1();
209   TD = getDataLayout();
210
211   resetOperationActions();
212 }
213
214 void X86TargetLowering::resetOperationActions() {
215   const TargetMachine &TM = getTargetMachine();
216   static bool FirstTimeThrough = true;
217
218   // If none of the target options have changed, then we don't need to reset the
219   // operation actions.
220   if (!FirstTimeThrough && TO == TM.Options) return;
221
222   if (!FirstTimeThrough) {
223     // Reinitialize the actions.
224     initActions();
225     FirstTimeThrough = false;
226   }
227
228   TO = TM.Options;
229
230   // Set up the TargetLowering object.
231   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
232
233   // X86 is weird, it always uses i8 for shift amounts and setcc results.
234   setBooleanContents(ZeroOrOneBooleanContent);
235   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
236   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
237
238   // For 64-bit since we have so many registers use the ILP scheduler, for
239   // 32-bit code use the register pressure specific scheduling.
240   // For Atom, always use ILP scheduling.
241   if (Subtarget->isAtom())
242     setSchedulingPreference(Sched::ILP);
243   else if (Subtarget->is64Bit())
244     setSchedulingPreference(Sched::ILP);
245   else
246     setSchedulingPreference(Sched::RegPressure);
247   const X86RegisterInfo *RegInfo =
248       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
249   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
250
251   // Bypass expensive divides on Atom when compiling with O2
252   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
253     addBypassSlowDiv(32, 8);
254     if (Subtarget->is64Bit())
255       addBypassSlowDiv(64, 16);
256   }
257
258   if (Subtarget->isTargetKnownWindowsMSVC()) {
259     // Setup Windows compiler runtime calls.
260     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
261     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
262     setLibcallName(RTLIB::SREM_I64, "_allrem");
263     setLibcallName(RTLIB::UREM_I64, "_aullrem");
264     setLibcallName(RTLIB::MUL_I64, "_allmul");
265     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
266     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
267     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
268     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
269     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
270
271     // The _ftol2 runtime function has an unusual calling conv, which
272     // is modeled by a special pseudo-instruction.
273     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
274     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
275     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
276     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
277   }
278
279   if (Subtarget->isTargetDarwin()) {
280     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
281     setUseUnderscoreSetJmp(false);
282     setUseUnderscoreLongJmp(false);
283   } else if (Subtarget->isTargetWindowsGNU()) {
284     // MS runtime is weird: it exports _setjmp, but longjmp!
285     setUseUnderscoreSetJmp(true);
286     setUseUnderscoreLongJmp(false);
287   } else {
288     setUseUnderscoreSetJmp(true);
289     setUseUnderscoreLongJmp(true);
290   }
291
292   // Set up the register classes.
293   addRegisterClass(MVT::i8, &X86::GR8RegClass);
294   addRegisterClass(MVT::i16, &X86::GR16RegClass);
295   addRegisterClass(MVT::i32, &X86::GR32RegClass);
296   if (Subtarget->is64Bit())
297     addRegisterClass(MVT::i64, &X86::GR64RegClass);
298
299   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
300
301   // We don't accept any truncstore of integer registers.
302   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
303   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
304   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
305   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
306   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
307   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
308
309   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
310
311   // SETOEQ and SETUNE require checking two conditions.
312   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
313   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
314   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
315   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
316   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
317   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
318
319   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
320   // operation.
321   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
322   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
323   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
324
325   if (Subtarget->is64Bit()) {
326     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
328   } else if (!TM.Options.UseSoftFloat) {
329     // We have an algorithm for SSE2->double, and we turn this into a
330     // 64-bit FILD followed by conditional FADD for other targets.
331     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
332     // We have an algorithm for SSE2, and we turn this into a 64-bit
333     // FILD for other targets.
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
335   }
336
337   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
338   // this operation.
339   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
340   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
341
342   if (!TM.Options.UseSoftFloat) {
343     // SSE has no i16 to fp conversion, only i32
344     if (X86ScalarSSEf32) {
345       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
346       // f32 and f64 cases are Legal, f80 case is not
347       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
348     } else {
349       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
350       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
351     }
352   } else {
353     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
355   }
356
357   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
358   // are Legal, f80 is custom lowered.
359   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
360   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
361
362   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
363   // this operation.
364   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
365   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
366
367   if (X86ScalarSSEf32) {
368     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
369     // f32 and f64 cases are Legal, f80 case is not
370     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
371   } else {
372     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
373     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
374   }
375
376   // Handle FP_TO_UINT by promoting the destination to a larger signed
377   // conversion.
378   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
379   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
380   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
381
382   if (Subtarget->is64Bit()) {
383     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
384     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
385   } else if (!TM.Options.UseSoftFloat) {
386     // Since AVX is a superset of SSE3, only check for SSE here.
387     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
388       // Expand FP_TO_UINT into a select.
389       // FIXME: We would like to use a Custom expander here eventually to do
390       // the optimal thing for SSE vs. the default expansion in the legalizer.
391       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
392     else
393       // With SSE3 we can use fisttpll to convert to a signed i64; without
394       // SSE, we're stuck with a fistpll.
395       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
396   }
397
398   if (isTargetFTOL()) {
399     // Use the _ftol2 runtime function, which has a pseudo-instruction
400     // to handle its weird calling convention.
401     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
402   }
403
404   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
405   if (!X86ScalarSSEf64) {
406     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
407     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
408     if (Subtarget->is64Bit()) {
409       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
410       // Without SSE, i64->f64 goes through memory.
411       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
412     }
413   }
414
415   // Scalar integer divide and remainder are lowered to use operations that
416   // produce two results, to match the available instructions. This exposes
417   // the two-result form to trivial CSE, which is able to combine x/y and x%y
418   // into a single instruction.
419   //
420   // Scalar integer multiply-high is also lowered to use two-result
421   // operations, to match the available instructions. However, plain multiply
422   // (low) operations are left as Legal, as there are single-result
423   // instructions for this in x86. Using the two-result multiply instructions
424   // when both high and low results are needed must be arranged by dagcombine.
425   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
426     MVT VT = IntVTs[i];
427     setOperationAction(ISD::MULHS, VT, Expand);
428     setOperationAction(ISD::MULHU, VT, Expand);
429     setOperationAction(ISD::SDIV, VT, Expand);
430     setOperationAction(ISD::UDIV, VT, Expand);
431     setOperationAction(ISD::SREM, VT, Expand);
432     setOperationAction(ISD::UREM, VT, Expand);
433
434     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
435     setOperationAction(ISD::ADDC, VT, Custom);
436     setOperationAction(ISD::ADDE, VT, Custom);
437     setOperationAction(ISD::SUBC, VT, Custom);
438     setOperationAction(ISD::SUBE, VT, Custom);
439   }
440
441   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
442   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
443   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
444   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
445   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
446   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
447   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
448   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
449   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
450   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
451   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
452   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
453   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
454   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
455   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
456   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
457   if (Subtarget->is64Bit())
458     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
459   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
460   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
461   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
462   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
463   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
464   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
465   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
466   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
467
468   // Promote the i8 variants and force them on up to i32 which has a shorter
469   // encoding.
470   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
471   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
472   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
473   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
474   if (Subtarget->hasBMI()) {
475     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
476     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
477     if (Subtarget->is64Bit())
478       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
479   } else {
480     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
481     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
482     if (Subtarget->is64Bit())
483       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
484   }
485
486   if (Subtarget->hasLZCNT()) {
487     // When promoting the i8 variants, force them to i32 for a shorter
488     // encoding.
489     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
490     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
491     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
492     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
493     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
494     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
495     if (Subtarget->is64Bit())
496       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
497   } else {
498     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
499     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
500     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
503     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
504     if (Subtarget->is64Bit()) {
505       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
506       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
507     }
508   }
509
510   // Special handling for half-precision floating point conversions.
511   // If we don't have F16C support, then lower half float conversions
512   // into library calls.
513   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
514     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
515     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
516   }
517
518   // There's never any support for operations beyond MVT::f32.
519   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
520   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
521   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
522   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
523
524   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
525   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
526   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
527   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
528
529   if (Subtarget->hasPOPCNT()) {
530     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
531   } else {
532     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
533     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
534     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
535     if (Subtarget->is64Bit())
536       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
537   }
538
539   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
540
541   if (!Subtarget->hasMOVBE())
542     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
543
544   // These should be promoted to a larger select which is supported.
545   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
546   // X86 wants to expand cmov itself.
547   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
548   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
549   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
550   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
551   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
552   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
553   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
554   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
555   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
556   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
557   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
558   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
559   if (Subtarget->is64Bit()) {
560     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
561     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
562   }
563   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
564   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
565   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
566   // support continuation, user-level threading, and etc.. As a result, no
567   // other SjLj exception interfaces are implemented and please don't build
568   // your own exception handling based on them.
569   // LLVM/Clang supports zero-cost DWARF exception handling.
570   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
571   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
572
573   // Darwin ABI issue.
574   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
575   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
576   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
577   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
578   if (Subtarget->is64Bit())
579     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
580   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
581   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
582   if (Subtarget->is64Bit()) {
583     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
584     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
585     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
586     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
587     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
588   }
589   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
590   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
591   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
592   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
593   if (Subtarget->is64Bit()) {
594     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
595     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
596     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
597   }
598
599   if (Subtarget->hasSSE1())
600     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
601
602   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
603
604   // Expand certain atomics
605   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
606     MVT VT = IntVTs[i];
607     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
608     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
609     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
610   }
611
612   if (Subtarget->hasCmpxchg16b()) {
613     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
614   }
615
616   // FIXME - use subtarget debug flags
617   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
618       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
619     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
620   }
621
622   if (Subtarget->is64Bit()) {
623     setExceptionPointerRegister(X86::RAX);
624     setExceptionSelectorRegister(X86::RDX);
625   } else {
626     setExceptionPointerRegister(X86::EAX);
627     setExceptionSelectorRegister(X86::EDX);
628   }
629   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
630   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
631
632   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
633   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
634
635   setOperationAction(ISD::TRAP, MVT::Other, Legal);
636   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
637
638   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
639   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
640   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
641   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
642     // TargetInfo::X86_64ABIBuiltinVaList
643     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
644     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
645   } else {
646     // TargetInfo::CharPtrBuiltinVaList
647     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
648     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
649   }
650
651   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
652   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
653
654   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
655
656   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
657     // f32 and f64 use SSE.
658     // Set up the FP register classes.
659     addRegisterClass(MVT::f32, &X86::FR32RegClass);
660     addRegisterClass(MVT::f64, &X86::FR64RegClass);
661
662     // Use ANDPD to simulate FABS.
663     setOperationAction(ISD::FABS , MVT::f64, Custom);
664     setOperationAction(ISD::FABS , MVT::f32, Custom);
665
666     // Use XORP to simulate FNEG.
667     setOperationAction(ISD::FNEG , MVT::f64, Custom);
668     setOperationAction(ISD::FNEG , MVT::f32, Custom);
669
670     // Use ANDPD and ORPD to simulate FCOPYSIGN.
671     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
672     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
673
674     // Lower this to FGETSIGNx86 plus an AND.
675     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
676     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
677
678     // We don't support sin/cos/fmod
679     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
680     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
681     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
682     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
683     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
684     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
685
686     // Expand FP immediates into loads from the stack, except for the special
687     // cases we handle.
688     addLegalFPImmediate(APFloat(+0.0)); // xorpd
689     addLegalFPImmediate(APFloat(+0.0f)); // xorps
690   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
691     // Use SSE for f32, x87 for f64.
692     // Set up the FP register classes.
693     addRegisterClass(MVT::f32, &X86::FR32RegClass);
694     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
695
696     // Use ANDPS to simulate FABS.
697     setOperationAction(ISD::FABS , MVT::f32, Custom);
698
699     // Use XORP to simulate FNEG.
700     setOperationAction(ISD::FNEG , MVT::f32, Custom);
701
702     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
703
704     // Use ANDPS and ORPS to simulate FCOPYSIGN.
705     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
706     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
707
708     // We don't support sin/cos/fmod
709     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
710     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
711     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
712
713     // Special cases we handle for FP constants.
714     addLegalFPImmediate(APFloat(+0.0f)); // xorps
715     addLegalFPImmediate(APFloat(+0.0)); // FLD0
716     addLegalFPImmediate(APFloat(+1.0)); // FLD1
717     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
718     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
719
720     if (!TM.Options.UnsafeFPMath) {
721       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
722       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
723       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
724     }
725   } else if (!TM.Options.UseSoftFloat) {
726     // f32 and f64 in x87.
727     // Set up the FP register classes.
728     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
729     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
730
731     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
732     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
733     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
734     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
735
736     if (!TM.Options.UnsafeFPMath) {
737       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
738       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
739       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
740       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
741       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
742       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
743     }
744     addLegalFPImmediate(APFloat(+0.0)); // FLD0
745     addLegalFPImmediate(APFloat(+1.0)); // FLD1
746     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
747     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
748     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
749     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
750     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
751     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
752   }
753
754   // We don't support FMA.
755   setOperationAction(ISD::FMA, MVT::f64, Expand);
756   setOperationAction(ISD::FMA, MVT::f32, Expand);
757
758   // Long double always uses X87.
759   if (!TM.Options.UseSoftFloat) {
760     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
761     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
762     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
763     {
764       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
765       addLegalFPImmediate(TmpFlt);  // FLD0
766       TmpFlt.changeSign();
767       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
768
769       bool ignored;
770       APFloat TmpFlt2(+1.0);
771       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
772                       &ignored);
773       addLegalFPImmediate(TmpFlt2);  // FLD1
774       TmpFlt2.changeSign();
775       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
776     }
777
778     if (!TM.Options.UnsafeFPMath) {
779       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
780       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
781       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
782     }
783
784     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
785     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
786     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
787     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
788     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
789     setOperationAction(ISD::FMA, MVT::f80, Expand);
790   }
791
792   // Always use a library call for pow.
793   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
794   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
795   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
796
797   setOperationAction(ISD::FLOG, MVT::f80, Expand);
798   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
799   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
800   setOperationAction(ISD::FEXP, MVT::f80, Expand);
801   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
802   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
803   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
804
805   // First set operation action for all vector types to either promote
806   // (for widening) or expand (for scalarization). Then we will selectively
807   // turn on ones that can be effectively codegen'd.
808   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
809            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
810     MVT VT = (MVT::SimpleValueType)i;
811     setOperationAction(ISD::ADD , VT, Expand);
812     setOperationAction(ISD::SUB , VT, Expand);
813     setOperationAction(ISD::FADD, VT, Expand);
814     setOperationAction(ISD::FNEG, VT, Expand);
815     setOperationAction(ISD::FSUB, VT, Expand);
816     setOperationAction(ISD::MUL , VT, Expand);
817     setOperationAction(ISD::FMUL, VT, Expand);
818     setOperationAction(ISD::SDIV, VT, Expand);
819     setOperationAction(ISD::UDIV, VT, Expand);
820     setOperationAction(ISD::FDIV, VT, Expand);
821     setOperationAction(ISD::SREM, VT, Expand);
822     setOperationAction(ISD::UREM, VT, Expand);
823     setOperationAction(ISD::LOAD, VT, Expand);
824     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
825     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
826     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
827     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
828     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
829     setOperationAction(ISD::FABS, VT, Expand);
830     setOperationAction(ISD::FSIN, VT, Expand);
831     setOperationAction(ISD::FSINCOS, VT, Expand);
832     setOperationAction(ISD::FCOS, VT, Expand);
833     setOperationAction(ISD::FSINCOS, VT, Expand);
834     setOperationAction(ISD::FREM, VT, Expand);
835     setOperationAction(ISD::FMA,  VT, Expand);
836     setOperationAction(ISD::FPOWI, VT, Expand);
837     setOperationAction(ISD::FSQRT, VT, Expand);
838     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
839     setOperationAction(ISD::FFLOOR, VT, Expand);
840     setOperationAction(ISD::FCEIL, VT, Expand);
841     setOperationAction(ISD::FTRUNC, VT, Expand);
842     setOperationAction(ISD::FRINT, VT, Expand);
843     setOperationAction(ISD::FNEARBYINT, VT, Expand);
844     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
845     setOperationAction(ISD::MULHS, VT, Expand);
846     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
847     setOperationAction(ISD::MULHU, VT, Expand);
848     setOperationAction(ISD::SDIVREM, VT, Expand);
849     setOperationAction(ISD::UDIVREM, VT, Expand);
850     setOperationAction(ISD::FPOW, VT, Expand);
851     setOperationAction(ISD::CTPOP, VT, Expand);
852     setOperationAction(ISD::CTTZ, VT, Expand);
853     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
854     setOperationAction(ISD::CTLZ, VT, Expand);
855     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
856     setOperationAction(ISD::SHL, VT, Expand);
857     setOperationAction(ISD::SRA, VT, Expand);
858     setOperationAction(ISD::SRL, VT, Expand);
859     setOperationAction(ISD::ROTL, VT, Expand);
860     setOperationAction(ISD::ROTR, VT, Expand);
861     setOperationAction(ISD::BSWAP, VT, Expand);
862     setOperationAction(ISD::SETCC, VT, Expand);
863     setOperationAction(ISD::FLOG, VT, Expand);
864     setOperationAction(ISD::FLOG2, VT, Expand);
865     setOperationAction(ISD::FLOG10, VT, Expand);
866     setOperationAction(ISD::FEXP, VT, Expand);
867     setOperationAction(ISD::FEXP2, VT, Expand);
868     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
869     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
870     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
871     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
872     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
873     setOperationAction(ISD::TRUNCATE, VT, Expand);
874     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
875     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
876     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
877     setOperationAction(ISD::VSELECT, VT, Expand);
878     setOperationAction(ISD::SELECT_CC, VT, Expand);
879     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
880              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
881       setTruncStoreAction(VT,
882                           (MVT::SimpleValueType)InnerVT, Expand);
883     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
884     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
885
886     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
887     // we have to deal with them whether we ask for Expansion or not. Setting
888     // Expand causes its own optimisation problems though, so leave them legal.
889     if (VT.getVectorElementType() == MVT::i1)
890       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
891   }
892
893   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
894   // with -msoft-float, disable use of MMX as well.
895   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
896     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
897     // No operations on x86mmx supported, everything uses intrinsics.
898   }
899
900   // MMX-sized vectors (other than x86mmx) are expected to be expanded
901   // into smaller operations.
902   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
903   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
904   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
905   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
906   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
907   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
908   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
909   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
910   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
911   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
912   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
913   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
914   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
915   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
916   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
917   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
918   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
919   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
920   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
921   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
922   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
923   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
924   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
925   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
926   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
927   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
928   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
929   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
930   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
931
932   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
933     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
934
935     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
936     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
937     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
938     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
939     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
940     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
941     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
942     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
944     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
946     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
947     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
948   }
949
950   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
951     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
952
953     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
954     // registers cannot be used even for integer operations.
955     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
956     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
957     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
958     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
959
960     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
961     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
962     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
963     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
964     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
965     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
966     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
967     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
968     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
969     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
970     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
971     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
972     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
973     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
974     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
975     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
976     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
977     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
978     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
979     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
980     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
981     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
982
983     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
984     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
985     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
986     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
987
988     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
989     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
992     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
993
994     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
995     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
996       MVT VT = (MVT::SimpleValueType)i;
997       // Do not attempt to custom lower non-power-of-2 vectors
998       if (!isPowerOf2_32(VT.getVectorNumElements()))
999         continue;
1000       // Do not attempt to custom lower non-128-bit vectors
1001       if (!VT.is128BitVector())
1002         continue;
1003       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1004       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1005       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1006     }
1007
1008     // We support custom legalizing of sext and anyext loads for specific
1009     // memory vector types which we can load as a scalar (or sequence of
1010     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1011     // loads these must work with a single scalar load.
1012     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1013     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1014     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1015     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1016     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1017     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1018     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1019     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1020     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1021
1022     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1023     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1024     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1025     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1026     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1027     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1028
1029     if (Subtarget->is64Bit()) {
1030       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1031       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1032     }
1033
1034     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1035     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1036       MVT VT = (MVT::SimpleValueType)i;
1037
1038       // Do not attempt to promote non-128-bit vectors
1039       if (!VT.is128BitVector())
1040         continue;
1041
1042       setOperationAction(ISD::AND,    VT, Promote);
1043       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1044       setOperationAction(ISD::OR,     VT, Promote);
1045       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1046       setOperationAction(ISD::XOR,    VT, Promote);
1047       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1048       setOperationAction(ISD::LOAD,   VT, Promote);
1049       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1050       setOperationAction(ISD::SELECT, VT, Promote);
1051       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1052     }
1053
1054     // Custom lower v2i64 and v2f64 selects.
1055     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1056     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1057     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1058     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1059
1060     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1061     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1062
1063     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1064     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1065     // As there is no 64-bit GPR available, we need build a special custom
1066     // sequence to convert from v2i32 to v2f32.
1067     if (!Subtarget->is64Bit())
1068       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1069
1070     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1071     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1072
1073     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1074
1075     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1076     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1077     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1078   }
1079
1080   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1081     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1082     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1083     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1084     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1085     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1086     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1087     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1088     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1089     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1090     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1091
1092     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1093     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1094     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1095     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1096     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1097     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1098     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1099     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1100     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1101     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1102
1103     // FIXME: Do we need to handle scalar-to-vector here?
1104     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1105
1106     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1107     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1108     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1109     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1110     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1111     // There is no BLENDI for byte vectors. We don't need to custom lower
1112     // some vselects for now.
1113     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1114
1115     // SSE41 brings specific instructions for doing vector sign extend even in
1116     // cases where we don't have SRA.
1117     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1118     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1119     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1120
1121     // i8 and i16 vectors are custom because the source register and source
1122     // source memory operand types are not the same width.  f32 vectors are
1123     // custom since the immediate controlling the insert encodes additional
1124     // information.
1125     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1126     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1127     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1128     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1129
1130     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1131     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1132     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1133     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1134
1135     // FIXME: these should be Legal, but that's only for the case where
1136     // the index is constant.  For now custom expand to deal with that.
1137     if (Subtarget->is64Bit()) {
1138       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1139       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1140     }
1141   }
1142
1143   if (Subtarget->hasSSE2()) {
1144     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1145     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1146
1147     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1148     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1149
1150     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1151     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1152
1153     // In the customized shift lowering, the legal cases in AVX2 will be
1154     // recognized.
1155     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1156     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1157
1158     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1159     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1160
1161     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1162   }
1163
1164   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1165     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1166     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1167     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1168     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1169     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1170     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1171
1172     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1173     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1174     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1175
1176     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1177     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1178     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1179     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1180     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1181     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1182     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1183     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1184     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1185     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1186     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1187     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1188
1189     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1190     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1191     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1192     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1193     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1194     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1195     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1196     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1197     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1198     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1199     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1200     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1201
1202     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1203     // even though v8i16 is a legal type.
1204     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1205     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1206     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1207
1208     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1209     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1210     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1211
1212     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1213     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1214
1215     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1216
1217     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1218     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1219
1220     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1221     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1222
1223     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1224     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1225
1226     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1227     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1228     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1229     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1230
1231     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1232     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1233     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1234
1235     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1236     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1237     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1238     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1239
1240     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1241     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1242     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1243     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1244     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1245     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1246     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1247     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1248     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1249     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1250     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1251     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1252
1253     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1254       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1255       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1256       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1257       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1258       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1259       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1260     }
1261
1262     if (Subtarget->hasInt256()) {
1263       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1264       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1265       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1266       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1267
1268       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1269       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1270       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1271       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1272
1273       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1274       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1275       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1276       // Don't lower v32i8 because there is no 128-bit byte mul
1277
1278       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1279       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1280       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1281       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1282
1283       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1284       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1285
1286       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1287       // when we have a 256bit-wide blend with immediate.
1288       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1289     } else {
1290       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1291       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1292       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1293       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1294
1295       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1296       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1297       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1298       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1299
1300       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1301       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1302       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1303       // Don't lower v32i8 because there is no 128-bit byte mul
1304     }
1305
1306     // In the customized shift lowering, the legal cases in AVX2 will be
1307     // recognized.
1308     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1309     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1310
1311     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1312     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1313
1314     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1315
1316     // Custom lower several nodes for 256-bit types.
1317     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1318              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1319       MVT VT = (MVT::SimpleValueType)i;
1320
1321       // Extract subvector is special because the value type
1322       // (result) is 128-bit but the source is 256-bit wide.
1323       if (VT.is128BitVector())
1324         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1325
1326       // Do not attempt to custom lower other non-256-bit vectors
1327       if (!VT.is256BitVector())
1328         continue;
1329
1330       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1331       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1332       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1333       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1334       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1335       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1336       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1337     }
1338
1339     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1340     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1341       MVT VT = (MVT::SimpleValueType)i;
1342
1343       // Do not attempt to promote non-256-bit vectors
1344       if (!VT.is256BitVector())
1345         continue;
1346
1347       setOperationAction(ISD::AND,    VT, Promote);
1348       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1349       setOperationAction(ISD::OR,     VT, Promote);
1350       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1351       setOperationAction(ISD::XOR,    VT, Promote);
1352       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1353       setOperationAction(ISD::LOAD,   VT, Promote);
1354       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1355       setOperationAction(ISD::SELECT, VT, Promote);
1356       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1357     }
1358   }
1359
1360   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1361     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1362     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1363     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1364     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1365
1366     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1367     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1368     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1369
1370     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1371     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1372     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1373     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1374     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1375     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1376     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1377     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1378     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1379     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1380     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1381
1382     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1383     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1384     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1385     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1386     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1387     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1388
1389     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1390     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1391     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1392     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1393     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1394     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1395     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1396     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1397
1398     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1399     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1400     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1401     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1402     if (Subtarget->is64Bit()) {
1403       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1404       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1405       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1406       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1407     }
1408     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1409     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1410     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1411     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1412     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1413     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1415     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1416     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1417     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1418
1419     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1420     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1421     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1422     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1423     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1424     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1425     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1426     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1427     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1428     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1429     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1430     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1431     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1432
1433     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1434     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1435     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1436     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1437     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1439
1440     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1441     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1442
1443     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1444
1445     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1446     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1447     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1448     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1449     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1450     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1451     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1452     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1453     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1454
1455     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1456     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1457
1458     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1459     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1460
1461     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1462
1463     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1464     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1465
1466     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1467     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1468
1469     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1470     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1471
1472     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1473     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1474     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1475     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1476     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1477     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1478
1479     if (Subtarget->hasCDI()) {
1480       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1481       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1482     }
1483
1484     // Custom lower several nodes.
1485     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1486              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1487       MVT VT = (MVT::SimpleValueType)i;
1488
1489       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1490       // Extract subvector is special because the value type
1491       // (result) is 256/128-bit but the source is 512-bit wide.
1492       if (VT.is128BitVector() || VT.is256BitVector())
1493         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1494
1495       if (VT.getVectorElementType() == MVT::i1)
1496         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1497
1498       // Do not attempt to custom lower other non-512-bit vectors
1499       if (!VT.is512BitVector())
1500         continue;
1501
1502       if ( EltSize >= 32) {
1503         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1504         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1505         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1506         setOperationAction(ISD::VSELECT,             VT, Legal);
1507         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1508         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1509         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1510       }
1511     }
1512     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1513       MVT VT = (MVT::SimpleValueType)i;
1514
1515       // Do not attempt to promote non-256-bit vectors
1516       if (!VT.is512BitVector())
1517         continue;
1518
1519       setOperationAction(ISD::SELECT, VT, Promote);
1520       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1521     }
1522   }// has  AVX-512
1523
1524   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1525     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1526     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1527
1528     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1529     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1530
1531     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1532     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1533     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1534     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1535
1536     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1537       const MVT VT = (MVT::SimpleValueType)i;
1538
1539       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1540
1541       // Do not attempt to promote non-256-bit vectors
1542       if (!VT.is512BitVector())
1543         continue;
1544
1545       if ( EltSize < 32) {
1546         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1547         setOperationAction(ISD::VSELECT,             VT, Legal);
1548       }
1549     }
1550   }
1551
1552   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1553     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1554     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1555
1556     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1557     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1558     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Legal);
1559   }
1560
1561   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1562   // of this type with custom code.
1563   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1564            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1565     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1566                        Custom);
1567   }
1568
1569   // We want to custom lower some of our intrinsics.
1570   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1571   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1572   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1573   if (!Subtarget->is64Bit())
1574     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1575
1576   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1577   // handle type legalization for these operations here.
1578   //
1579   // FIXME: We really should do custom legalization for addition and
1580   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1581   // than generic legalization for 64-bit multiplication-with-overflow, though.
1582   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1583     // Add/Sub/Mul with overflow operations are custom lowered.
1584     MVT VT = IntVTs[i];
1585     setOperationAction(ISD::SADDO, VT, Custom);
1586     setOperationAction(ISD::UADDO, VT, Custom);
1587     setOperationAction(ISD::SSUBO, VT, Custom);
1588     setOperationAction(ISD::USUBO, VT, Custom);
1589     setOperationAction(ISD::SMULO, VT, Custom);
1590     setOperationAction(ISD::UMULO, VT, Custom);
1591   }
1592
1593
1594   if (!Subtarget->is64Bit()) {
1595     // These libcalls are not available in 32-bit.
1596     setLibcallName(RTLIB::SHL_I128, nullptr);
1597     setLibcallName(RTLIB::SRL_I128, nullptr);
1598     setLibcallName(RTLIB::SRA_I128, nullptr);
1599   }
1600
1601   // Combine sin / cos into one node or libcall if possible.
1602   if (Subtarget->hasSinCos()) {
1603     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1604     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1605     if (Subtarget->isTargetDarwin()) {
1606       // For MacOSX, we don't want to the normal expansion of a libcall to
1607       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1608       // traffic.
1609       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1610       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1611     }
1612   }
1613
1614   if (Subtarget->isTargetWin64()) {
1615     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1616     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1617     setOperationAction(ISD::SREM, MVT::i128, Custom);
1618     setOperationAction(ISD::UREM, MVT::i128, Custom);
1619     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1620     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1621   }
1622
1623   // We have target-specific dag combine patterns for the following nodes:
1624   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1625   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1626   setTargetDAGCombine(ISD::VSELECT);
1627   setTargetDAGCombine(ISD::SELECT);
1628   setTargetDAGCombine(ISD::SHL);
1629   setTargetDAGCombine(ISD::SRA);
1630   setTargetDAGCombine(ISD::SRL);
1631   setTargetDAGCombine(ISD::OR);
1632   setTargetDAGCombine(ISD::AND);
1633   setTargetDAGCombine(ISD::ADD);
1634   setTargetDAGCombine(ISD::FADD);
1635   setTargetDAGCombine(ISD::FSUB);
1636   setTargetDAGCombine(ISD::FMA);
1637   setTargetDAGCombine(ISD::SUB);
1638   setTargetDAGCombine(ISD::LOAD);
1639   setTargetDAGCombine(ISD::STORE);
1640   setTargetDAGCombine(ISD::ZERO_EXTEND);
1641   setTargetDAGCombine(ISD::ANY_EXTEND);
1642   setTargetDAGCombine(ISD::SIGN_EXTEND);
1643   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1644   setTargetDAGCombine(ISD::TRUNCATE);
1645   setTargetDAGCombine(ISD::SINT_TO_FP);
1646   setTargetDAGCombine(ISD::SETCC);
1647   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1648   setTargetDAGCombine(ISD::BUILD_VECTOR);
1649   if (Subtarget->is64Bit())
1650     setTargetDAGCombine(ISD::MUL);
1651   setTargetDAGCombine(ISD::XOR);
1652
1653   computeRegisterProperties();
1654
1655   // On Darwin, -Os means optimize for size without hurting performance,
1656   // do not reduce the limit.
1657   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1658   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1659   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1660   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1661   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1662   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1663   setPrefLoopAlignment(4); // 2^4 bytes.
1664
1665   // Predictable cmov don't hurt on atom because it's in-order.
1666   PredictableSelectIsExpensive = !Subtarget->isAtom();
1667
1668   setPrefFunctionAlignment(4); // 2^4 bytes.
1669
1670   verifyIntrinsicTables();
1671 }
1672
1673 // This has so far only been implemented for 64-bit MachO.
1674 bool X86TargetLowering::useLoadStackGuardNode() const {
1675   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1676          Subtarget->is64Bit();
1677 }
1678
1679 TargetLoweringBase::LegalizeTypeAction
1680 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1681   if (ExperimentalVectorWideningLegalization &&
1682       VT.getVectorNumElements() != 1 &&
1683       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1684     return TypeWidenVector;
1685
1686   return TargetLoweringBase::getPreferredVectorAction(VT);
1687 }
1688
1689 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1690   if (!VT.isVector())
1691     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1692
1693   const unsigned NumElts = VT.getVectorNumElements();
1694   const EVT EltVT = VT.getVectorElementType();
1695   if (VT.is512BitVector()) {
1696     if (Subtarget->hasAVX512())
1697       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1698           EltVT == MVT::f32 || EltVT == MVT::f64)
1699         switch(NumElts) {
1700         case  8: return MVT::v8i1;
1701         case 16: return MVT::v16i1;
1702       }
1703     if (Subtarget->hasBWI())
1704       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1705         switch(NumElts) {
1706         case 32: return MVT::v32i1;
1707         case 64: return MVT::v64i1;
1708       }
1709   }
1710
1711   if (VT.is256BitVector() || VT.is128BitVector()) {
1712     if (Subtarget->hasVLX())
1713       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1714           EltVT == MVT::f32 || EltVT == MVT::f64)
1715         switch(NumElts) {
1716         case 2: return MVT::v2i1;
1717         case 4: return MVT::v4i1;
1718         case 8: return MVT::v8i1;
1719       }
1720     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1721       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1722         switch(NumElts) {
1723         case  8: return MVT::v8i1;
1724         case 16: return MVT::v16i1;
1725         case 32: return MVT::v32i1;
1726       }
1727   }
1728
1729   return VT.changeVectorElementTypeToInteger();
1730 }
1731
1732 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1733 /// the desired ByVal argument alignment.
1734 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1735   if (MaxAlign == 16)
1736     return;
1737   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1738     if (VTy->getBitWidth() == 128)
1739       MaxAlign = 16;
1740   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1741     unsigned EltAlign = 0;
1742     getMaxByValAlign(ATy->getElementType(), EltAlign);
1743     if (EltAlign > MaxAlign)
1744       MaxAlign = EltAlign;
1745   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1746     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1747       unsigned EltAlign = 0;
1748       getMaxByValAlign(STy->getElementType(i), EltAlign);
1749       if (EltAlign > MaxAlign)
1750         MaxAlign = EltAlign;
1751       if (MaxAlign == 16)
1752         break;
1753     }
1754   }
1755 }
1756
1757 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1758 /// function arguments in the caller parameter area. For X86, aggregates
1759 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1760 /// are at 4-byte boundaries.
1761 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1762   if (Subtarget->is64Bit()) {
1763     // Max of 8 and alignment of type.
1764     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1765     if (TyAlign > 8)
1766       return TyAlign;
1767     return 8;
1768   }
1769
1770   unsigned Align = 4;
1771   if (Subtarget->hasSSE1())
1772     getMaxByValAlign(Ty, Align);
1773   return Align;
1774 }
1775
1776 /// getOptimalMemOpType - Returns the target specific optimal type for load
1777 /// and store operations as a result of memset, memcpy, and memmove
1778 /// lowering. If DstAlign is zero that means it's safe to destination
1779 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1780 /// means there isn't a need to check it against alignment requirement,
1781 /// probably because the source does not need to be loaded. If 'IsMemset' is
1782 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1783 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1784 /// source is constant so it does not need to be loaded.
1785 /// It returns EVT::Other if the type should be determined using generic
1786 /// target-independent logic.
1787 EVT
1788 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1789                                        unsigned DstAlign, unsigned SrcAlign,
1790                                        bool IsMemset, bool ZeroMemset,
1791                                        bool MemcpyStrSrc,
1792                                        MachineFunction &MF) const {
1793   const Function *F = MF.getFunction();
1794   if ((!IsMemset || ZeroMemset) &&
1795       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1796                                        Attribute::NoImplicitFloat)) {
1797     if (Size >= 16 &&
1798         (Subtarget->isUnalignedMemAccessFast() ||
1799          ((DstAlign == 0 || DstAlign >= 16) &&
1800           (SrcAlign == 0 || SrcAlign >= 16)))) {
1801       if (Size >= 32) {
1802         if (Subtarget->hasInt256())
1803           return MVT::v8i32;
1804         if (Subtarget->hasFp256())
1805           return MVT::v8f32;
1806       }
1807       if (Subtarget->hasSSE2())
1808         return MVT::v4i32;
1809       if (Subtarget->hasSSE1())
1810         return MVT::v4f32;
1811     } else if (!MemcpyStrSrc && Size >= 8 &&
1812                !Subtarget->is64Bit() &&
1813                Subtarget->hasSSE2()) {
1814       // Do not use f64 to lower memcpy if source is string constant. It's
1815       // better to use i32 to avoid the loads.
1816       return MVT::f64;
1817     }
1818   }
1819   if (Subtarget->is64Bit() && Size >= 8)
1820     return MVT::i64;
1821   return MVT::i32;
1822 }
1823
1824 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1825   if (VT == MVT::f32)
1826     return X86ScalarSSEf32;
1827   else if (VT == MVT::f64)
1828     return X86ScalarSSEf64;
1829   return true;
1830 }
1831
1832 bool
1833 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1834                                                   unsigned,
1835                                                   unsigned,
1836                                                   bool *Fast) const {
1837   if (Fast)
1838     *Fast = Subtarget->isUnalignedMemAccessFast();
1839   return true;
1840 }
1841
1842 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1843 /// current function.  The returned value is a member of the
1844 /// MachineJumpTableInfo::JTEntryKind enum.
1845 unsigned X86TargetLowering::getJumpTableEncoding() const {
1846   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1847   // symbol.
1848   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1849       Subtarget->isPICStyleGOT())
1850     return MachineJumpTableInfo::EK_Custom32;
1851
1852   // Otherwise, use the normal jump table encoding heuristics.
1853   return TargetLowering::getJumpTableEncoding();
1854 }
1855
1856 const MCExpr *
1857 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1858                                              const MachineBasicBlock *MBB,
1859                                              unsigned uid,MCContext &Ctx) const{
1860   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1861          Subtarget->isPICStyleGOT());
1862   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1863   // entries.
1864   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1865                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1866 }
1867
1868 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1869 /// jumptable.
1870 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1871                                                     SelectionDAG &DAG) const {
1872   if (!Subtarget->is64Bit())
1873     // This doesn't have SDLoc associated with it, but is not really the
1874     // same as a Register.
1875     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1876   return Table;
1877 }
1878
1879 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1880 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1881 /// MCExpr.
1882 const MCExpr *X86TargetLowering::
1883 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1884                              MCContext &Ctx) const {
1885   // X86-64 uses RIP relative addressing based on the jump table label.
1886   if (Subtarget->isPICStyleRIPRel())
1887     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1888
1889   // Otherwise, the reference is relative to the PIC base.
1890   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1891 }
1892
1893 // FIXME: Why this routine is here? Move to RegInfo!
1894 std::pair<const TargetRegisterClass*, uint8_t>
1895 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1896   const TargetRegisterClass *RRC = nullptr;
1897   uint8_t Cost = 1;
1898   switch (VT.SimpleTy) {
1899   default:
1900     return TargetLowering::findRepresentativeClass(VT);
1901   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1902     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1903     break;
1904   case MVT::x86mmx:
1905     RRC = &X86::VR64RegClass;
1906     break;
1907   case MVT::f32: case MVT::f64:
1908   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1909   case MVT::v4f32: case MVT::v2f64:
1910   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1911   case MVT::v4f64:
1912     RRC = &X86::VR128RegClass;
1913     break;
1914   }
1915   return std::make_pair(RRC, Cost);
1916 }
1917
1918 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1919                                                unsigned &Offset) const {
1920   if (!Subtarget->isTargetLinux())
1921     return false;
1922
1923   if (Subtarget->is64Bit()) {
1924     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1925     Offset = 0x28;
1926     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1927       AddressSpace = 256;
1928     else
1929       AddressSpace = 257;
1930   } else {
1931     // %gs:0x14 on i386
1932     Offset = 0x14;
1933     AddressSpace = 256;
1934   }
1935   return true;
1936 }
1937
1938 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1939                                             unsigned DestAS) const {
1940   assert(SrcAS != DestAS && "Expected different address spaces!");
1941
1942   return SrcAS < 256 && DestAS < 256;
1943 }
1944
1945 //===----------------------------------------------------------------------===//
1946 //               Return Value Calling Convention Implementation
1947 //===----------------------------------------------------------------------===//
1948
1949 #include "X86GenCallingConv.inc"
1950
1951 bool
1952 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1953                                   MachineFunction &MF, bool isVarArg,
1954                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1955                         LLVMContext &Context) const {
1956   SmallVector<CCValAssign, 16> RVLocs;
1957   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1958   return CCInfo.CheckReturn(Outs, RetCC_X86);
1959 }
1960
1961 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1962   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1963   return ScratchRegs;
1964 }
1965
1966 SDValue
1967 X86TargetLowering::LowerReturn(SDValue Chain,
1968                                CallingConv::ID CallConv, bool isVarArg,
1969                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1970                                const SmallVectorImpl<SDValue> &OutVals,
1971                                SDLoc dl, SelectionDAG &DAG) const {
1972   MachineFunction &MF = DAG.getMachineFunction();
1973   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1974
1975   SmallVector<CCValAssign, 16> RVLocs;
1976   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1977   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1978
1979   SDValue Flag;
1980   SmallVector<SDValue, 6> RetOps;
1981   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1982   // Operand #1 = Bytes To Pop
1983   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1984                    MVT::i16));
1985
1986   // Copy the result values into the output registers.
1987   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1988     CCValAssign &VA = RVLocs[i];
1989     assert(VA.isRegLoc() && "Can only return in registers!");
1990     SDValue ValToCopy = OutVals[i];
1991     EVT ValVT = ValToCopy.getValueType();
1992
1993     // Promote values to the appropriate types
1994     if (VA.getLocInfo() == CCValAssign::SExt)
1995       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1996     else if (VA.getLocInfo() == CCValAssign::ZExt)
1997       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1998     else if (VA.getLocInfo() == CCValAssign::AExt)
1999       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2000     else if (VA.getLocInfo() == CCValAssign::BCvt)
2001       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2002
2003     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2004            "Unexpected FP-extend for return value.");  
2005
2006     // If this is x86-64, and we disabled SSE, we can't return FP values,
2007     // or SSE or MMX vectors.
2008     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2009          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2010           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2011       report_fatal_error("SSE register return with SSE disabled");
2012     }
2013     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2014     // llvm-gcc has never done it right and no one has noticed, so this
2015     // should be OK for now.
2016     if (ValVT == MVT::f64 &&
2017         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2018       report_fatal_error("SSE2 register return with SSE2 disabled");
2019
2020     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2021     // the RET instruction and handled by the FP Stackifier.
2022     if (VA.getLocReg() == X86::FP0 ||
2023         VA.getLocReg() == X86::FP1) {
2024       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2025       // change the value to the FP stack register class.
2026       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2027         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2028       RetOps.push_back(ValToCopy);
2029       // Don't emit a copytoreg.
2030       continue;
2031     }
2032
2033     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2034     // which is returned in RAX / RDX.
2035     if (Subtarget->is64Bit()) {
2036       if (ValVT == MVT::x86mmx) {
2037         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2038           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2039           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2040                                   ValToCopy);
2041           // If we don't have SSE2 available, convert to v4f32 so the generated
2042           // register is legal.
2043           if (!Subtarget->hasSSE2())
2044             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2045         }
2046       }
2047     }
2048
2049     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2050     Flag = Chain.getValue(1);
2051     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2052   }
2053
2054   // The x86-64 ABIs require that for returning structs by value we copy
2055   // the sret argument into %rax/%eax (depending on ABI) for the return.
2056   // Win32 requires us to put the sret argument to %eax as well.
2057   // We saved the argument into a virtual register in the entry block,
2058   // so now we copy the value out and into %rax/%eax.
2059   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2060       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2061     MachineFunction &MF = DAG.getMachineFunction();
2062     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2063     unsigned Reg = FuncInfo->getSRetReturnReg();
2064     assert(Reg &&
2065            "SRetReturnReg should have been set in LowerFormalArguments().");
2066     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2067
2068     unsigned RetValReg
2069         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2070           X86::RAX : X86::EAX;
2071     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2072     Flag = Chain.getValue(1);
2073
2074     // RAX/EAX now acts like a return value.
2075     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2076   }
2077
2078   RetOps[0] = Chain;  // Update chain.
2079
2080   // Add the flag if we have it.
2081   if (Flag.getNode())
2082     RetOps.push_back(Flag);
2083
2084   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2085 }
2086
2087 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2088   if (N->getNumValues() != 1)
2089     return false;
2090   if (!N->hasNUsesOfValue(1, 0))
2091     return false;
2092
2093   SDValue TCChain = Chain;
2094   SDNode *Copy = *N->use_begin();
2095   if (Copy->getOpcode() == ISD::CopyToReg) {
2096     // If the copy has a glue operand, we conservatively assume it isn't safe to
2097     // perform a tail call.
2098     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2099       return false;
2100     TCChain = Copy->getOperand(0);
2101   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2102     return false;
2103
2104   bool HasRet = false;
2105   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2106        UI != UE; ++UI) {
2107     if (UI->getOpcode() != X86ISD::RET_FLAG)
2108       return false;
2109     // If we are returning more than one value, we can definitely
2110     // not make a tail call see PR19530
2111     if (UI->getNumOperands() > 4)
2112       return false;
2113     if (UI->getNumOperands() == 4 &&
2114         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2115       return false;
2116     HasRet = true;
2117   }
2118
2119   if (!HasRet)
2120     return false;
2121
2122   Chain = TCChain;
2123   return true;
2124 }
2125
2126 EVT
2127 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2128                                             ISD::NodeType ExtendKind) const {
2129   MVT ReturnMVT;
2130   // TODO: Is this also valid on 32-bit?
2131   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2132     ReturnMVT = MVT::i8;
2133   else
2134     ReturnMVT = MVT::i32;
2135
2136   EVT MinVT = getRegisterType(Context, ReturnMVT);
2137   return VT.bitsLT(MinVT) ? MinVT : VT;
2138 }
2139
2140 /// LowerCallResult - Lower the result values of a call into the
2141 /// appropriate copies out of appropriate physical registers.
2142 ///
2143 SDValue
2144 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2145                                    CallingConv::ID CallConv, bool isVarArg,
2146                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2147                                    SDLoc dl, SelectionDAG &DAG,
2148                                    SmallVectorImpl<SDValue> &InVals) const {
2149
2150   // Assign locations to each value returned by this call.
2151   SmallVector<CCValAssign, 16> RVLocs;
2152   bool Is64Bit = Subtarget->is64Bit();
2153   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2154                  *DAG.getContext());
2155   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2156
2157   // Copy all of the result registers out of their specified physreg.
2158   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2159     CCValAssign &VA = RVLocs[i];
2160     EVT CopyVT = VA.getValVT();
2161
2162     // If this is x86-64, and we disabled SSE, we can't return FP values
2163     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2164         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2165       report_fatal_error("SSE register return with SSE disabled");
2166     }
2167
2168     // If we prefer to use the value in xmm registers, copy it out as f80 and
2169     // use a truncate to move it from fp stack reg to xmm reg.
2170     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2171         isScalarFPTypeInSSEReg(VA.getValVT()))
2172       CopyVT = MVT::f80;
2173
2174     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2175                                CopyVT, InFlag).getValue(1);
2176     SDValue Val = Chain.getValue(0);
2177
2178     if (CopyVT != VA.getValVT())
2179       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2180                         // This truncation won't change the value.
2181                         DAG.getIntPtrConstant(1));
2182
2183     InFlag = Chain.getValue(2);
2184     InVals.push_back(Val);
2185   }
2186
2187   return Chain;
2188 }
2189
2190 //===----------------------------------------------------------------------===//
2191 //                C & StdCall & Fast Calling Convention implementation
2192 //===----------------------------------------------------------------------===//
2193 //  StdCall calling convention seems to be standard for many Windows' API
2194 //  routines and around. It differs from C calling convention just a little:
2195 //  callee should clean up the stack, not caller. Symbols should be also
2196 //  decorated in some fancy way :) It doesn't support any vector arguments.
2197 //  For info on fast calling convention see Fast Calling Convention (tail call)
2198 //  implementation LowerX86_32FastCCCallTo.
2199
2200 /// CallIsStructReturn - Determines whether a call uses struct return
2201 /// semantics.
2202 enum StructReturnType {
2203   NotStructReturn,
2204   RegStructReturn,
2205   StackStructReturn
2206 };
2207 static StructReturnType
2208 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2209   if (Outs.empty())
2210     return NotStructReturn;
2211
2212   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2213   if (!Flags.isSRet())
2214     return NotStructReturn;
2215   if (Flags.isInReg())
2216     return RegStructReturn;
2217   return StackStructReturn;
2218 }
2219
2220 /// ArgsAreStructReturn - Determines whether a function uses struct
2221 /// return semantics.
2222 static StructReturnType
2223 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2224   if (Ins.empty())
2225     return NotStructReturn;
2226
2227   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2228   if (!Flags.isSRet())
2229     return NotStructReturn;
2230   if (Flags.isInReg())
2231     return RegStructReturn;
2232   return StackStructReturn;
2233 }
2234
2235 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2236 /// by "Src" to address "Dst" with size and alignment information specified by
2237 /// the specific parameter attribute. The copy will be passed as a byval
2238 /// function parameter.
2239 static SDValue
2240 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2241                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2242                           SDLoc dl) {
2243   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2244
2245   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2246                        /*isVolatile*/false, /*AlwaysInline=*/true,
2247                        MachinePointerInfo(), MachinePointerInfo());
2248 }
2249
2250 /// IsTailCallConvention - Return true if the calling convention is one that
2251 /// supports tail call optimization.
2252 static bool IsTailCallConvention(CallingConv::ID CC) {
2253   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2254           CC == CallingConv::HiPE);
2255 }
2256
2257 /// \brief Return true if the calling convention is a C calling convention.
2258 static bool IsCCallConvention(CallingConv::ID CC) {
2259   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2260           CC == CallingConv::X86_64_SysV);
2261 }
2262
2263 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2264   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2265     return false;
2266
2267   CallSite CS(CI);
2268   CallingConv::ID CalleeCC = CS.getCallingConv();
2269   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2270     return false;
2271
2272   return true;
2273 }
2274
2275 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2276 /// a tailcall target by changing its ABI.
2277 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2278                                    bool GuaranteedTailCallOpt) {
2279   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2280 }
2281
2282 SDValue
2283 X86TargetLowering::LowerMemArgument(SDValue Chain,
2284                                     CallingConv::ID CallConv,
2285                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2286                                     SDLoc dl, SelectionDAG &DAG,
2287                                     const CCValAssign &VA,
2288                                     MachineFrameInfo *MFI,
2289                                     unsigned i) const {
2290   // Create the nodes corresponding to a load from this parameter slot.
2291   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2292   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2293       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2294   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2295   EVT ValVT;
2296
2297   // If value is passed by pointer we have address passed instead of the value
2298   // itself.
2299   if (VA.getLocInfo() == CCValAssign::Indirect)
2300     ValVT = VA.getLocVT();
2301   else
2302     ValVT = VA.getValVT();
2303
2304   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2305   // changed with more analysis.
2306   // In case of tail call optimization mark all arguments mutable. Since they
2307   // could be overwritten by lowering of arguments in case of a tail call.
2308   if (Flags.isByVal()) {
2309     unsigned Bytes = Flags.getByValSize();
2310     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2311     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2312     return DAG.getFrameIndex(FI, getPointerTy());
2313   } else {
2314     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2315                                     VA.getLocMemOffset(), isImmutable);
2316     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2317     return DAG.getLoad(ValVT, dl, Chain, FIN,
2318                        MachinePointerInfo::getFixedStack(FI),
2319                        false, false, false, 0);
2320   }
2321 }
2322
2323 // FIXME: Get this from tablegen.
2324 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2325                                                 const X86Subtarget *Subtarget) {
2326   assert(Subtarget->is64Bit());
2327
2328   if (Subtarget->isCallingConvWin64(CallConv)) {
2329     static const MCPhysReg GPR64ArgRegsWin64[] = {
2330       X86::RCX, X86::RDX, X86::R8,  X86::R9
2331     };
2332     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2333   }
2334
2335   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2336     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2337   };
2338   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2339 }
2340
2341 // FIXME: Get this from tablegen.
2342 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2343                                                 CallingConv::ID CallConv,
2344                                                 const X86Subtarget *Subtarget) {
2345   assert(Subtarget->is64Bit());
2346   if (Subtarget->isCallingConvWin64(CallConv)) {
2347     // The XMM registers which might contain var arg parameters are shadowed
2348     // in their paired GPR.  So we only need to save the GPR to their home
2349     // slots.
2350     // TODO: __vectorcall will change this.
2351     return None;
2352   }
2353
2354   const Function *Fn = MF.getFunction();
2355   bool NoImplicitFloatOps = Fn->getAttributes().
2356       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2357   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2358          "SSE register cannot be used when SSE is disabled!");
2359   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2360       !Subtarget->hasSSE1())
2361     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2362     // registers.
2363     return None;
2364
2365   static const MCPhysReg XMMArgRegs64Bit[] = {
2366     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2367     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2368   };
2369   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2370 }
2371
2372 SDValue
2373 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2374                                         CallingConv::ID CallConv,
2375                                         bool isVarArg,
2376                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2377                                         SDLoc dl,
2378                                         SelectionDAG &DAG,
2379                                         SmallVectorImpl<SDValue> &InVals)
2380                                           const {
2381   MachineFunction &MF = DAG.getMachineFunction();
2382   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2383
2384   const Function* Fn = MF.getFunction();
2385   if (Fn->hasExternalLinkage() &&
2386       Subtarget->isTargetCygMing() &&
2387       Fn->getName() == "main")
2388     FuncInfo->setForceFramePointer(true);
2389
2390   MachineFrameInfo *MFI = MF.getFrameInfo();
2391   bool Is64Bit = Subtarget->is64Bit();
2392   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2393
2394   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2395          "Var args not supported with calling convention fastcc, ghc or hipe");
2396
2397   // Assign locations to all of the incoming arguments.
2398   SmallVector<CCValAssign, 16> ArgLocs;
2399   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2400
2401   // Allocate shadow area for Win64
2402   if (IsWin64)
2403     CCInfo.AllocateStack(32, 8);
2404
2405   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2406
2407   unsigned LastVal = ~0U;
2408   SDValue ArgValue;
2409   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2410     CCValAssign &VA = ArgLocs[i];
2411     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2412     // places.
2413     assert(VA.getValNo() != LastVal &&
2414            "Don't support value assigned to multiple locs yet");
2415     (void)LastVal;
2416     LastVal = VA.getValNo();
2417
2418     if (VA.isRegLoc()) {
2419       EVT RegVT = VA.getLocVT();
2420       const TargetRegisterClass *RC;
2421       if (RegVT == MVT::i32)
2422         RC = &X86::GR32RegClass;
2423       else if (Is64Bit && RegVT == MVT::i64)
2424         RC = &X86::GR64RegClass;
2425       else if (RegVT == MVT::f32)
2426         RC = &X86::FR32RegClass;
2427       else if (RegVT == MVT::f64)
2428         RC = &X86::FR64RegClass;
2429       else if (RegVT.is512BitVector())
2430         RC = &X86::VR512RegClass;
2431       else if (RegVT.is256BitVector())
2432         RC = &X86::VR256RegClass;
2433       else if (RegVT.is128BitVector())
2434         RC = &X86::VR128RegClass;
2435       else if (RegVT == MVT::x86mmx)
2436         RC = &X86::VR64RegClass;
2437       else if (RegVT == MVT::i1)
2438         RC = &X86::VK1RegClass;
2439       else if (RegVT == MVT::v8i1)
2440         RC = &X86::VK8RegClass;
2441       else if (RegVT == MVT::v16i1)
2442         RC = &X86::VK16RegClass;
2443       else if (RegVT == MVT::v32i1)
2444         RC = &X86::VK32RegClass;
2445       else if (RegVT == MVT::v64i1)
2446         RC = &X86::VK64RegClass;
2447       else
2448         llvm_unreachable("Unknown argument type!");
2449
2450       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2451       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2452
2453       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2454       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2455       // right size.
2456       if (VA.getLocInfo() == CCValAssign::SExt)
2457         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2458                                DAG.getValueType(VA.getValVT()));
2459       else if (VA.getLocInfo() == CCValAssign::ZExt)
2460         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2461                                DAG.getValueType(VA.getValVT()));
2462       else if (VA.getLocInfo() == CCValAssign::BCvt)
2463         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2464
2465       if (VA.isExtInLoc()) {
2466         // Handle MMX values passed in XMM regs.
2467         if (RegVT.isVector())
2468           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2469         else
2470           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2471       }
2472     } else {
2473       assert(VA.isMemLoc());
2474       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2475     }
2476
2477     // If value is passed via pointer - do a load.
2478     if (VA.getLocInfo() == CCValAssign::Indirect)
2479       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2480                              MachinePointerInfo(), false, false, false, 0);
2481
2482     InVals.push_back(ArgValue);
2483   }
2484
2485   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2486     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2487       // The x86-64 ABIs require that for returning structs by value we copy
2488       // the sret argument into %rax/%eax (depending on ABI) for the return.
2489       // Win32 requires us to put the sret argument to %eax as well.
2490       // Save the argument into a virtual register so that we can access it
2491       // from the return points.
2492       if (Ins[i].Flags.isSRet()) {
2493         unsigned Reg = FuncInfo->getSRetReturnReg();
2494         if (!Reg) {
2495           MVT PtrTy = getPointerTy();
2496           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2497           FuncInfo->setSRetReturnReg(Reg);
2498         }
2499         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2500         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2501         break;
2502       }
2503     }
2504   }
2505
2506   unsigned StackSize = CCInfo.getNextStackOffset();
2507   // Align stack specially for tail calls.
2508   if (FuncIsMadeTailCallSafe(CallConv,
2509                              MF.getTarget().Options.GuaranteedTailCallOpt))
2510     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2511
2512   // If the function takes variable number of arguments, make a frame index for
2513   // the start of the first vararg value... for expansion of llvm.va_start. We
2514   // can skip this if there are no va_start calls.
2515   if (MFI->hasVAStart() &&
2516       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2517                    CallConv != CallingConv::X86_ThisCall))) {
2518     FuncInfo->setVarArgsFrameIndex(
2519         MFI->CreateFixedObject(1, StackSize, true));
2520   }
2521
2522   // 64-bit calling conventions support varargs and register parameters, so we
2523   // have to do extra work to spill them in the prologue or forward them to
2524   // musttail calls.
2525   if (Is64Bit && isVarArg &&
2526       (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2527     // Find the first unallocated argument registers.
2528     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2529     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2530     unsigned NumIntRegs =
2531         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2532     unsigned NumXMMRegs =
2533         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2534     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2535            "SSE register cannot be used when SSE is disabled!");
2536
2537     // Gather all the live in physical registers.
2538     SmallVector<SDValue, 6> LiveGPRs;
2539     SmallVector<SDValue, 8> LiveXMMRegs;
2540     SDValue ALVal;
2541     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2542       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2543       LiveGPRs.push_back(
2544           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2545     }
2546     if (!ArgXMMs.empty()) {
2547       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2548       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2549       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2550         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2551         LiveXMMRegs.push_back(
2552             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2553       }
2554     }
2555
2556     // Store them to the va_list returned by va_start.
2557     if (MFI->hasVAStart()) {
2558       if (IsWin64) {
2559         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2560         // Get to the caller-allocated home save location.  Add 8 to account
2561         // for the return address.
2562         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2563         FuncInfo->setRegSaveFrameIndex(
2564           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2565         // Fixup to set vararg frame on shadow area (4 x i64).
2566         if (NumIntRegs < 4)
2567           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2568       } else {
2569         // For X86-64, if there are vararg parameters that are passed via
2570         // registers, then we must store them to their spots on the stack so
2571         // they may be loaded by deferencing the result of va_next.
2572         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2573         FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2574         FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2575             ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2576       }
2577
2578       // Store the integer parameter registers.
2579       SmallVector<SDValue, 8> MemOps;
2580       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2581                                         getPointerTy());
2582       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2583       for (SDValue Val : LiveGPRs) {
2584         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2585                                   DAG.getIntPtrConstant(Offset));
2586         SDValue Store =
2587           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2588                        MachinePointerInfo::getFixedStack(
2589                          FuncInfo->getRegSaveFrameIndex(), Offset),
2590                        false, false, 0);
2591         MemOps.push_back(Store);
2592         Offset += 8;
2593       }
2594
2595       if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2596         // Now store the XMM (fp + vector) parameter registers.
2597         SmallVector<SDValue, 12> SaveXMMOps;
2598         SaveXMMOps.push_back(Chain);
2599         SaveXMMOps.push_back(ALVal);
2600         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2601                                FuncInfo->getRegSaveFrameIndex()));
2602         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2603                                FuncInfo->getVarArgsFPOffset()));
2604         SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2605                           LiveXMMRegs.end());
2606         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2607                                      MVT::Other, SaveXMMOps));
2608       }
2609
2610       if (!MemOps.empty())
2611         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2612     } else {
2613       // Add all GPRs, al, and XMMs to the list of forwards.  We will add then
2614       // to the liveout set on a musttail call.
2615       assert(MFI->hasMustTailInVarArgFunc());
2616       auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2617       typedef X86MachineFunctionInfo::Forward Forward;
2618
2619       for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2620         unsigned VReg =
2621             MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2622         Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2623         Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2624       }
2625
2626       if (!ArgXMMs.empty()) {
2627         unsigned ALVReg =
2628             MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2629         Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2630         Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2631
2632         for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2633           unsigned VReg =
2634               MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2635           Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2636           Forwards.push_back(
2637               Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2638         }
2639       }
2640     }
2641   }
2642
2643   // Some CCs need callee pop.
2644   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2645                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2646     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2647   } else {
2648     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2649     // If this is an sret function, the return should pop the hidden pointer.
2650     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2651         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2652         argsAreStructReturn(Ins) == StackStructReturn)
2653       FuncInfo->setBytesToPopOnReturn(4);
2654   }
2655
2656   if (!Is64Bit) {
2657     // RegSaveFrameIndex is X86-64 only.
2658     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2659     if (CallConv == CallingConv::X86_FastCall ||
2660         CallConv == CallingConv::X86_ThisCall)
2661       // fastcc functions can't have varargs.
2662       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2663   }
2664
2665   FuncInfo->setArgumentStackSize(StackSize);
2666
2667   return Chain;
2668 }
2669
2670 SDValue
2671 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2672                                     SDValue StackPtr, SDValue Arg,
2673                                     SDLoc dl, SelectionDAG &DAG,
2674                                     const CCValAssign &VA,
2675                                     ISD::ArgFlagsTy Flags) const {
2676   unsigned LocMemOffset = VA.getLocMemOffset();
2677   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2678   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2679   if (Flags.isByVal())
2680     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2681
2682   return DAG.getStore(Chain, dl, Arg, PtrOff,
2683                       MachinePointerInfo::getStack(LocMemOffset),
2684                       false, false, 0);
2685 }
2686
2687 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2688 /// optimization is performed and it is required.
2689 SDValue
2690 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2691                                            SDValue &OutRetAddr, SDValue Chain,
2692                                            bool IsTailCall, bool Is64Bit,
2693                                            int FPDiff, SDLoc dl) const {
2694   // Adjust the Return address stack slot.
2695   EVT VT = getPointerTy();
2696   OutRetAddr = getReturnAddressFrameIndex(DAG);
2697
2698   // Load the "old" Return address.
2699   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2700                            false, false, false, 0);
2701   return SDValue(OutRetAddr.getNode(), 1);
2702 }
2703
2704 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2705 /// optimization is performed and it is required (FPDiff!=0).
2706 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2707                                         SDValue Chain, SDValue RetAddrFrIdx,
2708                                         EVT PtrVT, unsigned SlotSize,
2709                                         int FPDiff, SDLoc dl) {
2710   // Store the return address to the appropriate stack slot.
2711   if (!FPDiff) return Chain;
2712   // Calculate the new stack slot for the return address.
2713   int NewReturnAddrFI =
2714     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2715                                          false);
2716   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2717   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2718                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2719                        false, false, 0);
2720   return Chain;
2721 }
2722
2723 SDValue
2724 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2725                              SmallVectorImpl<SDValue> &InVals) const {
2726   SelectionDAG &DAG                     = CLI.DAG;
2727   SDLoc &dl                             = CLI.DL;
2728   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2729   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2730   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2731   SDValue Chain                         = CLI.Chain;
2732   SDValue Callee                        = CLI.Callee;
2733   CallingConv::ID CallConv              = CLI.CallConv;
2734   bool &isTailCall                      = CLI.IsTailCall;
2735   bool isVarArg                         = CLI.IsVarArg;
2736
2737   MachineFunction &MF = DAG.getMachineFunction();
2738   bool Is64Bit        = Subtarget->is64Bit();
2739   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2740   StructReturnType SR = callIsStructReturn(Outs);
2741   bool IsSibcall      = false;
2742   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2743
2744   if (MF.getTarget().Options.DisableTailCalls)
2745     isTailCall = false;
2746
2747   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2748   if (IsMustTail) {
2749     // Force this to be a tail call.  The verifier rules are enough to ensure
2750     // that we can lower this successfully without moving the return address
2751     // around.
2752     isTailCall = true;
2753   } else if (isTailCall) {
2754     // Check if it's really possible to do a tail call.
2755     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2756                     isVarArg, SR != NotStructReturn,
2757                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2758                     Outs, OutVals, Ins, DAG);
2759
2760     // Sibcalls are automatically detected tailcalls which do not require
2761     // ABI changes.
2762     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2763       IsSibcall = true;
2764
2765     if (isTailCall)
2766       ++NumTailCalls;
2767   }
2768
2769   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2770          "Var args not supported with calling convention fastcc, ghc or hipe");
2771
2772   // Analyze operands of the call, assigning locations to each operand.
2773   SmallVector<CCValAssign, 16> ArgLocs;
2774   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2775
2776   // Allocate shadow area for Win64
2777   if (IsWin64)
2778     CCInfo.AllocateStack(32, 8);
2779
2780   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2781
2782   // Get a count of how many bytes are to be pushed on the stack.
2783   unsigned NumBytes = CCInfo.getNextStackOffset();
2784   if (IsSibcall)
2785     // This is a sibcall. The memory operands are available in caller's
2786     // own caller's stack.
2787     NumBytes = 0;
2788   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2789            IsTailCallConvention(CallConv))
2790     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2791
2792   int FPDiff = 0;
2793   if (isTailCall && !IsSibcall && !IsMustTail) {
2794     // Lower arguments at fp - stackoffset + fpdiff.
2795     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2796
2797     FPDiff = NumBytesCallerPushed - NumBytes;
2798
2799     // Set the delta of movement of the returnaddr stackslot.
2800     // But only set if delta is greater than previous delta.
2801     if (FPDiff < X86Info->getTCReturnAddrDelta())
2802       X86Info->setTCReturnAddrDelta(FPDiff);
2803   }
2804
2805   unsigned NumBytesToPush = NumBytes;
2806   unsigned NumBytesToPop = NumBytes;
2807
2808   // If we have an inalloca argument, all stack space has already been allocated
2809   // for us and be right at the top of the stack.  We don't support multiple
2810   // arguments passed in memory when using inalloca.
2811   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2812     NumBytesToPush = 0;
2813     if (!ArgLocs.back().isMemLoc())
2814       report_fatal_error("cannot use inalloca attribute on a register "
2815                          "parameter");
2816     if (ArgLocs.back().getLocMemOffset() != 0)
2817       report_fatal_error("any parameter with the inalloca attribute must be "
2818                          "the only memory argument");
2819   }
2820
2821   if (!IsSibcall)
2822     Chain = DAG.getCALLSEQ_START(
2823         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2824
2825   SDValue RetAddrFrIdx;
2826   // Load return address for tail calls.
2827   if (isTailCall && FPDiff)
2828     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2829                                     Is64Bit, FPDiff, dl);
2830
2831   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2832   SmallVector<SDValue, 8> MemOpChains;
2833   SDValue StackPtr;
2834
2835   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2836   // of tail call optimization arguments are handle later.
2837   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2838       DAG.getSubtarget().getRegisterInfo());
2839   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2840     // Skip inalloca arguments, they have already been written.
2841     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2842     if (Flags.isInAlloca())
2843       continue;
2844
2845     CCValAssign &VA = ArgLocs[i];
2846     EVT RegVT = VA.getLocVT();
2847     SDValue Arg = OutVals[i];
2848     bool isByVal = Flags.isByVal();
2849
2850     // Promote the value if needed.
2851     switch (VA.getLocInfo()) {
2852     default: llvm_unreachable("Unknown loc info!");
2853     case CCValAssign::Full: break;
2854     case CCValAssign::SExt:
2855       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2856       break;
2857     case CCValAssign::ZExt:
2858       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2859       break;
2860     case CCValAssign::AExt:
2861       if (RegVT.is128BitVector()) {
2862         // Special case: passing MMX values in XMM registers.
2863         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2864         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2865         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2866       } else
2867         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2868       break;
2869     case CCValAssign::BCvt:
2870       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2871       break;
2872     case CCValAssign::Indirect: {
2873       // Store the argument.
2874       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2875       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2876       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2877                            MachinePointerInfo::getFixedStack(FI),
2878                            false, false, 0);
2879       Arg = SpillSlot;
2880       break;
2881     }
2882     }
2883
2884     if (VA.isRegLoc()) {
2885       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2886       if (isVarArg && IsWin64) {
2887         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2888         // shadow reg if callee is a varargs function.
2889         unsigned ShadowReg = 0;
2890         switch (VA.getLocReg()) {
2891         case X86::XMM0: ShadowReg = X86::RCX; break;
2892         case X86::XMM1: ShadowReg = X86::RDX; break;
2893         case X86::XMM2: ShadowReg = X86::R8; break;
2894         case X86::XMM3: ShadowReg = X86::R9; break;
2895         }
2896         if (ShadowReg)
2897           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2898       }
2899     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2900       assert(VA.isMemLoc());
2901       if (!StackPtr.getNode())
2902         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2903                                       getPointerTy());
2904       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2905                                              dl, DAG, VA, Flags));
2906     }
2907   }
2908
2909   if (!MemOpChains.empty())
2910     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2911
2912   if (Subtarget->isPICStyleGOT()) {
2913     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2914     // GOT pointer.
2915     if (!isTailCall) {
2916       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2917                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2918     } else {
2919       // If we are tail calling and generating PIC/GOT style code load the
2920       // address of the callee into ECX. The value in ecx is used as target of
2921       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2922       // for tail calls on PIC/GOT architectures. Normally we would just put the
2923       // address of GOT into ebx and then call target@PLT. But for tail calls
2924       // ebx would be restored (since ebx is callee saved) before jumping to the
2925       // target@PLT.
2926
2927       // Note: The actual moving to ECX is done further down.
2928       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2929       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2930           !G->getGlobal()->hasProtectedVisibility())
2931         Callee = LowerGlobalAddress(Callee, DAG);
2932       else if (isa<ExternalSymbolSDNode>(Callee))
2933         Callee = LowerExternalSymbol(Callee, DAG);
2934     }
2935   }
2936
2937   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2938     // From AMD64 ABI document:
2939     // For calls that may call functions that use varargs or stdargs
2940     // (prototype-less calls or calls to functions containing ellipsis (...) in
2941     // the declaration) %al is used as hidden argument to specify the number
2942     // of SSE registers used. The contents of %al do not need to match exactly
2943     // the number of registers, but must be an ubound on the number of SSE
2944     // registers used and is in the range 0 - 8 inclusive.
2945
2946     // Count the number of XMM registers allocated.
2947     static const MCPhysReg XMMArgRegs[] = {
2948       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2949       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2950     };
2951     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2952     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2953            && "SSE registers cannot be used when SSE is disabled");
2954
2955     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2956                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2957   }
2958
2959   if (Is64Bit && isVarArg && IsMustTail) {
2960     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2961     for (const auto &F : Forwards) {
2962       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2963       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2964     }
2965   }
2966
2967   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2968   // don't need this because the eligibility check rejects calls that require
2969   // shuffling arguments passed in memory.
2970   if (!IsSibcall && isTailCall) {
2971     // Force all the incoming stack arguments to be loaded from the stack
2972     // before any new outgoing arguments are stored to the stack, because the
2973     // outgoing stack slots may alias the incoming argument stack slots, and
2974     // the alias isn't otherwise explicit. This is slightly more conservative
2975     // than necessary, because it means that each store effectively depends
2976     // on every argument instead of just those arguments it would clobber.
2977     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2978
2979     SmallVector<SDValue, 8> MemOpChains2;
2980     SDValue FIN;
2981     int FI = 0;
2982     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2983       CCValAssign &VA = ArgLocs[i];
2984       if (VA.isRegLoc())
2985         continue;
2986       assert(VA.isMemLoc());
2987       SDValue Arg = OutVals[i];
2988       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2989       // Skip inalloca arguments.  They don't require any work.
2990       if (Flags.isInAlloca())
2991         continue;
2992       // Create frame index.
2993       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2994       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2995       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2996       FIN = DAG.getFrameIndex(FI, getPointerTy());
2997
2998       if (Flags.isByVal()) {
2999         // Copy relative to framepointer.
3000         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3001         if (!StackPtr.getNode())
3002           StackPtr = DAG.getCopyFromReg(Chain, dl,
3003                                         RegInfo->getStackRegister(),
3004                                         getPointerTy());
3005         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3006
3007         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3008                                                          ArgChain,
3009                                                          Flags, DAG, dl));
3010       } else {
3011         // Store relative to framepointer.
3012         MemOpChains2.push_back(
3013           DAG.getStore(ArgChain, dl, Arg, FIN,
3014                        MachinePointerInfo::getFixedStack(FI),
3015                        false, false, 0));
3016       }
3017     }
3018
3019     if (!MemOpChains2.empty())
3020       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3021
3022     // Store the return address to the appropriate stack slot.
3023     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3024                                      getPointerTy(), RegInfo->getSlotSize(),
3025                                      FPDiff, dl);
3026   }
3027
3028   // Build a sequence of copy-to-reg nodes chained together with token chain
3029   // and flag operands which copy the outgoing args into registers.
3030   SDValue InFlag;
3031   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3032     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3033                              RegsToPass[i].second, InFlag);
3034     InFlag = Chain.getValue(1);
3035   }
3036
3037   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3038     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3039     // In the 64-bit large code model, we have to make all calls
3040     // through a register, since the call instruction's 32-bit
3041     // pc-relative offset may not be large enough to hold the whole
3042     // address.
3043   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3044     // If the callee is a GlobalAddress node (quite common, every direct call
3045     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3046     // it.
3047
3048     // We should use extra load for direct calls to dllimported functions in
3049     // non-JIT mode.
3050     const GlobalValue *GV = G->getGlobal();
3051     if (!GV->hasDLLImportStorageClass()) {
3052       unsigned char OpFlags = 0;
3053       bool ExtraLoad = false;
3054       unsigned WrapperKind = ISD::DELETED_NODE;
3055
3056       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3057       // external symbols most go through the PLT in PIC mode.  If the symbol
3058       // has hidden or protected visibility, or if it is static or local, then
3059       // we don't need to use the PLT - we can directly call it.
3060       if (Subtarget->isTargetELF() &&
3061           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3062           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3063         OpFlags = X86II::MO_PLT;
3064       } else if (Subtarget->isPICStyleStubAny() &&
3065                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3066                  (!Subtarget->getTargetTriple().isMacOSX() ||
3067                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3068         // PC-relative references to external symbols should go through $stub,
3069         // unless we're building with the leopard linker or later, which
3070         // automatically synthesizes these stubs.
3071         OpFlags = X86II::MO_DARWIN_STUB;
3072       } else if (Subtarget->isPICStyleRIPRel() &&
3073                  isa<Function>(GV) &&
3074                  cast<Function>(GV)->getAttributes().
3075                    hasAttribute(AttributeSet::FunctionIndex,
3076                                 Attribute::NonLazyBind)) {
3077         // If the function is marked as non-lazy, generate an indirect call
3078         // which loads from the GOT directly. This avoids runtime overhead
3079         // at the cost of eager binding (and one extra byte of encoding).
3080         OpFlags = X86II::MO_GOTPCREL;
3081         WrapperKind = X86ISD::WrapperRIP;
3082         ExtraLoad = true;
3083       }
3084
3085       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3086                                           G->getOffset(), OpFlags);
3087
3088       // Add a wrapper if needed.
3089       if (WrapperKind != ISD::DELETED_NODE)
3090         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3091       // Add extra indirection if needed.
3092       if (ExtraLoad)
3093         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3094                              MachinePointerInfo::getGOT(),
3095                              false, false, false, 0);
3096     }
3097   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3098     unsigned char OpFlags = 0;
3099
3100     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3101     // external symbols should go through the PLT.
3102     if (Subtarget->isTargetELF() &&
3103         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3104       OpFlags = X86II::MO_PLT;
3105     } else if (Subtarget->isPICStyleStubAny() &&
3106                (!Subtarget->getTargetTriple().isMacOSX() ||
3107                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3108       // PC-relative references to external symbols should go through $stub,
3109       // unless we're building with the leopard linker or later, which
3110       // automatically synthesizes these stubs.
3111       OpFlags = X86II::MO_DARWIN_STUB;
3112     }
3113
3114     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3115                                          OpFlags);
3116   } else if (Subtarget->isTarget64BitILP32() && Callee->getValueType(0) == MVT::i32) {
3117     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3118     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3119   }
3120
3121   // Returns a chain & a flag for retval copy to use.
3122   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3123   SmallVector<SDValue, 8> Ops;
3124
3125   if (!IsSibcall && isTailCall) {
3126     Chain = DAG.getCALLSEQ_END(Chain,
3127                                DAG.getIntPtrConstant(NumBytesToPop, true),
3128                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3129     InFlag = Chain.getValue(1);
3130   }
3131
3132   Ops.push_back(Chain);
3133   Ops.push_back(Callee);
3134
3135   if (isTailCall)
3136     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3137
3138   // Add argument registers to the end of the list so that they are known live
3139   // into the call.
3140   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3141     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3142                                   RegsToPass[i].second.getValueType()));
3143
3144   // Add a register mask operand representing the call-preserved registers.
3145   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3146   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3147   assert(Mask && "Missing call preserved mask for calling convention");
3148   Ops.push_back(DAG.getRegisterMask(Mask));
3149
3150   if (InFlag.getNode())
3151     Ops.push_back(InFlag);
3152
3153   if (isTailCall) {
3154     // We used to do:
3155     //// If this is the first return lowered for this function, add the regs
3156     //// to the liveout set for the function.
3157     // This isn't right, although it's probably harmless on x86; liveouts
3158     // should be computed from returns not tail calls.  Consider a void
3159     // function making a tail call to a function returning int.
3160     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3161   }
3162
3163   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3164   InFlag = Chain.getValue(1);
3165
3166   // Create the CALLSEQ_END node.
3167   unsigned NumBytesForCalleeToPop;
3168   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3169                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3170     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3171   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3172            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3173            SR == StackStructReturn)
3174     // If this is a call to a struct-return function, the callee
3175     // pops the hidden struct pointer, so we have to push it back.
3176     // This is common for Darwin/X86, Linux & Mingw32 targets.
3177     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3178     NumBytesForCalleeToPop = 4;
3179   else
3180     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3181
3182   // Returns a flag for retval copy to use.
3183   if (!IsSibcall) {
3184     Chain = DAG.getCALLSEQ_END(Chain,
3185                                DAG.getIntPtrConstant(NumBytesToPop, true),
3186                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3187                                                      true),
3188                                InFlag, dl);
3189     InFlag = Chain.getValue(1);
3190   }
3191
3192   // Handle result values, copying them out of physregs into vregs that we
3193   // return.
3194   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3195                          Ins, dl, DAG, InVals);
3196 }
3197
3198 //===----------------------------------------------------------------------===//
3199 //                Fast Calling Convention (tail call) implementation
3200 //===----------------------------------------------------------------------===//
3201
3202 //  Like std call, callee cleans arguments, convention except that ECX is
3203 //  reserved for storing the tail called function address. Only 2 registers are
3204 //  free for argument passing (inreg). Tail call optimization is performed
3205 //  provided:
3206 //                * tailcallopt is enabled
3207 //                * caller/callee are fastcc
3208 //  On X86_64 architecture with GOT-style position independent code only local
3209 //  (within module) calls are supported at the moment.
3210 //  To keep the stack aligned according to platform abi the function
3211 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3212 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3213 //  If a tail called function callee has more arguments than the caller the
3214 //  caller needs to make sure that there is room to move the RETADDR to. This is
3215 //  achieved by reserving an area the size of the argument delta right after the
3216 //  original RETADDR, but before the saved framepointer or the spilled registers
3217 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3218 //  stack layout:
3219 //    arg1
3220 //    arg2
3221 //    RETADDR
3222 //    [ new RETADDR
3223 //      move area ]
3224 //    (possible EBP)
3225 //    ESI
3226 //    EDI
3227 //    local1 ..
3228
3229 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3230 /// for a 16 byte align requirement.
3231 unsigned
3232 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3233                                                SelectionDAG& DAG) const {
3234   MachineFunction &MF = DAG.getMachineFunction();
3235   const TargetMachine &TM = MF.getTarget();
3236   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3237       TM.getSubtargetImpl()->getRegisterInfo());
3238   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3239   unsigned StackAlignment = TFI.getStackAlignment();
3240   uint64_t AlignMask = StackAlignment - 1;
3241   int64_t Offset = StackSize;
3242   unsigned SlotSize = RegInfo->getSlotSize();
3243   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3244     // Number smaller than 12 so just add the difference.
3245     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3246   } else {
3247     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3248     Offset = ((~AlignMask) & Offset) + StackAlignment +
3249       (StackAlignment-SlotSize);
3250   }
3251   return Offset;
3252 }
3253
3254 /// MatchingStackOffset - Return true if the given stack call argument is
3255 /// already available in the same position (relatively) of the caller's
3256 /// incoming argument stack.
3257 static
3258 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3259                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3260                          const X86InstrInfo *TII) {
3261   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3262   int FI = INT_MAX;
3263   if (Arg.getOpcode() == ISD::CopyFromReg) {
3264     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3265     if (!TargetRegisterInfo::isVirtualRegister(VR))
3266       return false;
3267     MachineInstr *Def = MRI->getVRegDef(VR);
3268     if (!Def)
3269       return false;
3270     if (!Flags.isByVal()) {
3271       if (!TII->isLoadFromStackSlot(Def, FI))
3272         return false;
3273     } else {
3274       unsigned Opcode = Def->getOpcode();
3275       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3276           Def->getOperand(1).isFI()) {
3277         FI = Def->getOperand(1).getIndex();
3278         Bytes = Flags.getByValSize();
3279       } else
3280         return false;
3281     }
3282   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3283     if (Flags.isByVal())
3284       // ByVal argument is passed in as a pointer but it's now being
3285       // dereferenced. e.g.
3286       // define @foo(%struct.X* %A) {
3287       //   tail call @bar(%struct.X* byval %A)
3288       // }
3289       return false;
3290     SDValue Ptr = Ld->getBasePtr();
3291     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3292     if (!FINode)
3293       return false;
3294     FI = FINode->getIndex();
3295   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3296     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3297     FI = FINode->getIndex();
3298     Bytes = Flags.getByValSize();
3299   } else
3300     return false;
3301
3302   assert(FI != INT_MAX);
3303   if (!MFI->isFixedObjectIndex(FI))
3304     return false;
3305   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3306 }
3307
3308 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3309 /// for tail call optimization. Targets which want to do tail call
3310 /// optimization should implement this function.
3311 bool
3312 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3313                                                      CallingConv::ID CalleeCC,
3314                                                      bool isVarArg,
3315                                                      bool isCalleeStructRet,
3316                                                      bool isCallerStructRet,
3317                                                      Type *RetTy,
3318                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3319                                     const SmallVectorImpl<SDValue> &OutVals,
3320                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3321                                                      SelectionDAG &DAG) const {
3322   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3323     return false;
3324
3325   // If -tailcallopt is specified, make fastcc functions tail-callable.
3326   const MachineFunction &MF = DAG.getMachineFunction();
3327   const Function *CallerF = MF.getFunction();
3328
3329   // If the function return type is x86_fp80 and the callee return type is not,
3330   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3331   // perform a tailcall optimization here.
3332   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3333     return false;
3334
3335   CallingConv::ID CallerCC = CallerF->getCallingConv();
3336   bool CCMatch = CallerCC == CalleeCC;
3337   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3338   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3339
3340   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3341     if (IsTailCallConvention(CalleeCC) && CCMatch)
3342       return true;
3343     return false;
3344   }
3345
3346   // Look for obvious safe cases to perform tail call optimization that do not
3347   // require ABI changes. This is what gcc calls sibcall.
3348
3349   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3350   // emit a special epilogue.
3351   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3352       DAG.getSubtarget().getRegisterInfo());
3353   if (RegInfo->needsStackRealignment(MF))
3354     return false;
3355
3356   // Also avoid sibcall optimization if either caller or callee uses struct
3357   // return semantics.
3358   if (isCalleeStructRet || isCallerStructRet)
3359     return false;
3360
3361   // An stdcall/thiscall caller is expected to clean up its arguments; the
3362   // callee isn't going to do that.
3363   // FIXME: this is more restrictive than needed. We could produce a tailcall
3364   // when the stack adjustment matches. For example, with a thiscall that takes
3365   // only one argument.
3366   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3367                    CallerCC == CallingConv::X86_ThisCall))
3368     return false;
3369
3370   // Do not sibcall optimize vararg calls unless all arguments are passed via
3371   // registers.
3372   if (isVarArg && !Outs.empty()) {
3373
3374     // Optimizing for varargs on Win64 is unlikely to be safe without
3375     // additional testing.
3376     if (IsCalleeWin64 || IsCallerWin64)
3377       return false;
3378
3379     SmallVector<CCValAssign, 16> ArgLocs;
3380     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3381                    *DAG.getContext());
3382
3383     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3384     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3385       if (!ArgLocs[i].isRegLoc())
3386         return false;
3387   }
3388
3389   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3390   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3391   // this into a sibcall.
3392   bool Unused = false;
3393   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3394     if (!Ins[i].Used) {
3395       Unused = true;
3396       break;
3397     }
3398   }
3399   if (Unused) {
3400     SmallVector<CCValAssign, 16> RVLocs;
3401     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3402                    *DAG.getContext());
3403     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3404     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3405       CCValAssign &VA = RVLocs[i];
3406       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3407         return false;
3408     }
3409   }
3410
3411   // If the calling conventions do not match, then we'd better make sure the
3412   // results are returned in the same way as what the caller expects.
3413   if (!CCMatch) {
3414     SmallVector<CCValAssign, 16> RVLocs1;
3415     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3416                     *DAG.getContext());
3417     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3418
3419     SmallVector<CCValAssign, 16> RVLocs2;
3420     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3421                     *DAG.getContext());
3422     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3423
3424     if (RVLocs1.size() != RVLocs2.size())
3425       return false;
3426     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3427       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3428         return false;
3429       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3430         return false;
3431       if (RVLocs1[i].isRegLoc()) {
3432         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3433           return false;
3434       } else {
3435         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3436           return false;
3437       }
3438     }
3439   }
3440
3441   // If the callee takes no arguments then go on to check the results of the
3442   // call.
3443   if (!Outs.empty()) {
3444     // Check if stack adjustment is needed. For now, do not do this if any
3445     // argument is passed on the stack.
3446     SmallVector<CCValAssign, 16> ArgLocs;
3447     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3448                    *DAG.getContext());
3449
3450     // Allocate shadow area for Win64
3451     if (IsCalleeWin64)
3452       CCInfo.AllocateStack(32, 8);
3453
3454     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3455     if (CCInfo.getNextStackOffset()) {
3456       MachineFunction &MF = DAG.getMachineFunction();
3457       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3458         return false;
3459
3460       // Check if the arguments are already laid out in the right way as
3461       // the caller's fixed stack objects.
3462       MachineFrameInfo *MFI = MF.getFrameInfo();
3463       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3464       const X86InstrInfo *TII =
3465           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3466       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3467         CCValAssign &VA = ArgLocs[i];
3468         SDValue Arg = OutVals[i];
3469         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3470         if (VA.getLocInfo() == CCValAssign::Indirect)
3471           return false;
3472         if (!VA.isRegLoc()) {
3473           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3474                                    MFI, MRI, TII))
3475             return false;
3476         }
3477       }
3478     }
3479
3480     // If the tailcall address may be in a register, then make sure it's
3481     // possible to register allocate for it. In 32-bit, the call address can
3482     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3483     // callee-saved registers are restored. These happen to be the same
3484     // registers used to pass 'inreg' arguments so watch out for those.
3485     if (!Subtarget->is64Bit() &&
3486         ((!isa<GlobalAddressSDNode>(Callee) &&
3487           !isa<ExternalSymbolSDNode>(Callee)) ||
3488          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3489       unsigned NumInRegs = 0;
3490       // In PIC we need an extra register to formulate the address computation
3491       // for the callee.
3492       unsigned MaxInRegs =
3493         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3494
3495       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3496         CCValAssign &VA = ArgLocs[i];
3497         if (!VA.isRegLoc())
3498           continue;
3499         unsigned Reg = VA.getLocReg();
3500         switch (Reg) {
3501         default: break;
3502         case X86::EAX: case X86::EDX: case X86::ECX:
3503           if (++NumInRegs == MaxInRegs)
3504             return false;
3505           break;
3506         }
3507       }
3508     }
3509   }
3510
3511   return true;
3512 }
3513
3514 FastISel *
3515 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3516                                   const TargetLibraryInfo *libInfo) const {
3517   return X86::createFastISel(funcInfo, libInfo);
3518 }
3519
3520 //===----------------------------------------------------------------------===//
3521 //                           Other Lowering Hooks
3522 //===----------------------------------------------------------------------===//
3523
3524 static bool MayFoldLoad(SDValue Op) {
3525   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3526 }
3527
3528 static bool MayFoldIntoStore(SDValue Op) {
3529   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3530 }
3531
3532 static bool isTargetShuffle(unsigned Opcode) {
3533   switch(Opcode) {
3534   default: return false;
3535   case X86ISD::BLENDI:
3536   case X86ISD::PSHUFB:
3537   case X86ISD::PSHUFD:
3538   case X86ISD::PSHUFHW:
3539   case X86ISD::PSHUFLW:
3540   case X86ISD::SHUFP:
3541   case X86ISD::PALIGNR:
3542   case X86ISD::MOVLHPS:
3543   case X86ISD::MOVLHPD:
3544   case X86ISD::MOVHLPS:
3545   case X86ISD::MOVLPS:
3546   case X86ISD::MOVLPD:
3547   case X86ISD::MOVSHDUP:
3548   case X86ISD::MOVSLDUP:
3549   case X86ISD::MOVDDUP:
3550   case X86ISD::MOVSS:
3551   case X86ISD::MOVSD:
3552   case X86ISD::UNPCKL:
3553   case X86ISD::UNPCKH:
3554   case X86ISD::VPERMILPI:
3555   case X86ISD::VPERM2X128:
3556   case X86ISD::VPERMI:
3557     return true;
3558   }
3559 }
3560
3561 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3562                                     SDValue V1, SelectionDAG &DAG) {
3563   switch(Opc) {
3564   default: llvm_unreachable("Unknown x86 shuffle node");
3565   case X86ISD::MOVSHDUP:
3566   case X86ISD::MOVSLDUP:
3567   case X86ISD::MOVDDUP:
3568     return DAG.getNode(Opc, dl, VT, V1);
3569   }
3570 }
3571
3572 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3573                                     SDValue V1, unsigned TargetMask,
3574                                     SelectionDAG &DAG) {
3575   switch(Opc) {
3576   default: llvm_unreachable("Unknown x86 shuffle node");
3577   case X86ISD::PSHUFD:
3578   case X86ISD::PSHUFHW:
3579   case X86ISD::PSHUFLW:
3580   case X86ISD::VPERMILPI:
3581   case X86ISD::VPERMI:
3582     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3583   }
3584 }
3585
3586 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3587                                     SDValue V1, SDValue V2, unsigned TargetMask,
3588                                     SelectionDAG &DAG) {
3589   switch(Opc) {
3590   default: llvm_unreachable("Unknown x86 shuffle node");
3591   case X86ISD::PALIGNR:
3592   case X86ISD::VALIGN:
3593   case X86ISD::SHUFP:
3594   case X86ISD::VPERM2X128:
3595     return DAG.getNode(Opc, dl, VT, V1, V2,
3596                        DAG.getConstant(TargetMask, MVT::i8));
3597   }
3598 }
3599
3600 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3601                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3602   switch(Opc) {
3603   default: llvm_unreachable("Unknown x86 shuffle node");
3604   case X86ISD::MOVLHPS:
3605   case X86ISD::MOVLHPD:
3606   case X86ISD::MOVHLPS:
3607   case X86ISD::MOVLPS:
3608   case X86ISD::MOVLPD:
3609   case X86ISD::MOVSS:
3610   case X86ISD::MOVSD:
3611   case X86ISD::UNPCKL:
3612   case X86ISD::UNPCKH:
3613     return DAG.getNode(Opc, dl, VT, V1, V2);
3614   }
3615 }
3616
3617 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3618   MachineFunction &MF = DAG.getMachineFunction();
3619   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3620       DAG.getSubtarget().getRegisterInfo());
3621   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3622   int ReturnAddrIndex = FuncInfo->getRAIndex();
3623
3624   if (ReturnAddrIndex == 0) {
3625     // Set up a frame object for the return address.
3626     unsigned SlotSize = RegInfo->getSlotSize();
3627     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3628                                                            -(int64_t)SlotSize,
3629                                                            false);
3630     FuncInfo->setRAIndex(ReturnAddrIndex);
3631   }
3632
3633   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3634 }
3635
3636 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3637                                        bool hasSymbolicDisplacement) {
3638   // Offset should fit into 32 bit immediate field.
3639   if (!isInt<32>(Offset))
3640     return false;
3641
3642   // If we don't have a symbolic displacement - we don't have any extra
3643   // restrictions.
3644   if (!hasSymbolicDisplacement)
3645     return true;
3646
3647   // FIXME: Some tweaks might be needed for medium code model.
3648   if (M != CodeModel::Small && M != CodeModel::Kernel)
3649     return false;
3650
3651   // For small code model we assume that latest object is 16MB before end of 31
3652   // bits boundary. We may also accept pretty large negative constants knowing
3653   // that all objects are in the positive half of address space.
3654   if (M == CodeModel::Small && Offset < 16*1024*1024)
3655     return true;
3656
3657   // For kernel code model we know that all object resist in the negative half
3658   // of 32bits address space. We may not accept negative offsets, since they may
3659   // be just off and we may accept pretty large positive ones.
3660   if (M == CodeModel::Kernel && Offset > 0)
3661     return true;
3662
3663   return false;
3664 }
3665
3666 /// isCalleePop - Determines whether the callee is required to pop its
3667 /// own arguments. Callee pop is necessary to support tail calls.
3668 bool X86::isCalleePop(CallingConv::ID CallingConv,
3669                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3670   switch (CallingConv) {
3671   default:
3672     return false;
3673   case CallingConv::X86_StdCall:
3674   case CallingConv::X86_FastCall:
3675   case CallingConv::X86_ThisCall:
3676     return !is64Bit;
3677   case CallingConv::Fast:
3678   case CallingConv::GHC:
3679   case CallingConv::HiPE:
3680     if (IsVarArg)
3681       return false;
3682     return TailCallOpt;
3683   }
3684 }
3685
3686 /// \brief Return true if the condition is an unsigned comparison operation.
3687 static bool isX86CCUnsigned(unsigned X86CC) {
3688   switch (X86CC) {
3689   default: llvm_unreachable("Invalid integer condition!");
3690   case X86::COND_E:     return true;
3691   case X86::COND_G:     return false;
3692   case X86::COND_GE:    return false;
3693   case X86::COND_L:     return false;
3694   case X86::COND_LE:    return false;
3695   case X86::COND_NE:    return true;
3696   case X86::COND_B:     return true;
3697   case X86::COND_A:     return true;
3698   case X86::COND_BE:    return true;
3699   case X86::COND_AE:    return true;
3700   }
3701   llvm_unreachable("covered switch fell through?!");
3702 }
3703
3704 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3705 /// specific condition code, returning the condition code and the LHS/RHS of the
3706 /// comparison to make.
3707 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3708                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3709   if (!isFP) {
3710     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3711       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3712         // X > -1   -> X == 0, jump !sign.
3713         RHS = DAG.getConstant(0, RHS.getValueType());
3714         return X86::COND_NS;
3715       }
3716       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3717         // X < 0   -> X == 0, jump on sign.
3718         return X86::COND_S;
3719       }
3720       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3721         // X < 1   -> X <= 0
3722         RHS = DAG.getConstant(0, RHS.getValueType());
3723         return X86::COND_LE;
3724       }
3725     }
3726
3727     switch (SetCCOpcode) {
3728     default: llvm_unreachable("Invalid integer condition!");
3729     case ISD::SETEQ:  return X86::COND_E;
3730     case ISD::SETGT:  return X86::COND_G;
3731     case ISD::SETGE:  return X86::COND_GE;
3732     case ISD::SETLT:  return X86::COND_L;
3733     case ISD::SETLE:  return X86::COND_LE;
3734     case ISD::SETNE:  return X86::COND_NE;
3735     case ISD::SETULT: return X86::COND_B;
3736     case ISD::SETUGT: return X86::COND_A;
3737     case ISD::SETULE: return X86::COND_BE;
3738     case ISD::SETUGE: return X86::COND_AE;
3739     }
3740   }
3741
3742   // First determine if it is required or is profitable to flip the operands.
3743
3744   // If LHS is a foldable load, but RHS is not, flip the condition.
3745   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3746       !ISD::isNON_EXTLoad(RHS.getNode())) {
3747     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3748     std::swap(LHS, RHS);
3749   }
3750
3751   switch (SetCCOpcode) {
3752   default: break;
3753   case ISD::SETOLT:
3754   case ISD::SETOLE:
3755   case ISD::SETUGT:
3756   case ISD::SETUGE:
3757     std::swap(LHS, RHS);
3758     break;
3759   }
3760
3761   // On a floating point condition, the flags are set as follows:
3762   // ZF  PF  CF   op
3763   //  0 | 0 | 0 | X > Y
3764   //  0 | 0 | 1 | X < Y
3765   //  1 | 0 | 0 | X == Y
3766   //  1 | 1 | 1 | unordered
3767   switch (SetCCOpcode) {
3768   default: llvm_unreachable("Condcode should be pre-legalized away");
3769   case ISD::SETUEQ:
3770   case ISD::SETEQ:   return X86::COND_E;
3771   case ISD::SETOLT:              // flipped
3772   case ISD::SETOGT:
3773   case ISD::SETGT:   return X86::COND_A;
3774   case ISD::SETOLE:              // flipped
3775   case ISD::SETOGE:
3776   case ISD::SETGE:   return X86::COND_AE;
3777   case ISD::SETUGT:              // flipped
3778   case ISD::SETULT:
3779   case ISD::SETLT:   return X86::COND_B;
3780   case ISD::SETUGE:              // flipped
3781   case ISD::SETULE:
3782   case ISD::SETLE:   return X86::COND_BE;
3783   case ISD::SETONE:
3784   case ISD::SETNE:   return X86::COND_NE;
3785   case ISD::SETUO:   return X86::COND_P;
3786   case ISD::SETO:    return X86::COND_NP;
3787   case ISD::SETOEQ:
3788   case ISD::SETUNE:  return X86::COND_INVALID;
3789   }
3790 }
3791
3792 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3793 /// code. Current x86 isa includes the following FP cmov instructions:
3794 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3795 static bool hasFPCMov(unsigned X86CC) {
3796   switch (X86CC) {
3797   default:
3798     return false;
3799   case X86::COND_B:
3800   case X86::COND_BE:
3801   case X86::COND_E:
3802   case X86::COND_P:
3803   case X86::COND_A:
3804   case X86::COND_AE:
3805   case X86::COND_NE:
3806   case X86::COND_NP:
3807     return true;
3808   }
3809 }
3810
3811 /// isFPImmLegal - Returns true if the target can instruction select the
3812 /// specified FP immediate natively. If false, the legalizer will
3813 /// materialize the FP immediate as a load from a constant pool.
3814 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3815   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3816     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3817       return true;
3818   }
3819   return false;
3820 }
3821
3822 /// \brief Returns true if it is beneficial to convert a load of a constant
3823 /// to just the constant itself.
3824 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3825                                                           Type *Ty) const {
3826   assert(Ty->isIntegerTy());
3827
3828   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3829   if (BitSize == 0 || BitSize > 64)
3830     return false;
3831   return true;
3832 }
3833
3834 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3835 /// the specified range (L, H].
3836 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3837   return (Val < 0) || (Val >= Low && Val < Hi);
3838 }
3839
3840 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3841 /// specified value.
3842 static bool isUndefOrEqual(int Val, int CmpVal) {
3843   return (Val < 0 || Val == CmpVal);
3844 }
3845
3846 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3847 /// from position Pos and ending in Pos+Size, falls within the specified
3848 /// sequential range (L, L+Pos]. or is undef.
3849 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3850                                        unsigned Pos, unsigned Size, int Low) {
3851   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3852     if (!isUndefOrEqual(Mask[i], Low))
3853       return false;
3854   return true;
3855 }
3856
3857 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3858 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3859 /// the second operand.
3860 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3861   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3862     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3863   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3864     return (Mask[0] < 2 && Mask[1] < 2);
3865   return false;
3866 }
3867
3868 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3869 /// is suitable for input to PSHUFHW.
3870 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3871   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3872     return false;
3873
3874   // Lower quadword copied in order or undef.
3875   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3876     return false;
3877
3878   // Upper quadword shuffled.
3879   for (unsigned i = 4; i != 8; ++i)
3880     if (!isUndefOrInRange(Mask[i], 4, 8))
3881       return false;
3882
3883   if (VT == MVT::v16i16) {
3884     // Lower quadword copied in order or undef.
3885     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3886       return false;
3887
3888     // Upper quadword shuffled.
3889     for (unsigned i = 12; i != 16; ++i)
3890       if (!isUndefOrInRange(Mask[i], 12, 16))
3891         return false;
3892   }
3893
3894   return true;
3895 }
3896
3897 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3898 /// is suitable for input to PSHUFLW.
3899 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3900   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3901     return false;
3902
3903   // Upper quadword copied in order.
3904   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3905     return false;
3906
3907   // Lower quadword shuffled.
3908   for (unsigned i = 0; i != 4; ++i)
3909     if (!isUndefOrInRange(Mask[i], 0, 4))
3910       return false;
3911
3912   if (VT == MVT::v16i16) {
3913     // Upper quadword copied in order.
3914     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3915       return false;
3916
3917     // Lower quadword shuffled.
3918     for (unsigned i = 8; i != 12; ++i)
3919       if (!isUndefOrInRange(Mask[i], 8, 12))
3920         return false;
3921   }
3922
3923   return true;
3924 }
3925
3926 /// \brief Return true if the mask specifies a shuffle of elements that is
3927 /// suitable for input to intralane (palignr) or interlane (valign) vector
3928 /// right-shift.
3929 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3930   unsigned NumElts = VT.getVectorNumElements();
3931   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3932   unsigned NumLaneElts = NumElts/NumLanes;
3933
3934   // Do not handle 64-bit element shuffles with palignr.
3935   if (NumLaneElts == 2)
3936     return false;
3937
3938   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3939     unsigned i;
3940     for (i = 0; i != NumLaneElts; ++i) {
3941       if (Mask[i+l] >= 0)
3942         break;
3943     }
3944
3945     // Lane is all undef, go to next lane
3946     if (i == NumLaneElts)
3947       continue;
3948
3949     int Start = Mask[i+l];
3950
3951     // Make sure its in this lane in one of the sources
3952     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3953         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3954       return false;
3955
3956     // If not lane 0, then we must match lane 0
3957     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3958       return false;
3959
3960     // Correct second source to be contiguous with first source
3961     if (Start >= (int)NumElts)
3962       Start -= NumElts - NumLaneElts;
3963
3964     // Make sure we're shifting in the right direction.
3965     if (Start <= (int)(i+l))
3966       return false;
3967
3968     Start -= i;
3969
3970     // Check the rest of the elements to see if they are consecutive.
3971     for (++i; i != NumLaneElts; ++i) {
3972       int Idx = Mask[i+l];
3973
3974       // Make sure its in this lane
3975       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3976           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3977         return false;
3978
3979       // If not lane 0, then we must match lane 0
3980       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3981         return false;
3982
3983       if (Idx >= (int)NumElts)
3984         Idx -= NumElts - NumLaneElts;
3985
3986       if (!isUndefOrEqual(Idx, Start+i))
3987         return false;
3988
3989     }
3990   }
3991
3992   return true;
3993 }
3994
3995 /// \brief Return true if the node specifies a shuffle of elements that is
3996 /// suitable for input to PALIGNR.
3997 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3998                           const X86Subtarget *Subtarget) {
3999   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4000       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4001       VT.is512BitVector())
4002     // FIXME: Add AVX512BW.
4003     return false;
4004
4005   return isAlignrMask(Mask, VT, false);
4006 }
4007
4008 /// \brief Return true if the node specifies a shuffle of elements that is
4009 /// suitable for input to VALIGN.
4010 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4011                           const X86Subtarget *Subtarget) {
4012   // FIXME: Add AVX512VL.
4013   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4014     return false;
4015   return isAlignrMask(Mask, VT, true);
4016 }
4017
4018 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4019 /// the two vector operands have swapped position.
4020 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4021                                      unsigned NumElems) {
4022   for (unsigned i = 0; i != NumElems; ++i) {
4023     int idx = Mask[i];
4024     if (idx < 0)
4025       continue;
4026     else if (idx < (int)NumElems)
4027       Mask[i] = idx + NumElems;
4028     else
4029       Mask[i] = idx - NumElems;
4030   }
4031 }
4032
4033 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4034 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4035 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4036 /// reverse of what x86 shuffles want.
4037 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4038
4039   unsigned NumElems = VT.getVectorNumElements();
4040   unsigned NumLanes = VT.getSizeInBits()/128;
4041   unsigned NumLaneElems = NumElems/NumLanes;
4042
4043   if (NumLaneElems != 2 && NumLaneElems != 4)
4044     return false;
4045
4046   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4047   bool symetricMaskRequired =
4048     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4049
4050   // VSHUFPSY divides the resulting vector into 4 chunks.
4051   // The sources are also splitted into 4 chunks, and each destination
4052   // chunk must come from a different source chunk.
4053   //
4054   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4055   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4056   //
4057   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4058   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4059   //
4060   // VSHUFPDY divides the resulting vector into 4 chunks.
4061   // The sources are also splitted into 4 chunks, and each destination
4062   // chunk must come from a different source chunk.
4063   //
4064   //  SRC1 =>      X3       X2       X1       X0
4065   //  SRC2 =>      Y3       Y2       Y1       Y0
4066   //
4067   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4068   //
4069   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4070   unsigned HalfLaneElems = NumLaneElems/2;
4071   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4072     for (unsigned i = 0; i != NumLaneElems; ++i) {
4073       int Idx = Mask[i+l];
4074       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4075       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4076         return false;
4077       // For VSHUFPSY, the mask of the second half must be the same as the
4078       // first but with the appropriate offsets. This works in the same way as
4079       // VPERMILPS works with masks.
4080       if (!symetricMaskRequired || Idx < 0)
4081         continue;
4082       if (MaskVal[i] < 0) {
4083         MaskVal[i] = Idx - l;
4084         continue;
4085       }
4086       if ((signed)(Idx - l) != MaskVal[i])
4087         return false;
4088     }
4089   }
4090
4091   return true;
4092 }
4093
4094 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4095 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4096 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4097   if (!VT.is128BitVector())
4098     return false;
4099
4100   unsigned NumElems = VT.getVectorNumElements();
4101
4102   if (NumElems != 4)
4103     return false;
4104
4105   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4106   return isUndefOrEqual(Mask[0], 6) &&
4107          isUndefOrEqual(Mask[1], 7) &&
4108          isUndefOrEqual(Mask[2], 2) &&
4109          isUndefOrEqual(Mask[3], 3);
4110 }
4111
4112 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4113 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4114 /// <2, 3, 2, 3>
4115 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4116   if (!VT.is128BitVector())
4117     return false;
4118
4119   unsigned NumElems = VT.getVectorNumElements();
4120
4121   if (NumElems != 4)
4122     return false;
4123
4124   return isUndefOrEqual(Mask[0], 2) &&
4125          isUndefOrEqual(Mask[1], 3) &&
4126          isUndefOrEqual(Mask[2], 2) &&
4127          isUndefOrEqual(Mask[3], 3);
4128 }
4129
4130 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4131 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4132 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4133   if (!VT.is128BitVector())
4134     return false;
4135
4136   unsigned NumElems = VT.getVectorNumElements();
4137
4138   if (NumElems != 2 && NumElems != 4)
4139     return false;
4140
4141   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4142     if (!isUndefOrEqual(Mask[i], i + NumElems))
4143       return false;
4144
4145   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4146     if (!isUndefOrEqual(Mask[i], i))
4147       return false;
4148
4149   return true;
4150 }
4151
4152 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4153 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4154 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4155   if (!VT.is128BitVector())
4156     return false;
4157
4158   unsigned NumElems = VT.getVectorNumElements();
4159
4160   if (NumElems != 2 && NumElems != 4)
4161     return false;
4162
4163   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4164     if (!isUndefOrEqual(Mask[i], i))
4165       return false;
4166
4167   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4168     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4169       return false;
4170
4171   return true;
4172 }
4173
4174 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4175 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4176 /// i. e: If all but one element come from the same vector.
4177 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4178   // TODO: Deal with AVX's VINSERTPS
4179   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4180     return false;
4181
4182   unsigned CorrectPosV1 = 0;
4183   unsigned CorrectPosV2 = 0;
4184   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4185     if (Mask[i] == -1) {
4186       ++CorrectPosV1;
4187       ++CorrectPosV2;
4188       continue;
4189     }
4190
4191     if (Mask[i] == i)
4192       ++CorrectPosV1;
4193     else if (Mask[i] == i + 4)
4194       ++CorrectPosV2;
4195   }
4196
4197   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4198     // We have 3 elements (undefs count as elements from any vector) from one
4199     // vector, and one from another.
4200     return true;
4201
4202   return false;
4203 }
4204
4205 //
4206 // Some special combinations that can be optimized.
4207 //
4208 static
4209 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4210                                SelectionDAG &DAG) {
4211   MVT VT = SVOp->getSimpleValueType(0);
4212   SDLoc dl(SVOp);
4213
4214   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4215     return SDValue();
4216
4217   ArrayRef<int> Mask = SVOp->getMask();
4218
4219   // These are the special masks that may be optimized.
4220   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4221   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4222   bool MatchEvenMask = true;
4223   bool MatchOddMask  = true;
4224   for (int i=0; i<8; ++i) {
4225     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4226       MatchEvenMask = false;
4227     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4228       MatchOddMask = false;
4229   }
4230
4231   if (!MatchEvenMask && !MatchOddMask)
4232     return SDValue();
4233
4234   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4235
4236   SDValue Op0 = SVOp->getOperand(0);
4237   SDValue Op1 = SVOp->getOperand(1);
4238
4239   if (MatchEvenMask) {
4240     // Shift the second operand right to 32 bits.
4241     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4242     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4243   } else {
4244     // Shift the first operand left to 32 bits.
4245     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4246     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4247   }
4248   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4249   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4250 }
4251
4252 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4253 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4254 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4255                          bool HasInt256, bool V2IsSplat = false) {
4256
4257   assert(VT.getSizeInBits() >= 128 &&
4258          "Unsupported vector type for unpckl");
4259
4260   unsigned NumElts = VT.getVectorNumElements();
4261   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4262       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4263     return false;
4264
4265   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4266          "Unsupported vector type for unpckh");
4267
4268   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4269   unsigned NumLanes = VT.getSizeInBits()/128;
4270   unsigned NumLaneElts = NumElts/NumLanes;
4271
4272   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4273     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4274       int BitI  = Mask[l+i];
4275       int BitI1 = Mask[l+i+1];
4276       if (!isUndefOrEqual(BitI, j))
4277         return false;
4278       if (V2IsSplat) {
4279         if (!isUndefOrEqual(BitI1, NumElts))
4280           return false;
4281       } else {
4282         if (!isUndefOrEqual(BitI1, j + NumElts))
4283           return false;
4284       }
4285     }
4286   }
4287
4288   return true;
4289 }
4290
4291 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4292 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4293 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4294                          bool HasInt256, bool V2IsSplat = false) {
4295   assert(VT.getSizeInBits() >= 128 &&
4296          "Unsupported vector type for unpckh");
4297
4298   unsigned NumElts = VT.getVectorNumElements();
4299   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4300       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4301     return false;
4302
4303   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4304          "Unsupported vector type for unpckh");
4305
4306   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4307   unsigned NumLanes = VT.getSizeInBits()/128;
4308   unsigned NumLaneElts = NumElts/NumLanes;
4309
4310   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4311     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4312       int BitI  = Mask[l+i];
4313       int BitI1 = Mask[l+i+1];
4314       if (!isUndefOrEqual(BitI, j))
4315         return false;
4316       if (V2IsSplat) {
4317         if (isUndefOrEqual(BitI1, NumElts))
4318           return false;
4319       } else {
4320         if (!isUndefOrEqual(BitI1, j+NumElts))
4321           return false;
4322       }
4323     }
4324   }
4325   return true;
4326 }
4327
4328 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4329 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4330 /// <0, 0, 1, 1>
4331 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4332   unsigned NumElts = VT.getVectorNumElements();
4333   bool Is256BitVec = VT.is256BitVector();
4334
4335   if (VT.is512BitVector())
4336     return false;
4337   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4338          "Unsupported vector type for unpckh");
4339
4340   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4341       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4342     return false;
4343
4344   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4345   // FIXME: Need a better way to get rid of this, there's no latency difference
4346   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4347   // the former later. We should also remove the "_undef" special mask.
4348   if (NumElts == 4 && Is256BitVec)
4349     return false;
4350
4351   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4352   // independently on 128-bit lanes.
4353   unsigned NumLanes = VT.getSizeInBits()/128;
4354   unsigned NumLaneElts = NumElts/NumLanes;
4355
4356   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4357     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4358       int BitI  = Mask[l+i];
4359       int BitI1 = Mask[l+i+1];
4360
4361       if (!isUndefOrEqual(BitI, j))
4362         return false;
4363       if (!isUndefOrEqual(BitI1, j))
4364         return false;
4365     }
4366   }
4367
4368   return true;
4369 }
4370
4371 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4372 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4373 /// <2, 2, 3, 3>
4374 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4375   unsigned NumElts = VT.getVectorNumElements();
4376
4377   if (VT.is512BitVector())
4378     return false;
4379
4380   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4381          "Unsupported vector type for unpckh");
4382
4383   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4384       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4385     return false;
4386
4387   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4388   // independently on 128-bit lanes.
4389   unsigned NumLanes = VT.getSizeInBits()/128;
4390   unsigned NumLaneElts = NumElts/NumLanes;
4391
4392   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4393     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4394       int BitI  = Mask[l+i];
4395       int BitI1 = Mask[l+i+1];
4396       if (!isUndefOrEqual(BitI, j))
4397         return false;
4398       if (!isUndefOrEqual(BitI1, j))
4399         return false;
4400     }
4401   }
4402   return true;
4403 }
4404
4405 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4406 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4407 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4408   if (!VT.is512BitVector())
4409     return false;
4410
4411   unsigned NumElts = VT.getVectorNumElements();
4412   unsigned HalfSize = NumElts/2;
4413   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4414     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4415       *Imm = 1;
4416       return true;
4417     }
4418   }
4419   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4420     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4421       *Imm = 0;
4422       return true;
4423     }
4424   }
4425   return false;
4426 }
4427
4428 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4429 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4430 /// MOVSD, and MOVD, i.e. setting the lowest element.
4431 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4432   if (VT.getVectorElementType().getSizeInBits() < 32)
4433     return false;
4434   if (!VT.is128BitVector())
4435     return false;
4436
4437   unsigned NumElts = VT.getVectorNumElements();
4438
4439   if (!isUndefOrEqual(Mask[0], NumElts))
4440     return false;
4441
4442   for (unsigned i = 1; i != NumElts; ++i)
4443     if (!isUndefOrEqual(Mask[i], i))
4444       return false;
4445
4446   return true;
4447 }
4448
4449 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4450 /// as permutations between 128-bit chunks or halves. As an example: this
4451 /// shuffle bellow:
4452 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4453 /// The first half comes from the second half of V1 and the second half from the
4454 /// the second half of V2.
4455 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4456   if (!HasFp256 || !VT.is256BitVector())
4457     return false;
4458
4459   // The shuffle result is divided into half A and half B. In total the two
4460   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4461   // B must come from C, D, E or F.
4462   unsigned HalfSize = VT.getVectorNumElements()/2;
4463   bool MatchA = false, MatchB = false;
4464
4465   // Check if A comes from one of C, D, E, F.
4466   for (unsigned Half = 0; Half != 4; ++Half) {
4467     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4468       MatchA = true;
4469       break;
4470     }
4471   }
4472
4473   // Check if B comes from one of C, D, E, F.
4474   for (unsigned Half = 0; Half != 4; ++Half) {
4475     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4476       MatchB = true;
4477       break;
4478     }
4479   }
4480
4481   return MatchA && MatchB;
4482 }
4483
4484 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4485 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4486 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4487   MVT VT = SVOp->getSimpleValueType(0);
4488
4489   unsigned HalfSize = VT.getVectorNumElements()/2;
4490
4491   unsigned FstHalf = 0, SndHalf = 0;
4492   for (unsigned i = 0; i < HalfSize; ++i) {
4493     if (SVOp->getMaskElt(i) > 0) {
4494       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4495       break;
4496     }
4497   }
4498   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4499     if (SVOp->getMaskElt(i) > 0) {
4500       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4501       break;
4502     }
4503   }
4504
4505   return (FstHalf | (SndHalf << 4));
4506 }
4507
4508 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4509 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4510   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4511   if (EltSize < 32)
4512     return false;
4513
4514   unsigned NumElts = VT.getVectorNumElements();
4515   Imm8 = 0;
4516   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4517     for (unsigned i = 0; i != NumElts; ++i) {
4518       if (Mask[i] < 0)
4519         continue;
4520       Imm8 |= Mask[i] << (i*2);
4521     }
4522     return true;
4523   }
4524
4525   unsigned LaneSize = 4;
4526   SmallVector<int, 4> MaskVal(LaneSize, -1);
4527
4528   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4529     for (unsigned i = 0; i != LaneSize; ++i) {
4530       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4531         return false;
4532       if (Mask[i+l] < 0)
4533         continue;
4534       if (MaskVal[i] < 0) {
4535         MaskVal[i] = Mask[i+l] - l;
4536         Imm8 |= MaskVal[i] << (i*2);
4537         continue;
4538       }
4539       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4540         return false;
4541     }
4542   }
4543   return true;
4544 }
4545
4546 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4547 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4548 /// Note that VPERMIL mask matching is different depending whether theunderlying
4549 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4550 /// to the same elements of the low, but to the higher half of the source.
4551 /// In VPERMILPD the two lanes could be shuffled independently of each other
4552 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4553 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4554   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4555   if (VT.getSizeInBits() < 256 || EltSize < 32)
4556     return false;
4557   bool symetricMaskRequired = (EltSize == 32);
4558   unsigned NumElts = VT.getVectorNumElements();
4559
4560   unsigned NumLanes = VT.getSizeInBits()/128;
4561   unsigned LaneSize = NumElts/NumLanes;
4562   // 2 or 4 elements in one lane
4563
4564   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4565   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4566     for (unsigned i = 0; i != LaneSize; ++i) {
4567       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4568         return false;
4569       if (symetricMaskRequired) {
4570         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4571           ExpectedMaskVal[i] = Mask[i+l] - l;
4572           continue;
4573         }
4574         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4575           return false;
4576       }
4577     }
4578   }
4579   return true;
4580 }
4581
4582 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4583 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4584 /// element of vector 2 and the other elements to come from vector 1 in order.
4585 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4586                                bool V2IsSplat = false, bool V2IsUndef = false) {
4587   if (!VT.is128BitVector())
4588     return false;
4589
4590   unsigned NumOps = VT.getVectorNumElements();
4591   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4592     return false;
4593
4594   if (!isUndefOrEqual(Mask[0], 0))
4595     return false;
4596
4597   for (unsigned i = 1; i != NumOps; ++i)
4598     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4599           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4600           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4601       return false;
4602
4603   return true;
4604 }
4605
4606 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4607 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4608 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4609 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4610                            const X86Subtarget *Subtarget) {
4611   if (!Subtarget->hasSSE3())
4612     return false;
4613
4614   unsigned NumElems = VT.getVectorNumElements();
4615
4616   if ((VT.is128BitVector() && NumElems != 4) ||
4617       (VT.is256BitVector() && NumElems != 8) ||
4618       (VT.is512BitVector() && NumElems != 16))
4619     return false;
4620
4621   // "i+1" is the value the indexed mask element must have
4622   for (unsigned i = 0; i != NumElems; i += 2)
4623     if (!isUndefOrEqual(Mask[i], i+1) ||
4624         !isUndefOrEqual(Mask[i+1], i+1))
4625       return false;
4626
4627   return true;
4628 }
4629
4630 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4631 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4632 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4633 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4634                            const X86Subtarget *Subtarget) {
4635   if (!Subtarget->hasSSE3())
4636     return false;
4637
4638   unsigned NumElems = VT.getVectorNumElements();
4639
4640   if ((VT.is128BitVector() && NumElems != 4) ||
4641       (VT.is256BitVector() && NumElems != 8) ||
4642       (VT.is512BitVector() && NumElems != 16))
4643     return false;
4644
4645   // "i" is the value the indexed mask element must have
4646   for (unsigned i = 0; i != NumElems; i += 2)
4647     if (!isUndefOrEqual(Mask[i], i) ||
4648         !isUndefOrEqual(Mask[i+1], i))
4649       return false;
4650
4651   return true;
4652 }
4653
4654 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4655 /// specifies a shuffle of elements that is suitable for input to 256-bit
4656 /// version of MOVDDUP.
4657 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4658   if (!HasFp256 || !VT.is256BitVector())
4659     return false;
4660
4661   unsigned NumElts = VT.getVectorNumElements();
4662   if (NumElts != 4)
4663     return false;
4664
4665   for (unsigned i = 0; i != NumElts/2; ++i)
4666     if (!isUndefOrEqual(Mask[i], 0))
4667       return false;
4668   for (unsigned i = NumElts/2; i != NumElts; ++i)
4669     if (!isUndefOrEqual(Mask[i], NumElts/2))
4670       return false;
4671   return true;
4672 }
4673
4674 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4675 /// specifies a shuffle of elements that is suitable for input to 128-bit
4676 /// version of MOVDDUP.
4677 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4678   if (!VT.is128BitVector())
4679     return false;
4680
4681   unsigned e = VT.getVectorNumElements() / 2;
4682   for (unsigned i = 0; i != e; ++i)
4683     if (!isUndefOrEqual(Mask[i], i))
4684       return false;
4685   for (unsigned i = 0; i != e; ++i)
4686     if (!isUndefOrEqual(Mask[e+i], i))
4687       return false;
4688   return true;
4689 }
4690
4691 /// isVEXTRACTIndex - Return true if the specified
4692 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4693 /// suitable for instruction that extract 128 or 256 bit vectors
4694 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4695   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4696   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4697     return false;
4698
4699   // The index should be aligned on a vecWidth-bit boundary.
4700   uint64_t Index =
4701     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4702
4703   MVT VT = N->getSimpleValueType(0);
4704   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4705   bool Result = (Index * ElSize) % vecWidth == 0;
4706
4707   return Result;
4708 }
4709
4710 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4711 /// operand specifies a subvector insert that is suitable for input to
4712 /// insertion of 128 or 256-bit subvectors
4713 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4714   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4715   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4716     return false;
4717   // The index should be aligned on a vecWidth-bit boundary.
4718   uint64_t Index =
4719     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4720
4721   MVT VT = N->getSimpleValueType(0);
4722   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4723   bool Result = (Index * ElSize) % vecWidth == 0;
4724
4725   return Result;
4726 }
4727
4728 bool X86::isVINSERT128Index(SDNode *N) {
4729   return isVINSERTIndex(N, 128);
4730 }
4731
4732 bool X86::isVINSERT256Index(SDNode *N) {
4733   return isVINSERTIndex(N, 256);
4734 }
4735
4736 bool X86::isVEXTRACT128Index(SDNode *N) {
4737   return isVEXTRACTIndex(N, 128);
4738 }
4739
4740 bool X86::isVEXTRACT256Index(SDNode *N) {
4741   return isVEXTRACTIndex(N, 256);
4742 }
4743
4744 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4745 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4746 /// Handles 128-bit and 256-bit.
4747 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4748   MVT VT = N->getSimpleValueType(0);
4749
4750   assert((VT.getSizeInBits() >= 128) &&
4751          "Unsupported vector type for PSHUF/SHUFP");
4752
4753   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4754   // independently on 128-bit lanes.
4755   unsigned NumElts = VT.getVectorNumElements();
4756   unsigned NumLanes = VT.getSizeInBits()/128;
4757   unsigned NumLaneElts = NumElts/NumLanes;
4758
4759   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4760          "Only supports 2, 4 or 8 elements per lane");
4761
4762   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4763   unsigned Mask = 0;
4764   for (unsigned i = 0; i != NumElts; ++i) {
4765     int Elt = N->getMaskElt(i);
4766     if (Elt < 0) continue;
4767     Elt &= NumLaneElts - 1;
4768     unsigned ShAmt = (i << Shift) % 8;
4769     Mask |= Elt << ShAmt;
4770   }
4771
4772   return Mask;
4773 }
4774
4775 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4776 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4777 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4778   MVT VT = N->getSimpleValueType(0);
4779
4780   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4781          "Unsupported vector type for PSHUFHW");
4782
4783   unsigned NumElts = VT.getVectorNumElements();
4784
4785   unsigned Mask = 0;
4786   for (unsigned l = 0; l != NumElts; l += 8) {
4787     // 8 nodes per lane, but we only care about the last 4.
4788     for (unsigned i = 0; i < 4; ++i) {
4789       int Elt = N->getMaskElt(l+i+4);
4790       if (Elt < 0) continue;
4791       Elt &= 0x3; // only 2-bits.
4792       Mask |= Elt << (i * 2);
4793     }
4794   }
4795
4796   return Mask;
4797 }
4798
4799 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4800 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4801 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4802   MVT VT = N->getSimpleValueType(0);
4803
4804   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4805          "Unsupported vector type for PSHUFHW");
4806
4807   unsigned NumElts = VT.getVectorNumElements();
4808
4809   unsigned Mask = 0;
4810   for (unsigned l = 0; l != NumElts; l += 8) {
4811     // 8 nodes per lane, but we only care about the first 4.
4812     for (unsigned i = 0; i < 4; ++i) {
4813       int Elt = N->getMaskElt(l+i);
4814       if (Elt < 0) continue;
4815       Elt &= 0x3; // only 2-bits
4816       Mask |= Elt << (i * 2);
4817     }
4818   }
4819
4820   return Mask;
4821 }
4822
4823 /// \brief Return the appropriate immediate to shuffle the specified
4824 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4825 /// VALIGN (if Interlane is true) instructions.
4826 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4827                                            bool InterLane) {
4828   MVT VT = SVOp->getSimpleValueType(0);
4829   unsigned EltSize = InterLane ? 1 :
4830     VT.getVectorElementType().getSizeInBits() >> 3;
4831
4832   unsigned NumElts = VT.getVectorNumElements();
4833   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4834   unsigned NumLaneElts = NumElts/NumLanes;
4835
4836   int Val = 0;
4837   unsigned i;
4838   for (i = 0; i != NumElts; ++i) {
4839     Val = SVOp->getMaskElt(i);
4840     if (Val >= 0)
4841       break;
4842   }
4843   if (Val >= (int)NumElts)
4844     Val -= NumElts - NumLaneElts;
4845
4846   assert(Val - i > 0 && "PALIGNR imm should be positive");
4847   return (Val - i) * EltSize;
4848 }
4849
4850 /// \brief Return the appropriate immediate to shuffle the specified
4851 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4852 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4853   return getShuffleAlignrImmediate(SVOp, false);
4854 }
4855
4856 /// \brief Return the appropriate immediate to shuffle the specified
4857 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4858 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4859   return getShuffleAlignrImmediate(SVOp, true);
4860 }
4861
4862
4863 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4864   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4865   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4866     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4867
4868   uint64_t Index =
4869     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4870
4871   MVT VecVT = N->getOperand(0).getSimpleValueType();
4872   MVT ElVT = VecVT.getVectorElementType();
4873
4874   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4875   return Index / NumElemsPerChunk;
4876 }
4877
4878 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4879   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4880   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4881     llvm_unreachable("Illegal insert subvector for VINSERT");
4882
4883   uint64_t Index =
4884     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4885
4886   MVT VecVT = N->getSimpleValueType(0);
4887   MVT ElVT = VecVT.getVectorElementType();
4888
4889   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4890   return Index / NumElemsPerChunk;
4891 }
4892
4893 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4894 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4895 /// and VINSERTI128 instructions.
4896 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4897   return getExtractVEXTRACTImmediate(N, 128);
4898 }
4899
4900 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4901 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4902 /// and VINSERTI64x4 instructions.
4903 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4904   return getExtractVEXTRACTImmediate(N, 256);
4905 }
4906
4907 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4908 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4909 /// and VINSERTI128 instructions.
4910 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4911   return getInsertVINSERTImmediate(N, 128);
4912 }
4913
4914 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4915 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4916 /// and VINSERTI64x4 instructions.
4917 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4918   return getInsertVINSERTImmediate(N, 256);
4919 }
4920
4921 /// isZero - Returns true if Elt is a constant integer zero
4922 static bool isZero(SDValue V) {
4923   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4924   return C && C->isNullValue();
4925 }
4926
4927 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4928 /// constant +0.0.
4929 bool X86::isZeroNode(SDValue Elt) {
4930   if (isZero(Elt))
4931     return true;
4932   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4933     return CFP->getValueAPF().isPosZero();
4934   return false;
4935 }
4936
4937 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4938 /// match movhlps. The lower half elements should come from upper half of
4939 /// V1 (and in order), and the upper half elements should come from the upper
4940 /// half of V2 (and in order).
4941 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4942   if (!VT.is128BitVector())
4943     return false;
4944   if (VT.getVectorNumElements() != 4)
4945     return false;
4946   for (unsigned i = 0, e = 2; i != e; ++i)
4947     if (!isUndefOrEqual(Mask[i], i+2))
4948       return false;
4949   for (unsigned i = 2; i != 4; ++i)
4950     if (!isUndefOrEqual(Mask[i], i+4))
4951       return false;
4952   return true;
4953 }
4954
4955 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4956 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4957 /// required.
4958 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4959   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4960     return false;
4961   N = N->getOperand(0).getNode();
4962   if (!ISD::isNON_EXTLoad(N))
4963     return false;
4964   if (LD)
4965     *LD = cast<LoadSDNode>(N);
4966   return true;
4967 }
4968
4969 // Test whether the given value is a vector value which will be legalized
4970 // into a load.
4971 static bool WillBeConstantPoolLoad(SDNode *N) {
4972   if (N->getOpcode() != ISD::BUILD_VECTOR)
4973     return false;
4974
4975   // Check for any non-constant elements.
4976   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4977     switch (N->getOperand(i).getNode()->getOpcode()) {
4978     case ISD::UNDEF:
4979     case ISD::ConstantFP:
4980     case ISD::Constant:
4981       break;
4982     default:
4983       return false;
4984     }
4985
4986   // Vectors of all-zeros and all-ones are materialized with special
4987   // instructions rather than being loaded.
4988   return !ISD::isBuildVectorAllZeros(N) &&
4989          !ISD::isBuildVectorAllOnes(N);
4990 }
4991
4992 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4993 /// match movlp{s|d}. The lower half elements should come from lower half of
4994 /// V1 (and in order), and the upper half elements should come from the upper
4995 /// half of V2 (and in order). And since V1 will become the source of the
4996 /// MOVLP, it must be either a vector load or a scalar load to vector.
4997 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4998                                ArrayRef<int> Mask, MVT VT) {
4999   if (!VT.is128BitVector())
5000     return false;
5001
5002   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5003     return false;
5004   // Is V2 is a vector load, don't do this transformation. We will try to use
5005   // load folding shufps op.
5006   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5007     return false;
5008
5009   unsigned NumElems = VT.getVectorNumElements();
5010
5011   if (NumElems != 2 && NumElems != 4)
5012     return false;
5013   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5014     if (!isUndefOrEqual(Mask[i], i))
5015       return false;
5016   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5017     if (!isUndefOrEqual(Mask[i], i+NumElems))
5018       return false;
5019   return true;
5020 }
5021
5022 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5023 /// to an zero vector.
5024 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5025 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5026   SDValue V1 = N->getOperand(0);
5027   SDValue V2 = N->getOperand(1);
5028   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5029   for (unsigned i = 0; i != NumElems; ++i) {
5030     int Idx = N->getMaskElt(i);
5031     if (Idx >= (int)NumElems) {
5032       unsigned Opc = V2.getOpcode();
5033       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5034         continue;
5035       if (Opc != ISD::BUILD_VECTOR ||
5036           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5037         return false;
5038     } else if (Idx >= 0) {
5039       unsigned Opc = V1.getOpcode();
5040       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5041         continue;
5042       if (Opc != ISD::BUILD_VECTOR ||
5043           !X86::isZeroNode(V1.getOperand(Idx)))
5044         return false;
5045     }
5046   }
5047   return true;
5048 }
5049
5050 /// getZeroVector - Returns a vector of specified type with all zero elements.
5051 ///
5052 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5053                              SelectionDAG &DAG, SDLoc dl) {
5054   assert(VT.isVector() && "Expected a vector type");
5055
5056   // Always build SSE zero vectors as <4 x i32> bitcasted
5057   // to their dest type. This ensures they get CSE'd.
5058   SDValue Vec;
5059   if (VT.is128BitVector()) {  // SSE
5060     if (Subtarget->hasSSE2()) {  // SSE2
5061       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5062       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5063     } else { // SSE1
5064       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5065       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5066     }
5067   } else if (VT.is256BitVector()) { // AVX
5068     if (Subtarget->hasInt256()) { // AVX2
5069       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5070       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5071       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5072     } else {
5073       // 256-bit logic and arithmetic instructions in AVX are all
5074       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5075       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5076       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5077       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5078     }
5079   } else if (VT.is512BitVector()) { // AVX-512
5080       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5081       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5082                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5083       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5084   } else if (VT.getScalarType() == MVT::i1) {
5085     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5086     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5087     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5088     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5089   } else
5090     llvm_unreachable("Unexpected vector type");
5091
5092   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5093 }
5094
5095 /// getOnesVector - Returns a vector of specified type with all bits set.
5096 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5097 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5098 /// Then bitcast to their original type, ensuring they get CSE'd.
5099 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5100                              SDLoc dl) {
5101   assert(VT.isVector() && "Expected a vector type");
5102
5103   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5104   SDValue Vec;
5105   if (VT.is256BitVector()) {
5106     if (HasInt256) { // AVX2
5107       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5108       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5109     } else { // AVX
5110       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5111       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5112     }
5113   } else if (VT.is128BitVector()) {
5114     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5115   } else
5116     llvm_unreachable("Unexpected vector type");
5117
5118   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5119 }
5120
5121 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5122 /// that point to V2 points to its first element.
5123 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5124   for (unsigned i = 0; i != NumElems; ++i) {
5125     if (Mask[i] > (int)NumElems) {
5126       Mask[i] = NumElems;
5127     }
5128   }
5129 }
5130
5131 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5132 /// operation of specified width.
5133 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5134                        SDValue V2) {
5135   unsigned NumElems = VT.getVectorNumElements();
5136   SmallVector<int, 8> Mask;
5137   Mask.push_back(NumElems);
5138   for (unsigned i = 1; i != NumElems; ++i)
5139     Mask.push_back(i);
5140   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5141 }
5142
5143 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5144 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5145                           SDValue V2) {
5146   unsigned NumElems = VT.getVectorNumElements();
5147   SmallVector<int, 8> Mask;
5148   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5149     Mask.push_back(i);
5150     Mask.push_back(i + NumElems);
5151   }
5152   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5153 }
5154
5155 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5156 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5157                           SDValue V2) {
5158   unsigned NumElems = VT.getVectorNumElements();
5159   SmallVector<int, 8> Mask;
5160   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5161     Mask.push_back(i + Half);
5162     Mask.push_back(i + NumElems + Half);
5163   }
5164   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5165 }
5166
5167 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5168 // a generic shuffle instruction because the target has no such instructions.
5169 // Generate shuffles which repeat i16 and i8 several times until they can be
5170 // represented by v4f32 and then be manipulated by target suported shuffles.
5171 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5172   MVT VT = V.getSimpleValueType();
5173   int NumElems = VT.getVectorNumElements();
5174   SDLoc dl(V);
5175
5176   while (NumElems > 4) {
5177     if (EltNo < NumElems/2) {
5178       V = getUnpackl(DAG, dl, VT, V, V);
5179     } else {
5180       V = getUnpackh(DAG, dl, VT, V, V);
5181       EltNo -= NumElems/2;
5182     }
5183     NumElems >>= 1;
5184   }
5185   return V;
5186 }
5187
5188 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5189 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5190   MVT VT = V.getSimpleValueType();
5191   SDLoc dl(V);
5192
5193   if (VT.is128BitVector()) {
5194     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5195     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5196     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5197                              &SplatMask[0]);
5198   } else if (VT.is256BitVector()) {
5199     // To use VPERMILPS to splat scalars, the second half of indicies must
5200     // refer to the higher part, which is a duplication of the lower one,
5201     // because VPERMILPS can only handle in-lane permutations.
5202     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5203                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5204
5205     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5206     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5207                              &SplatMask[0]);
5208   } else
5209     llvm_unreachable("Vector size not supported");
5210
5211   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5212 }
5213
5214 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5215 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5216   MVT SrcVT = SV->getSimpleValueType(0);
5217   SDValue V1 = SV->getOperand(0);
5218   SDLoc dl(SV);
5219
5220   int EltNo = SV->getSplatIndex();
5221   int NumElems = SrcVT.getVectorNumElements();
5222   bool Is256BitVec = SrcVT.is256BitVector();
5223
5224   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5225          "Unknown how to promote splat for type");
5226
5227   // Extract the 128-bit part containing the splat element and update
5228   // the splat element index when it refers to the higher register.
5229   if (Is256BitVec) {
5230     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5231     if (EltNo >= NumElems/2)
5232       EltNo -= NumElems/2;
5233   }
5234
5235   // All i16 and i8 vector types can't be used directly by a generic shuffle
5236   // instruction because the target has no such instruction. Generate shuffles
5237   // which repeat i16 and i8 several times until they fit in i32, and then can
5238   // be manipulated by target suported shuffles.
5239   MVT EltVT = SrcVT.getVectorElementType();
5240   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5241     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5242
5243   // Recreate the 256-bit vector and place the same 128-bit vector
5244   // into the low and high part. This is necessary because we want
5245   // to use VPERM* to shuffle the vectors
5246   if (Is256BitVec) {
5247     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5248   }
5249
5250   return getLegalSplat(DAG, V1, EltNo);
5251 }
5252
5253 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5254 /// vector of zero or undef vector.  This produces a shuffle where the low
5255 /// element of V2 is swizzled into the zero/undef vector, landing at element
5256 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5257 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5258                                            bool IsZero,
5259                                            const X86Subtarget *Subtarget,
5260                                            SelectionDAG &DAG) {
5261   MVT VT = V2.getSimpleValueType();
5262   SDValue V1 = IsZero
5263     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5264   unsigned NumElems = VT.getVectorNumElements();
5265   SmallVector<int, 16> MaskVec;
5266   for (unsigned i = 0; i != NumElems; ++i)
5267     // If this is the insertion idx, put the low elt of V2 here.
5268     MaskVec.push_back(i == Idx ? NumElems : i);
5269   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5270 }
5271
5272 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5273 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5274 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5275 /// shuffles which use a single input multiple times, and in those cases it will
5276 /// adjust the mask to only have indices within that single input.
5277 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5278                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5279   unsigned NumElems = VT.getVectorNumElements();
5280   SDValue ImmN;
5281
5282   IsUnary = false;
5283   bool IsFakeUnary = false;
5284   switch(N->getOpcode()) {
5285   case X86ISD::BLENDI:
5286     ImmN = N->getOperand(N->getNumOperands()-1);
5287     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5288     break;
5289   case X86ISD::SHUFP:
5290     ImmN = N->getOperand(N->getNumOperands()-1);
5291     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5292     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5293     break;
5294   case X86ISD::UNPCKH:
5295     DecodeUNPCKHMask(VT, Mask);
5296     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5297     break;
5298   case X86ISD::UNPCKL:
5299     DecodeUNPCKLMask(VT, Mask);
5300     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5301     break;
5302   case X86ISD::MOVHLPS:
5303     DecodeMOVHLPSMask(NumElems, Mask);
5304     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5305     break;
5306   case X86ISD::MOVLHPS:
5307     DecodeMOVLHPSMask(NumElems, Mask);
5308     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5309     break;
5310   case X86ISD::PALIGNR:
5311     ImmN = N->getOperand(N->getNumOperands()-1);
5312     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5313     break;
5314   case X86ISD::PSHUFD:
5315   case X86ISD::VPERMILPI:
5316     ImmN = N->getOperand(N->getNumOperands()-1);
5317     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5318     IsUnary = true;
5319     break;
5320   case X86ISD::PSHUFHW:
5321     ImmN = N->getOperand(N->getNumOperands()-1);
5322     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5323     IsUnary = true;
5324     break;
5325   case X86ISD::PSHUFLW:
5326     ImmN = N->getOperand(N->getNumOperands()-1);
5327     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5328     IsUnary = true;
5329     break;
5330   case X86ISD::PSHUFB: {
5331     IsUnary = true;
5332     SDValue MaskNode = N->getOperand(1);
5333     while (MaskNode->getOpcode() == ISD::BITCAST)
5334       MaskNode = MaskNode->getOperand(0);
5335
5336     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5337       // If we have a build-vector, then things are easy.
5338       EVT VT = MaskNode.getValueType();
5339       assert(VT.isVector() &&
5340              "Can't produce a non-vector with a build_vector!");
5341       if (!VT.isInteger())
5342         return false;
5343
5344       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5345
5346       SmallVector<uint64_t, 32> RawMask;
5347       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5348         SDValue Op = MaskNode->getOperand(i);
5349         if (Op->getOpcode() == ISD::UNDEF) {
5350           RawMask.push_back((uint64_t)SM_SentinelUndef);
5351           continue;
5352         }
5353         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5354         if (!CN)
5355           return false;
5356         APInt MaskElement = CN->getAPIntValue();
5357
5358         // We now have to decode the element which could be any integer size and
5359         // extract each byte of it.
5360         for (int j = 0; j < NumBytesPerElement; ++j) {
5361           // Note that this is x86 and so always little endian: the low byte is
5362           // the first byte of the mask.
5363           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5364           MaskElement = MaskElement.lshr(8);
5365         }
5366       }
5367       DecodePSHUFBMask(RawMask, Mask);
5368       break;
5369     }
5370
5371     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5372     if (!MaskLoad)
5373       return false;
5374
5375     SDValue Ptr = MaskLoad->getBasePtr();
5376     if (Ptr->getOpcode() == X86ISD::Wrapper)
5377       Ptr = Ptr->getOperand(0);
5378
5379     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5380     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5381       return false;
5382
5383     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5384       // FIXME: Support AVX-512 here.
5385       Type *Ty = C->getType();
5386       if (!Ty->isVectorTy() || (Ty->getVectorNumElements() != 16 &&
5387                                 Ty->getVectorNumElements() != 32))
5388         return false;
5389
5390       DecodePSHUFBMask(C, Mask);
5391       break;
5392     }
5393
5394     return false;
5395   }
5396   case X86ISD::VPERMI:
5397     ImmN = N->getOperand(N->getNumOperands()-1);
5398     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5399     IsUnary = true;
5400     break;
5401   case X86ISD::MOVSS:
5402   case X86ISD::MOVSD: {
5403     // The index 0 always comes from the first element of the second source,
5404     // this is why MOVSS and MOVSD are used in the first place. The other
5405     // elements come from the other positions of the first source vector
5406     Mask.push_back(NumElems);
5407     for (unsigned i = 1; i != NumElems; ++i) {
5408       Mask.push_back(i);
5409     }
5410     break;
5411   }
5412   case X86ISD::VPERM2X128:
5413     ImmN = N->getOperand(N->getNumOperands()-1);
5414     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5415     if (Mask.empty()) return false;
5416     break;
5417   case X86ISD::MOVSLDUP:
5418     DecodeMOVSLDUPMask(VT, Mask);
5419     break;
5420   case X86ISD::MOVSHDUP:
5421     DecodeMOVSHDUPMask(VT, Mask);
5422     break;
5423   case X86ISD::MOVDDUP:
5424   case X86ISD::MOVLHPD:
5425   case X86ISD::MOVLPD:
5426   case X86ISD::MOVLPS:
5427     // Not yet implemented
5428     return false;
5429   default: llvm_unreachable("unknown target shuffle node");
5430   }
5431
5432   // If we have a fake unary shuffle, the shuffle mask is spread across two
5433   // inputs that are actually the same node. Re-map the mask to always point
5434   // into the first input.
5435   if (IsFakeUnary)
5436     for (int &M : Mask)
5437       if (M >= (int)Mask.size())
5438         M -= Mask.size();
5439
5440   return true;
5441 }
5442
5443 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5444 /// element of the result of the vector shuffle.
5445 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5446                                    unsigned Depth) {
5447   if (Depth == 6)
5448     return SDValue();  // Limit search depth.
5449
5450   SDValue V = SDValue(N, 0);
5451   EVT VT = V.getValueType();
5452   unsigned Opcode = V.getOpcode();
5453
5454   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5455   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5456     int Elt = SV->getMaskElt(Index);
5457
5458     if (Elt < 0)
5459       return DAG.getUNDEF(VT.getVectorElementType());
5460
5461     unsigned NumElems = VT.getVectorNumElements();
5462     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5463                                          : SV->getOperand(1);
5464     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5465   }
5466
5467   // Recurse into target specific vector shuffles to find scalars.
5468   if (isTargetShuffle(Opcode)) {
5469     MVT ShufVT = V.getSimpleValueType();
5470     unsigned NumElems = ShufVT.getVectorNumElements();
5471     SmallVector<int, 16> ShuffleMask;
5472     bool IsUnary;
5473
5474     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5475       return SDValue();
5476
5477     int Elt = ShuffleMask[Index];
5478     if (Elt < 0)
5479       return DAG.getUNDEF(ShufVT.getVectorElementType());
5480
5481     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5482                                          : N->getOperand(1);
5483     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5484                                Depth+1);
5485   }
5486
5487   // Actual nodes that may contain scalar elements
5488   if (Opcode == ISD::BITCAST) {
5489     V = V.getOperand(0);
5490     EVT SrcVT = V.getValueType();
5491     unsigned NumElems = VT.getVectorNumElements();
5492
5493     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5494       return SDValue();
5495   }
5496
5497   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5498     return (Index == 0) ? V.getOperand(0)
5499                         : DAG.getUNDEF(VT.getVectorElementType());
5500
5501   if (V.getOpcode() == ISD::BUILD_VECTOR)
5502     return V.getOperand(Index);
5503
5504   return SDValue();
5505 }
5506
5507 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5508 /// shuffle operation which come from a consecutively from a zero. The
5509 /// search can start in two different directions, from left or right.
5510 /// We count undefs as zeros until PreferredNum is reached.
5511 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5512                                          unsigned NumElems, bool ZerosFromLeft,
5513                                          SelectionDAG &DAG,
5514                                          unsigned PreferredNum = -1U) {
5515   unsigned NumZeros = 0;
5516   for (unsigned i = 0; i != NumElems; ++i) {
5517     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5518     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5519     if (!Elt.getNode())
5520       break;
5521
5522     if (X86::isZeroNode(Elt))
5523       ++NumZeros;
5524     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5525       NumZeros = std::min(NumZeros + 1, PreferredNum);
5526     else
5527       break;
5528   }
5529
5530   return NumZeros;
5531 }
5532
5533 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5534 /// correspond consecutively to elements from one of the vector operands,
5535 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5536 static
5537 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5538                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5539                               unsigned NumElems, unsigned &OpNum) {
5540   bool SeenV1 = false;
5541   bool SeenV2 = false;
5542
5543   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5544     int Idx = SVOp->getMaskElt(i);
5545     // Ignore undef indicies
5546     if (Idx < 0)
5547       continue;
5548
5549     if (Idx < (int)NumElems)
5550       SeenV1 = true;
5551     else
5552       SeenV2 = true;
5553
5554     // Only accept consecutive elements from the same vector
5555     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5556       return false;
5557   }
5558
5559   OpNum = SeenV1 ? 0 : 1;
5560   return true;
5561 }
5562
5563 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5564 /// logical left shift of a vector.
5565 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5566                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5567   unsigned NumElems =
5568     SVOp->getSimpleValueType(0).getVectorNumElements();
5569   unsigned NumZeros = getNumOfConsecutiveZeros(
5570       SVOp, NumElems, false /* check zeros from right */, DAG,
5571       SVOp->getMaskElt(0));
5572   unsigned OpSrc;
5573
5574   if (!NumZeros)
5575     return false;
5576
5577   // Considering the elements in the mask that are not consecutive zeros,
5578   // check if they consecutively come from only one of the source vectors.
5579   //
5580   //               V1 = {X, A, B, C}     0
5581   //                         \  \  \    /
5582   //   vector_shuffle V1, V2 <1, 2, 3, X>
5583   //
5584   if (!isShuffleMaskConsecutive(SVOp,
5585             0,                   // Mask Start Index
5586             NumElems-NumZeros,   // Mask End Index(exclusive)
5587             NumZeros,            // Where to start looking in the src vector
5588             NumElems,            // Number of elements in vector
5589             OpSrc))              // Which source operand ?
5590     return false;
5591
5592   isLeft = false;
5593   ShAmt = NumZeros;
5594   ShVal = SVOp->getOperand(OpSrc);
5595   return true;
5596 }
5597
5598 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5599 /// logical left shift of a vector.
5600 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5601                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5602   unsigned NumElems =
5603     SVOp->getSimpleValueType(0).getVectorNumElements();
5604   unsigned NumZeros = getNumOfConsecutiveZeros(
5605       SVOp, NumElems, true /* check zeros from left */, DAG,
5606       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5607   unsigned OpSrc;
5608
5609   if (!NumZeros)
5610     return false;
5611
5612   // Considering the elements in the mask that are not consecutive zeros,
5613   // check if they consecutively come from only one of the source vectors.
5614   //
5615   //                           0    { A, B, X, X } = V2
5616   //                          / \    /  /
5617   //   vector_shuffle V1, V2 <X, X, 4, 5>
5618   //
5619   if (!isShuffleMaskConsecutive(SVOp,
5620             NumZeros,     // Mask Start Index
5621             NumElems,     // Mask End Index(exclusive)
5622             0,            // Where to start looking in the src vector
5623             NumElems,     // Number of elements in vector
5624             OpSrc))       // Which source operand ?
5625     return false;
5626
5627   isLeft = true;
5628   ShAmt = NumZeros;
5629   ShVal = SVOp->getOperand(OpSrc);
5630   return true;
5631 }
5632
5633 /// isVectorShift - Returns true if the shuffle can be implemented as a
5634 /// logical left or right shift of a vector.
5635 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5636                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5637   // Although the logic below support any bitwidth size, there are no
5638   // shift instructions which handle more than 128-bit vectors.
5639   if (!SVOp->getSimpleValueType(0).is128BitVector())
5640     return false;
5641
5642   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5643       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5644     return true;
5645
5646   return false;
5647 }
5648
5649 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5650 ///
5651 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5652                                        unsigned NumNonZero, unsigned NumZero,
5653                                        SelectionDAG &DAG,
5654                                        const X86Subtarget* Subtarget,
5655                                        const TargetLowering &TLI) {
5656   if (NumNonZero > 8)
5657     return SDValue();
5658
5659   SDLoc dl(Op);
5660   SDValue V;
5661   bool First = true;
5662   for (unsigned i = 0; i < 16; ++i) {
5663     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5664     if (ThisIsNonZero && First) {
5665       if (NumZero)
5666         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5667       else
5668         V = DAG.getUNDEF(MVT::v8i16);
5669       First = false;
5670     }
5671
5672     if ((i & 1) != 0) {
5673       SDValue ThisElt, LastElt;
5674       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5675       if (LastIsNonZero) {
5676         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5677                               MVT::i16, Op.getOperand(i-1));
5678       }
5679       if (ThisIsNonZero) {
5680         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5681         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5682                               ThisElt, DAG.getConstant(8, MVT::i8));
5683         if (LastIsNonZero)
5684           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5685       } else
5686         ThisElt = LastElt;
5687
5688       if (ThisElt.getNode())
5689         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5690                         DAG.getIntPtrConstant(i/2));
5691     }
5692   }
5693
5694   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5695 }
5696
5697 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5698 ///
5699 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5700                                      unsigned NumNonZero, unsigned NumZero,
5701                                      SelectionDAG &DAG,
5702                                      const X86Subtarget* Subtarget,
5703                                      const TargetLowering &TLI) {
5704   if (NumNonZero > 4)
5705     return SDValue();
5706
5707   SDLoc dl(Op);
5708   SDValue V;
5709   bool First = true;
5710   for (unsigned i = 0; i < 8; ++i) {
5711     bool isNonZero = (NonZeros & (1 << i)) != 0;
5712     if (isNonZero) {
5713       if (First) {
5714         if (NumZero)
5715           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5716         else
5717           V = DAG.getUNDEF(MVT::v8i16);
5718         First = false;
5719       }
5720       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5721                       MVT::v8i16, V, Op.getOperand(i),
5722                       DAG.getIntPtrConstant(i));
5723     }
5724   }
5725
5726   return V;
5727 }
5728
5729 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5730 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5731                                      unsigned NonZeros, unsigned NumNonZero,
5732                                      unsigned NumZero, SelectionDAG &DAG,
5733                                      const X86Subtarget *Subtarget,
5734                                      const TargetLowering &TLI) {
5735   // We know there's at least one non-zero element
5736   unsigned FirstNonZeroIdx = 0;
5737   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5738   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5739          X86::isZeroNode(FirstNonZero)) {
5740     ++FirstNonZeroIdx;
5741     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5742   }
5743
5744   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5745       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5746     return SDValue();
5747
5748   SDValue V = FirstNonZero.getOperand(0);
5749   MVT VVT = V.getSimpleValueType();
5750   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5751     return SDValue();
5752
5753   unsigned FirstNonZeroDst =
5754       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5755   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5756   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5757   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5758
5759   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5760     SDValue Elem = Op.getOperand(Idx);
5761     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5762       continue;
5763
5764     // TODO: What else can be here? Deal with it.
5765     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5766       return SDValue();
5767
5768     // TODO: Some optimizations are still possible here
5769     // ex: Getting one element from a vector, and the rest from another.
5770     if (Elem.getOperand(0) != V)
5771       return SDValue();
5772
5773     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5774     if (Dst == Idx)
5775       ++CorrectIdx;
5776     else if (IncorrectIdx == -1U) {
5777       IncorrectIdx = Idx;
5778       IncorrectDst = Dst;
5779     } else
5780       // There was already one element with an incorrect index.
5781       // We can't optimize this case to an insertps.
5782       return SDValue();
5783   }
5784
5785   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5786     SDLoc dl(Op);
5787     EVT VT = Op.getSimpleValueType();
5788     unsigned ElementMoveMask = 0;
5789     if (IncorrectIdx == -1U)
5790       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5791     else
5792       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5793
5794     SDValue InsertpsMask =
5795         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5796     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5797   }
5798
5799   return SDValue();
5800 }
5801
5802 /// getVShift - Return a vector logical shift node.
5803 ///
5804 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5805                          unsigned NumBits, SelectionDAG &DAG,
5806                          const TargetLowering &TLI, SDLoc dl) {
5807   assert(VT.is128BitVector() && "Unknown type for VShift");
5808   EVT ShVT = MVT::v2i64;
5809   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5810   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5811   return DAG.getNode(ISD::BITCAST, dl, VT,
5812                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5813                              DAG.getConstant(NumBits,
5814                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5815 }
5816
5817 static SDValue
5818 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5819
5820   // Check if the scalar load can be widened into a vector load. And if
5821   // the address is "base + cst" see if the cst can be "absorbed" into
5822   // the shuffle mask.
5823   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5824     SDValue Ptr = LD->getBasePtr();
5825     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5826       return SDValue();
5827     EVT PVT = LD->getValueType(0);
5828     if (PVT != MVT::i32 && PVT != MVT::f32)
5829       return SDValue();
5830
5831     int FI = -1;
5832     int64_t Offset = 0;
5833     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5834       FI = FINode->getIndex();
5835       Offset = 0;
5836     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5837                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5838       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5839       Offset = Ptr.getConstantOperandVal(1);
5840       Ptr = Ptr.getOperand(0);
5841     } else {
5842       return SDValue();
5843     }
5844
5845     // FIXME: 256-bit vector instructions don't require a strict alignment,
5846     // improve this code to support it better.
5847     unsigned RequiredAlign = VT.getSizeInBits()/8;
5848     SDValue Chain = LD->getChain();
5849     // Make sure the stack object alignment is at least 16 or 32.
5850     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5851     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5852       if (MFI->isFixedObjectIndex(FI)) {
5853         // Can't change the alignment. FIXME: It's possible to compute
5854         // the exact stack offset and reference FI + adjust offset instead.
5855         // If someone *really* cares about this. That's the way to implement it.
5856         return SDValue();
5857       } else {
5858         MFI->setObjectAlignment(FI, RequiredAlign);
5859       }
5860     }
5861
5862     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5863     // Ptr + (Offset & ~15).
5864     if (Offset < 0)
5865       return SDValue();
5866     if ((Offset % RequiredAlign) & 3)
5867       return SDValue();
5868     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5869     if (StartOffset)
5870       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5871                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5872
5873     int EltNo = (Offset - StartOffset) >> 2;
5874     unsigned NumElems = VT.getVectorNumElements();
5875
5876     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5877     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5878                              LD->getPointerInfo().getWithOffset(StartOffset),
5879                              false, false, false, 0);
5880
5881     SmallVector<int, 8> Mask;
5882     for (unsigned i = 0; i != NumElems; ++i)
5883       Mask.push_back(EltNo);
5884
5885     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5886   }
5887
5888   return SDValue();
5889 }
5890
5891 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5892 /// vector of type 'VT', see if the elements can be replaced by a single large
5893 /// load which has the same value as a build_vector whose operands are 'elts'.
5894 ///
5895 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5896 ///
5897 /// FIXME: we'd also like to handle the case where the last elements are zero
5898 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5899 /// There's even a handy isZeroNode for that purpose.
5900 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5901                                         SDLoc &DL, SelectionDAG &DAG,
5902                                         bool isAfterLegalize) {
5903   EVT EltVT = VT.getVectorElementType();
5904   unsigned NumElems = Elts.size();
5905
5906   LoadSDNode *LDBase = nullptr;
5907   unsigned LastLoadedElt = -1U;
5908
5909   // For each element in the initializer, see if we've found a load or an undef.
5910   // If we don't find an initial load element, or later load elements are
5911   // non-consecutive, bail out.
5912   for (unsigned i = 0; i < NumElems; ++i) {
5913     SDValue Elt = Elts[i];
5914
5915     if (!Elt.getNode() ||
5916         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5917       return SDValue();
5918     if (!LDBase) {
5919       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5920         return SDValue();
5921       LDBase = cast<LoadSDNode>(Elt.getNode());
5922       LastLoadedElt = i;
5923       continue;
5924     }
5925     if (Elt.getOpcode() == ISD::UNDEF)
5926       continue;
5927
5928     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5929     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5930       return SDValue();
5931     LastLoadedElt = i;
5932   }
5933
5934   // If we have found an entire vector of loads and undefs, then return a large
5935   // load of the entire vector width starting at the base pointer.  If we found
5936   // consecutive loads for the low half, generate a vzext_load node.
5937   if (LastLoadedElt == NumElems - 1) {
5938
5939     if (isAfterLegalize &&
5940         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5941       return SDValue();
5942
5943     SDValue NewLd = SDValue();
5944
5945     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5946       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5947                           LDBase->getPointerInfo(),
5948                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5949                           LDBase->isInvariant(), 0);
5950     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5951                         LDBase->getPointerInfo(),
5952                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5953                         LDBase->isInvariant(), LDBase->getAlignment());
5954
5955     if (LDBase->hasAnyUseOfValue(1)) {
5956       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5957                                      SDValue(LDBase, 1),
5958                                      SDValue(NewLd.getNode(), 1));
5959       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5960       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5961                              SDValue(NewLd.getNode(), 1));
5962     }
5963
5964     return NewLd;
5965   }
5966   if (NumElems == 4 && LastLoadedElt == 1 &&
5967       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5968     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5969     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5970     SDValue ResNode =
5971         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5972                                 LDBase->getPointerInfo(),
5973                                 LDBase->getAlignment(),
5974                                 false/*isVolatile*/, true/*ReadMem*/,
5975                                 false/*WriteMem*/);
5976
5977     // Make sure the newly-created LOAD is in the same position as LDBase in
5978     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5979     // update uses of LDBase's output chain to use the TokenFactor.
5980     if (LDBase->hasAnyUseOfValue(1)) {
5981       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5982                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5983       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5984       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5985                              SDValue(ResNode.getNode(), 1));
5986     }
5987
5988     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5989   }
5990   return SDValue();
5991 }
5992
5993 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5994 /// to generate a splat value for the following cases:
5995 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5996 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5997 /// a scalar load, or a constant.
5998 /// The VBROADCAST node is returned when a pattern is found,
5999 /// or SDValue() otherwise.
6000 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6001                                     SelectionDAG &DAG) {
6002   // VBROADCAST requires AVX.
6003   // TODO: Splats could be generated for non-AVX CPUs using SSE
6004   // instructions, but there's less potential gain for only 128-bit vectors.
6005   if (!Subtarget->hasAVX())
6006     return SDValue();
6007
6008   MVT VT = Op.getSimpleValueType();
6009   SDLoc dl(Op);
6010
6011   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6012          "Unsupported vector type for broadcast.");
6013
6014   SDValue Ld;
6015   bool ConstSplatVal;
6016
6017   switch (Op.getOpcode()) {
6018     default:
6019       // Unknown pattern found.
6020       return SDValue();
6021
6022     case ISD::BUILD_VECTOR: {
6023       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6024       BitVector UndefElements;
6025       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6026
6027       // We need a splat of a single value to use broadcast, and it doesn't
6028       // make any sense if the value is only in one element of the vector.
6029       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6030         return SDValue();
6031
6032       Ld = Splat;
6033       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6034                        Ld.getOpcode() == ISD::ConstantFP);
6035
6036       // Make sure that all of the users of a non-constant load are from the
6037       // BUILD_VECTOR node.
6038       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6039         return SDValue();
6040       break;
6041     }
6042
6043     case ISD::VECTOR_SHUFFLE: {
6044       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6045
6046       // Shuffles must have a splat mask where the first element is
6047       // broadcasted.
6048       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6049         return SDValue();
6050
6051       SDValue Sc = Op.getOperand(0);
6052       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6053           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6054
6055         if (!Subtarget->hasInt256())
6056           return SDValue();
6057
6058         // Use the register form of the broadcast instruction available on AVX2.
6059         if (VT.getSizeInBits() >= 256)
6060           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6061         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6062       }
6063
6064       Ld = Sc.getOperand(0);
6065       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6066                        Ld.getOpcode() == ISD::ConstantFP);
6067
6068       // The scalar_to_vector node and the suspected
6069       // load node must have exactly one user.
6070       // Constants may have multiple users.
6071
6072       // AVX-512 has register version of the broadcast
6073       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6074         Ld.getValueType().getSizeInBits() >= 32;
6075       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6076           !hasRegVer))
6077         return SDValue();
6078       break;
6079     }
6080   }
6081
6082   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6083   bool IsGE256 = (VT.getSizeInBits() >= 256);
6084
6085   // When optimizing for size, generate up to 5 extra bytes for a broadcast
6086   // instruction to save 8 or more bytes of constant pool data.
6087   // TODO: If multiple splats are generated to load the same constant,
6088   // it may be detrimental to overall size. There needs to be a way to detect
6089   // that condition to know if this is truly a size win.
6090   const Function *F = DAG.getMachineFunction().getFunction();
6091   bool OptForSize = F->getAttributes().
6092     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6093
6094   // Handle broadcasting a single constant scalar from the constant pool
6095   // into a vector.
6096   // On Sandybridge (no AVX2), it is still better to load a constant vector
6097   // from the constant pool and not to broadcast it from a scalar.
6098   // But override that restriction when optimizing for size.
6099   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
6100   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
6101     EVT CVT = Ld.getValueType();
6102     assert(!CVT.isVector() && "Must not broadcast a vector type");
6103
6104     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
6105     // For size optimization, also splat v2f64 and v2i64, and for size opt
6106     // with AVX2, also splat i8 and i16.
6107     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
6108     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6109         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
6110       const Constant *C = nullptr;
6111       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6112         C = CI->getConstantIntValue();
6113       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6114         C = CF->getConstantFPValue();
6115
6116       assert(C && "Invalid constant type");
6117
6118       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6119       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6120       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6121       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6122                        MachinePointerInfo::getConstantPool(),
6123                        false, false, false, Alignment);
6124
6125       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6126     }
6127   }
6128
6129   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6130
6131   // Handle AVX2 in-register broadcasts.
6132   if (!IsLoad && Subtarget->hasInt256() &&
6133       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6134     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6135
6136   // The scalar source must be a normal load.
6137   if (!IsLoad)
6138     return SDValue();
6139
6140   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6141     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6142
6143   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6144   // double since there is no vbroadcastsd xmm
6145   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6146     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6147       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6148   }
6149
6150   // Unsupported broadcast.
6151   return SDValue();
6152 }
6153
6154 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6155 /// underlying vector and index.
6156 ///
6157 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6158 /// index.
6159 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6160                                          SDValue ExtIdx) {
6161   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6162   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6163     return Idx;
6164
6165   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6166   // lowered this:
6167   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6168   // to:
6169   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6170   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6171   //                           undef)
6172   //                       Constant<0>)
6173   // In this case the vector is the extract_subvector expression and the index
6174   // is 2, as specified by the shuffle.
6175   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6176   SDValue ShuffleVec = SVOp->getOperand(0);
6177   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6178   assert(ShuffleVecVT.getVectorElementType() ==
6179          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6180
6181   int ShuffleIdx = SVOp->getMaskElt(Idx);
6182   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6183     ExtractedFromVec = ShuffleVec;
6184     return ShuffleIdx;
6185   }
6186   return Idx;
6187 }
6188
6189 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6190   MVT VT = Op.getSimpleValueType();
6191
6192   // Skip if insert_vec_elt is not supported.
6193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6194   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6195     return SDValue();
6196
6197   SDLoc DL(Op);
6198   unsigned NumElems = Op.getNumOperands();
6199
6200   SDValue VecIn1;
6201   SDValue VecIn2;
6202   SmallVector<unsigned, 4> InsertIndices;
6203   SmallVector<int, 8> Mask(NumElems, -1);
6204
6205   for (unsigned i = 0; i != NumElems; ++i) {
6206     unsigned Opc = Op.getOperand(i).getOpcode();
6207
6208     if (Opc == ISD::UNDEF)
6209       continue;
6210
6211     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6212       // Quit if more than 1 elements need inserting.
6213       if (InsertIndices.size() > 1)
6214         return SDValue();
6215
6216       InsertIndices.push_back(i);
6217       continue;
6218     }
6219
6220     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6221     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6222     // Quit if non-constant index.
6223     if (!isa<ConstantSDNode>(ExtIdx))
6224       return SDValue();
6225     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6226
6227     // Quit if extracted from vector of different type.
6228     if (ExtractedFromVec.getValueType() != VT)
6229       return SDValue();
6230
6231     if (!VecIn1.getNode())
6232       VecIn1 = ExtractedFromVec;
6233     else if (VecIn1 != ExtractedFromVec) {
6234       if (!VecIn2.getNode())
6235         VecIn2 = ExtractedFromVec;
6236       else if (VecIn2 != ExtractedFromVec)
6237         // Quit if more than 2 vectors to shuffle
6238         return SDValue();
6239     }
6240
6241     if (ExtractedFromVec == VecIn1)
6242       Mask[i] = Idx;
6243     else if (ExtractedFromVec == VecIn2)
6244       Mask[i] = Idx + NumElems;
6245   }
6246
6247   if (!VecIn1.getNode())
6248     return SDValue();
6249
6250   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6251   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6252   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6253     unsigned Idx = InsertIndices[i];
6254     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6255                      DAG.getIntPtrConstant(Idx));
6256   }
6257
6258   return NV;
6259 }
6260
6261 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6262 SDValue
6263 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6264
6265   MVT VT = Op.getSimpleValueType();
6266   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6267          "Unexpected type in LowerBUILD_VECTORvXi1!");
6268
6269   SDLoc dl(Op);
6270   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6271     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6272     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6273     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6274   }
6275
6276   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6277     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6278     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6279     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6280   }
6281
6282   bool AllContants = true;
6283   uint64_t Immediate = 0;
6284   int NonConstIdx = -1;
6285   bool IsSplat = true;
6286   unsigned NumNonConsts = 0;
6287   unsigned NumConsts = 0;
6288   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6289     SDValue In = Op.getOperand(idx);
6290     if (In.getOpcode() == ISD::UNDEF)
6291       continue;
6292     if (!isa<ConstantSDNode>(In)) {
6293       AllContants = false;
6294       NonConstIdx = idx;
6295       NumNonConsts++;
6296     }
6297     else {
6298       NumConsts++;
6299       if (cast<ConstantSDNode>(In)->getZExtValue())
6300       Immediate |= (1ULL << idx);
6301     }
6302     if (In != Op.getOperand(0))
6303       IsSplat = false;
6304   }
6305
6306   if (AllContants) {
6307     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6308       DAG.getConstant(Immediate, MVT::i16));
6309     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6310                        DAG.getIntPtrConstant(0));
6311   }
6312
6313   if (NumNonConsts == 1 && NonConstIdx != 0) {
6314     SDValue DstVec;
6315     if (NumConsts) {
6316       SDValue VecAsImm = DAG.getConstant(Immediate,
6317                                          MVT::getIntegerVT(VT.getSizeInBits()));
6318       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6319     }
6320     else 
6321       DstVec = DAG.getUNDEF(VT);
6322     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6323                        Op.getOperand(NonConstIdx),
6324                        DAG.getIntPtrConstant(NonConstIdx));
6325   }
6326   if (!IsSplat && (NonConstIdx != 0))
6327     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6328   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6329   SDValue Select;
6330   if (IsSplat)
6331     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6332                           DAG.getConstant(-1, SelectVT),
6333                           DAG.getConstant(0, SelectVT));
6334   else
6335     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6336                          DAG.getConstant((Immediate | 1), SelectVT),
6337                          DAG.getConstant(Immediate, SelectVT));
6338   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6339 }
6340
6341 /// \brief Return true if \p N implements a horizontal binop and return the
6342 /// operands for the horizontal binop into V0 and V1.
6343 /// 
6344 /// This is a helper function of PerformBUILD_VECTORCombine.
6345 /// This function checks that the build_vector \p N in input implements a
6346 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6347 /// operation to match.
6348 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6349 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6350 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6351 /// arithmetic sub.
6352 ///
6353 /// This function only analyzes elements of \p N whose indices are
6354 /// in range [BaseIdx, LastIdx).
6355 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6356                               SelectionDAG &DAG,
6357                               unsigned BaseIdx, unsigned LastIdx,
6358                               SDValue &V0, SDValue &V1) {
6359   EVT VT = N->getValueType(0);
6360
6361   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6362   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6363          "Invalid Vector in input!");
6364   
6365   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6366   bool CanFold = true;
6367   unsigned ExpectedVExtractIdx = BaseIdx;
6368   unsigned NumElts = LastIdx - BaseIdx;
6369   V0 = DAG.getUNDEF(VT);
6370   V1 = DAG.getUNDEF(VT);
6371
6372   // Check if N implements a horizontal binop.
6373   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6374     SDValue Op = N->getOperand(i + BaseIdx);
6375
6376     // Skip UNDEFs.
6377     if (Op->getOpcode() == ISD::UNDEF) {
6378       // Update the expected vector extract index.
6379       if (i * 2 == NumElts)
6380         ExpectedVExtractIdx = BaseIdx;
6381       ExpectedVExtractIdx += 2;
6382       continue;
6383     }
6384
6385     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6386
6387     if (!CanFold)
6388       break;
6389
6390     SDValue Op0 = Op.getOperand(0);
6391     SDValue Op1 = Op.getOperand(1);
6392
6393     // Try to match the following pattern:
6394     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6395     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6396         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6397         Op0.getOperand(0) == Op1.getOperand(0) &&
6398         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6399         isa<ConstantSDNode>(Op1.getOperand(1)));
6400     if (!CanFold)
6401       break;
6402
6403     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6404     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6405
6406     if (i * 2 < NumElts) {
6407       if (V0.getOpcode() == ISD::UNDEF)
6408         V0 = Op0.getOperand(0);
6409     } else {
6410       if (V1.getOpcode() == ISD::UNDEF)
6411         V1 = Op0.getOperand(0);
6412       if (i * 2 == NumElts)
6413         ExpectedVExtractIdx = BaseIdx;
6414     }
6415
6416     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6417     if (I0 == ExpectedVExtractIdx)
6418       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6419     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6420       // Try to match the following dag sequence:
6421       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6422       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6423     } else
6424       CanFold = false;
6425
6426     ExpectedVExtractIdx += 2;
6427   }
6428
6429   return CanFold;
6430 }
6431
6432 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6433 /// a concat_vector. 
6434 ///
6435 /// This is a helper function of PerformBUILD_VECTORCombine.
6436 /// This function expects two 256-bit vectors called V0 and V1.
6437 /// At first, each vector is split into two separate 128-bit vectors.
6438 /// Then, the resulting 128-bit vectors are used to implement two
6439 /// horizontal binary operations. 
6440 ///
6441 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6442 ///
6443 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6444 /// the two new horizontal binop.
6445 /// When Mode is set, the first horizontal binop dag node would take as input
6446 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6447 /// horizontal binop dag node would take as input the lower 128-bit of V1
6448 /// and the upper 128-bit of V1.
6449 ///   Example:
6450 ///     HADD V0_LO, V0_HI
6451 ///     HADD V1_LO, V1_HI
6452 ///
6453 /// Otherwise, the first horizontal binop dag node takes as input the lower
6454 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6455 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6456 ///   Example:
6457 ///     HADD V0_LO, V1_LO
6458 ///     HADD V0_HI, V1_HI
6459 ///
6460 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6461 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6462 /// the upper 128-bits of the result.
6463 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6464                                      SDLoc DL, SelectionDAG &DAG,
6465                                      unsigned X86Opcode, bool Mode,
6466                                      bool isUndefLO, bool isUndefHI) {
6467   EVT VT = V0.getValueType();
6468   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6469          "Invalid nodes in input!");
6470
6471   unsigned NumElts = VT.getVectorNumElements();
6472   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6473   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6474   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6475   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6476   EVT NewVT = V0_LO.getValueType();
6477
6478   SDValue LO = DAG.getUNDEF(NewVT);
6479   SDValue HI = DAG.getUNDEF(NewVT);
6480
6481   if (Mode) {
6482     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6483     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6484       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6485     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6486       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6487   } else {
6488     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6489     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6490                        V1_LO->getOpcode() != ISD::UNDEF))
6491       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6492
6493     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6494                        V1_HI->getOpcode() != ISD::UNDEF))
6495       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6496   }
6497
6498   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6499 }
6500
6501 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6502 /// sequence of 'vadd + vsub + blendi'.
6503 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6504                            const X86Subtarget *Subtarget) {
6505   SDLoc DL(BV);
6506   EVT VT = BV->getValueType(0);
6507   unsigned NumElts = VT.getVectorNumElements();
6508   SDValue InVec0 = DAG.getUNDEF(VT);
6509   SDValue InVec1 = DAG.getUNDEF(VT);
6510
6511   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6512           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6513
6514   // Odd-numbered elements in the input build vector are obtained from
6515   // adding two integer/float elements.
6516   // Even-numbered elements in the input build vector are obtained from
6517   // subtracting two integer/float elements.
6518   unsigned ExpectedOpcode = ISD::FSUB;
6519   unsigned NextExpectedOpcode = ISD::FADD;
6520   bool AddFound = false;
6521   bool SubFound = false;
6522
6523   for (unsigned i = 0, e = NumElts; i != e; i++) {
6524     SDValue Op = BV->getOperand(i);
6525
6526     // Skip 'undef' values.
6527     unsigned Opcode = Op.getOpcode();
6528     if (Opcode == ISD::UNDEF) {
6529       std::swap(ExpectedOpcode, NextExpectedOpcode);
6530       continue;
6531     }
6532
6533     // Early exit if we found an unexpected opcode.
6534     if (Opcode != ExpectedOpcode)
6535       return SDValue();
6536
6537     SDValue Op0 = Op.getOperand(0);
6538     SDValue Op1 = Op.getOperand(1);
6539
6540     // Try to match the following pattern:
6541     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6542     // Early exit if we cannot match that sequence.
6543     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6544         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6545         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6546         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6547         Op0.getOperand(1) != Op1.getOperand(1))
6548       return SDValue();
6549
6550     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6551     if (I0 != i)
6552       return SDValue();
6553
6554     // We found a valid add/sub node. Update the information accordingly.
6555     if (i & 1)
6556       AddFound = true;
6557     else
6558       SubFound = true;
6559
6560     // Update InVec0 and InVec1.
6561     if (InVec0.getOpcode() == ISD::UNDEF)
6562       InVec0 = Op0.getOperand(0);
6563     if (InVec1.getOpcode() == ISD::UNDEF)
6564       InVec1 = Op1.getOperand(0);
6565
6566     // Make sure that operands in input to each add/sub node always
6567     // come from a same pair of vectors.
6568     if (InVec0 != Op0.getOperand(0)) {
6569       if (ExpectedOpcode == ISD::FSUB)
6570         return SDValue();
6571
6572       // FADD is commutable. Try to commute the operands
6573       // and then test again.
6574       std::swap(Op0, Op1);
6575       if (InVec0 != Op0.getOperand(0))
6576         return SDValue();
6577     }
6578
6579     if (InVec1 != Op1.getOperand(0))
6580       return SDValue();
6581
6582     // Update the pair of expected opcodes.
6583     std::swap(ExpectedOpcode, NextExpectedOpcode);
6584   }
6585
6586   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6587   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6588       InVec1.getOpcode() != ISD::UNDEF)
6589     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6590
6591   return SDValue();
6592 }
6593
6594 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6595                                           const X86Subtarget *Subtarget) {
6596   SDLoc DL(N);
6597   EVT VT = N->getValueType(0);
6598   unsigned NumElts = VT.getVectorNumElements();
6599   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6600   SDValue InVec0, InVec1;
6601
6602   // Try to match an ADDSUB.
6603   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6604       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6605     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6606     if (Value.getNode())
6607       return Value;
6608   }
6609
6610   // Try to match horizontal ADD/SUB.
6611   unsigned NumUndefsLO = 0;
6612   unsigned NumUndefsHI = 0;
6613   unsigned Half = NumElts/2;
6614
6615   // Count the number of UNDEF operands in the build_vector in input.
6616   for (unsigned i = 0, e = Half; i != e; ++i)
6617     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6618       NumUndefsLO++;
6619
6620   for (unsigned i = Half, e = NumElts; i != e; ++i)
6621     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6622       NumUndefsHI++;
6623
6624   // Early exit if this is either a build_vector of all UNDEFs or all the
6625   // operands but one are UNDEF.
6626   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6627     return SDValue();
6628
6629   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6630     // Try to match an SSE3 float HADD/HSUB.
6631     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6632       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6633     
6634     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6635       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6636   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6637     // Try to match an SSSE3 integer HADD/HSUB.
6638     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6639       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6640     
6641     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6642       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6643   }
6644   
6645   if (!Subtarget->hasAVX())
6646     return SDValue();
6647
6648   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6649     // Try to match an AVX horizontal add/sub of packed single/double
6650     // precision floating point values from 256-bit vectors.
6651     SDValue InVec2, InVec3;
6652     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6653         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6654         ((InVec0.getOpcode() == ISD::UNDEF ||
6655           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6656         ((InVec1.getOpcode() == ISD::UNDEF ||
6657           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6658       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6659
6660     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6661         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6662         ((InVec0.getOpcode() == ISD::UNDEF ||
6663           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6664         ((InVec1.getOpcode() == ISD::UNDEF ||
6665           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6666       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6667   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6668     // Try to match an AVX2 horizontal add/sub of signed integers.
6669     SDValue InVec2, InVec3;
6670     unsigned X86Opcode;
6671     bool CanFold = true;
6672
6673     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6674         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6675         ((InVec0.getOpcode() == ISD::UNDEF ||
6676           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6677         ((InVec1.getOpcode() == ISD::UNDEF ||
6678           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6679       X86Opcode = X86ISD::HADD;
6680     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6681         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6682         ((InVec0.getOpcode() == ISD::UNDEF ||
6683           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6684         ((InVec1.getOpcode() == ISD::UNDEF ||
6685           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6686       X86Opcode = X86ISD::HSUB;
6687     else
6688       CanFold = false;
6689
6690     if (CanFold) {
6691       // Fold this build_vector into a single horizontal add/sub.
6692       // Do this only if the target has AVX2.
6693       if (Subtarget->hasAVX2())
6694         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6695  
6696       // Do not try to expand this build_vector into a pair of horizontal
6697       // add/sub if we can emit a pair of scalar add/sub.
6698       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6699         return SDValue();
6700
6701       // Convert this build_vector into a pair of horizontal binop followed by
6702       // a concat vector.
6703       bool isUndefLO = NumUndefsLO == Half;
6704       bool isUndefHI = NumUndefsHI == Half;
6705       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6706                                    isUndefLO, isUndefHI);
6707     }
6708   }
6709
6710   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6711        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6712     unsigned X86Opcode;
6713     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6714       X86Opcode = X86ISD::HADD;
6715     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6716       X86Opcode = X86ISD::HSUB;
6717     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6718       X86Opcode = X86ISD::FHADD;
6719     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6720       X86Opcode = X86ISD::FHSUB;
6721     else
6722       return SDValue();
6723
6724     // Don't try to expand this build_vector into a pair of horizontal add/sub
6725     // if we can simply emit a pair of scalar add/sub.
6726     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6727       return SDValue();
6728
6729     // Convert this build_vector into two horizontal add/sub followed by
6730     // a concat vector.
6731     bool isUndefLO = NumUndefsLO == Half;
6732     bool isUndefHI = NumUndefsHI == Half;
6733     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6734                                  isUndefLO, isUndefHI);
6735   }
6736
6737   return SDValue();
6738 }
6739
6740 SDValue
6741 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6742   SDLoc dl(Op);
6743
6744   MVT VT = Op.getSimpleValueType();
6745   MVT ExtVT = VT.getVectorElementType();
6746   unsigned NumElems = Op.getNumOperands();
6747
6748   // Generate vectors for predicate vectors.
6749   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6750     return LowerBUILD_VECTORvXi1(Op, DAG);
6751
6752   // Vectors containing all zeros can be matched by pxor and xorps later
6753   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6754     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6755     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6756     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6757       return Op;
6758
6759     return getZeroVector(VT, Subtarget, DAG, dl);
6760   }
6761
6762   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6763   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6764   // vpcmpeqd on 256-bit vectors.
6765   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6766     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6767       return Op;
6768
6769     if (!VT.is512BitVector())
6770       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6771   }
6772
6773   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6774   if (Broadcast.getNode())
6775     return Broadcast;
6776
6777   unsigned EVTBits = ExtVT.getSizeInBits();
6778
6779   unsigned NumZero  = 0;
6780   unsigned NumNonZero = 0;
6781   unsigned NonZeros = 0;
6782   bool IsAllConstants = true;
6783   SmallSet<SDValue, 8> Values;
6784   for (unsigned i = 0; i < NumElems; ++i) {
6785     SDValue Elt = Op.getOperand(i);
6786     if (Elt.getOpcode() == ISD::UNDEF)
6787       continue;
6788     Values.insert(Elt);
6789     if (Elt.getOpcode() != ISD::Constant &&
6790         Elt.getOpcode() != ISD::ConstantFP)
6791       IsAllConstants = false;
6792     if (X86::isZeroNode(Elt))
6793       NumZero++;
6794     else {
6795       NonZeros |= (1 << i);
6796       NumNonZero++;
6797     }
6798   }
6799
6800   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6801   if (NumNonZero == 0)
6802     return DAG.getUNDEF(VT);
6803
6804   // Special case for single non-zero, non-undef, element.
6805   if (NumNonZero == 1) {
6806     unsigned Idx = countTrailingZeros(NonZeros);
6807     SDValue Item = Op.getOperand(Idx);
6808
6809     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6810     // the value are obviously zero, truncate the value to i32 and do the
6811     // insertion that way.  Only do this if the value is non-constant or if the
6812     // value is a constant being inserted into element 0.  It is cheaper to do
6813     // a constant pool load than it is to do a movd + shuffle.
6814     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6815         (!IsAllConstants || Idx == 0)) {
6816       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6817         // Handle SSE only.
6818         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6819         EVT VecVT = MVT::v4i32;
6820         unsigned VecElts = 4;
6821
6822         // Truncate the value (which may itself be a constant) to i32, and
6823         // convert it to a vector with movd (S2V+shuffle to zero extend).
6824         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6825         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6826
6827         // If using the new shuffle lowering, just directly insert this.
6828         if (ExperimentalVectorShuffleLowering)
6829           return DAG.getNode(
6830               ISD::BITCAST, dl, VT,
6831               getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6832
6833         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6834
6835         // Now we have our 32-bit value zero extended in the low element of
6836         // a vector.  If Idx != 0, swizzle it into place.
6837         if (Idx != 0) {
6838           SmallVector<int, 4> Mask;
6839           Mask.push_back(Idx);
6840           for (unsigned i = 1; i != VecElts; ++i)
6841             Mask.push_back(i);
6842           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6843                                       &Mask[0]);
6844         }
6845         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6846       }
6847     }
6848
6849     // If we have a constant or non-constant insertion into the low element of
6850     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6851     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6852     // depending on what the source datatype is.
6853     if (Idx == 0) {
6854       if (NumZero == 0)
6855         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6856
6857       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6858           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6859         if (VT.is256BitVector() || VT.is512BitVector()) {
6860           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6861           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6862                              Item, DAG.getIntPtrConstant(0));
6863         }
6864         assert(VT.is128BitVector() && "Expected an SSE value type!");
6865         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6866         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6867         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6868       }
6869
6870       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6871         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6872         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6873         if (VT.is256BitVector()) {
6874           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6875           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6876         } else {
6877           assert(VT.is128BitVector() && "Expected an SSE value type!");
6878           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6879         }
6880         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6881       }
6882     }
6883
6884     // Is it a vector logical left shift?
6885     if (NumElems == 2 && Idx == 1 &&
6886         X86::isZeroNode(Op.getOperand(0)) &&
6887         !X86::isZeroNode(Op.getOperand(1))) {
6888       unsigned NumBits = VT.getSizeInBits();
6889       return getVShift(true, VT,
6890                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6891                                    VT, Op.getOperand(1)),
6892                        NumBits/2, DAG, *this, dl);
6893     }
6894
6895     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6896       return SDValue();
6897
6898     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6899     // is a non-constant being inserted into an element other than the low one,
6900     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6901     // movd/movss) to move this into the low element, then shuffle it into
6902     // place.
6903     if (EVTBits == 32) {
6904       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6905
6906       // If using the new shuffle lowering, just directly insert this.
6907       if (ExperimentalVectorShuffleLowering)
6908         return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6909
6910       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6911       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6912       SmallVector<int, 8> MaskVec;
6913       for (unsigned i = 0; i != NumElems; ++i)
6914         MaskVec.push_back(i == Idx ? 0 : 1);
6915       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6916     }
6917   }
6918
6919   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6920   if (Values.size() == 1) {
6921     if (EVTBits == 32) {
6922       // Instead of a shuffle like this:
6923       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6924       // Check if it's possible to issue this instead.
6925       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6926       unsigned Idx = countTrailingZeros(NonZeros);
6927       SDValue Item = Op.getOperand(Idx);
6928       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6929         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6930     }
6931     return SDValue();
6932   }
6933
6934   // A vector full of immediates; various special cases are already
6935   // handled, so this is best done with a single constant-pool load.
6936   if (IsAllConstants)
6937     return SDValue();
6938
6939   // For AVX-length vectors, build the individual 128-bit pieces and use
6940   // shuffles to put them in place.
6941   if (VT.is256BitVector() || VT.is512BitVector()) {
6942     SmallVector<SDValue, 64> V;
6943     for (unsigned i = 0; i != NumElems; ++i)
6944       V.push_back(Op.getOperand(i));
6945
6946     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6947
6948     // Build both the lower and upper subvector.
6949     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6950                                 makeArrayRef(&V[0], NumElems/2));
6951     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6952                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6953
6954     // Recreate the wider vector with the lower and upper part.
6955     if (VT.is256BitVector())
6956       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6957     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6958   }
6959
6960   // Let legalizer expand 2-wide build_vectors.
6961   if (EVTBits == 64) {
6962     if (NumNonZero == 1) {
6963       // One half is zero or undef.
6964       unsigned Idx = countTrailingZeros(NonZeros);
6965       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6966                                  Op.getOperand(Idx));
6967       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6968     }
6969     return SDValue();
6970   }
6971
6972   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6973   if (EVTBits == 8 && NumElems == 16) {
6974     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6975                                         Subtarget, *this);
6976     if (V.getNode()) return V;
6977   }
6978
6979   if (EVTBits == 16 && NumElems == 8) {
6980     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6981                                       Subtarget, *this);
6982     if (V.getNode()) return V;
6983   }
6984
6985   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6986   if (EVTBits == 32 && NumElems == 4) {
6987     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6988                                       NumZero, DAG, Subtarget, *this);
6989     if (V.getNode())
6990       return V;
6991   }
6992
6993   // If element VT is == 32 bits, turn it into a number of shuffles.
6994   SmallVector<SDValue, 8> V(NumElems);
6995   if (NumElems == 4 && NumZero > 0) {
6996     for (unsigned i = 0; i < 4; ++i) {
6997       bool isZero = !(NonZeros & (1 << i));
6998       if (isZero)
6999         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7000       else
7001         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7002     }
7003
7004     for (unsigned i = 0; i < 2; ++i) {
7005       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7006         default: break;
7007         case 0:
7008           V[i] = V[i*2];  // Must be a zero vector.
7009           break;
7010         case 1:
7011           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7012           break;
7013         case 2:
7014           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7015           break;
7016         case 3:
7017           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7018           break;
7019       }
7020     }
7021
7022     bool Reverse1 = (NonZeros & 0x3) == 2;
7023     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7024     int MaskVec[] = {
7025       Reverse1 ? 1 : 0,
7026       Reverse1 ? 0 : 1,
7027       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7028       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7029     };
7030     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7031   }
7032
7033   if (Values.size() > 1 && VT.is128BitVector()) {
7034     // Check for a build vector of consecutive loads.
7035     for (unsigned i = 0; i < NumElems; ++i)
7036       V[i] = Op.getOperand(i);
7037
7038     // Check for elements which are consecutive loads.
7039     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7040     if (LD.getNode())
7041       return LD;
7042
7043     // Check for a build vector from mostly shuffle plus few inserting.
7044     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7045     if (Sh.getNode())
7046       return Sh;
7047
7048     // For SSE 4.1, use insertps to put the high elements into the low element.
7049     if (getSubtarget()->hasSSE41()) {
7050       SDValue Result;
7051       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7052         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7053       else
7054         Result = DAG.getUNDEF(VT);
7055
7056       for (unsigned i = 1; i < NumElems; ++i) {
7057         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7058         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7059                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7060       }
7061       return Result;
7062     }
7063
7064     // Otherwise, expand into a number of unpckl*, start by extending each of
7065     // our (non-undef) elements to the full vector width with the element in the
7066     // bottom slot of the vector (which generates no code for SSE).
7067     for (unsigned i = 0; i < NumElems; ++i) {
7068       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7069         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7070       else
7071         V[i] = DAG.getUNDEF(VT);
7072     }
7073
7074     // Next, we iteratively mix elements, e.g. for v4f32:
7075     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7076     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7077     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7078     unsigned EltStride = NumElems >> 1;
7079     while (EltStride != 0) {
7080       for (unsigned i = 0; i < EltStride; ++i) {
7081         // If V[i+EltStride] is undef and this is the first round of mixing,
7082         // then it is safe to just drop this shuffle: V[i] is already in the
7083         // right place, the one element (since it's the first round) being
7084         // inserted as undef can be dropped.  This isn't safe for successive
7085         // rounds because they will permute elements within both vectors.
7086         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7087             EltStride == NumElems/2)
7088           continue;
7089
7090         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7091       }
7092       EltStride >>= 1;
7093     }
7094     return V[0];
7095   }
7096   return SDValue();
7097 }
7098
7099 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7100 // to create 256-bit vectors from two other 128-bit ones.
7101 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7102   SDLoc dl(Op);
7103   MVT ResVT = Op.getSimpleValueType();
7104
7105   assert((ResVT.is256BitVector() ||
7106           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7107
7108   SDValue V1 = Op.getOperand(0);
7109   SDValue V2 = Op.getOperand(1);
7110   unsigned NumElems = ResVT.getVectorNumElements();
7111   if(ResVT.is256BitVector())
7112     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7113
7114   if (Op.getNumOperands() == 4) {
7115     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7116                                 ResVT.getVectorNumElements()/2);
7117     SDValue V3 = Op.getOperand(2);
7118     SDValue V4 = Op.getOperand(3);
7119     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7120       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7121   }
7122   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7123 }
7124
7125 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7126   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7127   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7128          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7129           Op.getNumOperands() == 4)));
7130
7131   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7132   // from two other 128-bit ones.
7133
7134   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7135   return LowerAVXCONCAT_VECTORS(Op, DAG);
7136 }
7137
7138
7139 //===----------------------------------------------------------------------===//
7140 // Vector shuffle lowering
7141 //
7142 // This is an experimental code path for lowering vector shuffles on x86. It is
7143 // designed to handle arbitrary vector shuffles and blends, gracefully
7144 // degrading performance as necessary. It works hard to recognize idiomatic
7145 // shuffles and lower them to optimal instruction patterns without leaving
7146 // a framework that allows reasonably efficient handling of all vector shuffle
7147 // patterns.
7148 //===----------------------------------------------------------------------===//
7149
7150 /// \brief Tiny helper function to identify a no-op mask.
7151 ///
7152 /// This is a somewhat boring predicate function. It checks whether the mask
7153 /// array input, which is assumed to be a single-input shuffle mask of the kind
7154 /// used by the X86 shuffle instructions (not a fully general
7155 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7156 /// in-place shuffle are 'no-op's.
7157 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7158   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7159     if (Mask[i] != -1 && Mask[i] != i)
7160       return false;
7161   return true;
7162 }
7163
7164 /// \brief Helper function to classify a mask as a single-input mask.
7165 ///
7166 /// This isn't a generic single-input test because in the vector shuffle
7167 /// lowering we canonicalize single inputs to be the first input operand. This
7168 /// means we can more quickly test for a single input by only checking whether
7169 /// an input from the second operand exists. We also assume that the size of
7170 /// mask corresponds to the size of the input vectors which isn't true in the
7171 /// fully general case.
7172 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7173   for (int M : Mask)
7174     if (M >= (int)Mask.size())
7175       return false;
7176   return true;
7177 }
7178
7179 /// \brief Test whether there are elements crossing 128-bit lanes in this
7180 /// shuffle mask.
7181 ///
7182 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
7183 /// and we routinely test for these.
7184 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
7185   int LaneSize = 128 / VT.getScalarSizeInBits();
7186   int Size = Mask.size();
7187   for (int i = 0; i < Size; ++i)
7188     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
7189       return true;
7190   return false;
7191 }
7192
7193 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
7194 ///
7195 /// This checks a shuffle mask to see if it is performing the same
7196 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
7197 /// that it is also not lane-crossing. It may however involve a blend from the
7198 /// same lane of a second vector.
7199 ///
7200 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
7201 /// non-trivial to compute in the face of undef lanes. The representation is
7202 /// *not* suitable for use with existing 128-bit shuffles as it will contain
7203 /// entries from both V1 and V2 inputs to the wider mask.
7204 static bool
7205 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
7206                                 SmallVectorImpl<int> &RepeatedMask) {
7207   int LaneSize = 128 / VT.getScalarSizeInBits();
7208   RepeatedMask.resize(LaneSize, -1);
7209   int Size = Mask.size();
7210   for (int i = 0; i < Size; ++i) {
7211     if (Mask[i] < 0)
7212       continue;
7213     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
7214       // This entry crosses lanes, so there is no way to model this shuffle.
7215       return false;
7216
7217     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
7218     if (RepeatedMask[i % LaneSize] == -1)
7219       // This is the first non-undef entry in this slot of a 128-bit lane.
7220       RepeatedMask[i % LaneSize] =
7221           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
7222     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
7223       // Found a mismatch with the repeated mask.
7224       return false;
7225   }
7226   return true;
7227 }
7228
7229 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7230 // 2013 will allow us to use it as a non-type template parameter.
7231 namespace {
7232
7233 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7234 ///
7235 /// See its documentation for details.
7236 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7237   if (Mask.size() != Args.size())
7238     return false;
7239   for (int i = 0, e = Mask.size(); i < e; ++i) {
7240     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7241     if (Mask[i] != -1 && Mask[i] != *Args[i])
7242       return false;
7243   }
7244   return true;
7245 }
7246
7247 } // namespace
7248
7249 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7250 /// arguments.
7251 ///
7252 /// This is a fast way to test a shuffle mask against a fixed pattern:
7253 ///
7254 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7255 ///
7256 /// It returns true if the mask is exactly as wide as the argument list, and
7257 /// each element of the mask is either -1 (signifying undef) or the value given
7258 /// in the argument.
7259 static const VariadicFunction1<
7260     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7261
7262 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7263 ///
7264 /// This helper function produces an 8-bit shuffle immediate corresponding to
7265 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7266 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7267 /// example.
7268 ///
7269 /// NB: We rely heavily on "undef" masks preserving the input lane.
7270 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7271                                           SelectionDAG &DAG) {
7272   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7273   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7274   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7275   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7276   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7277
7278   unsigned Imm = 0;
7279   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7280   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7281   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7282   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7283   return DAG.getConstant(Imm, MVT::i8);
7284 }
7285
7286 /// \brief Try to emit a blend instruction for a shuffle.
7287 ///
7288 /// This doesn't do any checks for the availability of instructions for blending
7289 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7290 /// be matched in the backend with the type given. What it does check for is
7291 /// that the shuffle mask is in fact a blend.
7292 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7293                                          SDValue V2, ArrayRef<int> Mask,
7294                                          const X86Subtarget *Subtarget,
7295                                          SelectionDAG &DAG) {
7296
7297   unsigned BlendMask = 0;
7298   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7299     if (Mask[i] >= Size) {
7300       if (Mask[i] != i + Size)
7301         return SDValue(); // Shuffled V2 input!
7302       BlendMask |= 1u << i;
7303       continue;
7304     }
7305     if (Mask[i] >= 0 && Mask[i] != i)
7306       return SDValue(); // Shuffled V1 input!
7307   }
7308   switch (VT.SimpleTy) {
7309   case MVT::v2f64:
7310   case MVT::v4f32:
7311   case MVT::v4f64:
7312   case MVT::v8f32:
7313     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7314                        DAG.getConstant(BlendMask, MVT::i8));
7315
7316   case MVT::v4i64:
7317   case MVT::v8i32:
7318     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7319     // FALLTHROUGH
7320   case MVT::v2i64:
7321   case MVT::v4i32:
7322     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7323     // that instruction.
7324     if (Subtarget->hasAVX2()) {
7325       // Scale the blend by the number of 32-bit dwords per element.
7326       int Scale =  VT.getScalarSizeInBits() / 32;
7327       BlendMask = 0;
7328       for (int i = 0, Size = Mask.size(); i < Size; ++i)
7329         if (Mask[i] >= Size)
7330           for (int j = 0; j < Scale; ++j)
7331             BlendMask |= 1u << (i * Scale + j);
7332
7333       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7334       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
7335       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
7336       return DAG.getNode(ISD::BITCAST, DL, VT,
7337                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7338                                      DAG.getConstant(BlendMask, MVT::i8)));
7339     }
7340     // FALLTHROUGH
7341   case MVT::v8i16: {
7342     // For integer shuffles we need to expand the mask and cast the inputs to
7343     // v8i16s prior to blending.
7344     int Scale = 8 / VT.getVectorNumElements();
7345     BlendMask = 0;
7346     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7347       if (Mask[i] >= Size)
7348         for (int j = 0; j < Scale; ++j)
7349           BlendMask |= 1u << (i * Scale + j);
7350
7351     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
7352     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
7353     return DAG.getNode(ISD::BITCAST, DL, VT,
7354                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7355                                    DAG.getConstant(BlendMask, MVT::i8)));
7356   }
7357
7358   case MVT::v16i16: {
7359     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7360     SmallVector<int, 8> RepeatedMask;
7361     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7362       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7363       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7364       BlendMask = 0;
7365       for (int i = 0; i < 8; ++i)
7366         if (RepeatedMask[i] >= 16)
7367           BlendMask |= 1u << i;
7368       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7369                          DAG.getConstant(BlendMask, MVT::i8));
7370     }
7371   }
7372     // FALLTHROUGH
7373   case MVT::v32i8: {
7374     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7375     // Scale the blend by the number of bytes per element.
7376     int Scale =  VT.getScalarSizeInBits() / 8;
7377     assert(Mask.size() * Scale == 32 && "Not a 256-bit vector!");
7378
7379     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7380     // mix of LLVM's code generator and the x86 backend. We tell the code
7381     // generator that boolean values in the elements of an x86 vector register
7382     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7383     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7384     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7385     // of the element (the remaining are ignored) and 0 in that high bit would
7386     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7387     // the LLVM model for boolean values in vector elements gets the relevant
7388     // bit set, it is set backwards and over constrained relative to x86's
7389     // actual model.
7390     SDValue VSELECTMask[32];
7391     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7392       for (int j = 0; j < Scale; ++j)
7393         VSELECTMask[Scale * i + j] =
7394             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7395                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8);
7396
7397     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1);
7398     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V2);
7399     return DAG.getNode(
7400         ISD::BITCAST, DL, VT,
7401         DAG.getNode(ISD::VSELECT, DL, MVT::v32i8,
7402                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, VSELECTMask),
7403                     V1, V2));
7404   }
7405
7406   default:
7407     llvm_unreachable("Not a supported integer vector type!");
7408   }
7409 }
7410
7411 /// \brief Generic routine to lower a shuffle and blend as a decomposed set of
7412 /// unblended shuffles followed by an unshuffled blend.
7413 ///
7414 /// This matches the extremely common pattern for handling combined
7415 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7416 /// operations.
7417 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7418                                                           SDValue V1,
7419                                                           SDValue V2,
7420                                                           ArrayRef<int> Mask,
7421                                                           SelectionDAG &DAG) {
7422   // Shuffle the input elements into the desired positions in V1 and V2 and
7423   // blend them together.
7424   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7425   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7426   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7427   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7428     if (Mask[i] >= 0 && Mask[i] < Size) {
7429       V1Mask[i] = Mask[i];
7430       BlendMask[i] = i;
7431     } else if (Mask[i] >= Size) {
7432       V2Mask[i] = Mask[i] - Size;
7433       BlendMask[i] = i + Size;
7434     }
7435
7436   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7437   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7438   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7439 }
7440
7441 /// \brief Try to lower a vector shuffle as a byte rotation.
7442 ///
7443 /// We have a generic PALIGNR instruction in x86 that will do an arbitrary
7444 /// byte-rotation of the concatenation of two vectors. This routine will
7445 /// try to generically lower a vector shuffle through such an instruction. It
7446 /// does not check for the availability of PALIGNR-based lowerings, only the
7447 /// applicability of this strategy to the given mask. This matches shuffle
7448 /// vectors that look like:
7449 /// 
7450 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7451 /// 
7452 /// Essentially it concatenates V1 and V2, shifts right by some number of
7453 /// elements, and takes the low elements as the result. Note that while this is
7454 /// specified as a *right shift* because x86 is little-endian, it is a *left
7455 /// rotate* of the vector lanes.
7456 ///
7457 /// Note that this only handles 128-bit vector widths currently.
7458 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7459                                               SDValue V2,
7460                                               ArrayRef<int> Mask,
7461                                               SelectionDAG &DAG) {
7462   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7463
7464   // We need to detect various ways of spelling a rotation:
7465   //   [11, 12, 13, 14, 15,  0,  1,  2]
7466   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7467   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7468   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7469   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7470   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7471   int Rotation = 0;
7472   SDValue Lo, Hi;
7473   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7474     if (Mask[i] == -1)
7475       continue;
7476     assert(Mask[i] >= 0 && "Only -1 is a valid negative mask element!");
7477
7478     // Based on the mod-Size value of this mask element determine where
7479     // a rotated vector would have started.
7480     int StartIdx = i - (Mask[i] % Size);
7481     if (StartIdx == 0)
7482       // The identity rotation isn't interesting, stop.
7483       return SDValue();
7484
7485     // If we found the tail of a vector the rotation must be the missing
7486     // front. If we found the head of a vector, it must be how much of the head.
7487     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
7488
7489     if (Rotation == 0)
7490       Rotation = CandidateRotation;
7491     else if (Rotation != CandidateRotation)
7492       // The rotations don't match, so we can't match this mask.
7493       return SDValue();
7494
7495     // Compute which value this mask is pointing at.
7496     SDValue MaskV = Mask[i] < Size ? V1 : V2;
7497
7498     // Compute which of the two target values this index should be assigned to.
7499     // This reflects whether the high elements are remaining or the low elements
7500     // are remaining.
7501     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7502
7503     // Either set up this value if we've not encountered it before, or check
7504     // that it remains consistent.
7505     if (!TargetV)
7506       TargetV = MaskV;
7507     else if (TargetV != MaskV)
7508       // This may be a rotation, but it pulls from the inputs in some
7509       // unsupported interleaving.
7510       return SDValue();
7511   }
7512
7513   // Check that we successfully analyzed the mask, and normalize the results.
7514   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7515   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7516   if (!Lo)
7517     Lo = Hi;
7518   else if (!Hi)
7519     Hi = Lo;
7520
7521   // Cast the inputs to v16i8 to match PALIGNR.
7522   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Lo);
7523   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Hi);
7524
7525   assert(VT.getSizeInBits() == 128 &&
7526          "Rotate-based lowering only supports 128-bit lowering!");
7527   assert(Mask.size() <= 16 &&
7528          "Can shuffle at most 16 bytes in a 128-bit vector!");
7529   // The actual rotate instruction rotates bytes, so we need to scale the
7530   // rotation based on how many bytes are in the vector.
7531   int Scale = 16 / Mask.size();
7532
7533   return DAG.getNode(ISD::BITCAST, DL, VT,
7534                      DAG.getNode(X86ISD::PALIGNR, DL, MVT::v16i8, Hi, Lo,
7535                                  DAG.getConstant(Rotation * Scale, MVT::i8)));
7536 }
7537
7538 /// \brief Compute whether each element of a shuffle is zeroable.
7539 ///
7540 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7541 /// Either it is an undef element in the shuffle mask, the element of the input
7542 /// referenced is undef, or the element of the input referenced is known to be
7543 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7544 /// as many lanes with this technique as possible to simplify the remaining
7545 /// shuffle.
7546 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
7547                                                      SDValue V1, SDValue V2) {
7548   SmallBitVector Zeroable(Mask.size(), false);
7549
7550   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7551   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7552
7553   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7554     int M = Mask[i];
7555     // Handle the easy cases.
7556     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7557       Zeroable[i] = true;
7558       continue;
7559     }
7560
7561     // If this is an index into a build_vector node, dig out the input value and
7562     // use it.
7563     SDValue V = M < Size ? V1 : V2;
7564     if (V.getOpcode() != ISD::BUILD_VECTOR)
7565       continue;
7566
7567     SDValue Input = V.getOperand(M % Size);
7568     // The UNDEF opcode check really should be dead code here, but not quite
7569     // worth asserting on (it isn't invalid, just unexpected).
7570     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
7571       Zeroable[i] = true;
7572   }
7573
7574   return Zeroable;
7575 }
7576
7577 /// \brief Lower a vector shuffle as a zero or any extension.
7578 ///
7579 /// Given a specific number of elements, element bit width, and extension
7580 /// stride, produce either a zero or any extension based on the available
7581 /// features of the subtarget.
7582 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7583     SDLoc DL, MVT VT, int NumElements, int Scale, bool AnyExt, SDValue InputV,
7584     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7585   assert(Scale > 1 && "Need a scale to extend.");
7586   int EltBits = VT.getSizeInBits() / NumElements;
7587   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7588          "Only 8, 16, and 32 bit elements can be extended.");
7589   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7590
7591   // Found a valid zext mask! Try various lowering strategies based on the
7592   // input type and available ISA extensions.
7593   if (Subtarget->hasSSE41()) {
7594     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7595     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7596                                  NumElements / Scale);
7597     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7598     return DAG.getNode(ISD::BITCAST, DL, VT,
7599                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7600   }
7601
7602   // For any extends we can cheat for larger element sizes and use shuffle
7603   // instructions that can fold with a load and/or copy.
7604   if (AnyExt && EltBits == 32) {
7605     int PSHUFDMask[4] = {0, -1, 1, -1};
7606     return DAG.getNode(
7607         ISD::BITCAST, DL, VT,
7608         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7609                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7610                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7611   }
7612   if (AnyExt && EltBits == 16 && Scale > 2) {
7613     int PSHUFDMask[4] = {0, -1, 0, -1};
7614     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7615                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7616                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
7617     int PSHUFHWMask[4] = {1, -1, -1, -1};
7618     return DAG.getNode(
7619         ISD::BITCAST, DL, VT,
7620         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7621                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
7622                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
7623   }
7624
7625   // If this would require more than 2 unpack instructions to expand, use
7626   // pshufb when available. We can only use more than 2 unpack instructions
7627   // when zero extending i8 elements which also makes it easier to use pshufb.
7628   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7629     assert(NumElements == 16 && "Unexpected byte vector width!");
7630     SDValue PSHUFBMask[16];
7631     for (int i = 0; i < 16; ++i)
7632       PSHUFBMask[i] =
7633           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
7634     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
7635     return DAG.getNode(ISD::BITCAST, DL, VT,
7636                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7637                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
7638                                                MVT::v16i8, PSHUFBMask)));
7639   }
7640
7641   // Otherwise emit a sequence of unpacks.
7642   do {
7643     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7644     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7645                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7646     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7647     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7648     Scale /= 2;
7649     EltBits *= 2;
7650     NumElements /= 2;
7651   } while (Scale > 1);
7652   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
7653 }
7654
7655 /// \brief Try to lower a vector shuffle as a zero extension on any micrarch.
7656 ///
7657 /// This routine will try to do everything in its power to cleverly lower
7658 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7659 /// check for the profitability of this lowering,  it tries to aggressively
7660 /// match this pattern. It will use all of the micro-architectural details it
7661 /// can to emit an efficient lowering. It handles both blends with all-zero
7662 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7663 /// masking out later).
7664 ///
7665 /// The reason we have dedicated lowering for zext-style shuffles is that they
7666 /// are both incredibly common and often quite performance sensitive.
7667 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7668     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7669     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7670   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7671
7672   int Bits = VT.getSizeInBits();
7673   int NumElements = Mask.size();
7674
7675   // Define a helper function to check a particular ext-scale and lower to it if
7676   // valid.
7677   auto Lower = [&](int Scale) -> SDValue {
7678     SDValue InputV;
7679     bool AnyExt = true;
7680     for (int i = 0; i < NumElements; ++i) {
7681       if (Mask[i] == -1)
7682         continue; // Valid anywhere but doesn't tell us anything.
7683       if (i % Scale != 0) {
7684         // Each of the extend elements needs to be zeroable.
7685         if (!Zeroable[i])
7686           return SDValue();
7687
7688         // We no lorger are in the anyext case.
7689         AnyExt = false;
7690         continue;
7691       }
7692
7693       // Each of the base elements needs to be consecutive indices into the
7694       // same input vector.
7695       SDValue V = Mask[i] < NumElements ? V1 : V2;
7696       if (!InputV)
7697         InputV = V;
7698       else if (InputV != V)
7699         return SDValue(); // Flip-flopping inputs.
7700
7701       if (Mask[i] % NumElements != i / Scale)
7702         return SDValue(); // Non-consecutive strided elemenst.
7703     }
7704
7705     // If we fail to find an input, we have a zero-shuffle which should always
7706     // have already been handled.
7707     // FIXME: Maybe handle this here in case during blending we end up with one?
7708     if (!InputV)
7709       return SDValue();
7710
7711     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7712         DL, VT, NumElements, Scale, AnyExt, InputV, Subtarget, DAG);
7713   };
7714
7715   // The widest scale possible for extending is to a 64-bit integer.
7716   assert(Bits % 64 == 0 &&
7717          "The number of bits in a vector must be divisible by 64 on x86!");
7718   int NumExtElements = Bits / 64;
7719
7720   // Each iteration, try extending the elements half as much, but into twice as
7721   // many elements.
7722   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7723     assert(NumElements % NumExtElements == 0 &&
7724            "The input vector size must be divisble by the extended size.");
7725     if (SDValue V = Lower(NumElements / NumExtElements))
7726       return V;
7727   }
7728
7729   // No viable ext lowering found.
7730   return SDValue();
7731 }
7732
7733 /// \brief Try to get a scalar value for a specific element of a vector.
7734 ///
7735 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7736 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7737                                               SelectionDAG &DAG) {
7738   MVT VT = V.getSimpleValueType();
7739   MVT EltVT = VT.getVectorElementType();
7740   while (V.getOpcode() == ISD::BITCAST)
7741     V = V.getOperand(0);
7742   // If the bitcasts shift the element size, we can't extract an equivalent
7743   // element from it.
7744   MVT NewVT = V.getSimpleValueType();
7745   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7746     return SDValue();
7747
7748   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7749       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
7750     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
7751
7752   return SDValue();
7753 }
7754
7755 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7756 ///
7757 /// This is particularly important because the set of instructions varies
7758 /// significantly based on whether the operand is a load or not.
7759 static bool isShuffleFoldableLoad(SDValue V) {
7760   while (V.getOpcode() == ISD::BITCAST)
7761     V = V.getOperand(0);
7762
7763   return ISD::isNON_EXTLoad(V.getNode());
7764 }
7765
7766 /// \brief Try to lower insertion of a single element into a zero vector.
7767 ///
7768 /// This is a common pattern that we have especially efficient patterns to lower
7769 /// across all subtarget feature sets.
7770 static SDValue lowerVectorShuffleAsElementInsertion(
7771     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7772     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7773   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7774   MVT ExtVT = VT;
7775   MVT EltVT = VT.getVectorElementType();
7776
7777   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7778                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7779                 Mask.begin();
7780   bool IsV1Zeroable = true;
7781   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7782     if (i != V2Index && !Zeroable[i]) {
7783       IsV1Zeroable = false;
7784       break;
7785     }
7786
7787   // Check for a single input from a SCALAR_TO_VECTOR node.
7788   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7789   // all the smarts here sunk into that routine. However, the current
7790   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7791   // vector shuffle lowering is dead.
7792   if (SDValue V2S = getScalarValueForVectorElement(
7793           V2, Mask[V2Index] - Mask.size(), DAG)) {
7794     // We need to zext the scalar if it is smaller than an i32.
7795     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7796     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7797       // Using zext to expand a narrow element won't work for non-zero
7798       // insertions.
7799       if (!IsV1Zeroable)
7800         return SDValue();
7801
7802       // Zero-extend directly to i32.
7803       ExtVT = MVT::v4i32;
7804       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7805     }
7806     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7807   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7808              EltVT == MVT::i16) {
7809     // Either not inserting from the low element of the input or the input
7810     // element size is too small to use VZEXT_MOVL to clear the high bits.
7811     return SDValue();
7812   }
7813
7814   if (!IsV1Zeroable) {
7815     // If V1 can't be treated as a zero vector we have fewer options to lower
7816     // this. We can't support integer vectors or non-zero targets cheaply, and
7817     // the V1 elements can't be permuted in any way.
7818     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7819     if (!VT.isFloatingPoint() || V2Index != 0)
7820       return SDValue();
7821     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7822     V1Mask[V2Index] = -1;
7823     if (!isNoopShuffleMask(V1Mask))
7824       return SDValue();
7825     // This is essentially a special case blend operation, but if we have
7826     // general purpose blend operations, they are always faster. Bail and let
7827     // the rest of the lowering handle these as blends.
7828     if (Subtarget->hasSSE41())
7829       return SDValue();
7830
7831     // Otherwise, use MOVSD or MOVSS.
7832     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7833            "Only two types of floating point element types to handle!");
7834     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7835                        ExtVT, V1, V2);
7836   }
7837
7838   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7839   if (ExtVT != VT)
7840     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7841
7842   if (V2Index != 0) {
7843     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7844     // the desired position. Otherwise it is more efficient to do a vector
7845     // shift left. We know that we can do a vector shift left because all
7846     // the inputs are zero.
7847     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7848       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7849       V2Shuffle[V2Index] = 0;
7850       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7851     } else {
7852       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7853       V2 = DAG.getNode(
7854           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7855           DAG.getConstant(
7856               V2Index * EltVT.getSizeInBits(),
7857               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7858       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7859     }
7860   }
7861   return V2;
7862 }
7863
7864 /// \brief Try to lower broadcast of a single element.
7865 ///
7866 /// For convenience, this code also bundles all of the subtarget feature set
7867 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7868 /// a convenient way to factor it out.
7869 static SDValue lowerVectorShuffleAsBroadcast(MVT VT, SDLoc DL, SDValue V,
7870                                              ArrayRef<int> Mask,
7871                                              const X86Subtarget *Subtarget,
7872                                              SelectionDAG &DAG) {
7873   if (!Subtarget->hasAVX())
7874     return SDValue();
7875   if (VT.isInteger() && !Subtarget->hasAVX2())
7876     return SDValue();
7877
7878   // Check that the mask is a broadcast.
7879   int BroadcastIdx = -1;
7880   for (int M : Mask)
7881     if (M >= 0 && BroadcastIdx == -1)
7882       BroadcastIdx = M;
7883     else if (M >= 0 && M != BroadcastIdx)
7884       return SDValue();
7885
7886   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7887                                             "a sorted mask where the broadcast "
7888                                             "comes from V1.");
7889
7890   // Go up the chain of (vector) values to try and find a scalar load that
7891   // we can combine with the broadcast.
7892   for (;;) {
7893     switch (V.getOpcode()) {
7894     case ISD::CONCAT_VECTORS: {
7895       int OperandSize = Mask.size() / V.getNumOperands();
7896       V = V.getOperand(BroadcastIdx / OperandSize);
7897       BroadcastIdx %= OperandSize;
7898       continue;
7899     }
7900
7901     case ISD::INSERT_SUBVECTOR: {
7902       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7903       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7904       if (!ConstantIdx)
7905         break;
7906
7907       int BeginIdx = (int)ConstantIdx->getZExtValue();
7908       int EndIdx =
7909           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7910       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7911         BroadcastIdx -= BeginIdx;
7912         V = VInner;
7913       } else {
7914         V = VOuter;
7915       }
7916       continue;
7917     }
7918     }
7919     break;
7920   }
7921
7922   // Check if this is a broadcast of a scalar. We special case lowering
7923   // for scalars so that we can more effectively fold with loads.
7924   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7925       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7926     V = V.getOperand(BroadcastIdx);
7927
7928     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
7929     // AVX2.
7930     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7931       return SDValue();
7932   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7933     // We can't broadcast from a vector register w/o AVX2, and we can only
7934     // broadcast from the zero-element of a vector register.
7935     return SDValue();
7936   }
7937
7938   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7939 }
7940
7941 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7942 ///
7943 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7944 /// support for floating point shuffles but not integer shuffles. These
7945 /// instructions will incur a domain crossing penalty on some chips though so
7946 /// it is better to avoid lowering through this for integer vectors where
7947 /// possible.
7948 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7949                                        const X86Subtarget *Subtarget,
7950                                        SelectionDAG &DAG) {
7951   SDLoc DL(Op);
7952   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7953   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7954   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7955   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7956   ArrayRef<int> Mask = SVOp->getMask();
7957   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7958
7959   if (isSingleInputShuffleMask(Mask)) {
7960     // Straight shuffle of a single input vector. Simulate this by using the
7961     // single input as both of the "inputs" to this instruction..
7962     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7963
7964     if (Subtarget->hasAVX()) {
7965       // If we have AVX, we can use VPERMILPS which will allow folding a load
7966       // into the shuffle.
7967       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7968                          DAG.getConstant(SHUFPDMask, MVT::i8));
7969     }
7970
7971     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7972                        DAG.getConstant(SHUFPDMask, MVT::i8));
7973   }
7974   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7975   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7976
7977   // Use dedicated unpack instructions for masks that match their pattern.
7978   if (isShuffleEquivalent(Mask, 0, 2))
7979     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7980   if (isShuffleEquivalent(Mask, 1, 3))
7981     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7982
7983   // If we have a single input, insert that into V1 if we can do so cheaply.
7984   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7985     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7986             MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
7987       return Insertion;
7988     // Try inverting the insertion since for v2 masks it is easy to do and we
7989     // can't reliably sort the mask one way or the other.
7990     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7991                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7992     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7993             MVT::v2f64, DL, V2, V1, InverseMask, Subtarget, DAG))
7994       return Insertion;
7995   }
7996
7997   // Try to use one of the special instruction patterns to handle two common
7998   // blend patterns if a zero-blend above didn't work.
7999   if (isShuffleEquivalent(Mask, 0, 3) || isShuffleEquivalent(Mask, 1, 3))
8000     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8001       // We can either use a special instruction to load over the low double or
8002       // to move just the low double.
8003       return DAG.getNode(
8004           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8005           DL, MVT::v2f64, V2,
8006           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8007
8008   if (Subtarget->hasSSE41())
8009     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8010                                                   Subtarget, DAG))
8011       return Blend;
8012
8013   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8014   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
8015                      DAG.getConstant(SHUFPDMask, MVT::i8));
8016 }
8017
8018 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8019 ///
8020 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8021 /// the integer unit to minimize domain crossing penalties. However, for blends
8022 /// it falls back to the floating point shuffle operation with appropriate bit
8023 /// casting.
8024 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8025                                        const X86Subtarget *Subtarget,
8026                                        SelectionDAG &DAG) {
8027   SDLoc DL(Op);
8028   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8029   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8030   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8031   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8032   ArrayRef<int> Mask = SVOp->getMask();
8033   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8034
8035   if (isSingleInputShuffleMask(Mask)) {
8036     // Check for being able to broadcast a single element.
8037     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v2i64, DL, V1,
8038                                                           Mask, Subtarget, DAG))
8039       return Broadcast;
8040
8041     // Straight shuffle of a single input vector. For everything from SSE2
8042     // onward this has a single fast instruction with no scary immediates.
8043     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8044     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
8045     int WidenedMask[4] = {
8046         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8047         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8048     return DAG.getNode(
8049         ISD::BITCAST, DL, MVT::v2i64,
8050         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
8051                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
8052   }
8053
8054   // If we have a single input from V2 insert that into V1 if we can do so
8055   // cheaply.
8056   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8057     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8058             MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
8059       return Insertion;
8060     // Try inverting the insertion since for v2 masks it is easy to do and we
8061     // can't reliably sort the mask one way or the other.
8062     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8063                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8064     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8065             MVT::v2i64, DL, V2, V1, InverseMask, Subtarget, DAG))
8066       return Insertion;
8067   }
8068
8069   // Use dedicated unpack instructions for masks that match their pattern.
8070   if (isShuffleEquivalent(Mask, 0, 2))
8071     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8072   if (isShuffleEquivalent(Mask, 1, 3))
8073     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8074
8075   if (Subtarget->hasSSE41())
8076     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8077                                                   Subtarget, DAG))
8078       return Blend;
8079
8080   // Try to use rotation instructions if available.
8081   if (Subtarget->hasSSSE3())
8082     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8083             DL, MVT::v2i64, V1, V2, Mask, DAG))
8084       return Rotate;
8085
8086   // We implement this with SHUFPD which is pretty lame because it will likely
8087   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8088   // However, all the alternatives are still more cycles and newer chips don't
8089   // have this problem. It would be really nice if x86 had better shuffles here.
8090   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
8091   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
8092   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
8093                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8094 }
8095
8096 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8097 ///
8098 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8099 /// It makes no assumptions about whether this is the *best* lowering, it simply
8100 /// uses it.
8101 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8102                                             ArrayRef<int> Mask, SDValue V1,
8103                                             SDValue V2, SelectionDAG &DAG) {
8104   SDValue LowV = V1, HighV = V2;
8105   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8106
8107   int NumV2Elements =
8108       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8109
8110   if (NumV2Elements == 1) {
8111     int V2Index =
8112         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8113         Mask.begin();
8114
8115     // Compute the index adjacent to V2Index and in the same half by toggling
8116     // the low bit.
8117     int V2AdjIndex = V2Index ^ 1;
8118
8119     if (Mask[V2AdjIndex] == -1) {
8120       // Handles all the cases where we have a single V2 element and an undef.
8121       // This will only ever happen in the high lanes because we commute the
8122       // vector otherwise.
8123       if (V2Index < 2)
8124         std::swap(LowV, HighV);
8125       NewMask[V2Index] -= 4;
8126     } else {
8127       // Handle the case where the V2 element ends up adjacent to a V1 element.
8128       // To make this work, blend them together as the first step.
8129       int V1Index = V2AdjIndex;
8130       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8131       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8132                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8133
8134       // Now proceed to reconstruct the final blend as we have the necessary
8135       // high or low half formed.
8136       if (V2Index < 2) {
8137         LowV = V2;
8138         HighV = V1;
8139       } else {
8140         HighV = V2;
8141       }
8142       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8143       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8144     }
8145   } else if (NumV2Elements == 2) {
8146     if (Mask[0] < 4 && Mask[1] < 4) {
8147       // Handle the easy case where we have V1 in the low lanes and V2 in the
8148       // high lanes.
8149       NewMask[2] -= 4;
8150       NewMask[3] -= 4;
8151     } else if (Mask[2] < 4 && Mask[3] < 4) {
8152       // We also handle the reversed case because this utility may get called
8153       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8154       // arrange things in the right direction.
8155       NewMask[0] -= 4;
8156       NewMask[1] -= 4;
8157       HighV = V1;
8158       LowV = V2;
8159     } else {
8160       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8161       // trying to place elements directly, just blend them and set up the final
8162       // shuffle to place them.
8163
8164       // The first two blend mask elements are for V1, the second two are for
8165       // V2.
8166       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8167                           Mask[2] < 4 ? Mask[2] : Mask[3],
8168                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8169                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8170       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8171                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8172
8173       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8174       // a blend.
8175       LowV = HighV = V1;
8176       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8177       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8178       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8179       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8180     }
8181   }
8182   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8183                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
8184 }
8185
8186 /// \brief Lower 4-lane 32-bit floating point shuffles.
8187 ///
8188 /// Uses instructions exclusively from the floating point unit to minimize
8189 /// domain crossing penalties, as these are sufficient to implement all v4f32
8190 /// shuffles.
8191 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8192                                        const X86Subtarget *Subtarget,
8193                                        SelectionDAG &DAG) {
8194   SDLoc DL(Op);
8195   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8196   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8197   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8198   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8199   ArrayRef<int> Mask = SVOp->getMask();
8200   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8201
8202   int NumV2Elements =
8203       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8204
8205   if (NumV2Elements == 0) {
8206     // Check for being able to broadcast a single element.
8207     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f32, DL, V1,
8208                                                           Mask, Subtarget, DAG))
8209       return Broadcast;
8210
8211     if (Subtarget->hasAVX()) {
8212       // If we have AVX, we can use VPERMILPS which will allow folding a load
8213       // into the shuffle.
8214       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8215                          getV4X86ShuffleImm8ForMask(Mask, DAG));
8216     }
8217
8218     // Otherwise, use a straight shuffle of a single input vector. We pass the
8219     // input vector to both operands to simulate this with a SHUFPS.
8220     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8221                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8222   }
8223
8224   // Use dedicated unpack instructions for masks that match their pattern.
8225   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8226     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8227   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8228     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8229
8230   // There are special ways we can lower some single-element blends. However, we
8231   // have custom ways we can lower more complex single-element blends below that
8232   // we defer to if both this and BLENDPS fail to match, so restrict this to
8233   // when the V2 input is targeting element 0 of the mask -- that is the fast
8234   // case here.
8235   if (NumV2Elements == 1 && Mask[0] >= 4)
8236     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
8237                                                          Mask, Subtarget, DAG))
8238       return V;
8239
8240   if (Subtarget->hasSSE41())
8241     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8242                                                   Subtarget, DAG))
8243       return Blend;
8244
8245   // Check for whether we can use INSERTPS to perform the blend. We only use
8246   // INSERTPS when the V1 elements are already in the correct locations
8247   // because otherwise we can just always use two SHUFPS instructions which
8248   // are much smaller to encode than a SHUFPS and an INSERTPS.
8249   if (NumV2Elements == 1 && Subtarget->hasSSE41()) {
8250     int V2Index =
8251         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8252         Mask.begin();
8253
8254     // When using INSERTPS we can zero any lane of the destination. Collect
8255     // the zero inputs into a mask and drop them from the lanes of V1 which
8256     // actually need to be present as inputs to the INSERTPS.
8257     SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8258
8259     // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
8260     bool InsertNeedsShuffle = false;
8261     unsigned ZMask = 0;
8262     for (int i = 0; i < 4; ++i)
8263       if (i != V2Index) {
8264         if (Zeroable[i]) {
8265           ZMask |= 1 << i;
8266         } else if (Mask[i] != i) {
8267           InsertNeedsShuffle = true;
8268           break;
8269         }
8270       }
8271
8272     // We don't want to use INSERTPS or other insertion techniques if it will
8273     // require shuffling anyways.
8274     if (!InsertNeedsShuffle) {
8275       // If all of V1 is zeroable, replace it with undef.
8276       if ((ZMask | 1 << V2Index) == 0xF)
8277         V1 = DAG.getUNDEF(MVT::v4f32);
8278
8279       unsigned InsertPSMask = (Mask[V2Index] - 4) << 6 | V2Index << 4 | ZMask;
8280       assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8281
8282       // Insert the V2 element into the desired position.
8283       return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8284                          DAG.getConstant(InsertPSMask, MVT::i8));
8285     }
8286   }
8287
8288   // Otherwise fall back to a SHUFPS lowering strategy.
8289   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8290 }
8291
8292 /// \brief Lower 4-lane i32 vector shuffles.
8293 ///
8294 /// We try to handle these with integer-domain shuffles where we can, but for
8295 /// blends we use the floating point domain blend instructions.
8296 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8297                                        const X86Subtarget *Subtarget,
8298                                        SelectionDAG &DAG) {
8299   SDLoc DL(Op);
8300   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8301   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8302   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8303   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8304   ArrayRef<int> Mask = SVOp->getMask();
8305   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8306
8307   // Whenever we can lower this as a zext, that instruction is strictly faster
8308   // than any alternative. It also allows us to fold memory operands into the
8309   // shuffle in many cases.
8310   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8311                                                          Mask, Subtarget, DAG))
8312     return ZExt;
8313
8314   int NumV2Elements =
8315       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8316
8317   if (NumV2Elements == 0) {
8318     // Check for being able to broadcast a single element.
8319     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i32, DL, V1,
8320                                                           Mask, Subtarget, DAG))
8321       return Broadcast;
8322
8323     // Straight shuffle of a single input vector. For everything from SSE2
8324     // onward this has a single fast instruction with no scary immediates.
8325     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8326     // but we aren't actually going to use the UNPCK instruction because doing
8327     // so prevents folding a load into this instruction or making a copy.
8328     const int UnpackLoMask[] = {0, 0, 1, 1};
8329     const int UnpackHiMask[] = {2, 2, 3, 3};
8330     if (isShuffleEquivalent(Mask, 0, 0, 1, 1))
8331       Mask = UnpackLoMask;
8332     else if (isShuffleEquivalent(Mask, 2, 2, 3, 3))
8333       Mask = UnpackHiMask;
8334
8335     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8336                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8337   }
8338
8339   // There are special ways we can lower some single-element blends.
8340   if (NumV2Elements == 1)
8341     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
8342                                                          Mask, Subtarget, DAG))
8343       return V;
8344
8345   // Use dedicated unpack instructions for masks that match their pattern.
8346   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8347     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8348   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8349     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8350
8351   if (Subtarget->hasSSE41())
8352     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8353                                                   Subtarget, DAG))
8354       return Blend;
8355
8356   // Try to use rotation instructions if available.
8357   if (Subtarget->hasSSSE3())
8358     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8359             DL, MVT::v4i32, V1, V2, Mask, DAG))
8360       return Rotate;
8361
8362   // We implement this with SHUFPS because it can blend from two vectors.
8363   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8364   // up the inputs, bypassing domain shift penalties that we would encur if we
8365   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8366   // relevant.
8367   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
8368                      DAG.getVectorShuffle(
8369                          MVT::v4f32, DL,
8370                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
8371                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
8372 }
8373
8374 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8375 /// shuffle lowering, and the most complex part.
8376 ///
8377 /// The lowering strategy is to try to form pairs of input lanes which are
8378 /// targeted at the same half of the final vector, and then use a dword shuffle
8379 /// to place them onto the right half, and finally unpack the paired lanes into
8380 /// their final position.
8381 ///
8382 /// The exact breakdown of how to form these dword pairs and align them on the
8383 /// correct sides is really tricky. See the comments within the function for
8384 /// more of the details.
8385 static SDValue lowerV8I16SingleInputVectorShuffle(
8386     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
8387     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8388   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8389   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8390   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8391
8392   SmallVector<int, 4> LoInputs;
8393   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8394                [](int M) { return M >= 0; });
8395   std::sort(LoInputs.begin(), LoInputs.end());
8396   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8397   SmallVector<int, 4> HiInputs;
8398   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8399                [](int M) { return M >= 0; });
8400   std::sort(HiInputs.begin(), HiInputs.end());
8401   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8402   int NumLToL =
8403       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8404   int NumHToL = LoInputs.size() - NumLToL;
8405   int NumLToH =
8406       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8407   int NumHToH = HiInputs.size() - NumLToH;
8408   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8409   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8410   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8411   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8412
8413   // Check for being able to broadcast a single element.
8414   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i16, DL, V,
8415                                                         Mask, Subtarget, DAG))
8416     return Broadcast;
8417
8418   // Use dedicated unpack instructions for masks that match their pattern.
8419   if (isShuffleEquivalent(Mask, 0, 0, 1, 1, 2, 2, 3, 3))
8420     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
8421   if (isShuffleEquivalent(Mask, 4, 4, 5, 5, 6, 6, 7, 7))
8422     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
8423
8424   // Try to use rotation instructions if available.
8425   if (Subtarget->hasSSSE3())
8426     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8427             DL, MVT::v8i16, V, V, Mask, DAG))
8428       return Rotate;
8429
8430   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8431   // such inputs we can swap two of the dwords across the half mark and end up
8432   // with <=2 inputs to each half in each half. Once there, we can fall through
8433   // to the generic code below. For example:
8434   //
8435   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8436   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8437   //
8438   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8439   // and an existing 2-into-2 on the other half. In this case we may have to
8440   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8441   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8442   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8443   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8444   // half than the one we target for fixing) will be fixed when we re-enter this
8445   // path. We will also combine away any sequence of PSHUFD instructions that
8446   // result into a single instruction. Here is an example of the tricky case:
8447   //
8448   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8449   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8450   //
8451   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8452   //
8453   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8454   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8455   //
8456   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8457   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8458   //
8459   // The result is fine to be handled by the generic logic.
8460   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8461                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8462                           int AOffset, int BOffset) {
8463     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8464            "Must call this with A having 3 or 1 inputs from the A half.");
8465     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8466            "Must call this with B having 1 or 3 inputs from the B half.");
8467     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8468            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8469
8470     // Compute the index of dword with only one word among the three inputs in
8471     // a half by taking the sum of the half with three inputs and subtracting
8472     // the sum of the actual three inputs. The difference is the remaining
8473     // slot.
8474     int ADWord, BDWord;
8475     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8476     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8477     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8478     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8479     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8480     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8481     int TripleNonInputIdx =
8482         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8483     TripleDWord = TripleNonInputIdx / 2;
8484
8485     // We use xor with one to compute the adjacent DWord to whichever one the
8486     // OneInput is in.
8487     OneInputDWord = (OneInput / 2) ^ 1;
8488
8489     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8490     // and BToA inputs. If there is also such a problem with the BToB and AToB
8491     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8492     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8493     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8494     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8495       // Compute how many inputs will be flipped by swapping these DWords. We
8496       // need
8497       // to balance this to ensure we don't form a 3-1 shuffle in the other
8498       // half.
8499       int NumFlippedAToBInputs =
8500           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8501           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8502       int NumFlippedBToBInputs =
8503           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8504           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8505       if ((NumFlippedAToBInputs == 1 &&
8506            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8507           (NumFlippedBToBInputs == 1 &&
8508            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8509         // We choose whether to fix the A half or B half based on whether that
8510         // half has zero flipped inputs. At zero, we may not be able to fix it
8511         // with that half. We also bias towards fixing the B half because that
8512         // will more commonly be the high half, and we have to bias one way.
8513         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8514                                                        ArrayRef<int> Inputs) {
8515           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8516           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8517                                          PinnedIdx ^ 1) != Inputs.end();
8518           // Determine whether the free index is in the flipped dword or the
8519           // unflipped dword based on where the pinned index is. We use this bit
8520           // in an xor to conditionally select the adjacent dword.
8521           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8522           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8523                                              FixFreeIdx) != Inputs.end();
8524           if (IsFixIdxInput == IsFixFreeIdxInput)
8525             FixFreeIdx += 1;
8526           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8527                                         FixFreeIdx) != Inputs.end();
8528           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8529                  "We need to be changing the number of flipped inputs!");
8530           int PSHUFHalfMask[] = {0, 1, 2, 3};
8531           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8532           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8533                           MVT::v8i16, V,
8534                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
8535
8536           for (int &M : Mask)
8537             if (M != -1 && M == FixIdx)
8538               M = FixFreeIdx;
8539             else if (M != -1 && M == FixFreeIdx)
8540               M = FixIdx;
8541         };
8542         if (NumFlippedBToBInputs != 0) {
8543           int BPinnedIdx =
8544               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8545           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8546         } else {
8547           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8548           int APinnedIdx =
8549               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8550           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8551         }
8552       }
8553     }
8554
8555     int PSHUFDMask[] = {0, 1, 2, 3};
8556     PSHUFDMask[ADWord] = BDWord;
8557     PSHUFDMask[BDWord] = ADWord;
8558     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8559                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8560                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8561                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8562
8563     // Adjust the mask to match the new locations of A and B.
8564     for (int &M : Mask)
8565       if (M != -1 && M/2 == ADWord)
8566         M = 2 * BDWord + M % 2;
8567       else if (M != -1 && M/2 == BDWord)
8568         M = 2 * ADWord + M % 2;
8569
8570     // Recurse back into this routine to re-compute state now that this isn't
8571     // a 3 and 1 problem.
8572     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8573                                 Mask);
8574   };
8575   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8576     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8577   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8578     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8579
8580   // At this point there are at most two inputs to the low and high halves from
8581   // each half. That means the inputs can always be grouped into dwords and
8582   // those dwords can then be moved to the correct half with a dword shuffle.
8583   // We use at most one low and one high word shuffle to collect these paired
8584   // inputs into dwords, and finally a dword shuffle to place them.
8585   int PSHUFLMask[4] = {-1, -1, -1, -1};
8586   int PSHUFHMask[4] = {-1, -1, -1, -1};
8587   int PSHUFDMask[4] = {-1, -1, -1, -1};
8588
8589   // First fix the masks for all the inputs that are staying in their
8590   // original halves. This will then dictate the targets of the cross-half
8591   // shuffles.
8592   auto fixInPlaceInputs =
8593       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8594                     MutableArrayRef<int> SourceHalfMask,
8595                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8596     if (InPlaceInputs.empty())
8597       return;
8598     if (InPlaceInputs.size() == 1) {
8599       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8600           InPlaceInputs[0] - HalfOffset;
8601       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8602       return;
8603     }
8604     if (IncomingInputs.empty()) {
8605       // Just fix all of the in place inputs.
8606       for (int Input : InPlaceInputs) {
8607         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8608         PSHUFDMask[Input / 2] = Input / 2;
8609       }
8610       return;
8611     }
8612
8613     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8614     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8615         InPlaceInputs[0] - HalfOffset;
8616     // Put the second input next to the first so that they are packed into
8617     // a dword. We find the adjacent index by toggling the low bit.
8618     int AdjIndex = InPlaceInputs[0] ^ 1;
8619     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8620     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8621     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8622   };
8623   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8624   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8625
8626   // Now gather the cross-half inputs and place them into a free dword of
8627   // their target half.
8628   // FIXME: This operation could almost certainly be simplified dramatically to
8629   // look more like the 3-1 fixing operation.
8630   auto moveInputsToRightHalf = [&PSHUFDMask](
8631       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8632       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8633       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8634       int DestOffset) {
8635     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8636       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8637     };
8638     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8639                                                int Word) {
8640       int LowWord = Word & ~1;
8641       int HighWord = Word | 1;
8642       return isWordClobbered(SourceHalfMask, LowWord) ||
8643              isWordClobbered(SourceHalfMask, HighWord);
8644     };
8645
8646     if (IncomingInputs.empty())
8647       return;
8648
8649     if (ExistingInputs.empty()) {
8650       // Map any dwords with inputs from them into the right half.
8651       for (int Input : IncomingInputs) {
8652         // If the source half mask maps over the inputs, turn those into
8653         // swaps and use the swapped lane.
8654         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8655           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8656             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8657                 Input - SourceOffset;
8658             // We have to swap the uses in our half mask in one sweep.
8659             for (int &M : HalfMask)
8660               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8661                 M = Input;
8662               else if (M == Input)
8663                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8664           } else {
8665             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8666                        Input - SourceOffset &&
8667                    "Previous placement doesn't match!");
8668           }
8669           // Note that this correctly re-maps both when we do a swap and when
8670           // we observe the other side of the swap above. We rely on that to
8671           // avoid swapping the members of the input list directly.
8672           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8673         }
8674
8675         // Map the input's dword into the correct half.
8676         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8677           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8678         else
8679           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8680                      Input / 2 &&
8681                  "Previous placement doesn't match!");
8682       }
8683
8684       // And just directly shift any other-half mask elements to be same-half
8685       // as we will have mirrored the dword containing the element into the
8686       // same position within that half.
8687       for (int &M : HalfMask)
8688         if (M >= SourceOffset && M < SourceOffset + 4) {
8689           M = M - SourceOffset + DestOffset;
8690           assert(M >= 0 && "This should never wrap below zero!");
8691         }
8692       return;
8693     }
8694
8695     // Ensure we have the input in a viable dword of its current half. This
8696     // is particularly tricky because the original position may be clobbered
8697     // by inputs being moved and *staying* in that half.
8698     if (IncomingInputs.size() == 1) {
8699       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8700         int InputFixed = std::find(std::begin(SourceHalfMask),
8701                                    std::end(SourceHalfMask), -1) -
8702                          std::begin(SourceHalfMask) + SourceOffset;
8703         SourceHalfMask[InputFixed - SourceOffset] =
8704             IncomingInputs[0] - SourceOffset;
8705         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8706                      InputFixed);
8707         IncomingInputs[0] = InputFixed;
8708       }
8709     } else if (IncomingInputs.size() == 2) {
8710       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8711           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8712         // We have two non-adjacent or clobbered inputs we need to extract from
8713         // the source half. To do this, we need to map them into some adjacent
8714         // dword slot in the source mask.
8715         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8716                               IncomingInputs[1] - SourceOffset};
8717
8718         // If there is a free slot in the source half mask adjacent to one of
8719         // the inputs, place the other input in it. We use (Index XOR 1) to
8720         // compute an adjacent index.
8721         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8722             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8723           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8724           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8725           InputsFixed[1] = InputsFixed[0] ^ 1;
8726         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8727                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8728           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8729           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8730           InputsFixed[0] = InputsFixed[1] ^ 1;
8731         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8732                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8733           // The two inputs are in the same DWord but it is clobbered and the
8734           // adjacent DWord isn't used at all. Move both inputs to the free
8735           // slot.
8736           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8737           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8738           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8739           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8740         } else {
8741           // The only way we hit this point is if there is no clobbering
8742           // (because there are no off-half inputs to this half) and there is no
8743           // free slot adjacent to one of the inputs. In this case, we have to
8744           // swap an input with a non-input.
8745           for (int i = 0; i < 4; ++i)
8746             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8747                    "We can't handle any clobbers here!");
8748           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8749                  "Cannot have adjacent inputs here!");
8750
8751           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8752           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8753
8754           // We also have to update the final source mask in this case because
8755           // it may need to undo the above swap.
8756           for (int &M : FinalSourceHalfMask)
8757             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8758               M = InputsFixed[1] + SourceOffset;
8759             else if (M == InputsFixed[1] + SourceOffset)
8760               M = (InputsFixed[0] ^ 1) + SourceOffset;
8761
8762           InputsFixed[1] = InputsFixed[0] ^ 1;
8763         }
8764
8765         // Point everything at the fixed inputs.
8766         for (int &M : HalfMask)
8767           if (M == IncomingInputs[0])
8768             M = InputsFixed[0] + SourceOffset;
8769           else if (M == IncomingInputs[1])
8770             M = InputsFixed[1] + SourceOffset;
8771
8772         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8773         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8774       }
8775     } else {
8776       llvm_unreachable("Unhandled input size!");
8777     }
8778
8779     // Now hoist the DWord down to the right half.
8780     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8781     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8782     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8783     for (int &M : HalfMask)
8784       for (int Input : IncomingInputs)
8785         if (M == Input)
8786           M = FreeDWord * 2 + Input % 2;
8787   };
8788   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8789                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8790   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8791                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8792
8793   // Now enact all the shuffles we've computed to move the inputs into their
8794   // target half.
8795   if (!isNoopShuffleMask(PSHUFLMask))
8796     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8797                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8798   if (!isNoopShuffleMask(PSHUFHMask))
8799     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8800                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8801   if (!isNoopShuffleMask(PSHUFDMask))
8802     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8803                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8804                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8805                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8806
8807   // At this point, each half should contain all its inputs, and we can then
8808   // just shuffle them into their final position.
8809   assert(std::count_if(LoMask.begin(), LoMask.end(),
8810                        [](int M) { return M >= 4; }) == 0 &&
8811          "Failed to lift all the high half inputs to the low mask!");
8812   assert(std::count_if(HiMask.begin(), HiMask.end(),
8813                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8814          "Failed to lift all the low half inputs to the high mask!");
8815
8816   // Do a half shuffle for the low mask.
8817   if (!isNoopShuffleMask(LoMask))
8818     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8819                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8820
8821   // Do a half shuffle with the high mask after shifting its values down.
8822   for (int &M : HiMask)
8823     if (M >= 0)
8824       M -= 4;
8825   if (!isNoopShuffleMask(HiMask))
8826     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8827                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8828
8829   return V;
8830 }
8831
8832 /// \brief Detect whether the mask pattern should be lowered through
8833 /// interleaving.
8834 ///
8835 /// This essentially tests whether viewing the mask as an interleaving of two
8836 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
8837 /// lowering it through interleaving is a significantly better strategy.
8838 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
8839   int NumEvenInputs[2] = {0, 0};
8840   int NumOddInputs[2] = {0, 0};
8841   int NumLoInputs[2] = {0, 0};
8842   int NumHiInputs[2] = {0, 0};
8843   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
8844     if (Mask[i] < 0)
8845       continue;
8846
8847     int InputIdx = Mask[i] >= Size;
8848
8849     if (i < Size / 2)
8850       ++NumLoInputs[InputIdx];
8851     else
8852       ++NumHiInputs[InputIdx];
8853
8854     if ((i % 2) == 0)
8855       ++NumEvenInputs[InputIdx];
8856     else
8857       ++NumOddInputs[InputIdx];
8858   }
8859
8860   // The minimum number of cross-input results for both the interleaved and
8861   // split cases. If interleaving results in fewer cross-input results, return
8862   // true.
8863   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
8864                                     NumEvenInputs[0] + NumOddInputs[1]);
8865   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
8866                               NumLoInputs[0] + NumHiInputs[1]);
8867   return InterleavedCrosses < SplitCrosses;
8868 }
8869
8870 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
8871 ///
8872 /// This strategy only works when the inputs from each vector fit into a single
8873 /// half of that vector, and generally there are not so many inputs as to leave
8874 /// the in-place shuffles required highly constrained (and thus expensive). It
8875 /// shifts all the inputs into a single side of both input vectors and then
8876 /// uses an unpack to interleave these inputs in a single vector. At that
8877 /// point, we will fall back on the generic single input shuffle lowering.
8878 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
8879                                                  SDValue V2,
8880                                                  MutableArrayRef<int> Mask,
8881                                                  const X86Subtarget *Subtarget,
8882                                                  SelectionDAG &DAG) {
8883   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8884   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8885   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
8886   for (int i = 0; i < 8; ++i)
8887     if (Mask[i] >= 0 && Mask[i] < 4)
8888       LoV1Inputs.push_back(i);
8889     else if (Mask[i] >= 4 && Mask[i] < 8)
8890       HiV1Inputs.push_back(i);
8891     else if (Mask[i] >= 8 && Mask[i] < 12)
8892       LoV2Inputs.push_back(i);
8893     else if (Mask[i] >= 12)
8894       HiV2Inputs.push_back(i);
8895
8896   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
8897   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
8898   (void)NumV1Inputs;
8899   (void)NumV2Inputs;
8900   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
8901   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
8902   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
8903
8904   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
8905                      HiV1Inputs.size() + HiV2Inputs.size();
8906
8907   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
8908                               ArrayRef<int> HiInputs, bool MoveToLo,
8909                               int MaskOffset) {
8910     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
8911     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
8912     if (BadInputs.empty())
8913       return V;
8914
8915     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8916     int MoveOffset = MoveToLo ? 0 : 4;
8917
8918     if (GoodInputs.empty()) {
8919       for (int BadInput : BadInputs) {
8920         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
8921         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
8922       }
8923     } else {
8924       if (GoodInputs.size() == 2) {
8925         // If the low inputs are spread across two dwords, pack them into
8926         // a single dword.
8927         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
8928         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
8929         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
8930         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
8931       } else {
8932         // Otherwise pin the good inputs.
8933         for (int GoodInput : GoodInputs)
8934           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
8935       }
8936
8937       if (BadInputs.size() == 2) {
8938         // If we have two bad inputs then there may be either one or two good
8939         // inputs fixed in place. Find a fixed input, and then find the *other*
8940         // two adjacent indices by using modular arithmetic.
8941         int GoodMaskIdx =
8942             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
8943                          [](int M) { return M >= 0; }) -
8944             std::begin(MoveMask);
8945         int MoveMaskIdx =
8946             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
8947         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
8948         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
8949         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8950         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
8951         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8952         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
8953       } else {
8954         assert(BadInputs.size() == 1 && "All sizes handled");
8955         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
8956                                     std::end(MoveMask), -1) -
8957                           std::begin(MoveMask);
8958         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8959         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8960       }
8961     }
8962
8963     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8964                                 MoveMask);
8965   };
8966   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
8967                         /*MaskOffset*/ 0);
8968   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
8969                         /*MaskOffset*/ 8);
8970
8971   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
8972   // cross-half traffic in the final shuffle.
8973
8974   // Munge the mask to be a single-input mask after the unpack merges the
8975   // results.
8976   for (int &M : Mask)
8977     if (M != -1)
8978       M = 2 * (M % 4) + (M / 8);
8979
8980   return DAG.getVectorShuffle(
8981       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
8982                                   DL, MVT::v8i16, V1, V2),
8983       DAG.getUNDEF(MVT::v8i16), Mask);
8984 }
8985
8986 /// \brief Generic lowering of 8-lane i16 shuffles.
8987 ///
8988 /// This handles both single-input shuffles and combined shuffle/blends with
8989 /// two inputs. The single input shuffles are immediately delegated to
8990 /// a dedicated lowering routine.
8991 ///
8992 /// The blends are lowered in one of three fundamental ways. If there are few
8993 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8994 /// of the input is significantly cheaper when lowered as an interleaving of
8995 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8996 /// halves of the inputs separately (making them have relatively few inputs)
8997 /// and then concatenate them.
8998 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8999                                        const X86Subtarget *Subtarget,
9000                                        SelectionDAG &DAG) {
9001   SDLoc DL(Op);
9002   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9003   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9004   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9005   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9006   ArrayRef<int> OrigMask = SVOp->getMask();
9007   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9008                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9009   MutableArrayRef<int> Mask(MaskStorage);
9010
9011   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9012
9013   // Whenever we can lower this as a zext, that instruction is strictly faster
9014   // than any alternative.
9015   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9016           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9017     return ZExt;
9018
9019   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9020   auto isV2 = [](int M) { return M >= 8; };
9021
9022   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
9023   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9024
9025   if (NumV2Inputs == 0)
9026     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
9027
9028   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
9029                             "to be V1-input shuffles.");
9030
9031   // There are special ways we can lower some single-element blends.
9032   if (NumV2Inputs == 1)
9033     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
9034                                                          Mask, Subtarget, DAG))
9035       return V;
9036
9037   // Use dedicated unpack instructions for masks that match their pattern.
9038   if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 2, 10, 3, 11))
9039     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9040   if (isShuffleEquivalent(Mask, 4, 12, 5, 13, 6, 14, 7, 15))
9041     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9042
9043   if (Subtarget->hasSSE41())
9044     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9045                                                   Subtarget, DAG))
9046       return Blend;
9047
9048   // Try to use rotation instructions if available.
9049   if (Subtarget->hasSSSE3())
9050     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9051             DL, MVT::v8i16, V1, V2, Mask, DAG))
9052       return Rotate;
9053
9054   if (NumV1Inputs + NumV2Inputs <= 4)
9055     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
9056
9057   // Check whether an interleaving lowering is likely to be more efficient.
9058   // This isn't perfect but it is a strong heuristic that tends to work well on
9059   // the kinds of shuffles that show up in practice.
9060   //
9061   // FIXME: Handle 1x, 2x, and 4x interleaving.
9062   if (shouldLowerAsInterleaving(Mask)) {
9063     // FIXME: Figure out whether we should pack these into the low or high
9064     // halves.
9065
9066     int EMask[8], OMask[8];
9067     for (int i = 0; i < 4; ++i) {
9068       EMask[i] = Mask[2*i];
9069       OMask[i] = Mask[2*i + 1];
9070       EMask[i + 4] = -1;
9071       OMask[i + 4] = -1;
9072     }
9073
9074     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
9075     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
9076
9077     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
9078   }
9079
9080   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9081   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9082
9083   for (int i = 0; i < 4; ++i) {
9084     LoBlendMask[i] = Mask[i];
9085     HiBlendMask[i] = Mask[i + 4];
9086   }
9087
9088   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9089   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9090   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
9091   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
9092
9093   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9094                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
9095 }
9096
9097 /// \brief Check whether a compaction lowering can be done by dropping even
9098 /// elements and compute how many times even elements must be dropped.
9099 ///
9100 /// This handles shuffles which take every Nth element where N is a power of
9101 /// two. Example shuffle masks:
9102 ///
9103 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9104 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9105 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9106 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9107 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9108 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9109 ///
9110 /// Any of these lanes can of course be undef.
9111 ///
9112 /// This routine only supports N <= 3.
9113 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9114 /// for larger N.
9115 ///
9116 /// \returns N above, or the number of times even elements must be dropped if
9117 /// there is such a number. Otherwise returns zero.
9118 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9119   // Figure out whether we're looping over two inputs or just one.
9120   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9121
9122   // The modulus for the shuffle vector entries is based on whether this is
9123   // a single input or not.
9124   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9125   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9126          "We should only be called with masks with a power-of-2 size!");
9127
9128   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9129
9130   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9131   // and 2^3 simultaneously. This is because we may have ambiguity with
9132   // partially undef inputs.
9133   bool ViableForN[3] = {true, true, true};
9134
9135   for (int i = 0, e = Mask.size(); i < e; ++i) {
9136     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9137     // want.
9138     if (Mask[i] == -1)
9139       continue;
9140
9141     bool IsAnyViable = false;
9142     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9143       if (ViableForN[j]) {
9144         uint64_t N = j + 1;
9145
9146         // The shuffle mask must be equal to (i * 2^N) % M.
9147         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9148           IsAnyViable = true;
9149         else
9150           ViableForN[j] = false;
9151       }
9152     // Early exit if we exhaust the possible powers of two.
9153     if (!IsAnyViable)
9154       break;
9155   }
9156
9157   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9158     if (ViableForN[j])
9159       return j + 1;
9160
9161   // Return 0 as there is no viable power of two.
9162   return 0;
9163 }
9164
9165 /// \brief Generic lowering of v16i8 shuffles.
9166 ///
9167 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9168 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9169 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9170 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9171 /// back together.
9172 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9173                                        const X86Subtarget *Subtarget,
9174                                        SelectionDAG &DAG) {
9175   SDLoc DL(Op);
9176   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9177   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9178   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9179   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9180   ArrayRef<int> OrigMask = SVOp->getMask();
9181   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9182
9183   // Try to use rotation instructions if available.
9184   if (Subtarget->hasSSSE3())
9185     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9186             DL, MVT::v16i8, V1, V2, OrigMask, DAG))
9187       return Rotate;
9188
9189   // Try to use a zext lowering.
9190   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9191           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9192     return ZExt;
9193
9194   int MaskStorage[16] = {
9195       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
9196       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
9197       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
9198       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
9199   MutableArrayRef<int> Mask(MaskStorage);
9200   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
9201   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
9202
9203   int NumV2Elements =
9204       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9205
9206   // For single-input shuffles, there are some nicer lowering tricks we can use.
9207   if (NumV2Elements == 0) {
9208     // Check for being able to broadcast a single element.
9209     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i8, DL, V1,
9210                                                           Mask, Subtarget, DAG))
9211       return Broadcast;
9212
9213     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9214     // Notably, this handles splat and partial-splat shuffles more efficiently.
9215     // However, it only makes sense if the pre-duplication shuffle simplifies
9216     // things significantly. Currently, this means we need to be able to
9217     // express the pre-duplication shuffle as an i16 shuffle.
9218     //
9219     // FIXME: We should check for other patterns which can be widened into an
9220     // i16 shuffle as well.
9221     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9222       for (int i = 0; i < 16; i += 2)
9223         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9224           return false;
9225
9226       return true;
9227     };
9228     auto tryToWidenViaDuplication = [&]() -> SDValue {
9229       if (!canWidenViaDuplication(Mask))
9230         return SDValue();
9231       SmallVector<int, 4> LoInputs;
9232       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9233                    [](int M) { return M >= 0 && M < 8; });
9234       std::sort(LoInputs.begin(), LoInputs.end());
9235       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9236                      LoInputs.end());
9237       SmallVector<int, 4> HiInputs;
9238       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9239                    [](int M) { return M >= 8; });
9240       std::sort(HiInputs.begin(), HiInputs.end());
9241       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9242                      HiInputs.end());
9243
9244       bool TargetLo = LoInputs.size() >= HiInputs.size();
9245       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9246       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9247
9248       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9249       SmallDenseMap<int, int, 8> LaneMap;
9250       for (int I : InPlaceInputs) {
9251         PreDupI16Shuffle[I/2] = I/2;
9252         LaneMap[I] = I;
9253       }
9254       int j = TargetLo ? 0 : 4, je = j + 4;
9255       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9256         // Check if j is already a shuffle of this input. This happens when
9257         // there are two adjacent bytes after we move the low one.
9258         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9259           // If we haven't yet mapped the input, search for a slot into which
9260           // we can map it.
9261           while (j < je && PreDupI16Shuffle[j] != -1)
9262             ++j;
9263
9264           if (j == je)
9265             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9266             return SDValue();
9267
9268           // Map this input with the i16 shuffle.
9269           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9270         }
9271
9272         // Update the lane map based on the mapping we ended up with.
9273         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9274       }
9275       V1 = DAG.getNode(
9276           ISD::BITCAST, DL, MVT::v16i8,
9277           DAG.getVectorShuffle(MVT::v8i16, DL,
9278                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9279                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9280
9281       // Unpack the bytes to form the i16s that will be shuffled into place.
9282       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9283                        MVT::v16i8, V1, V1);
9284
9285       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9286       for (int i = 0; i < 16; ++i)
9287         if (Mask[i] != -1) {
9288           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9289           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9290           if (PostDupI16Shuffle[i / 2] == -1)
9291             PostDupI16Shuffle[i / 2] = MappedMask;
9292           else
9293             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9294                    "Conflicting entrties in the original shuffle!");
9295         }
9296       return DAG.getNode(
9297           ISD::BITCAST, DL, MVT::v16i8,
9298           DAG.getVectorShuffle(MVT::v8i16, DL,
9299                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9300                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9301     };
9302     if (SDValue V = tryToWidenViaDuplication())
9303       return V;
9304   }
9305
9306   // Check whether an interleaving lowering is likely to be more efficient.
9307   // This isn't perfect but it is a strong heuristic that tends to work well on
9308   // the kinds of shuffles that show up in practice.
9309   //
9310   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
9311   if (shouldLowerAsInterleaving(Mask)) {
9312     int NumLoHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9313       return (M >= 0 && M < 8) || (M >= 16 && M < 24);
9314     });
9315     int NumHiHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9316       return (M >= 8 && M < 16) || M >= 24;
9317     });
9318     int EMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9319                      -1, -1, -1, -1, -1, -1, -1, -1};
9320     int OMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9321                      -1, -1, -1, -1, -1, -1, -1, -1};
9322     bool UnpackLo = NumLoHalf >= NumHiHalf;
9323     MutableArrayRef<int> TargetEMask(UnpackLo ? EMask : EMask + 8, 8);
9324     MutableArrayRef<int> TargetOMask(UnpackLo ? OMask : OMask + 8, 8);
9325     for (int i = 0; i < 8; ++i) {
9326       TargetEMask[i] = Mask[2 * i];
9327       TargetOMask[i] = Mask[2 * i + 1];
9328     }
9329
9330     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
9331     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
9332
9333     return DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9334                        MVT::v16i8, Evens, Odds);
9335   }
9336
9337   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9338   // with PSHUFB. It is important to do this before we attempt to generate any
9339   // blends but after all of the single-input lowerings. If the single input
9340   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9341   // want to preserve that and we can DAG combine any longer sequences into
9342   // a PSHUFB in the end. But once we start blending from multiple inputs,
9343   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9344   // and there are *very* few patterns that would actually be faster than the
9345   // PSHUFB approach because of its ability to zero lanes.
9346   //
9347   // FIXME: The only exceptions to the above are blends which are exact
9348   // interleavings with direct instructions supporting them. We currently don't
9349   // handle those well here.
9350   if (Subtarget->hasSSSE3()) {
9351     SDValue V1Mask[16];
9352     SDValue V2Mask[16];
9353     for (int i = 0; i < 16; ++i)
9354       if (Mask[i] == -1) {
9355         V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9356       } else {
9357         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
9358         V2Mask[i] =
9359             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
9360       }
9361     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
9362                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9363     if (isSingleInputShuffleMask(Mask))
9364       return V1; // Single inputs are easy.
9365
9366     // Otherwise, blend the two.
9367     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
9368                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9369     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9370   }
9371
9372   // There are special ways we can lower some single-element blends.
9373   if (NumV2Elements == 1)
9374     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
9375                                                          Mask, Subtarget, DAG))
9376       return V;
9377
9378   // Check whether a compaction lowering can be done. This handles shuffles
9379   // which take every Nth element for some even N. See the helper function for
9380   // details.
9381   //
9382   // We special case these as they can be particularly efficiently handled with
9383   // the PACKUSB instruction on x86 and they show up in common patterns of
9384   // rearranging bytes to truncate wide elements.
9385   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9386     // NumEvenDrops is the power of two stride of the elements. Another way of
9387     // thinking about it is that we need to drop the even elements this many
9388     // times to get the original input.
9389     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9390
9391     // First we need to zero all the dropped bytes.
9392     assert(NumEvenDrops <= 3 &&
9393            "No support for dropping even elements more than 3 times.");
9394     // We use the mask type to pick which bytes are preserved based on how many
9395     // elements are dropped.
9396     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9397     SDValue ByteClearMask =
9398         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
9399                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
9400     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9401     if (!IsSingleInput)
9402       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9403
9404     // Now pack things back together.
9405     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
9406     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
9407     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9408     for (int i = 1; i < NumEvenDrops; ++i) {
9409       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
9410       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9411     }
9412
9413     return Result;
9414   }
9415
9416   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9417   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9418   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9419   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9420
9421   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
9422                             MutableArrayRef<int> V1HalfBlendMask,
9423                             MutableArrayRef<int> V2HalfBlendMask) {
9424     for (int i = 0; i < 8; ++i)
9425       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
9426         V1HalfBlendMask[i] = HalfMask[i];
9427         HalfMask[i] = i;
9428       } else if (HalfMask[i] >= 16) {
9429         V2HalfBlendMask[i] = HalfMask[i] - 16;
9430         HalfMask[i] = i + 8;
9431       }
9432   };
9433   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
9434   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
9435
9436   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9437
9438   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
9439                              MutableArrayRef<int> HiBlendMask) {
9440     SDValue V1, V2;
9441     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9442     // them out and avoid using UNPCK{L,H} to extract the elements of V as
9443     // i16s.
9444     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
9445                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
9446         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
9447                      [](int M) { return M >= 0 && M % 2 == 1; })) {
9448       // Use a mask to drop the high bytes.
9449       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
9450       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
9451                        DAG.getConstant(0x00FF, MVT::v8i16));
9452
9453       // This will be a single vector shuffle instead of a blend so nuke V2.
9454       V2 = DAG.getUNDEF(MVT::v8i16);
9455
9456       // Squash the masks to point directly into V1.
9457       for (int &M : LoBlendMask)
9458         if (M >= 0)
9459           M /= 2;
9460       for (int &M : HiBlendMask)
9461         if (M >= 0)
9462           M /= 2;
9463     } else {
9464       // Otherwise just unpack the low half of V into V1 and the high half into
9465       // V2 so that we can blend them as i16s.
9466       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9467                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9468       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9469                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9470     }
9471
9472     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9473     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9474     return std::make_pair(BlendedLo, BlendedHi);
9475   };
9476   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
9477   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
9478   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
9479
9480   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
9481   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
9482
9483   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9484 }
9485
9486 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9487 ///
9488 /// This routine breaks down the specific type of 128-bit shuffle and
9489 /// dispatches to the lowering routines accordingly.
9490 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9491                                         MVT VT, const X86Subtarget *Subtarget,
9492                                         SelectionDAG &DAG) {
9493   switch (VT.SimpleTy) {
9494   case MVT::v2i64:
9495     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9496   case MVT::v2f64:
9497     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9498   case MVT::v4i32:
9499     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9500   case MVT::v4f32:
9501     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9502   case MVT::v8i16:
9503     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9504   case MVT::v16i8:
9505     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9506
9507   default:
9508     llvm_unreachable("Unimplemented!");
9509   }
9510 }
9511
9512 /// \brief Helper function to test whether a shuffle mask could be
9513 /// simplified by widening the elements being shuffled.
9514 ///
9515 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9516 /// leaves it in an unspecified state.
9517 ///
9518 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9519 /// shuffle masks. The latter have the special property of a '-2' representing
9520 /// a zero-ed lane of a vector.
9521 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9522                                     SmallVectorImpl<int> &WidenedMask) {
9523   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9524     // If both elements are undef, its trivial.
9525     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9526       WidenedMask.push_back(SM_SentinelUndef);
9527       continue;
9528     }
9529
9530     // Check for an undef mask and a mask value properly aligned to fit with
9531     // a pair of values. If we find such a case, use the non-undef mask's value.
9532     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9533       WidenedMask.push_back(Mask[i + 1] / 2);
9534       continue;
9535     }
9536     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9537       WidenedMask.push_back(Mask[i] / 2);
9538       continue;
9539     }
9540
9541     // When zeroing, we need to spread the zeroing across both lanes to widen.
9542     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9543       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9544           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9545         WidenedMask.push_back(SM_SentinelZero);
9546         continue;
9547       }
9548       return false;
9549     }
9550
9551     // Finally check if the two mask values are adjacent and aligned with
9552     // a pair.
9553     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9554       WidenedMask.push_back(Mask[i] / 2);
9555       continue;
9556     }
9557
9558     // Otherwise we can't safely widen the elements used in this shuffle.
9559     return false;
9560   }
9561   assert(WidenedMask.size() == Mask.size() / 2 &&
9562          "Incorrect size of mask after widening the elements!");
9563
9564   return true;
9565 }
9566
9567 /// \brief Generic routine to split ector shuffle into half-sized shuffles.
9568 ///
9569 /// This routine just extracts two subvectors, shuffles them independently, and
9570 /// then concatenates them back together. This should work effectively with all
9571 /// AVX vector shuffle types.
9572 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9573                                           SDValue V2, ArrayRef<int> Mask,
9574                                           SelectionDAG &DAG) {
9575   assert(VT.getSizeInBits() >= 256 &&
9576          "Only for 256-bit or wider vector shuffles!");
9577   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9578   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9579
9580   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9581   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9582
9583   int NumElements = VT.getVectorNumElements();
9584   int SplitNumElements = NumElements / 2;
9585   MVT ScalarVT = VT.getScalarType();
9586   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9587
9588   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9589                              DAG.getIntPtrConstant(0));
9590   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9591                              DAG.getIntPtrConstant(SplitNumElements));
9592   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9593                              DAG.getIntPtrConstant(0));
9594   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9595                              DAG.getIntPtrConstant(SplitNumElements));
9596
9597   // Now create two 4-way blends of these half-width vectors.
9598   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9599     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9600     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9601     for (int i = 0; i < SplitNumElements; ++i) {
9602       int M = HalfMask[i];
9603       if (M >= NumElements) {
9604         if (M >= NumElements + SplitNumElements)
9605           UseHiV2 = true;
9606         else
9607           UseLoV2 = true;
9608         V2BlendMask.push_back(M - NumElements);
9609         V1BlendMask.push_back(-1);
9610         BlendMask.push_back(SplitNumElements + i);
9611       } else if (M >= 0) {
9612         if (M >= SplitNumElements)
9613           UseHiV1 = true;
9614         else
9615           UseLoV1 = true;
9616         V2BlendMask.push_back(-1);
9617         V1BlendMask.push_back(M);
9618         BlendMask.push_back(i);
9619       } else {
9620         V2BlendMask.push_back(-1);
9621         V1BlendMask.push_back(-1);
9622         BlendMask.push_back(-1);
9623       }
9624     }
9625
9626     // Because the lowering happens after all combining takes place, we need to
9627     // manually combine these blend masks as much as possible so that we create
9628     // a minimal number of high-level vector shuffle nodes.
9629
9630     // First try just blending the halves of V1 or V2.
9631     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9632       return DAG.getUNDEF(SplitVT);
9633     if (!UseLoV2 && !UseHiV2)
9634       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9635     if (!UseLoV1 && !UseHiV1)
9636       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9637
9638     SDValue V1Blend, V2Blend;
9639     if (UseLoV1 && UseHiV1) {
9640       V1Blend =
9641         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9642     } else {
9643       // We only use half of V1 so map the usage down into the final blend mask.
9644       V1Blend = UseLoV1 ? LoV1 : HiV1;
9645       for (int i = 0; i < SplitNumElements; ++i)
9646         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9647           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9648     }
9649     if (UseLoV2 && UseHiV2) {
9650       V2Blend =
9651         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9652     } else {
9653       // We only use half of V2 so map the usage down into the final blend mask.
9654       V2Blend = UseLoV2 ? LoV2 : HiV2;
9655       for (int i = 0; i < SplitNumElements; ++i)
9656         if (BlendMask[i] >= SplitNumElements)
9657           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9658     }
9659     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9660   };
9661   SDValue Lo = HalfBlend(LoMask);
9662   SDValue Hi = HalfBlend(HiMask);
9663   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9664 }
9665
9666 /// \brief Either split a vector in halves or decompose the shuffles and the
9667 /// blend.
9668 ///
9669 /// This is provided as a good fallback for many lowerings of non-single-input
9670 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9671 /// between splitting the shuffle into 128-bit components and stitching those
9672 /// back together vs. extracting the single-input shuffles and blending those
9673 /// results.
9674 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9675                                                 SDValue V2, ArrayRef<int> Mask,
9676                                                 SelectionDAG &DAG) {
9677   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9678                                             "lower single-input shuffles as it "
9679                                             "could then recurse on itself.");
9680   int Size = Mask.size();
9681
9682   // If this can be modeled as a broadcast of two elements followed by a blend,
9683   // prefer that lowering. This is especially important because broadcasts can
9684   // often fold with memory operands.
9685   auto DoBothBroadcast = [&] {
9686     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9687     for (int M : Mask)
9688       if (M >= Size) {
9689         if (V2BroadcastIdx == -1)
9690           V2BroadcastIdx = M - Size;
9691         else if (M - Size != V2BroadcastIdx)
9692           return false;
9693       } else if (M >= 0) {
9694         if (V1BroadcastIdx == -1)
9695           V1BroadcastIdx = M;
9696         else if (M != V1BroadcastIdx)
9697           return false;
9698       }
9699     return true;
9700   };
9701   if (DoBothBroadcast())
9702     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9703                                                       DAG);
9704
9705   // If the inputs all stem from a single 128-bit lane of each input, then we
9706   // split them rather than blending because the split will decompose to
9707   // unusually few instructions.
9708   int LaneCount = VT.getSizeInBits() / 128;
9709   int LaneSize = Size / LaneCount;
9710   SmallBitVector LaneInputs[2];
9711   LaneInputs[0].resize(LaneCount, false);
9712   LaneInputs[1].resize(LaneCount, false);
9713   for (int i = 0; i < Size; ++i)
9714     if (Mask[i] >= 0)
9715       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9716   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9717     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9718
9719   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9720   // that the decomposed single-input shuffles don't end up here.
9721   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9722 }
9723
9724 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9725 /// a permutation and blend of those lanes.
9726 ///
9727 /// This essentially blends the out-of-lane inputs to each lane into the lane
9728 /// from a permuted copy of the vector. This lowering strategy results in four
9729 /// instructions in the worst case for a single-input cross lane shuffle which
9730 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9731 /// of. Special cases for each particular shuffle pattern should be handled
9732 /// prior to trying this lowering.
9733 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9734                                                        SDValue V1, SDValue V2,
9735                                                        ArrayRef<int> Mask,
9736                                                        SelectionDAG &DAG) {
9737   // FIXME: This should probably be generalized for 512-bit vectors as well.
9738   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9739   int LaneSize = Mask.size() / 2;
9740
9741   // If there are only inputs from one 128-bit lane, splitting will in fact be
9742   // less expensive. The flags track wether the given lane contains an element
9743   // that crosses to another lane.
9744   bool LaneCrossing[2] = {false, false};
9745   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9746     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9747       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9748   if (!LaneCrossing[0] || !LaneCrossing[1])
9749     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9750
9751   if (isSingleInputShuffleMask(Mask)) {
9752     SmallVector<int, 32> FlippedBlendMask;
9753     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9754       FlippedBlendMask.push_back(
9755           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9756                                   ? Mask[i]
9757                                   : Mask[i] % LaneSize +
9758                                         (i / LaneSize) * LaneSize + Size));
9759
9760     // Flip the vector, and blend the results which should now be in-lane. The
9761     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9762     // 5 for the high source. The value 3 selects the high half of source 2 and
9763     // the value 2 selects the low half of source 2. We only use source 2 to
9764     // allow folding it into a memory operand.
9765     unsigned PERMMask = 3 | 2 << 4;
9766     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9767                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9768     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9769   }
9770
9771   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9772   // will be handled by the above logic and a blend of the results, much like
9773   // other patterns in AVX.
9774   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9775 }
9776
9777 /// \brief Handle lowering 2-lane 128-bit shuffles.
9778 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9779                                         SDValue V2, ArrayRef<int> Mask,
9780                                         const X86Subtarget *Subtarget,
9781                                         SelectionDAG &DAG) {
9782   // Blends are faster and handle all the non-lane-crossing cases.
9783   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9784                                                 Subtarget, DAG))
9785     return Blend;
9786
9787   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9788                                VT.getVectorNumElements() / 2);
9789   // Check for patterns which can be matched with a single insert of a 128-bit
9790   // subvector.
9791   if (isShuffleEquivalent(Mask, 0, 1, 0, 1) ||
9792       isShuffleEquivalent(Mask, 0, 1, 4, 5)) {
9793     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9794                               DAG.getIntPtrConstant(0));
9795     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9796                               Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
9797     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9798   }
9799   if (isShuffleEquivalent(Mask, 0, 1, 6, 7)) {
9800     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9801                               DAG.getIntPtrConstant(0));
9802     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9803                               DAG.getIntPtrConstant(2));
9804     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9805   }
9806
9807   // Otherwise form a 128-bit permutation.
9808   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9809   unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
9810   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9811                      DAG.getConstant(PermMask, MVT::i8));
9812 }
9813
9814 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9815 ///
9816 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9817 /// isn't available.
9818 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9819                                        const X86Subtarget *Subtarget,
9820                                        SelectionDAG &DAG) {
9821   SDLoc DL(Op);
9822   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9823   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9824   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9825   ArrayRef<int> Mask = SVOp->getMask();
9826   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9827
9828   SmallVector<int, 4> WidenedMask;
9829   if (canWidenShuffleElements(Mask, WidenedMask))
9830     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9831                                     DAG);
9832
9833   if (isSingleInputShuffleMask(Mask)) {
9834     // Check for being able to broadcast a single element.
9835     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f64, DL, V1,
9836                                                           Mask, Subtarget, DAG))
9837       return Broadcast;
9838
9839     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9840       // Non-half-crossing single input shuffles can be lowerid with an
9841       // interleaved permutation.
9842       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9843                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9844       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9845                          DAG.getConstant(VPERMILPMask, MVT::i8));
9846     }
9847
9848     // With AVX2 we have direct support for this permutation.
9849     if (Subtarget->hasAVX2())
9850       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9851                          getV4X86ShuffleImm8ForMask(Mask, DAG));
9852
9853     // Otherwise, fall back.
9854     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9855                                                    DAG);
9856   }
9857
9858   // X86 has dedicated unpack instructions that can handle specific blend
9859   // operations: UNPCKH and UNPCKL.
9860   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
9861     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9862   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
9863     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9864
9865   // If we have a single input to the zero element, insert that into V1 if we
9866   // can do so cheaply.
9867   int NumV2Elements =
9868       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9869   if (NumV2Elements == 1 && Mask[0] >= 4)
9870     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9871             MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
9872       return Insertion;
9873
9874   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9875                                                 Subtarget, DAG))
9876     return Blend;
9877
9878   // Check if the blend happens to exactly fit that of SHUFPD.
9879   if ((Mask[0] == -1 || Mask[0] < 2) &&
9880       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9881       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9882       (Mask[3] == -1 || Mask[3] >= 6)) {
9883     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9884                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9885     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9886                        DAG.getConstant(SHUFPDMask, MVT::i8));
9887   }
9888   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9889       (Mask[1] == -1 || Mask[1] < 2) &&
9890       (Mask[2] == -1 || Mask[2] >= 6) &&
9891       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9892     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9893                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9894     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9895                        DAG.getConstant(SHUFPDMask, MVT::i8));
9896   }
9897
9898   // If we have AVX2 then we always want to lower with a blend because an v4 we
9899   // can fully permute the elements.
9900   if (Subtarget->hasAVX2())
9901     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9902                                                       Mask, DAG);
9903
9904   // Otherwise fall back on generic lowering.
9905   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9906 }
9907
9908 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9909 ///
9910 /// This routine is only called when we have AVX2 and thus a reasonable
9911 /// instruction set for v4i64 shuffling..
9912 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9913                                        const X86Subtarget *Subtarget,
9914                                        SelectionDAG &DAG) {
9915   SDLoc DL(Op);
9916   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9917   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9918   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9919   ArrayRef<int> Mask = SVOp->getMask();
9920   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9921   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9922
9923   SmallVector<int, 4> WidenedMask;
9924   if (canWidenShuffleElements(Mask, WidenedMask))
9925     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9926                                     DAG);
9927
9928   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9929                                                 Subtarget, DAG))
9930     return Blend;
9931
9932   // Check for being able to broadcast a single element.
9933   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i64, DL, V1,
9934                                                         Mask, Subtarget, DAG))
9935     return Broadcast;
9936
9937   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9938   // use lower latency instructions that will operate on both 128-bit lanes.
9939   SmallVector<int, 2> RepeatedMask;
9940   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9941     if (isSingleInputShuffleMask(Mask)) {
9942       int PSHUFDMask[] = {-1, -1, -1, -1};
9943       for (int i = 0; i < 2; ++i)
9944         if (RepeatedMask[i] >= 0) {
9945           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9946           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9947         }
9948       return DAG.getNode(
9949           ISD::BITCAST, DL, MVT::v4i64,
9950           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9951                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9952                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9953     }
9954
9955     // Use dedicated unpack instructions for masks that match their pattern.
9956     if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
9957       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9958     if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
9959       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9960   }
9961
9962   // AVX2 provides a direct instruction for permuting a single input across
9963   // lanes.
9964   if (isSingleInputShuffleMask(Mask))
9965     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9966                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9967
9968   // Otherwise fall back on generic blend lowering.
9969   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9970                                                     Mask, DAG);
9971 }
9972
9973 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9974 ///
9975 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9976 /// isn't available.
9977 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9978                                        const X86Subtarget *Subtarget,
9979                                        SelectionDAG &DAG) {
9980   SDLoc DL(Op);
9981   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9982   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9983   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9984   ArrayRef<int> Mask = SVOp->getMask();
9985   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9986
9987   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9988                                                 Subtarget, DAG))
9989     return Blend;
9990
9991   // Check for being able to broadcast a single element.
9992   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8f32, DL, V1,
9993                                                         Mask, Subtarget, DAG))
9994     return Broadcast;
9995
9996   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9997   // options to efficiently lower the shuffle.
9998   SmallVector<int, 4> RepeatedMask;
9999   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10000     assert(RepeatedMask.size() == 4 &&
10001            "Repeated masks must be half the mask width!");
10002     if (isSingleInputShuffleMask(Mask))
10003       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10004                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10005
10006     // Use dedicated unpack instructions for masks that match their pattern.
10007     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10008       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10009     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10010       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10011
10012     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10013     // have already handled any direct blends. We also need to squash the
10014     // repeated mask into a simulated v4f32 mask.
10015     for (int i = 0; i < 4; ++i)
10016       if (RepeatedMask[i] >= 8)
10017         RepeatedMask[i] -= 4;
10018     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10019   }
10020
10021   // If we have a single input shuffle with different shuffle patterns in the
10022   // two 128-bit lanes use the variable mask to VPERMILPS.
10023   if (isSingleInputShuffleMask(Mask)) {
10024     SDValue VPermMask[8];
10025     for (int i = 0; i < 8; ++i)
10026       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10027                                  : DAG.getConstant(Mask[i], MVT::i32);
10028     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10029       return DAG.getNode(
10030           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10031           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10032
10033     if (Subtarget->hasAVX2())
10034       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
10035                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
10036                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
10037                                                  MVT::v8i32, VPermMask)),
10038                          V1);
10039
10040     // Otherwise, fall back.
10041     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10042                                                    DAG);
10043   }
10044
10045   // If we have AVX2 then we always want to lower with a blend because at v8 we
10046   // can fully permute the elements.
10047   if (Subtarget->hasAVX2())
10048     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10049                                                       Mask, DAG);
10050
10051   // Otherwise fall back on generic lowering.
10052   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10053 }
10054
10055 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10056 ///
10057 /// This routine is only called when we have AVX2 and thus a reasonable
10058 /// instruction set for v8i32 shuffling..
10059 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10060                                        const X86Subtarget *Subtarget,
10061                                        SelectionDAG &DAG) {
10062   SDLoc DL(Op);
10063   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10064   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10065   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10066   ArrayRef<int> Mask = SVOp->getMask();
10067   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10068   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10069
10070   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10071                                                 Subtarget, DAG))
10072     return Blend;
10073
10074   // Check for being able to broadcast a single element.
10075   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i32, DL, V1,
10076                                                         Mask, Subtarget, DAG))
10077     return Broadcast;
10078
10079   // If the shuffle mask is repeated in each 128-bit lane we can use more
10080   // efficient instructions that mirror the shuffles across the two 128-bit
10081   // lanes.
10082   SmallVector<int, 4> RepeatedMask;
10083   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10084     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10085     if (isSingleInputShuffleMask(Mask))
10086       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10087                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10088
10089     // Use dedicated unpack instructions for masks that match their pattern.
10090     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10091       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10092     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10093       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10094   }
10095
10096   // If the shuffle patterns aren't repeated but it is a single input, directly
10097   // generate a cross-lane VPERMD instruction.
10098   if (isSingleInputShuffleMask(Mask)) {
10099     SDValue VPermMask[8];
10100     for (int i = 0; i < 8; ++i)
10101       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10102                                  : DAG.getConstant(Mask[i], MVT::i32);
10103     return DAG.getNode(
10104         X86ISD::VPERMV, DL, MVT::v8i32,
10105         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10106   }
10107
10108   // Otherwise fall back on generic blend lowering.
10109   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10110                                                     Mask, DAG);
10111 }
10112
10113 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10114 ///
10115 /// This routine is only called when we have AVX2 and thus a reasonable
10116 /// instruction set for v16i16 shuffling..
10117 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10118                                         const X86Subtarget *Subtarget,
10119                                         SelectionDAG &DAG) {
10120   SDLoc DL(Op);
10121   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10122   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10123   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10124   ArrayRef<int> Mask = SVOp->getMask();
10125   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10126   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10127
10128   // Check for being able to broadcast a single element.
10129   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i16, DL, V1,
10130                                                         Mask, Subtarget, DAG))
10131     return Broadcast;
10132
10133   // There are no generalized cross-lane shuffle operations available on i16
10134   // element types.
10135   if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10136     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10137                                                    Mask, DAG);
10138
10139   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10140                                                 Subtarget, DAG))
10141     return Blend;
10142
10143   // Use dedicated unpack instructions for masks that match their pattern.
10144   if (isShuffleEquivalent(Mask,
10145                           // First 128-bit lane:
10146                           0, 16, 1, 17, 2, 18, 3, 19,
10147                           // Second 128-bit lane:
10148                           8, 24, 9, 25, 10, 26, 11, 27))
10149     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10150   if (isShuffleEquivalent(Mask,
10151                           // First 128-bit lane:
10152                           4, 20, 5, 21, 6, 22, 7, 23,
10153                           // Second 128-bit lane:
10154                           12, 28, 13, 29, 14, 30, 15, 31))
10155     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10156
10157   if (isSingleInputShuffleMask(Mask)) {
10158     SDValue PSHUFBMask[32];
10159     for (int i = 0; i < 16; ++i) {
10160       if (Mask[i] == -1) {
10161         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10162         continue;
10163       }
10164
10165       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10166       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10167       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
10168       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
10169     }
10170     return DAG.getNode(
10171         ISD::BITCAST, DL, MVT::v16i16,
10172         DAG.getNode(
10173             X86ISD::PSHUFB, DL, MVT::v32i8,
10174             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
10175             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
10176   }
10177
10178   // Otherwise fall back on generic lowering.
10179   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10180 }
10181
10182 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10183 ///
10184 /// This routine is only called when we have AVX2 and thus a reasonable
10185 /// instruction set for v32i8 shuffling..
10186 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10187                                        const X86Subtarget *Subtarget,
10188                                        SelectionDAG &DAG) {
10189   SDLoc DL(Op);
10190   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10191   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10192   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10193   ArrayRef<int> Mask = SVOp->getMask();
10194   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10195   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10196
10197   // Check for being able to broadcast a single element.
10198   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v32i8, DL, V1,
10199                                                         Mask, Subtarget, DAG))
10200     return Broadcast;
10201
10202   // There are no generalized cross-lane shuffle operations available on i8
10203   // element types.
10204   if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10205     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10206                                                    Mask, DAG);
10207
10208   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10209                                                 Subtarget, DAG))
10210     return Blend;
10211
10212   // Use dedicated unpack instructions for masks that match their pattern.
10213   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10214   // 256-bit lanes.
10215   if (isShuffleEquivalent(
10216           Mask,
10217           // First 128-bit lane:
10218           0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10219           // Second 128-bit lane:
10220           16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55))
10221     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10222   if (isShuffleEquivalent(
10223           Mask,
10224           // First 128-bit lane:
10225           8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10226           // Second 128-bit lane:
10227           24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63))
10228     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10229
10230   if (isSingleInputShuffleMask(Mask)) {
10231     SDValue PSHUFBMask[32];
10232     for (int i = 0; i < 32; ++i)
10233       PSHUFBMask[i] =
10234           Mask[i] < 0
10235               ? DAG.getUNDEF(MVT::i8)
10236               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
10237
10238     return DAG.getNode(
10239         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10240         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10241   }
10242
10243   // Otherwise fall back on generic lowering.
10244   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10245 }
10246
10247 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10248 ///
10249 /// This routine either breaks down the specific type of a 256-bit x86 vector
10250 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10251 /// together based on the available instructions.
10252 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10253                                         MVT VT, const X86Subtarget *Subtarget,
10254                                         SelectionDAG &DAG) {
10255   SDLoc DL(Op);
10256   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10257   ArrayRef<int> Mask = SVOp->getMask();
10258
10259   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10260   // check for those subtargets here and avoid much of the subtarget querying in
10261   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10262   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10263   // floating point types there eventually, just immediately cast everything to
10264   // a float and operate entirely in that domain.
10265   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10266     int ElementBits = VT.getScalarSizeInBits();
10267     if (ElementBits < 32)
10268       // No floating point type available, decompose into 128-bit vectors.
10269       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10270
10271     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10272                                 VT.getVectorNumElements());
10273     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10274     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10275     return DAG.getNode(ISD::BITCAST, DL, VT,
10276                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10277   }
10278
10279   switch (VT.SimpleTy) {
10280   case MVT::v4f64:
10281     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10282   case MVT::v4i64:
10283     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10284   case MVT::v8f32:
10285     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10286   case MVT::v8i32:
10287     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10288   case MVT::v16i16:
10289     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10290   case MVT::v32i8:
10291     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10292
10293   default:
10294     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10295   }
10296 }
10297
10298 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10299 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10300                                        const X86Subtarget *Subtarget,
10301                                        SelectionDAG &DAG) {
10302   SDLoc DL(Op);
10303   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10304   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10305   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10306   ArrayRef<int> Mask = SVOp->getMask();
10307   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10308
10309   // FIXME: Implement direct support for this type!
10310   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10311 }
10312
10313 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10314 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10315                                        const X86Subtarget *Subtarget,
10316                                        SelectionDAG &DAG) {
10317   SDLoc DL(Op);
10318   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10319   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10320   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10321   ArrayRef<int> Mask = SVOp->getMask();
10322   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10323
10324   // FIXME: Implement direct support for this type!
10325   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10326 }
10327
10328 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10329 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10330                                        const X86Subtarget *Subtarget,
10331                                        SelectionDAG &DAG) {
10332   SDLoc DL(Op);
10333   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10334   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10335   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10336   ArrayRef<int> Mask = SVOp->getMask();
10337   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10338
10339   // FIXME: Implement direct support for this type!
10340   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10341 }
10342
10343 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10344 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10345                                        const X86Subtarget *Subtarget,
10346                                        SelectionDAG &DAG) {
10347   SDLoc DL(Op);
10348   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10349   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10350   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10351   ArrayRef<int> Mask = SVOp->getMask();
10352   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10353
10354   // FIXME: Implement direct support for this type!
10355   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10356 }
10357
10358 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10359 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10360                                         const X86Subtarget *Subtarget,
10361                                         SelectionDAG &DAG) {
10362   SDLoc DL(Op);
10363   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10364   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10365   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10366   ArrayRef<int> Mask = SVOp->getMask();
10367   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10368   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10369
10370   // FIXME: Implement direct support for this type!
10371   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10372 }
10373
10374 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10375 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10376                                        const X86Subtarget *Subtarget,
10377                                        SelectionDAG &DAG) {
10378   SDLoc DL(Op);
10379   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10380   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10381   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10382   ArrayRef<int> Mask = SVOp->getMask();
10383   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10384   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10385
10386   // FIXME: Implement direct support for this type!
10387   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10388 }
10389
10390 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10391 ///
10392 /// This routine either breaks down the specific type of a 512-bit x86 vector
10393 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10394 /// together based on the available instructions.
10395 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10396                                         MVT VT, const X86Subtarget *Subtarget,
10397                                         SelectionDAG &DAG) {
10398   SDLoc DL(Op);
10399   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10400   ArrayRef<int> Mask = SVOp->getMask();
10401   assert(Subtarget->hasAVX512() &&
10402          "Cannot lower 512-bit vectors w/ basic ISA!");
10403
10404   // Check for being able to broadcast a single element.
10405   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(VT.SimpleTy, DL, V1,
10406                                                         Mask, Subtarget, DAG))
10407     return Broadcast;
10408
10409   // Dispatch to each element type for lowering. If we don't have supprot for
10410   // specific element type shuffles at 512 bits, immediately split them and
10411   // lower them. Each lowering routine of a given type is allowed to assume that
10412   // the requisite ISA extensions for that element type are available.
10413   switch (VT.SimpleTy) {
10414   case MVT::v8f64:
10415     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10416   case MVT::v16f32:
10417     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10418   case MVT::v8i64:
10419     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10420   case MVT::v16i32:
10421     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10422   case MVT::v32i16:
10423     if (Subtarget->hasBWI())
10424       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10425     break;
10426   case MVT::v64i8:
10427     if (Subtarget->hasBWI())
10428       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10429     break;
10430
10431   default:
10432     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10433   }
10434
10435   // Otherwise fall back on splitting.
10436   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10437 }
10438
10439 /// \brief Top-level lowering for x86 vector shuffles.
10440 ///
10441 /// This handles decomposition, canonicalization, and lowering of all x86
10442 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10443 /// above in helper routines. The canonicalization attempts to widen shuffles
10444 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10445 /// s.t. only one of the two inputs needs to be tested, etc.
10446 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10447                                   SelectionDAG &DAG) {
10448   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10449   ArrayRef<int> Mask = SVOp->getMask();
10450   SDValue V1 = Op.getOperand(0);
10451   SDValue V2 = Op.getOperand(1);
10452   MVT VT = Op.getSimpleValueType();
10453   int NumElements = VT.getVectorNumElements();
10454   SDLoc dl(Op);
10455
10456   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10457
10458   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10459   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10460   if (V1IsUndef && V2IsUndef)
10461     return DAG.getUNDEF(VT);
10462
10463   // When we create a shuffle node we put the UNDEF node to second operand,
10464   // but in some cases the first operand may be transformed to UNDEF.
10465   // In this case we should just commute the node.
10466   if (V1IsUndef)
10467     return DAG.getCommutedVectorShuffle(*SVOp);
10468
10469   // Check for non-undef masks pointing at an undef vector and make the masks
10470   // undef as well. This makes it easier to match the shuffle based solely on
10471   // the mask.
10472   if (V2IsUndef)
10473     for (int M : Mask)
10474       if (M >= NumElements) {
10475         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10476         for (int &M : NewMask)
10477           if (M >= NumElements)
10478             M = -1;
10479         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10480       }
10481
10482   // Try to collapse shuffles into using a vector type with fewer elements but
10483   // wider element types. We cap this to not form integers or floating point
10484   // elements wider than 64 bits, but it might be interesting to form i128
10485   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10486   SmallVector<int, 16> WidenedMask;
10487   if (VT.getScalarSizeInBits() < 64 &&
10488       canWidenShuffleElements(Mask, WidenedMask)) {
10489     MVT NewEltVT = VT.isFloatingPoint()
10490                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10491                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10492     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10493     // Make sure that the new vector type is legal. For example, v2f64 isn't
10494     // legal on SSE1.
10495     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10496       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10497       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10498       return DAG.getNode(ISD::BITCAST, dl, VT,
10499                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10500     }
10501   }
10502
10503   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10504   for (int M : SVOp->getMask())
10505     if (M < 0)
10506       ++NumUndefElements;
10507     else if (M < NumElements)
10508       ++NumV1Elements;
10509     else
10510       ++NumV2Elements;
10511
10512   // Commute the shuffle as needed such that more elements come from V1 than
10513   // V2. This allows us to match the shuffle pattern strictly on how many
10514   // elements come from V1 without handling the symmetric cases.
10515   if (NumV2Elements > NumV1Elements)
10516     return DAG.getCommutedVectorShuffle(*SVOp);
10517
10518   // When the number of V1 and V2 elements are the same, try to minimize the
10519   // number of uses of V2 in the low half of the vector. When that is tied,
10520   // ensure that the sum of indices for V1 is equal to or lower than the sum
10521   // indices for V2.
10522   if (NumV1Elements == NumV2Elements) {
10523     int LowV1Elements = 0, LowV2Elements = 0;
10524     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10525       if (M >= NumElements)
10526         ++LowV2Elements;
10527       else if (M >= 0)
10528         ++LowV1Elements;
10529     if (LowV2Elements > LowV1Elements) {
10530       return DAG.getCommutedVectorShuffle(*SVOp);
10531     } else if (LowV2Elements == LowV1Elements) {
10532       int SumV1Indices = 0, SumV2Indices = 0;
10533       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10534         if (SVOp->getMask()[i] >= NumElements)
10535           SumV2Indices += i;
10536         else if (SVOp->getMask()[i] >= 0)
10537           SumV1Indices += i;
10538       if (SumV2Indices < SumV1Indices)
10539         return DAG.getCommutedVectorShuffle(*SVOp);
10540     }
10541   }
10542
10543   // For each vector width, delegate to a specialized lowering routine.
10544   if (VT.getSizeInBits() == 128)
10545     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10546
10547   if (VT.getSizeInBits() == 256)
10548     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10549
10550   // Force AVX-512 vectors to be scalarized for now.
10551   // FIXME: Implement AVX-512 support!
10552   if (VT.getSizeInBits() == 512)
10553     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10554
10555   llvm_unreachable("Unimplemented!");
10556 }
10557
10558
10559 //===----------------------------------------------------------------------===//
10560 // Legacy vector shuffle lowering
10561 //
10562 // This code is the legacy code handling vector shuffles until the above
10563 // replaces its functionality and performance.
10564 //===----------------------------------------------------------------------===//
10565
10566 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
10567                         bool hasInt256, unsigned *MaskOut = nullptr) {
10568   MVT EltVT = VT.getVectorElementType();
10569
10570   // There is no blend with immediate in AVX-512.
10571   if (VT.is512BitVector())
10572     return false;
10573
10574   if (!hasSSE41 || EltVT == MVT::i8)
10575     return false;
10576   if (!hasInt256 && VT == MVT::v16i16)
10577     return false;
10578
10579   unsigned MaskValue = 0;
10580   unsigned NumElems = VT.getVectorNumElements();
10581   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10582   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10583   unsigned NumElemsInLane = NumElems / NumLanes;
10584
10585   // Blend for v16i16 should be symetric for the both lanes.
10586   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10587
10588     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
10589     int EltIdx = MaskVals[i];
10590
10591     if ((EltIdx < 0 || EltIdx == (int)i) &&
10592         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
10593       continue;
10594
10595     if (((unsigned)EltIdx == (i + NumElems)) &&
10596         (SndLaneEltIdx < 0 ||
10597          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
10598       MaskValue |= (1 << i);
10599     else
10600       return false;
10601   }
10602
10603   if (MaskOut)
10604     *MaskOut = MaskValue;
10605   return true;
10606 }
10607
10608 // Try to lower a shuffle node into a simple blend instruction.
10609 // This function assumes isBlendMask returns true for this
10610 // SuffleVectorSDNode
10611 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
10612                                           unsigned MaskValue,
10613                                           const X86Subtarget *Subtarget,
10614                                           SelectionDAG &DAG) {
10615   MVT VT = SVOp->getSimpleValueType(0);
10616   MVT EltVT = VT.getVectorElementType();
10617   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
10618                      Subtarget->hasInt256() && "Trying to lower a "
10619                                                "VECTOR_SHUFFLE to a Blend but "
10620                                                "with the wrong mask"));
10621   SDValue V1 = SVOp->getOperand(0);
10622   SDValue V2 = SVOp->getOperand(1);
10623   SDLoc dl(SVOp);
10624   unsigned NumElems = VT.getVectorNumElements();
10625
10626   // Convert i32 vectors to floating point if it is not AVX2.
10627   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10628   MVT BlendVT = VT;
10629   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10630     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10631                                NumElems);
10632     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
10633     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
10634   }
10635
10636   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
10637                             DAG.getConstant(MaskValue, MVT::i32));
10638   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10639 }
10640
10641 /// In vector type \p VT, return true if the element at index \p InputIdx
10642 /// falls on a different 128-bit lane than \p OutputIdx.
10643 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
10644                                      unsigned OutputIdx) {
10645   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
10646   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
10647 }
10648
10649 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
10650 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
10651 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
10652 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
10653 /// zero.
10654 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
10655                          SelectionDAG &DAG) {
10656   MVT VT = V1.getSimpleValueType();
10657   assert(VT.is128BitVector() || VT.is256BitVector());
10658
10659   MVT EltVT = VT.getVectorElementType();
10660   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
10661   unsigned NumElts = VT.getVectorNumElements();
10662
10663   SmallVector<SDValue, 32> PshufbMask;
10664   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
10665     int InputIdx = MaskVals[OutputIdx];
10666     unsigned InputByteIdx;
10667
10668     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
10669       InputByteIdx = 0x80;
10670     else {
10671       // Cross lane is not allowed.
10672       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
10673         return SDValue();
10674       InputByteIdx = InputIdx * EltSizeInBytes;
10675       // Index is an byte offset within the 128-bit lane.
10676       InputByteIdx &= 0xf;
10677     }
10678
10679     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
10680       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
10681       if (InputByteIdx != 0x80)
10682         ++InputByteIdx;
10683     }
10684   }
10685
10686   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
10687   if (ShufVT != VT)
10688     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
10689   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
10690                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
10691 }
10692
10693 // v8i16 shuffles - Prefer shuffles in the following order:
10694 // 1. [all]   pshuflw, pshufhw, optional move
10695 // 2. [ssse3] 1 x pshufb
10696 // 3. [ssse3] 2 x pshufb + 1 x por
10697 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
10698 static SDValue
10699 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
10700                          SelectionDAG &DAG) {
10701   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10702   SDValue V1 = SVOp->getOperand(0);
10703   SDValue V2 = SVOp->getOperand(1);
10704   SDLoc dl(SVOp);
10705   SmallVector<int, 8> MaskVals;
10706
10707   // Determine if more than 1 of the words in each of the low and high quadwords
10708   // of the result come from the same quadword of one of the two inputs.  Undef
10709   // mask values count as coming from any quadword, for better codegen.
10710   //
10711   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
10712   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
10713   unsigned LoQuad[] = { 0, 0, 0, 0 };
10714   unsigned HiQuad[] = { 0, 0, 0, 0 };
10715   // Indices of quads used.
10716   std::bitset<4> InputQuads;
10717   for (unsigned i = 0; i < 8; ++i) {
10718     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
10719     int EltIdx = SVOp->getMaskElt(i);
10720     MaskVals.push_back(EltIdx);
10721     if (EltIdx < 0) {
10722       ++Quad[0];
10723       ++Quad[1];
10724       ++Quad[2];
10725       ++Quad[3];
10726       continue;
10727     }
10728     ++Quad[EltIdx / 4];
10729     InputQuads.set(EltIdx / 4);
10730   }
10731
10732   int BestLoQuad = -1;
10733   unsigned MaxQuad = 1;
10734   for (unsigned i = 0; i < 4; ++i) {
10735     if (LoQuad[i] > MaxQuad) {
10736       BestLoQuad = i;
10737       MaxQuad = LoQuad[i];
10738     }
10739   }
10740
10741   int BestHiQuad = -1;
10742   MaxQuad = 1;
10743   for (unsigned i = 0; i < 4; ++i) {
10744     if (HiQuad[i] > MaxQuad) {
10745       BestHiQuad = i;
10746       MaxQuad = HiQuad[i];
10747     }
10748   }
10749
10750   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
10751   // of the two input vectors, shuffle them into one input vector so only a
10752   // single pshufb instruction is necessary. If there are more than 2 input
10753   // quads, disable the next transformation since it does not help SSSE3.
10754   bool V1Used = InputQuads[0] || InputQuads[1];
10755   bool V2Used = InputQuads[2] || InputQuads[3];
10756   if (Subtarget->hasSSSE3()) {
10757     if (InputQuads.count() == 2 && V1Used && V2Used) {
10758       BestLoQuad = InputQuads[0] ? 0 : 1;
10759       BestHiQuad = InputQuads[2] ? 2 : 3;
10760     }
10761     if (InputQuads.count() > 2) {
10762       BestLoQuad = -1;
10763       BestHiQuad = -1;
10764     }
10765   }
10766
10767   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
10768   // the shuffle mask.  If a quad is scored as -1, that means that it contains
10769   // words from all 4 input quadwords.
10770   SDValue NewV;
10771   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
10772     int MaskV[] = {
10773       BestLoQuad < 0 ? 0 : BestLoQuad,
10774       BestHiQuad < 0 ? 1 : BestHiQuad
10775     };
10776     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
10777                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
10778                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
10779     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
10780
10781     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
10782     // source words for the shuffle, to aid later transformations.
10783     bool AllWordsInNewV = true;
10784     bool InOrder[2] = { true, true };
10785     for (unsigned i = 0; i != 8; ++i) {
10786       int idx = MaskVals[i];
10787       if (idx != (int)i)
10788         InOrder[i/4] = false;
10789       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
10790         continue;
10791       AllWordsInNewV = false;
10792       break;
10793     }
10794
10795     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
10796     if (AllWordsInNewV) {
10797       for (int i = 0; i != 8; ++i) {
10798         int idx = MaskVals[i];
10799         if (idx < 0)
10800           continue;
10801         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
10802         if ((idx != i) && idx < 4)
10803           pshufhw = false;
10804         if ((idx != i) && idx > 3)
10805           pshuflw = false;
10806       }
10807       V1 = NewV;
10808       V2Used = false;
10809       BestLoQuad = 0;
10810       BestHiQuad = 1;
10811     }
10812
10813     // If we've eliminated the use of V2, and the new mask is a pshuflw or
10814     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
10815     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
10816       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
10817       unsigned TargetMask = 0;
10818       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
10819                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
10820       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
10821       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
10822                              getShufflePSHUFLWImmediate(SVOp);
10823       V1 = NewV.getOperand(0);
10824       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
10825     }
10826   }
10827
10828   // Promote splats to a larger type which usually leads to more efficient code.
10829   // FIXME: Is this true if pshufb is available?
10830   if (SVOp->isSplat())
10831     return PromoteSplat(SVOp, DAG);
10832
10833   // If we have SSSE3, and all words of the result are from 1 input vector,
10834   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
10835   // is present, fall back to case 4.
10836   if (Subtarget->hasSSSE3()) {
10837     SmallVector<SDValue,16> pshufbMask;
10838
10839     // If we have elements from both input vectors, set the high bit of the
10840     // shuffle mask element to zero out elements that come from V2 in the V1
10841     // mask, and elements that come from V1 in the V2 mask, so that the two
10842     // results can be OR'd together.
10843     bool TwoInputs = V1Used && V2Used;
10844     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
10845     if (!TwoInputs)
10846       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10847
10848     // Calculate the shuffle mask for the second input, shuffle it, and
10849     // OR it with the first shuffled input.
10850     CommuteVectorShuffleMask(MaskVals, 8);
10851     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
10852     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
10853     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10854   }
10855
10856   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
10857   // and update MaskVals with new element order.
10858   std::bitset<8> InOrder;
10859   if (BestLoQuad >= 0) {
10860     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
10861     for (int i = 0; i != 4; ++i) {
10862       int idx = MaskVals[i];
10863       if (idx < 0) {
10864         InOrder.set(i);
10865       } else if ((idx / 4) == BestLoQuad) {
10866         MaskV[i] = idx & 3;
10867         InOrder.set(i);
10868       }
10869     }
10870     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
10871                                 &MaskV[0]);
10872
10873     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
10874       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
10875       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
10876                                   NewV.getOperand(0),
10877                                   getShufflePSHUFLWImmediate(SVOp), DAG);
10878     }
10879   }
10880
10881   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
10882   // and update MaskVals with the new element order.
10883   if (BestHiQuad >= 0) {
10884     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
10885     for (unsigned i = 4; i != 8; ++i) {
10886       int idx = MaskVals[i];
10887       if (idx < 0) {
10888         InOrder.set(i);
10889       } else if ((idx / 4) == BestHiQuad) {
10890         MaskV[i] = (idx & 3) + 4;
10891         InOrder.set(i);
10892       }
10893     }
10894     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
10895                                 &MaskV[0]);
10896
10897     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
10898       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
10899       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
10900                                   NewV.getOperand(0),
10901                                   getShufflePSHUFHWImmediate(SVOp), DAG);
10902     }
10903   }
10904
10905   // In case BestHi & BestLo were both -1, which means each quadword has a word
10906   // from each of the four input quadwords, calculate the InOrder bitvector now
10907   // before falling through to the insert/extract cleanup.
10908   if (BestLoQuad == -1 && BestHiQuad == -1) {
10909     NewV = V1;
10910     for (int i = 0; i != 8; ++i)
10911       if (MaskVals[i] < 0 || MaskVals[i] == i)
10912         InOrder.set(i);
10913   }
10914
10915   // The other elements are put in the right place using pextrw and pinsrw.
10916   for (unsigned i = 0; i != 8; ++i) {
10917     if (InOrder[i])
10918       continue;
10919     int EltIdx = MaskVals[i];
10920     if (EltIdx < 0)
10921       continue;
10922     SDValue ExtOp = (EltIdx < 8) ?
10923       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
10924                   DAG.getIntPtrConstant(EltIdx)) :
10925       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
10926                   DAG.getIntPtrConstant(EltIdx - 8));
10927     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
10928                        DAG.getIntPtrConstant(i));
10929   }
10930   return NewV;
10931 }
10932
10933 /// \brief v16i16 shuffles
10934 ///
10935 /// FIXME: We only support generation of a single pshufb currently.  We can
10936 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
10937 /// well (e.g 2 x pshufb + 1 x por).
10938 static SDValue
10939 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
10940   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10941   SDValue V1 = SVOp->getOperand(0);
10942   SDValue V2 = SVOp->getOperand(1);
10943   SDLoc dl(SVOp);
10944
10945   if (V2.getOpcode() != ISD::UNDEF)
10946     return SDValue();
10947
10948   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
10949   return getPSHUFB(MaskVals, V1, dl, DAG);
10950 }
10951
10952 // v16i8 shuffles - Prefer shuffles in the following order:
10953 // 1. [ssse3] 1 x pshufb
10954 // 2. [ssse3] 2 x pshufb + 1 x por
10955 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
10956 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
10957                                         const X86Subtarget* Subtarget,
10958                                         SelectionDAG &DAG) {
10959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10960   SDValue V1 = SVOp->getOperand(0);
10961   SDValue V2 = SVOp->getOperand(1);
10962   SDLoc dl(SVOp);
10963   ArrayRef<int> MaskVals = SVOp->getMask();
10964
10965   // Promote splats to a larger type which usually leads to more efficient code.
10966   // FIXME: Is this true if pshufb is available?
10967   if (SVOp->isSplat())
10968     return PromoteSplat(SVOp, DAG);
10969
10970   // If we have SSSE3, case 1 is generated when all result bytes come from
10971   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
10972   // present, fall back to case 3.
10973
10974   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
10975   if (Subtarget->hasSSSE3()) {
10976     SmallVector<SDValue,16> pshufbMask;
10977
10978     // If all result elements are from one input vector, then only translate
10979     // undef mask values to 0x80 (zero out result) in the pshufb mask.
10980     //
10981     // Otherwise, we have elements from both input vectors, and must zero out
10982     // elements that come from V2 in the first mask, and V1 in the second mask
10983     // so that we can OR them together.
10984     for (unsigned i = 0; i != 16; ++i) {
10985       int EltIdx = MaskVals[i];
10986       if (EltIdx < 0 || EltIdx >= 16)
10987         EltIdx = 0x80;
10988       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
10989     }
10990     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
10991                      DAG.getNode(ISD::BUILD_VECTOR, dl,
10992                                  MVT::v16i8, pshufbMask));
10993
10994     // As PSHUFB will zero elements with negative indices, it's safe to ignore
10995     // the 2nd operand if it's undefined or zero.
10996     if (V2.getOpcode() == ISD::UNDEF ||
10997         ISD::isBuildVectorAllZeros(V2.getNode()))
10998       return V1;
10999
11000     // Calculate the shuffle mask for the second input, shuffle it, and
11001     // OR it with the first shuffled input.
11002     pshufbMask.clear();
11003     for (unsigned i = 0; i != 16; ++i) {
11004       int EltIdx = MaskVals[i];
11005       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
11006       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11007     }
11008     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
11009                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11010                                  MVT::v16i8, pshufbMask));
11011     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11012   }
11013
11014   // No SSSE3 - Calculate in place words and then fix all out of place words
11015   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
11016   // the 16 different words that comprise the two doublequadword input vectors.
11017   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11018   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
11019   SDValue NewV = V1;
11020   for (int i = 0; i != 8; ++i) {
11021     int Elt0 = MaskVals[i*2];
11022     int Elt1 = MaskVals[i*2+1];
11023
11024     // This word of the result is all undef, skip it.
11025     if (Elt0 < 0 && Elt1 < 0)
11026       continue;
11027
11028     // This word of the result is already in the correct place, skip it.
11029     if ((Elt0 == i*2) && (Elt1 == i*2+1))
11030       continue;
11031
11032     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
11033     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
11034     SDValue InsElt;
11035
11036     // If Elt0 and Elt1 are defined, are consecutive, and can be load
11037     // using a single extract together, load it and store it.
11038     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
11039       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11040                            DAG.getIntPtrConstant(Elt1 / 2));
11041       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11042                         DAG.getIntPtrConstant(i));
11043       continue;
11044     }
11045
11046     // If Elt1 is defined, extract it from the appropriate source.  If the
11047     // source byte is not also odd, shift the extracted word left 8 bits
11048     // otherwise clear the bottom 8 bits if we need to do an or.
11049     if (Elt1 >= 0) {
11050       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11051                            DAG.getIntPtrConstant(Elt1 / 2));
11052       if ((Elt1 & 1) == 0)
11053         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
11054                              DAG.getConstant(8,
11055                                   TLI.getShiftAmountTy(InsElt.getValueType())));
11056       else if (Elt0 >= 0)
11057         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
11058                              DAG.getConstant(0xFF00, MVT::i16));
11059     }
11060     // If Elt0 is defined, extract it from the appropriate source.  If the
11061     // source byte is not also even, shift the extracted word right 8 bits. If
11062     // Elt1 was also defined, OR the extracted values together before
11063     // inserting them in the result.
11064     if (Elt0 >= 0) {
11065       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
11066                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
11067       if ((Elt0 & 1) != 0)
11068         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
11069                               DAG.getConstant(8,
11070                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
11071       else if (Elt1 >= 0)
11072         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
11073                              DAG.getConstant(0x00FF, MVT::i16));
11074       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
11075                          : InsElt0;
11076     }
11077     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11078                        DAG.getIntPtrConstant(i));
11079   }
11080   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
11081 }
11082
11083 // v32i8 shuffles - Translate to VPSHUFB if possible.
11084 static
11085 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
11086                                  const X86Subtarget *Subtarget,
11087                                  SelectionDAG &DAG) {
11088   MVT VT = SVOp->getSimpleValueType(0);
11089   SDValue V1 = SVOp->getOperand(0);
11090   SDValue V2 = SVOp->getOperand(1);
11091   SDLoc dl(SVOp);
11092   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11093
11094   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11095   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
11096   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
11097
11098   // VPSHUFB may be generated if
11099   // (1) one of input vector is undefined or zeroinitializer.
11100   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
11101   // And (2) the mask indexes don't cross the 128-bit lane.
11102   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
11103       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
11104     return SDValue();
11105
11106   if (V1IsAllZero && !V2IsAllZero) {
11107     CommuteVectorShuffleMask(MaskVals, 32);
11108     V1 = V2;
11109   }
11110   return getPSHUFB(MaskVals, V1, dl, DAG);
11111 }
11112
11113 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
11114 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
11115 /// done when every pair / quad of shuffle mask elements point to elements in
11116 /// the right sequence. e.g.
11117 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
11118 static
11119 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
11120                                  SelectionDAG &DAG) {
11121   MVT VT = SVOp->getSimpleValueType(0);
11122   SDLoc dl(SVOp);
11123   unsigned NumElems = VT.getVectorNumElements();
11124   MVT NewVT;
11125   unsigned Scale;
11126   switch (VT.SimpleTy) {
11127   default: llvm_unreachable("Unexpected!");
11128   case MVT::v2i64:
11129   case MVT::v2f64:
11130            return SDValue(SVOp, 0);
11131   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
11132   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
11133   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
11134   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
11135   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
11136   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
11137   }
11138
11139   SmallVector<int, 8> MaskVec;
11140   for (unsigned i = 0; i != NumElems; i += Scale) {
11141     int StartIdx = -1;
11142     for (unsigned j = 0; j != Scale; ++j) {
11143       int EltIdx = SVOp->getMaskElt(i+j);
11144       if (EltIdx < 0)
11145         continue;
11146       if (StartIdx < 0)
11147         StartIdx = (EltIdx / Scale);
11148       if (EltIdx != (int)(StartIdx*Scale + j))
11149         return SDValue();
11150     }
11151     MaskVec.push_back(StartIdx);
11152   }
11153
11154   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
11155   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
11156   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
11157 }
11158
11159 /// getVZextMovL - Return a zero-extending vector move low node.
11160 ///
11161 static SDValue getVZextMovL(MVT VT, MVT OpVT,
11162                             SDValue SrcOp, SelectionDAG &DAG,
11163                             const X86Subtarget *Subtarget, SDLoc dl) {
11164   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
11165     LoadSDNode *LD = nullptr;
11166     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
11167       LD = dyn_cast<LoadSDNode>(SrcOp);
11168     if (!LD) {
11169       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
11170       // instead.
11171       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
11172       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
11173           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11174           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
11175           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
11176         // PR2108
11177         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
11178         return DAG.getNode(ISD::BITCAST, dl, VT,
11179                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11180                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11181                                                    OpVT,
11182                                                    SrcOp.getOperand(0)
11183                                                           .getOperand(0))));
11184       }
11185     }
11186   }
11187
11188   return DAG.getNode(ISD::BITCAST, dl, VT,
11189                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11190                                  DAG.getNode(ISD::BITCAST, dl,
11191                                              OpVT, SrcOp)));
11192 }
11193
11194 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
11195 /// which could not be matched by any known target speficic shuffle
11196 static SDValue
11197 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11198
11199   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
11200   if (NewOp.getNode())
11201     return NewOp;
11202
11203   MVT VT = SVOp->getSimpleValueType(0);
11204
11205   unsigned NumElems = VT.getVectorNumElements();
11206   unsigned NumLaneElems = NumElems / 2;
11207
11208   SDLoc dl(SVOp);
11209   MVT EltVT = VT.getVectorElementType();
11210   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
11211   SDValue Output[2];
11212
11213   SmallVector<int, 16> Mask;
11214   for (unsigned l = 0; l < 2; ++l) {
11215     // Build a shuffle mask for the output, discovering on the fly which
11216     // input vectors to use as shuffle operands (recorded in InputUsed).
11217     // If building a suitable shuffle vector proves too hard, then bail
11218     // out with UseBuildVector set.
11219     bool UseBuildVector = false;
11220     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
11221     unsigned LaneStart = l * NumLaneElems;
11222     for (unsigned i = 0; i != NumLaneElems; ++i) {
11223       // The mask element.  This indexes into the input.
11224       int Idx = SVOp->getMaskElt(i+LaneStart);
11225       if (Idx < 0) {
11226         // the mask element does not index into any input vector.
11227         Mask.push_back(-1);
11228         continue;
11229       }
11230
11231       // The input vector this mask element indexes into.
11232       int Input = Idx / NumLaneElems;
11233
11234       // Turn the index into an offset from the start of the input vector.
11235       Idx -= Input * NumLaneElems;
11236
11237       // Find or create a shuffle vector operand to hold this input.
11238       unsigned OpNo;
11239       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
11240         if (InputUsed[OpNo] == Input)
11241           // This input vector is already an operand.
11242           break;
11243         if (InputUsed[OpNo] < 0) {
11244           // Create a new operand for this input vector.
11245           InputUsed[OpNo] = Input;
11246           break;
11247         }
11248       }
11249
11250       if (OpNo >= array_lengthof(InputUsed)) {
11251         // More than two input vectors used!  Give up on trying to create a
11252         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
11253         UseBuildVector = true;
11254         break;
11255       }
11256
11257       // Add the mask index for the new shuffle vector.
11258       Mask.push_back(Idx + OpNo * NumLaneElems);
11259     }
11260
11261     if (UseBuildVector) {
11262       SmallVector<SDValue, 16> SVOps;
11263       for (unsigned i = 0; i != NumLaneElems; ++i) {
11264         // The mask element.  This indexes into the input.
11265         int Idx = SVOp->getMaskElt(i+LaneStart);
11266         if (Idx < 0) {
11267           SVOps.push_back(DAG.getUNDEF(EltVT));
11268           continue;
11269         }
11270
11271         // The input vector this mask element indexes into.
11272         int Input = Idx / NumElems;
11273
11274         // Turn the index into an offset from the start of the input vector.
11275         Idx -= Input * NumElems;
11276
11277         // Extract the vector element by hand.
11278         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
11279                                     SVOp->getOperand(Input),
11280                                     DAG.getIntPtrConstant(Idx)));
11281       }
11282
11283       // Construct the output using a BUILD_VECTOR.
11284       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
11285     } else if (InputUsed[0] < 0) {
11286       // No input vectors were used! The result is undefined.
11287       Output[l] = DAG.getUNDEF(NVT);
11288     } else {
11289       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
11290                                         (InputUsed[0] % 2) * NumLaneElems,
11291                                         DAG, dl);
11292       // If only one input was used, use an undefined vector for the other.
11293       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
11294         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
11295                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
11296       // At least one input vector was used. Create a new shuffle vector.
11297       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
11298     }
11299
11300     Mask.clear();
11301   }
11302
11303   // Concatenate the result back
11304   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
11305 }
11306
11307 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
11308 /// 4 elements, and match them with several different shuffle types.
11309 static SDValue
11310 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11311   SDValue V1 = SVOp->getOperand(0);
11312   SDValue V2 = SVOp->getOperand(1);
11313   SDLoc dl(SVOp);
11314   MVT VT = SVOp->getSimpleValueType(0);
11315
11316   assert(VT.is128BitVector() && "Unsupported vector size");
11317
11318   std::pair<int, int> Locs[4];
11319   int Mask1[] = { -1, -1, -1, -1 };
11320   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
11321
11322   unsigned NumHi = 0;
11323   unsigned NumLo = 0;
11324   for (unsigned i = 0; i != 4; ++i) {
11325     int Idx = PermMask[i];
11326     if (Idx < 0) {
11327       Locs[i] = std::make_pair(-1, -1);
11328     } else {
11329       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
11330       if (Idx < 4) {
11331         Locs[i] = std::make_pair(0, NumLo);
11332         Mask1[NumLo] = Idx;
11333         NumLo++;
11334       } else {
11335         Locs[i] = std::make_pair(1, NumHi);
11336         if (2+NumHi < 4)
11337           Mask1[2+NumHi] = Idx;
11338         NumHi++;
11339       }
11340     }
11341   }
11342
11343   if (NumLo <= 2 && NumHi <= 2) {
11344     // If no more than two elements come from either vector. This can be
11345     // implemented with two shuffles. First shuffle gather the elements.
11346     // The second shuffle, which takes the first shuffle as both of its
11347     // vector operands, put the elements into the right order.
11348     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11349
11350     int Mask2[] = { -1, -1, -1, -1 };
11351
11352     for (unsigned i = 0; i != 4; ++i)
11353       if (Locs[i].first != -1) {
11354         unsigned Idx = (i < 2) ? 0 : 4;
11355         Idx += Locs[i].first * 2 + Locs[i].second;
11356         Mask2[i] = Idx;
11357       }
11358
11359     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
11360   }
11361
11362   if (NumLo == 3 || NumHi == 3) {
11363     // Otherwise, we must have three elements from one vector, call it X, and
11364     // one element from the other, call it Y.  First, use a shufps to build an
11365     // intermediate vector with the one element from Y and the element from X
11366     // that will be in the same half in the final destination (the indexes don't
11367     // matter). Then, use a shufps to build the final vector, taking the half
11368     // containing the element from Y from the intermediate, and the other half
11369     // from X.
11370     if (NumHi == 3) {
11371       // Normalize it so the 3 elements come from V1.
11372       CommuteVectorShuffleMask(PermMask, 4);
11373       std::swap(V1, V2);
11374     }
11375
11376     // Find the element from V2.
11377     unsigned HiIndex;
11378     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
11379       int Val = PermMask[HiIndex];
11380       if (Val < 0)
11381         continue;
11382       if (Val >= 4)
11383         break;
11384     }
11385
11386     Mask1[0] = PermMask[HiIndex];
11387     Mask1[1] = -1;
11388     Mask1[2] = PermMask[HiIndex^1];
11389     Mask1[3] = -1;
11390     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11391
11392     if (HiIndex >= 2) {
11393       Mask1[0] = PermMask[0];
11394       Mask1[1] = PermMask[1];
11395       Mask1[2] = HiIndex & 1 ? 6 : 4;
11396       Mask1[3] = HiIndex & 1 ? 4 : 6;
11397       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11398     }
11399
11400     Mask1[0] = HiIndex & 1 ? 2 : 0;
11401     Mask1[1] = HiIndex & 1 ? 0 : 2;
11402     Mask1[2] = PermMask[2];
11403     Mask1[3] = PermMask[3];
11404     if (Mask1[2] >= 0)
11405       Mask1[2] += 4;
11406     if (Mask1[3] >= 0)
11407       Mask1[3] += 4;
11408     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
11409   }
11410
11411   // Break it into (shuffle shuffle_hi, shuffle_lo).
11412   int LoMask[] = { -1, -1, -1, -1 };
11413   int HiMask[] = { -1, -1, -1, -1 };
11414
11415   int *MaskPtr = LoMask;
11416   unsigned MaskIdx = 0;
11417   unsigned LoIdx = 0;
11418   unsigned HiIdx = 2;
11419   for (unsigned i = 0; i != 4; ++i) {
11420     if (i == 2) {
11421       MaskPtr = HiMask;
11422       MaskIdx = 1;
11423       LoIdx = 0;
11424       HiIdx = 2;
11425     }
11426     int Idx = PermMask[i];
11427     if (Idx < 0) {
11428       Locs[i] = std::make_pair(-1, -1);
11429     } else if (Idx < 4) {
11430       Locs[i] = std::make_pair(MaskIdx, LoIdx);
11431       MaskPtr[LoIdx] = Idx;
11432       LoIdx++;
11433     } else {
11434       Locs[i] = std::make_pair(MaskIdx, HiIdx);
11435       MaskPtr[HiIdx] = Idx;
11436       HiIdx++;
11437     }
11438   }
11439
11440   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
11441   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
11442   int MaskOps[] = { -1, -1, -1, -1 };
11443   for (unsigned i = 0; i != 4; ++i)
11444     if (Locs[i].first != -1)
11445       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
11446   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
11447 }
11448
11449 static bool MayFoldVectorLoad(SDValue V) {
11450   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
11451     V = V.getOperand(0);
11452
11453   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
11454     V = V.getOperand(0);
11455   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
11456       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
11457     // BUILD_VECTOR (load), undef
11458     V = V.getOperand(0);
11459
11460   return MayFoldLoad(V);
11461 }
11462
11463 static
11464 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
11465   MVT VT = Op.getSimpleValueType();
11466
11467   // Canonizalize to v2f64.
11468   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
11469   return DAG.getNode(ISD::BITCAST, dl, VT,
11470                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
11471                                           V1, DAG));
11472 }
11473
11474 static
11475 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
11476                         bool HasSSE2) {
11477   SDValue V1 = Op.getOperand(0);
11478   SDValue V2 = Op.getOperand(1);
11479   MVT VT = Op.getSimpleValueType();
11480
11481   assert(VT != MVT::v2i64 && "unsupported shuffle type");
11482
11483   if (HasSSE2 && VT == MVT::v2f64)
11484     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
11485
11486   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
11487   return DAG.getNode(ISD::BITCAST, dl, VT,
11488                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
11489                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
11490                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
11491 }
11492
11493 static
11494 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
11495   SDValue V1 = Op.getOperand(0);
11496   SDValue V2 = Op.getOperand(1);
11497   MVT VT = Op.getSimpleValueType();
11498
11499   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
11500          "unsupported shuffle type");
11501
11502   if (V2.getOpcode() == ISD::UNDEF)
11503     V2 = V1;
11504
11505   // v4i32 or v4f32
11506   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
11507 }
11508
11509 static
11510 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
11511   SDValue V1 = Op.getOperand(0);
11512   SDValue V2 = Op.getOperand(1);
11513   MVT VT = Op.getSimpleValueType();
11514   unsigned NumElems = VT.getVectorNumElements();
11515
11516   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
11517   // operand of these instructions is only memory, so check if there's a
11518   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
11519   // same masks.
11520   bool CanFoldLoad = false;
11521
11522   // Trivial case, when V2 comes from a load.
11523   if (MayFoldVectorLoad(V2))
11524     CanFoldLoad = true;
11525
11526   // When V1 is a load, it can be folded later into a store in isel, example:
11527   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
11528   //    turns into:
11529   //  (MOVLPSmr addr:$src1, VR128:$src2)
11530   // So, recognize this potential and also use MOVLPS or MOVLPD
11531   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
11532     CanFoldLoad = true;
11533
11534   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11535   if (CanFoldLoad) {
11536     if (HasSSE2 && NumElems == 2)
11537       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
11538
11539     if (NumElems == 4)
11540       // If we don't care about the second element, proceed to use movss.
11541       if (SVOp->getMaskElt(1) != -1)
11542         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
11543   }
11544
11545   // movl and movlp will both match v2i64, but v2i64 is never matched by
11546   // movl earlier because we make it strict to avoid messing with the movlp load
11547   // folding logic (see the code above getMOVLP call). Match it here then,
11548   // this is horrible, but will stay like this until we move all shuffle
11549   // matching to x86 specific nodes. Note that for the 1st condition all
11550   // types are matched with movsd.
11551   if (HasSSE2) {
11552     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
11553     // as to remove this logic from here, as much as possible
11554     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
11555       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
11556     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
11557   }
11558
11559   assert(VT != MVT::v4i32 && "unsupported shuffle type");
11560
11561   // Invert the operand order and use SHUFPS to match it.
11562   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
11563                               getShuffleSHUFImmediate(SVOp), DAG);
11564 }
11565
11566 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
11567                                          SelectionDAG &DAG) {
11568   SDLoc dl(Load);
11569   MVT VT = Load->getSimpleValueType(0);
11570   MVT EVT = VT.getVectorElementType();
11571   SDValue Addr = Load->getOperand(1);
11572   SDValue NewAddr = DAG.getNode(
11573       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
11574       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
11575
11576   SDValue NewLoad =
11577       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
11578                   DAG.getMachineFunction().getMachineMemOperand(
11579                       Load->getMemOperand(), 0, EVT.getStoreSize()));
11580   return NewLoad;
11581 }
11582
11583 // It is only safe to call this function if isINSERTPSMask is true for
11584 // this shufflevector mask.
11585 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
11586                            SelectionDAG &DAG) {
11587   // Generate an insertps instruction when inserting an f32 from memory onto a
11588   // v4f32 or when copying a member from one v4f32 to another.
11589   // We also use it for transferring i32 from one register to another,
11590   // since it simply copies the same bits.
11591   // If we're transferring an i32 from memory to a specific element in a
11592   // register, we output a generic DAG that will match the PINSRD
11593   // instruction.
11594   MVT VT = SVOp->getSimpleValueType(0);
11595   MVT EVT = VT.getVectorElementType();
11596   SDValue V1 = SVOp->getOperand(0);
11597   SDValue V2 = SVOp->getOperand(1);
11598   auto Mask = SVOp->getMask();
11599   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
11600          "unsupported vector type for insertps/pinsrd");
11601
11602   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
11603   auto FromV2Predicate = [](const int &i) { return i >= 4; };
11604   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
11605
11606   SDValue From;
11607   SDValue To;
11608   unsigned DestIndex;
11609   if (FromV1 == 1) {
11610     From = V1;
11611     To = V2;
11612     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
11613                 Mask.begin();
11614
11615     // If we have 1 element from each vector, we have to check if we're
11616     // changing V1's element's place. If so, we're done. Otherwise, we
11617     // should assume we're changing V2's element's place and behave
11618     // accordingly.
11619     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
11620     assert(DestIndex <= INT32_MAX && "truncated destination index");
11621     if (FromV1 == FromV2 &&
11622         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
11623       From = V2;
11624       To = V1;
11625       DestIndex =
11626           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
11627     }
11628   } else {
11629     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
11630            "More than one element from V1 and from V2, or no elements from one "
11631            "of the vectors. This case should not have returned true from "
11632            "isINSERTPSMask");
11633     From = V2;
11634     To = V1;
11635     DestIndex =
11636         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
11637   }
11638
11639   // Get an index into the source vector in the range [0,4) (the mask is
11640   // in the range [0,8) because it can address V1 and V2)
11641   unsigned SrcIndex = Mask[DestIndex] % 4;
11642   if (MayFoldLoad(From)) {
11643     // Trivial case, when From comes from a load and is only used by the
11644     // shuffle. Make it use insertps from the vector that we need from that
11645     // load.
11646     SDValue NewLoad =
11647         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
11648     if (!NewLoad.getNode())
11649       return SDValue();
11650
11651     if (EVT == MVT::f32) {
11652       // Create this as a scalar to vector to match the instruction pattern.
11653       SDValue LoadScalarToVector =
11654           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
11655       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
11656       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
11657                          InsertpsMask);
11658     } else { // EVT == MVT::i32
11659       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
11660       // instruction, to match the PINSRD instruction, which loads an i32 to a
11661       // certain vector element.
11662       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
11663                          DAG.getConstant(DestIndex, MVT::i32));
11664     }
11665   }
11666
11667   // Vector-element-to-vector
11668   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
11669   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
11670 }
11671
11672 // Reduce a vector shuffle to zext.
11673 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
11674                                     SelectionDAG &DAG) {
11675   // PMOVZX is only available from SSE41.
11676   if (!Subtarget->hasSSE41())
11677     return SDValue();
11678
11679   MVT VT = Op.getSimpleValueType();
11680
11681   // Only AVX2 support 256-bit vector integer extending.
11682   if (!Subtarget->hasInt256() && VT.is256BitVector())
11683     return SDValue();
11684
11685   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11686   SDLoc DL(Op);
11687   SDValue V1 = Op.getOperand(0);
11688   SDValue V2 = Op.getOperand(1);
11689   unsigned NumElems = VT.getVectorNumElements();
11690
11691   // Extending is an unary operation and the element type of the source vector
11692   // won't be equal to or larger than i64.
11693   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
11694       VT.getVectorElementType() == MVT::i64)
11695     return SDValue();
11696
11697   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
11698   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
11699   while ((1U << Shift) < NumElems) {
11700     if (SVOp->getMaskElt(1U << Shift) == 1)
11701       break;
11702     Shift += 1;
11703     // The maximal ratio is 8, i.e. from i8 to i64.
11704     if (Shift > 3)
11705       return SDValue();
11706   }
11707
11708   // Check the shuffle mask.
11709   unsigned Mask = (1U << Shift) - 1;
11710   for (unsigned i = 0; i != NumElems; ++i) {
11711     int EltIdx = SVOp->getMaskElt(i);
11712     if ((i & Mask) != 0 && EltIdx != -1)
11713       return SDValue();
11714     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
11715       return SDValue();
11716   }
11717
11718   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
11719   MVT NeVT = MVT::getIntegerVT(NBits);
11720   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
11721
11722   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
11723     return SDValue();
11724
11725   return DAG.getNode(ISD::BITCAST, DL, VT,
11726                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
11727 }
11728
11729 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11730                                       SelectionDAG &DAG) {
11731   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11732   MVT VT = Op.getSimpleValueType();
11733   SDLoc dl(Op);
11734   SDValue V1 = Op.getOperand(0);
11735   SDValue V2 = Op.getOperand(1);
11736
11737   if (isZeroShuffle(SVOp))
11738     return getZeroVector(VT, Subtarget, DAG, dl);
11739
11740   // Handle splat operations
11741   if (SVOp->isSplat()) {
11742     // Use vbroadcast whenever the splat comes from a foldable load
11743     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
11744     if (Broadcast.getNode())
11745       return Broadcast;
11746   }
11747
11748   // Check integer expanding shuffles.
11749   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
11750   if (NewOp.getNode())
11751     return NewOp;
11752
11753   // If the shuffle can be profitably rewritten as a narrower shuffle, then
11754   // do it!
11755   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
11756       VT == MVT::v32i8) {
11757     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
11758     if (NewOp.getNode())
11759       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
11760   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
11761     // FIXME: Figure out a cleaner way to do this.
11762     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
11763       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
11764       if (NewOp.getNode()) {
11765         MVT NewVT = NewOp.getSimpleValueType();
11766         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
11767                                NewVT, true, false))
11768           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
11769                               dl);
11770       }
11771     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
11772       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
11773       if (NewOp.getNode()) {
11774         MVT NewVT = NewOp.getSimpleValueType();
11775         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
11776           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
11777                               dl);
11778       }
11779     }
11780   }
11781   return SDValue();
11782 }
11783
11784 SDValue
11785 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
11786   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11787   SDValue V1 = Op.getOperand(0);
11788   SDValue V2 = Op.getOperand(1);
11789   MVT VT = Op.getSimpleValueType();
11790   SDLoc dl(Op);
11791   unsigned NumElems = VT.getVectorNumElements();
11792   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11793   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11794   bool V1IsSplat = false;
11795   bool V2IsSplat = false;
11796   bool HasSSE2 = Subtarget->hasSSE2();
11797   bool HasFp256    = Subtarget->hasFp256();
11798   bool HasInt256   = Subtarget->hasInt256();
11799   MachineFunction &MF = DAG.getMachineFunction();
11800   bool OptForSize = MF.getFunction()->getAttributes().
11801     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
11802
11803   // Check if we should use the experimental vector shuffle lowering. If so,
11804   // delegate completely to that code path.
11805   if (ExperimentalVectorShuffleLowering)
11806     return lowerVectorShuffle(Op, Subtarget, DAG);
11807
11808   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
11809
11810   if (V1IsUndef && V2IsUndef)
11811     return DAG.getUNDEF(VT);
11812
11813   // When we create a shuffle node we put the UNDEF node to second operand,
11814   // but in some cases the first operand may be transformed to UNDEF.
11815   // In this case we should just commute the node.
11816   if (V1IsUndef)
11817     return DAG.getCommutedVectorShuffle(*SVOp);
11818
11819   // Vector shuffle lowering takes 3 steps:
11820   //
11821   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
11822   //    narrowing and commutation of operands should be handled.
11823   // 2) Matching of shuffles with known shuffle masks to x86 target specific
11824   //    shuffle nodes.
11825   // 3) Rewriting of unmatched masks into new generic shuffle operations,
11826   //    so the shuffle can be broken into other shuffles and the legalizer can
11827   //    try the lowering again.
11828   //
11829   // The general idea is that no vector_shuffle operation should be left to
11830   // be matched during isel, all of them must be converted to a target specific
11831   // node here.
11832
11833   // Normalize the input vectors. Here splats, zeroed vectors, profitable
11834   // narrowing and commutation of operands should be handled. The actual code
11835   // doesn't include all of those, work in progress...
11836   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
11837   if (NewOp.getNode())
11838     return NewOp;
11839
11840   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
11841
11842   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
11843   // unpckh_undef). Only use pshufd if speed is more important than size.
11844   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
11845     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
11846   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
11847     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
11848
11849   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
11850       V2IsUndef && MayFoldVectorLoad(V1))
11851     return getMOVDDup(Op, dl, V1, DAG);
11852
11853   if (isMOVHLPS_v_undef_Mask(M, VT))
11854     return getMOVHighToLow(Op, dl, DAG);
11855
11856   // Use to match splats
11857   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
11858       (VT == MVT::v2f64 || VT == MVT::v2i64))
11859     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
11860
11861   if (isPSHUFDMask(M, VT)) {
11862     // The actual implementation will match the mask in the if above and then
11863     // during isel it can match several different instructions, not only pshufd
11864     // as its name says, sad but true, emulate the behavior for now...
11865     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
11866       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
11867
11868     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
11869
11870     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
11871       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
11872
11873     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
11874       return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1, TargetMask,
11875                                   DAG);
11876
11877     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
11878                                 TargetMask, DAG);
11879   }
11880
11881   if (isPALIGNRMask(M, VT, Subtarget))
11882     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
11883                                 getShufflePALIGNRImmediate(SVOp),
11884                                 DAG);
11885
11886   if (isVALIGNMask(M, VT, Subtarget))
11887     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
11888                                 getShuffleVALIGNImmediate(SVOp),
11889                                 DAG);
11890
11891   // Check if this can be converted into a logical shift.
11892   bool isLeft = false;
11893   unsigned ShAmt = 0;
11894   SDValue ShVal;
11895   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
11896   if (isShift && ShVal.hasOneUse()) {
11897     // If the shifted value has multiple uses, it may be cheaper to use
11898     // v_set0 + movlhps or movhlps, etc.
11899     MVT EltVT = VT.getVectorElementType();
11900     ShAmt *= EltVT.getSizeInBits();
11901     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
11902   }
11903
11904   if (isMOVLMask(M, VT)) {
11905     if (ISD::isBuildVectorAllZeros(V1.getNode()))
11906       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
11907     if (!isMOVLPMask(M, VT)) {
11908       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
11909         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
11910
11911       if (VT == MVT::v4i32 || VT == MVT::v4f32)
11912         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
11913     }
11914   }
11915
11916   // FIXME: fold these into legal mask.
11917   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
11918     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
11919
11920   if (isMOVHLPSMask(M, VT))
11921     return getMOVHighToLow(Op, dl, DAG);
11922
11923   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
11924     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
11925
11926   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
11927     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
11928
11929   if (isMOVLPMask(M, VT))
11930     return getMOVLP(Op, dl, DAG, HasSSE2);
11931
11932   if (ShouldXformToMOVHLPS(M, VT) ||
11933       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
11934     return DAG.getCommutedVectorShuffle(*SVOp);
11935
11936   if (isShift) {
11937     // No better options. Use a vshldq / vsrldq.
11938     MVT EltVT = VT.getVectorElementType();
11939     ShAmt *= EltVT.getSizeInBits();
11940     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
11941   }
11942
11943   bool Commuted = false;
11944   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
11945   // 1,1,1,1 -> v8i16 though.
11946   BitVector UndefElements;
11947   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
11948     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
11949       V1IsSplat = true;
11950   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
11951     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
11952       V2IsSplat = true;
11953
11954   // Canonicalize the splat or undef, if present, to be on the RHS.
11955   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
11956     CommuteVectorShuffleMask(M, NumElems);
11957     std::swap(V1, V2);
11958     std::swap(V1IsSplat, V2IsSplat);
11959     Commuted = true;
11960   }
11961
11962   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
11963     // Shuffling low element of v1 into undef, just return v1.
11964     if (V2IsUndef)
11965       return V1;
11966     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
11967     // the instruction selector will not match, so get a canonical MOVL with
11968     // swapped operands to undo the commute.
11969     return getMOVL(DAG, dl, VT, V2, V1);
11970   }
11971
11972   if (isUNPCKLMask(M, VT, HasInt256))
11973     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
11974
11975   if (isUNPCKHMask(M, VT, HasInt256))
11976     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
11977
11978   if (V2IsSplat) {
11979     // Normalize mask so all entries that point to V2 points to its first
11980     // element then try to match unpck{h|l} again. If match, return a
11981     // new vector_shuffle with the corrected mask.p
11982     SmallVector<int, 8> NewMask(M.begin(), M.end());
11983     NormalizeMask(NewMask, NumElems);
11984     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
11985       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
11986     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
11987       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
11988   }
11989
11990   if (Commuted) {
11991     // Commute is back and try unpck* again.
11992     // FIXME: this seems wrong.
11993     CommuteVectorShuffleMask(M, NumElems);
11994     std::swap(V1, V2);
11995     std::swap(V1IsSplat, V2IsSplat);
11996
11997     if (isUNPCKLMask(M, VT, HasInt256))
11998       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
11999
12000     if (isUNPCKHMask(M, VT, HasInt256))
12001       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12002   }
12003
12004   // Normalize the node to match x86 shuffle ops if needed
12005   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
12006     return DAG.getCommutedVectorShuffle(*SVOp);
12007
12008   // The checks below are all present in isShuffleMaskLegal, but they are
12009   // inlined here right now to enable us to directly emit target specific
12010   // nodes, and remove one by one until they don't return Op anymore.
12011
12012   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
12013       SVOp->getSplatIndex() == 0 && V2IsUndef) {
12014     if (VT == MVT::v2f64 || VT == MVT::v2i64)
12015       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12016   }
12017
12018   if (isPSHUFHWMask(M, VT, HasInt256))
12019     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
12020                                 getShufflePSHUFHWImmediate(SVOp),
12021                                 DAG);
12022
12023   if (isPSHUFLWMask(M, VT, HasInt256))
12024     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
12025                                 getShufflePSHUFLWImmediate(SVOp),
12026                                 DAG);
12027
12028   unsigned MaskValue;
12029   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
12030                   &MaskValue))
12031     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
12032
12033   if (isSHUFPMask(M, VT))
12034     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
12035                                 getShuffleSHUFImmediate(SVOp), DAG);
12036
12037   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12038     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12039   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12040     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12041
12042   //===--------------------------------------------------------------------===//
12043   // Generate target specific nodes for 128 or 256-bit shuffles only
12044   // supported in the AVX instruction set.
12045   //
12046
12047   // Handle VMOVDDUPY permutations
12048   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
12049     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
12050
12051   // Handle VPERMILPS/D* permutations
12052   if (isVPERMILPMask(M, VT)) {
12053     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
12054       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
12055                                   getShuffleSHUFImmediate(SVOp), DAG);
12056     return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1,
12057                                 getShuffleSHUFImmediate(SVOp), DAG);
12058   }
12059
12060   unsigned Idx;
12061   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
12062     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
12063                               Idx*(NumElems/2), DAG, dl);
12064
12065   // Handle VPERM2F128/VPERM2I128 permutations
12066   if (isVPERM2X128Mask(M, VT, HasFp256))
12067     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
12068                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
12069
12070   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
12071     return getINSERTPS(SVOp, dl, DAG);
12072
12073   unsigned Imm8;
12074   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
12075     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
12076
12077   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
12078       VT.is512BitVector()) {
12079     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
12080     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
12081     SmallVector<SDValue, 16> permclMask;
12082     for (unsigned i = 0; i != NumElems; ++i) {
12083       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
12084     }
12085
12086     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
12087     if (V2IsUndef)
12088       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
12089       return DAG.getNode(X86ISD::VPERMV, dl, VT,
12090                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
12091     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
12092                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
12093   }
12094
12095   //===--------------------------------------------------------------------===//
12096   // Since no target specific shuffle was selected for this generic one,
12097   // lower it into other known shuffles. FIXME: this isn't true yet, but
12098   // this is the plan.
12099   //
12100
12101   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
12102   if (VT == MVT::v8i16) {
12103     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
12104     if (NewOp.getNode())
12105       return NewOp;
12106   }
12107
12108   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
12109     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
12110     if (NewOp.getNode())
12111       return NewOp;
12112   }
12113
12114   if (VT == MVT::v16i8) {
12115     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
12116     if (NewOp.getNode())
12117       return NewOp;
12118   }
12119
12120   if (VT == MVT::v32i8) {
12121     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
12122     if (NewOp.getNode())
12123       return NewOp;
12124   }
12125
12126   // Handle all 128-bit wide vectors with 4 elements, and match them with
12127   // several different shuffle types.
12128   if (NumElems == 4 && VT.is128BitVector())
12129     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
12130
12131   // Handle general 256-bit shuffles
12132   if (VT.is256BitVector())
12133     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
12134
12135   return SDValue();
12136 }
12137
12138 // This function assumes its argument is a BUILD_VECTOR of constants or
12139 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
12140 // true.
12141 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
12142                                     unsigned &MaskValue) {
12143   MaskValue = 0;
12144   unsigned NumElems = BuildVector->getNumOperands();
12145   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
12146   unsigned NumLanes = (NumElems - 1) / 8 + 1;
12147   unsigned NumElemsInLane = NumElems / NumLanes;
12148
12149   // Blend for v16i16 should be symetric for the both lanes.
12150   for (unsigned i = 0; i < NumElemsInLane; ++i) {
12151     SDValue EltCond = BuildVector->getOperand(i);
12152     SDValue SndLaneEltCond =
12153         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
12154
12155     int Lane1Cond = -1, Lane2Cond = -1;
12156     if (isa<ConstantSDNode>(EltCond))
12157       Lane1Cond = !isZero(EltCond);
12158     if (isa<ConstantSDNode>(SndLaneEltCond))
12159       Lane2Cond = !isZero(SndLaneEltCond);
12160
12161     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
12162       // Lane1Cond != 0, means we want the first argument.
12163       // Lane1Cond == 0, means we want the second argument.
12164       // The encoding of this argument is 0 for the first argument, 1
12165       // for the second. Therefore, invert the condition.
12166       MaskValue |= !Lane1Cond << i;
12167     else if (Lane1Cond < 0)
12168       MaskValue |= !Lane2Cond << i;
12169     else
12170       return false;
12171   }
12172   return true;
12173 }
12174
12175 /// \brief Try to lower a VSELECT instruction to an immediate-controlled blend
12176 /// instruction.
12177 static SDValue lowerVSELECTtoBLENDI(SDValue Op, const X86Subtarget *Subtarget,
12178                                     SelectionDAG &DAG) {
12179   SDValue Cond = Op.getOperand(0);
12180   SDValue LHS = Op.getOperand(1);
12181   SDValue RHS = Op.getOperand(2);
12182   SDLoc dl(Op);
12183   MVT VT = Op.getSimpleValueType();
12184   MVT EltVT = VT.getVectorElementType();
12185   unsigned NumElems = VT.getVectorNumElements();
12186
12187   // There is no blend with immediate in AVX-512.
12188   if (VT.is512BitVector())
12189     return SDValue();
12190
12191   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
12192     return SDValue();
12193   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
12194     return SDValue();
12195
12196   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
12197     return SDValue();
12198
12199   // Check the mask for BLEND and build the value.
12200   unsigned MaskValue = 0;
12201   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
12202     return SDValue();
12203
12204   // Convert i32 vectors to floating point if it is not AVX2.
12205   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
12206   MVT BlendVT = VT;
12207   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
12208     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
12209                                NumElems);
12210     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
12211     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
12212   }
12213
12214   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
12215                             DAG.getConstant(MaskValue, MVT::i32));
12216   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
12217 }
12218
12219 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
12220   // A vselect where all conditions and data are constants can be optimized into
12221   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
12222   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
12223       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
12224       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
12225     return SDValue();
12226
12227   SDValue BlendOp = lowerVSELECTtoBLENDI(Op, Subtarget, DAG);
12228   if (BlendOp.getNode())
12229     return BlendOp;
12230
12231   // Some types for vselect were previously set to Expand, not Legal or
12232   // Custom. Return an empty SDValue so we fall-through to Expand, after
12233   // the Custom lowering phase.
12234   MVT VT = Op.getSimpleValueType();
12235   switch (VT.SimpleTy) {
12236   default:
12237     break;
12238   case MVT::v8i16:
12239   case MVT::v16i16:
12240     if (Subtarget->hasBWI() && Subtarget->hasVLX())
12241       break;
12242     return SDValue();
12243   }
12244
12245   // We couldn't create a "Blend with immediate" node.
12246   // This node should still be legal, but we'll have to emit a blendv*
12247   // instruction.
12248   return Op;
12249 }
12250
12251 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
12252   MVT VT = Op.getSimpleValueType();
12253   SDLoc dl(Op);
12254
12255   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
12256     return SDValue();
12257
12258   if (VT.getSizeInBits() == 8) {
12259     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
12260                                   Op.getOperand(0), Op.getOperand(1));
12261     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12262                                   DAG.getValueType(VT));
12263     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12264   }
12265
12266   if (VT.getSizeInBits() == 16) {
12267     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12268     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
12269     if (Idx == 0)
12270       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12271                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12272                                      DAG.getNode(ISD::BITCAST, dl,
12273                                                  MVT::v4i32,
12274                                                  Op.getOperand(0)),
12275                                      Op.getOperand(1)));
12276     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
12277                                   Op.getOperand(0), Op.getOperand(1));
12278     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12279                                   DAG.getValueType(VT));
12280     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12281   }
12282
12283   if (VT == MVT::f32) {
12284     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
12285     // the result back to FR32 register. It's only worth matching if the
12286     // result has a single use which is a store or a bitcast to i32.  And in
12287     // the case of a store, it's not worth it if the index is a constant 0,
12288     // because a MOVSSmr can be used instead, which is smaller and faster.
12289     if (!Op.hasOneUse())
12290       return SDValue();
12291     SDNode *User = *Op.getNode()->use_begin();
12292     if ((User->getOpcode() != ISD::STORE ||
12293          (isa<ConstantSDNode>(Op.getOperand(1)) &&
12294           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
12295         (User->getOpcode() != ISD::BITCAST ||
12296          User->getValueType(0) != MVT::i32))
12297       return SDValue();
12298     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12299                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
12300                                               Op.getOperand(0)),
12301                                               Op.getOperand(1));
12302     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
12303   }
12304
12305   if (VT == MVT::i32 || VT == MVT::i64) {
12306     // ExtractPS/pextrq works with constant index.
12307     if (isa<ConstantSDNode>(Op.getOperand(1)))
12308       return Op;
12309   }
12310   return SDValue();
12311 }
12312
12313 /// Extract one bit from mask vector, like v16i1 or v8i1.
12314 /// AVX-512 feature.
12315 SDValue
12316 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
12317   SDValue Vec = Op.getOperand(0);
12318   SDLoc dl(Vec);
12319   MVT VecVT = Vec.getSimpleValueType();
12320   SDValue Idx = Op.getOperand(1);
12321   MVT EltVT = Op.getSimpleValueType();
12322
12323   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
12324
12325   // variable index can't be handled in mask registers,
12326   // extend vector to VR512
12327   if (!isa<ConstantSDNode>(Idx)) {
12328     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12329     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
12330     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
12331                               ExtVT.getVectorElementType(), Ext, Idx);
12332     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
12333   }
12334
12335   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12336   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12337   unsigned MaxSift = rc->getSize()*8 - 1;
12338   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
12339                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12340   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
12341                     DAG.getConstant(MaxSift, MVT::i8));
12342   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
12343                        DAG.getIntPtrConstant(0));
12344 }
12345
12346 SDValue
12347 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
12348                                            SelectionDAG &DAG) const {
12349   SDLoc dl(Op);
12350   SDValue Vec = Op.getOperand(0);
12351   MVT VecVT = Vec.getSimpleValueType();
12352   SDValue Idx = Op.getOperand(1);
12353
12354   if (Op.getSimpleValueType() == MVT::i1)
12355     return ExtractBitFromMaskVector(Op, DAG);
12356
12357   if (!isa<ConstantSDNode>(Idx)) {
12358     if (VecVT.is512BitVector() ||
12359         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
12360          VecVT.getVectorElementType().getSizeInBits() == 32)) {
12361
12362       MVT MaskEltVT =
12363         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
12364       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
12365                                     MaskEltVT.getSizeInBits());
12366
12367       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
12368       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
12369                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
12370                                 Idx, DAG.getConstant(0, getPointerTy()));
12371       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
12372       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
12373                         Perm, DAG.getConstant(0, getPointerTy()));
12374     }
12375     return SDValue();
12376   }
12377
12378   // If this is a 256-bit vector result, first extract the 128-bit vector and
12379   // then extract the element from the 128-bit vector.
12380   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
12381
12382     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12383     // Get the 128-bit vector.
12384     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
12385     MVT EltVT = VecVT.getVectorElementType();
12386
12387     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
12388
12389     //if (IdxVal >= NumElems/2)
12390     //  IdxVal -= NumElems/2;
12391     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
12392     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
12393                        DAG.getConstant(IdxVal, MVT::i32));
12394   }
12395
12396   assert(VecVT.is128BitVector() && "Unexpected vector length");
12397
12398   if (Subtarget->hasSSE41()) {
12399     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
12400     if (Res.getNode())
12401       return Res;
12402   }
12403
12404   MVT VT = Op.getSimpleValueType();
12405   // TODO: handle v16i8.
12406   if (VT.getSizeInBits() == 16) {
12407     SDValue Vec = Op.getOperand(0);
12408     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12409     if (Idx == 0)
12410       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12411                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12412                                      DAG.getNode(ISD::BITCAST, dl,
12413                                                  MVT::v4i32, Vec),
12414                                      Op.getOperand(1)));
12415     // Transform it so it match pextrw which produces a 32-bit result.
12416     MVT EltVT = MVT::i32;
12417     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
12418                                   Op.getOperand(0), Op.getOperand(1));
12419     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
12420                                   DAG.getValueType(VT));
12421     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12422   }
12423
12424   if (VT.getSizeInBits() == 32) {
12425     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12426     if (Idx == 0)
12427       return Op;
12428
12429     // SHUFPS the element to the lowest double word, then movss.
12430     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
12431     MVT VVT = Op.getOperand(0).getSimpleValueType();
12432     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12433                                        DAG.getUNDEF(VVT), Mask);
12434     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12435                        DAG.getIntPtrConstant(0));
12436   }
12437
12438   if (VT.getSizeInBits() == 64) {
12439     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
12440     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
12441     //        to match extract_elt for f64.
12442     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12443     if (Idx == 0)
12444       return Op;
12445
12446     // UNPCKHPD the element to the lowest double word, then movsd.
12447     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
12448     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
12449     int Mask[2] = { 1, -1 };
12450     MVT VVT = Op.getOperand(0).getSimpleValueType();
12451     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12452                                        DAG.getUNDEF(VVT), Mask);
12453     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12454                        DAG.getIntPtrConstant(0));
12455   }
12456
12457   return SDValue();
12458 }
12459
12460 /// Insert one bit to mask vector, like v16i1 or v8i1.
12461 /// AVX-512 feature.
12462 SDValue 
12463 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
12464   SDLoc dl(Op);
12465   SDValue Vec = Op.getOperand(0);
12466   SDValue Elt = Op.getOperand(1);
12467   SDValue Idx = Op.getOperand(2);
12468   MVT VecVT = Vec.getSimpleValueType();
12469
12470   if (!isa<ConstantSDNode>(Idx)) {
12471     // Non constant index. Extend source and destination,
12472     // insert element and then truncate the result.
12473     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12474     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
12475     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
12476       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
12477       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
12478     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
12479   }
12480
12481   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12482   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
12483   if (Vec.getOpcode() == ISD::UNDEF)
12484     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12485                        DAG.getConstant(IdxVal, MVT::i8));
12486   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12487   unsigned MaxSift = rc->getSize()*8 - 1;
12488   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12489                     DAG.getConstant(MaxSift, MVT::i8));
12490   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
12491                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12492   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
12493 }
12494
12495 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12496                                                   SelectionDAG &DAG) const {
12497   MVT VT = Op.getSimpleValueType();
12498   MVT EltVT = VT.getVectorElementType();
12499
12500   if (EltVT == MVT::i1)
12501     return InsertBitToMaskVector(Op, DAG);
12502
12503   SDLoc dl(Op);
12504   SDValue N0 = Op.getOperand(0);
12505   SDValue N1 = Op.getOperand(1);
12506   SDValue N2 = Op.getOperand(2);
12507   if (!isa<ConstantSDNode>(N2))
12508     return SDValue();
12509   auto *N2C = cast<ConstantSDNode>(N2);
12510   unsigned IdxVal = N2C->getZExtValue();
12511
12512   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
12513   // into that, and then insert the subvector back into the result.
12514   if (VT.is256BitVector() || VT.is512BitVector()) {
12515     // Get the desired 128-bit vector half.
12516     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
12517
12518     // Insert the element into the desired half.
12519     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
12520     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
12521
12522     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
12523                     DAG.getConstant(IdxIn128, MVT::i32));
12524
12525     // Insert the changed part back to the 256-bit vector
12526     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
12527   }
12528   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
12529
12530   if (Subtarget->hasSSE41()) {
12531     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
12532       unsigned Opc;
12533       if (VT == MVT::v8i16) {
12534         Opc = X86ISD::PINSRW;
12535       } else {
12536         assert(VT == MVT::v16i8);
12537         Opc = X86ISD::PINSRB;
12538       }
12539
12540       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
12541       // argument.
12542       if (N1.getValueType() != MVT::i32)
12543         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12544       if (N2.getValueType() != MVT::i32)
12545         N2 = DAG.getIntPtrConstant(IdxVal);
12546       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
12547     }
12548
12549     if (EltVT == MVT::f32) {
12550       // Bits [7:6] of the constant are the source select.  This will always be
12551       //  zero here.  The DAG Combiner may combine an extract_elt index into
12552       //  these
12553       //  bits.  For example (insert (extract, 3), 2) could be matched by
12554       //  putting
12555       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
12556       // Bits [5:4] of the constant are the destination select.  This is the
12557       //  value of the incoming immediate.
12558       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
12559       //   combine either bitwise AND or insert of float 0.0 to set these bits.
12560       N2 = DAG.getIntPtrConstant(IdxVal << 4);
12561       // Create this as a scalar to vector..
12562       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
12563       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
12564     }
12565
12566     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
12567       // PINSR* works with constant index.
12568       return Op;
12569     }
12570   }
12571
12572   if (EltVT == MVT::i8)
12573     return SDValue();
12574
12575   if (EltVT.getSizeInBits() == 16) {
12576     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12577     // as its second argument.
12578     if (N1.getValueType() != MVT::i32)
12579       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12580     if (N2.getValueType() != MVT::i32)
12581       N2 = DAG.getIntPtrConstant(IdxVal);
12582     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12583   }
12584   return SDValue();
12585 }
12586
12587 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12588   SDLoc dl(Op);
12589   MVT OpVT = Op.getSimpleValueType();
12590
12591   // If this is a 256-bit vector result, first insert into a 128-bit
12592   // vector and then insert into the 256-bit vector.
12593   if (!OpVT.is128BitVector()) {
12594     // Insert into a 128-bit vector.
12595     unsigned SizeFactor = OpVT.getSizeInBits()/128;
12596     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12597                                  OpVT.getVectorNumElements() / SizeFactor);
12598
12599     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12600
12601     // Insert the 128-bit vector.
12602     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12603   }
12604
12605   if (OpVT == MVT::v1i64 &&
12606       Op.getOperand(0).getValueType() == MVT::i64)
12607     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12608
12609   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12610   assert(OpVT.is128BitVector() && "Expected an SSE type!");
12611   return DAG.getNode(ISD::BITCAST, dl, OpVT,
12612                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
12613 }
12614
12615 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
12616 // a simple subregister reference or explicit instructions to grab
12617 // upper bits of a vector.
12618 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12619                                       SelectionDAG &DAG) {
12620   SDLoc dl(Op);
12621   SDValue In =  Op.getOperand(0);
12622   SDValue Idx = Op.getOperand(1);
12623   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12624   MVT ResVT   = Op.getSimpleValueType();
12625   MVT InVT    = In.getSimpleValueType();
12626
12627   if (Subtarget->hasFp256()) {
12628     if (ResVT.is128BitVector() &&
12629         (InVT.is256BitVector() || InVT.is512BitVector()) &&
12630         isa<ConstantSDNode>(Idx)) {
12631       return Extract128BitVector(In, IdxVal, DAG, dl);
12632     }
12633     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12634         isa<ConstantSDNode>(Idx)) {
12635       return Extract256BitVector(In, IdxVal, DAG, dl);
12636     }
12637   }
12638   return SDValue();
12639 }
12640
12641 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12642 // simple superregister reference or explicit instructions to insert
12643 // the upper bits of a vector.
12644 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12645                                      SelectionDAG &DAG) {
12646   if (Subtarget->hasFp256()) {
12647     SDLoc dl(Op.getNode());
12648     SDValue Vec = Op.getNode()->getOperand(0);
12649     SDValue SubVec = Op.getNode()->getOperand(1);
12650     SDValue Idx = Op.getNode()->getOperand(2);
12651
12652     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
12653          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
12654         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
12655         isa<ConstantSDNode>(Idx)) {
12656       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12657       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12658     }
12659
12660     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
12661         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
12662         isa<ConstantSDNode>(Idx)) {
12663       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12664       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12665     }
12666   }
12667   return SDValue();
12668 }
12669
12670 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12671 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12672 // one of the above mentioned nodes. It has to be wrapped because otherwise
12673 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12674 // be used to form addressing mode. These wrapped nodes will be selected
12675 // into MOV32ri.
12676 SDValue
12677 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12678   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12679
12680   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12681   // global base reg.
12682   unsigned char OpFlag = 0;
12683   unsigned WrapperKind = X86ISD::Wrapper;
12684   CodeModel::Model M = DAG.getTarget().getCodeModel();
12685
12686   if (Subtarget->isPICStyleRIPRel() &&
12687       (M == CodeModel::Small || M == CodeModel::Kernel))
12688     WrapperKind = X86ISD::WrapperRIP;
12689   else if (Subtarget->isPICStyleGOT())
12690     OpFlag = X86II::MO_GOTOFF;
12691   else if (Subtarget->isPICStyleStubPIC())
12692     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12693
12694   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
12695                                              CP->getAlignment(),
12696                                              CP->getOffset(), OpFlag);
12697   SDLoc DL(CP);
12698   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
12699   // With PIC, the address is actually $g + Offset.
12700   if (OpFlag) {
12701     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12702                          DAG.getNode(X86ISD::GlobalBaseReg,
12703                                      SDLoc(), getPointerTy()),
12704                          Result);
12705   }
12706
12707   return Result;
12708 }
12709
12710 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12711   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12712
12713   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12714   // global base reg.
12715   unsigned char OpFlag = 0;
12716   unsigned WrapperKind = X86ISD::Wrapper;
12717   CodeModel::Model M = DAG.getTarget().getCodeModel();
12718
12719   if (Subtarget->isPICStyleRIPRel() &&
12720       (M == CodeModel::Small || M == CodeModel::Kernel))
12721     WrapperKind = X86ISD::WrapperRIP;
12722   else if (Subtarget->isPICStyleGOT())
12723     OpFlag = X86II::MO_GOTOFF;
12724   else if (Subtarget->isPICStyleStubPIC())
12725     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12726
12727   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
12728                                           OpFlag);
12729   SDLoc DL(JT);
12730   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
12731
12732   // With PIC, the address is actually $g + Offset.
12733   if (OpFlag)
12734     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12735                          DAG.getNode(X86ISD::GlobalBaseReg,
12736                                      SDLoc(), getPointerTy()),
12737                          Result);
12738
12739   return Result;
12740 }
12741
12742 SDValue
12743 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12744   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12745
12746   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12747   // global base reg.
12748   unsigned char OpFlag = 0;
12749   unsigned WrapperKind = X86ISD::Wrapper;
12750   CodeModel::Model M = DAG.getTarget().getCodeModel();
12751
12752   if (Subtarget->isPICStyleRIPRel() &&
12753       (M == CodeModel::Small || M == CodeModel::Kernel)) {
12754     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12755       OpFlag = X86II::MO_GOTPCREL;
12756     WrapperKind = X86ISD::WrapperRIP;
12757   } else if (Subtarget->isPICStyleGOT()) {
12758     OpFlag = X86II::MO_GOT;
12759   } else if (Subtarget->isPICStyleStubPIC()) {
12760     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12761   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12762     OpFlag = X86II::MO_DARWIN_NONLAZY;
12763   }
12764
12765   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
12766
12767   SDLoc DL(Op);
12768   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
12769
12770   // With PIC, the address is actually $g + Offset.
12771   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12772       !Subtarget->is64Bit()) {
12773     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12774                          DAG.getNode(X86ISD::GlobalBaseReg,
12775                                      SDLoc(), getPointerTy()),
12776                          Result);
12777   }
12778
12779   // For symbols that require a load from a stub to get the address, emit the
12780   // load.
12781   if (isGlobalStubReference(OpFlag))
12782     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
12783                          MachinePointerInfo::getGOT(), false, false, false, 0);
12784
12785   return Result;
12786 }
12787
12788 SDValue
12789 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12790   // Create the TargetBlockAddressAddress node.
12791   unsigned char OpFlags =
12792     Subtarget->ClassifyBlockAddressReference();
12793   CodeModel::Model M = DAG.getTarget().getCodeModel();
12794   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12795   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12796   SDLoc dl(Op);
12797   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
12798                                              OpFlags);
12799
12800   if (Subtarget->isPICStyleRIPRel() &&
12801       (M == CodeModel::Small || M == CodeModel::Kernel))
12802     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
12803   else
12804     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
12805
12806   // With PIC, the address is actually $g + Offset.
12807   if (isGlobalRelativeToPICBase(OpFlags)) {
12808     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
12809                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
12810                          Result);
12811   }
12812
12813   return Result;
12814 }
12815
12816 SDValue
12817 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12818                                       int64_t Offset, SelectionDAG &DAG) const {
12819   // Create the TargetGlobalAddress node, folding in the constant
12820   // offset if it is legal.
12821   unsigned char OpFlags =
12822       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12823   CodeModel::Model M = DAG.getTarget().getCodeModel();
12824   SDValue Result;
12825   if (OpFlags == X86II::MO_NO_FLAG &&
12826       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12827     // A direct static reference to a global.
12828     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
12829     Offset = 0;
12830   } else {
12831     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
12832   }
12833
12834   if (Subtarget->isPICStyleRIPRel() &&
12835       (M == CodeModel::Small || M == CodeModel::Kernel))
12836     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
12837   else
12838     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
12839
12840   // With PIC, the address is actually $g + Offset.
12841   if (isGlobalRelativeToPICBase(OpFlags)) {
12842     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
12843                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
12844                          Result);
12845   }
12846
12847   // For globals that require a load from a stub to get the address, emit the
12848   // load.
12849   if (isGlobalStubReference(OpFlags))
12850     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
12851                          MachinePointerInfo::getGOT(), false, false, false, 0);
12852
12853   // If there was a non-zero offset that we didn't fold, create an explicit
12854   // addition for it.
12855   if (Offset != 0)
12856     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
12857                          DAG.getConstant(Offset, getPointerTy()));
12858
12859   return Result;
12860 }
12861
12862 SDValue
12863 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12864   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12865   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12866   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12867 }
12868
12869 static SDValue
12870 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12871            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12872            unsigned char OperandFlags, bool LocalDynamic = false) {
12873   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12874   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12875   SDLoc dl(GA);
12876   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12877                                            GA->getValueType(0),
12878                                            GA->getOffset(),
12879                                            OperandFlags);
12880
12881   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12882                                            : X86ISD::TLSADDR;
12883
12884   if (InFlag) {
12885     SDValue Ops[] = { Chain,  TGA, *InFlag };
12886     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12887   } else {
12888     SDValue Ops[]  = { Chain, TGA };
12889     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12890   }
12891
12892   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12893   MFI->setAdjustsStack(true);
12894   MFI->setHasCalls(true);
12895
12896   SDValue Flag = Chain.getValue(1);
12897   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12898 }
12899
12900 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12901 static SDValue
12902 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12903                                 const EVT PtrVT) {
12904   SDValue InFlag;
12905   SDLoc dl(GA);  // ? function entry point might be better
12906   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12907                                    DAG.getNode(X86ISD::GlobalBaseReg,
12908                                                SDLoc(), PtrVT), InFlag);
12909   InFlag = Chain.getValue(1);
12910
12911   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12912 }
12913
12914 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12915 static SDValue
12916 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12917                                 const EVT PtrVT) {
12918   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12919                     X86::RAX, X86II::MO_TLSGD);
12920 }
12921
12922 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12923                                            SelectionDAG &DAG,
12924                                            const EVT PtrVT,
12925                                            bool is64Bit) {
12926   SDLoc dl(GA);
12927
12928   // Get the start address of the TLS block for this module.
12929   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12930       .getInfo<X86MachineFunctionInfo>();
12931   MFI->incNumLocalDynamicTLSAccesses();
12932
12933   SDValue Base;
12934   if (is64Bit) {
12935     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12936                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12937   } else {
12938     SDValue InFlag;
12939     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12940         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12941     InFlag = Chain.getValue(1);
12942     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12943                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12944   }
12945
12946   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12947   // of Base.
12948
12949   // Build x@dtpoff.
12950   unsigned char OperandFlags = X86II::MO_DTPOFF;
12951   unsigned WrapperKind = X86ISD::Wrapper;
12952   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12953                                            GA->getValueType(0),
12954                                            GA->getOffset(), OperandFlags);
12955   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12956
12957   // Add x@dtpoff with the base.
12958   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12959 }
12960
12961 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12962 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12963                                    const EVT PtrVT, TLSModel::Model model,
12964                                    bool is64Bit, bool isPIC) {
12965   SDLoc dl(GA);
12966
12967   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12968   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12969                                                          is64Bit ? 257 : 256));
12970
12971   SDValue ThreadPointer =
12972       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
12973                   MachinePointerInfo(Ptr), false, false, false, 0);
12974
12975   unsigned char OperandFlags = 0;
12976   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12977   // initialexec.
12978   unsigned WrapperKind = X86ISD::Wrapper;
12979   if (model == TLSModel::LocalExec) {
12980     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12981   } else if (model == TLSModel::InitialExec) {
12982     if (is64Bit) {
12983       OperandFlags = X86II::MO_GOTTPOFF;
12984       WrapperKind = X86ISD::WrapperRIP;
12985     } else {
12986       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12987     }
12988   } else {
12989     llvm_unreachable("Unexpected model");
12990   }
12991
12992   // emit "addl x@ntpoff,%eax" (local exec)
12993   // or "addl x@indntpoff,%eax" (initial exec)
12994   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12995   SDValue TGA =
12996       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12997                                  GA->getOffset(), OperandFlags);
12998   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12999
13000   if (model == TLSModel::InitialExec) {
13001     if (isPIC && !is64Bit) {
13002       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
13003                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
13004                            Offset);
13005     }
13006
13007     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
13008                          MachinePointerInfo::getGOT(), false, false, false, 0);
13009   }
13010
13011   // The address of the thread local variable is the add of the thread
13012   // pointer with the offset of the variable.
13013   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
13014 }
13015
13016 SDValue
13017 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
13018
13019   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
13020   const GlobalValue *GV = GA->getGlobal();
13021
13022   if (Subtarget->isTargetELF()) {
13023     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
13024
13025     switch (model) {
13026       case TLSModel::GeneralDynamic:
13027         if (Subtarget->is64Bit())
13028           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
13029         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
13030       case TLSModel::LocalDynamic:
13031         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
13032                                            Subtarget->is64Bit());
13033       case TLSModel::InitialExec:
13034       case TLSModel::LocalExec:
13035         return LowerToTLSExecModel(
13036             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
13037             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
13038     }
13039     llvm_unreachable("Unknown TLS model.");
13040   }
13041
13042   if (Subtarget->isTargetDarwin()) {
13043     // Darwin only has one model of TLS.  Lower to that.
13044     unsigned char OpFlag = 0;
13045     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
13046                            X86ISD::WrapperRIP : X86ISD::Wrapper;
13047
13048     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13049     // global base reg.
13050     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
13051                  !Subtarget->is64Bit();
13052     if (PIC32)
13053       OpFlag = X86II::MO_TLVP_PIC_BASE;
13054     else
13055       OpFlag = X86II::MO_TLVP;
13056     SDLoc DL(Op);
13057     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
13058                                                 GA->getValueType(0),
13059                                                 GA->getOffset(), OpFlag);
13060     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13061
13062     // With PIC32, the address is actually $g + Offset.
13063     if (PIC32)
13064       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13065                            DAG.getNode(X86ISD::GlobalBaseReg,
13066                                        SDLoc(), getPointerTy()),
13067                            Offset);
13068
13069     // Lowering the machine isd will make sure everything is in the right
13070     // location.
13071     SDValue Chain = DAG.getEntryNode();
13072     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13073     SDValue Args[] = { Chain, Offset };
13074     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
13075
13076     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
13077     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13078     MFI->setAdjustsStack(true);
13079
13080     // And our return value (tls address) is in the standard call return value
13081     // location.
13082     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13083     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
13084                               Chain.getValue(1));
13085   }
13086
13087   if (Subtarget->isTargetKnownWindowsMSVC() ||
13088       Subtarget->isTargetWindowsGNU()) {
13089     // Just use the implicit TLS architecture
13090     // Need to generate someting similar to:
13091     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
13092     //                                  ; from TEB
13093     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
13094     //   mov     rcx, qword [rdx+rcx*8]
13095     //   mov     eax, .tls$:tlsvar
13096     //   [rax+rcx] contains the address
13097     // Windows 64bit: gs:0x58
13098     // Windows 32bit: fs:__tls_array
13099
13100     SDLoc dl(GA);
13101     SDValue Chain = DAG.getEntryNode();
13102
13103     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
13104     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
13105     // use its literal value of 0x2C.
13106     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
13107                                         ? Type::getInt8PtrTy(*DAG.getContext(),
13108                                                              256)
13109                                         : Type::getInt32PtrTy(*DAG.getContext(),
13110                                                               257));
13111
13112     SDValue TlsArray =
13113         Subtarget->is64Bit()
13114             ? DAG.getIntPtrConstant(0x58)
13115             : (Subtarget->isTargetWindowsGNU()
13116                    ? DAG.getIntPtrConstant(0x2C)
13117                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
13118
13119     SDValue ThreadPointer =
13120         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
13121                     MachinePointerInfo(Ptr), false, false, false, 0);
13122
13123     // Load the _tls_index variable
13124     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
13125     if (Subtarget->is64Bit())
13126       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
13127                            IDX, MachinePointerInfo(), MVT::i32,
13128                            false, false, false, 0);
13129     else
13130       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
13131                         false, false, false, 0);
13132
13133     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
13134                                     getPointerTy());
13135     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
13136
13137     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
13138     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
13139                       false, false, false, 0);
13140
13141     // Get the offset of start of .tls section
13142     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13143                                              GA->getValueType(0),
13144                                              GA->getOffset(), X86II::MO_SECREL);
13145     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
13146
13147     // The address of the thread local variable is the add of the thread
13148     // pointer with the offset of the variable.
13149     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
13150   }
13151
13152   llvm_unreachable("TLS not implemented for this target.");
13153 }
13154
13155 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
13156 /// and take a 2 x i32 value to shift plus a shift amount.
13157 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
13158   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
13159   MVT VT = Op.getSimpleValueType();
13160   unsigned VTBits = VT.getSizeInBits();
13161   SDLoc dl(Op);
13162   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
13163   SDValue ShOpLo = Op.getOperand(0);
13164   SDValue ShOpHi = Op.getOperand(1);
13165   SDValue ShAmt  = Op.getOperand(2);
13166   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
13167   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
13168   // during isel.
13169   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13170                                   DAG.getConstant(VTBits - 1, MVT::i8));
13171   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
13172                                      DAG.getConstant(VTBits - 1, MVT::i8))
13173                        : DAG.getConstant(0, VT);
13174
13175   SDValue Tmp2, Tmp3;
13176   if (Op.getOpcode() == ISD::SHL_PARTS) {
13177     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
13178     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
13179   } else {
13180     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
13181     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
13182   }
13183
13184   // If the shift amount is larger or equal than the width of a part we can't
13185   // rely on the results of shld/shrd. Insert a test and select the appropriate
13186   // values for large shift amounts.
13187   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13188                                 DAG.getConstant(VTBits, MVT::i8));
13189   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13190                              AndNode, DAG.getConstant(0, MVT::i8));
13191
13192   SDValue Hi, Lo;
13193   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13194   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
13195   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
13196
13197   if (Op.getOpcode() == ISD::SHL_PARTS) {
13198     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13199     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13200   } else {
13201     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13202     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13203   }
13204
13205   SDValue Ops[2] = { Lo, Hi };
13206   return DAG.getMergeValues(Ops, dl);
13207 }
13208
13209 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
13210                                            SelectionDAG &DAG) const {
13211   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13212
13213   if (SrcVT.isVector())
13214     return SDValue();
13215
13216   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
13217          "Unknown SINT_TO_FP to lower!");
13218
13219   // These are really Legal; return the operand so the caller accepts it as
13220   // Legal.
13221   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
13222     return Op;
13223   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
13224       Subtarget->is64Bit()) {
13225     return Op;
13226   }
13227
13228   SDLoc dl(Op);
13229   unsigned Size = SrcVT.getSizeInBits()/8;
13230   MachineFunction &MF = DAG.getMachineFunction();
13231   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
13232   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13233   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13234                                StackSlot,
13235                                MachinePointerInfo::getFixedStack(SSFI),
13236                                false, false, 0);
13237   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
13238 }
13239
13240 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
13241                                      SDValue StackSlot,
13242                                      SelectionDAG &DAG) const {
13243   // Build the FILD
13244   SDLoc DL(Op);
13245   SDVTList Tys;
13246   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
13247   if (useSSE)
13248     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
13249   else
13250     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
13251
13252   unsigned ByteSize = SrcVT.getSizeInBits()/8;
13253
13254   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
13255   MachineMemOperand *MMO;
13256   if (FI) {
13257     int SSFI = FI->getIndex();
13258     MMO =
13259       DAG.getMachineFunction()
13260       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13261                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
13262   } else {
13263     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
13264     StackSlot = StackSlot.getOperand(1);
13265   }
13266   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
13267   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
13268                                            X86ISD::FILD, DL,
13269                                            Tys, Ops, SrcVT, MMO);
13270
13271   if (useSSE) {
13272     Chain = Result.getValue(1);
13273     SDValue InFlag = Result.getValue(2);
13274
13275     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
13276     // shouldn't be necessary except that RFP cannot be live across
13277     // multiple blocks. When stackifier is fixed, they can be uncoupled.
13278     MachineFunction &MF = DAG.getMachineFunction();
13279     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
13280     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
13281     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13282     Tys = DAG.getVTList(MVT::Other);
13283     SDValue Ops[] = {
13284       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
13285     };
13286     MachineMemOperand *MMO =
13287       DAG.getMachineFunction()
13288       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13289                             MachineMemOperand::MOStore, SSFISize, SSFISize);
13290
13291     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
13292                                     Ops, Op.getValueType(), MMO);
13293     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
13294                          MachinePointerInfo::getFixedStack(SSFI),
13295                          false, false, false, 0);
13296   }
13297
13298   return Result;
13299 }
13300
13301 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
13302 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
13303                                                SelectionDAG &DAG) const {
13304   // This algorithm is not obvious. Here it is what we're trying to output:
13305   /*
13306      movq       %rax,  %xmm0
13307      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
13308      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
13309      #ifdef __SSE3__
13310        haddpd   %xmm0, %xmm0
13311      #else
13312        pshufd   $0x4e, %xmm0, %xmm1
13313        addpd    %xmm1, %xmm0
13314      #endif
13315   */
13316
13317   SDLoc dl(Op);
13318   LLVMContext *Context = DAG.getContext();
13319
13320   // Build some magic constants.
13321   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
13322   Constant *C0 = ConstantDataVector::get(*Context, CV0);
13323   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
13324
13325   SmallVector<Constant*,2> CV1;
13326   CV1.push_back(
13327     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13328                                       APInt(64, 0x4330000000000000ULL))));
13329   CV1.push_back(
13330     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13331                                       APInt(64, 0x4530000000000000ULL))));
13332   Constant *C1 = ConstantVector::get(CV1);
13333   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
13334
13335   // Load the 64-bit value into an XMM register.
13336   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
13337                             Op.getOperand(0));
13338   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
13339                               MachinePointerInfo::getConstantPool(),
13340                               false, false, false, 16);
13341   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
13342                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
13343                               CLod0);
13344
13345   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
13346                               MachinePointerInfo::getConstantPool(),
13347                               false, false, false, 16);
13348   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
13349   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
13350   SDValue Result;
13351
13352   if (Subtarget->hasSSE3()) {
13353     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
13354     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
13355   } else {
13356     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
13357     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
13358                                            S2F, 0x4E, DAG);
13359     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
13360                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
13361                          Sub);
13362   }
13363
13364   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
13365                      DAG.getIntPtrConstant(0));
13366 }
13367
13368 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
13369 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
13370                                                SelectionDAG &DAG) const {
13371   SDLoc dl(Op);
13372   // FP constant to bias correct the final result.
13373   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13374                                    MVT::f64);
13375
13376   // Load the 32-bit value into an XMM register.
13377   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
13378                              Op.getOperand(0));
13379
13380   // Zero out the upper parts of the register.
13381   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
13382
13383   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13384                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
13385                      DAG.getIntPtrConstant(0));
13386
13387   // Or the load with the bias.
13388   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
13389                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13390                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13391                                                    MVT::v2f64, Load)),
13392                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13393                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13394                                                    MVT::v2f64, Bias)));
13395   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13396                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
13397                    DAG.getIntPtrConstant(0));
13398
13399   // Subtract the bias.
13400   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
13401
13402   // Handle final rounding.
13403   EVT DestVT = Op.getValueType();
13404
13405   if (DestVT.bitsLT(MVT::f64))
13406     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
13407                        DAG.getIntPtrConstant(0));
13408   if (DestVT.bitsGT(MVT::f64))
13409     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
13410
13411   // Handle final rounding.
13412   return Sub;
13413 }
13414
13415 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
13416                                      const X86Subtarget &Subtarget) {
13417   // The algorithm is the following:
13418   // #ifdef __SSE4_1__
13419   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13420   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13421   //                                 (uint4) 0x53000000, 0xaa);
13422   // #else
13423   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13424   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13425   // #endif
13426   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13427   //     return (float4) lo + fhi;
13428
13429   SDLoc DL(Op);
13430   SDValue V = Op->getOperand(0);
13431   EVT VecIntVT = V.getValueType();
13432   bool Is128 = VecIntVT == MVT::v4i32;
13433   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
13434   unsigned NumElts = VecIntVT.getVectorNumElements();
13435   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
13436          "Unsupported custom type");
13437   assert(NumElts <= 8 && "The size of the constant array must be fixed");
13438
13439   // In the #idef/#else code, we have in common:
13440   // - The vector of constants:
13441   // -- 0x4b000000
13442   // -- 0x53000000
13443   // - A shift:
13444   // -- v >> 16
13445
13446   // Create the splat vector for 0x4b000000.
13447   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
13448   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
13449                            CstLow, CstLow, CstLow, CstLow};
13450   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13451                                   makeArrayRef(&CstLowArray[0], NumElts));
13452   // Create the splat vector for 0x53000000.
13453   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
13454   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
13455                             CstHigh, CstHigh, CstHigh, CstHigh};
13456   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13457                                    makeArrayRef(&CstHighArray[0], NumElts));
13458
13459   // Create the right shift.
13460   SDValue CstShift = DAG.getConstant(16, MVT::i32);
13461   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
13462                              CstShift, CstShift, CstShift, CstShift};
13463   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13464                                     makeArrayRef(&CstShiftArray[0], NumElts));
13465   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
13466
13467   SDValue Low, High;
13468   if (Subtarget.hasSSE41()) {
13469     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
13470     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13471     SDValue VecCstLowBitcast =
13472         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
13473     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
13474     // Low will be bitcasted right away, so do not bother bitcasting back to its
13475     // original type.
13476     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
13477                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
13478     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13479     //                                 (uint4) 0x53000000, 0xaa);
13480     SDValue VecCstHighBitcast =
13481         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
13482     SDValue VecShiftBitcast =
13483         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
13484     // High will be bitcasted right away, so do not bother bitcasting back to
13485     // its original type.
13486     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
13487                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
13488   } else {
13489     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
13490     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13491                                      CstMask, CstMask, CstMask);
13492     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13493     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13494     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13495
13496     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13497     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13498   }
13499
13500   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13501   SDValue CstFAdd = DAG.getConstantFP(
13502       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
13503   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13504                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13505   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13506                                    makeArrayRef(&CstFAddArray[0], NumElts));
13507
13508   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13509   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
13510   SDValue FHigh =
13511       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13512   //     return (float4) lo + fhi;
13513   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
13514   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13515 }
13516
13517 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13518                                                SelectionDAG &DAG) const {
13519   SDValue N0 = Op.getOperand(0);
13520   MVT SVT = N0.getSimpleValueType();
13521   SDLoc dl(Op);
13522
13523   switch (SVT.SimpleTy) {
13524   default:
13525     llvm_unreachable("Custom UINT_TO_FP is not supported!");
13526   case MVT::v4i8:
13527   case MVT::v4i16:
13528   case MVT::v8i8:
13529   case MVT::v8i16: {
13530     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13531     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13532                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13533   }
13534   case MVT::v4i32:
13535   case MVT::v8i32:
13536     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13537   }
13538   llvm_unreachable(nullptr);
13539 }
13540
13541 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13542                                            SelectionDAG &DAG) const {
13543   SDValue N0 = Op.getOperand(0);
13544   SDLoc dl(Op);
13545
13546   if (Op.getValueType().isVector())
13547     return lowerUINT_TO_FP_vec(Op, DAG);
13548
13549   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13550   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13551   // the optimization here.
13552   if (DAG.SignBitIsZero(N0))
13553     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13554
13555   MVT SrcVT = N0.getSimpleValueType();
13556   MVT DstVT = Op.getSimpleValueType();
13557   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13558     return LowerUINT_TO_FP_i64(Op, DAG);
13559   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13560     return LowerUINT_TO_FP_i32(Op, DAG);
13561   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13562     return SDValue();
13563
13564   // Make a 64-bit buffer, and use it to build an FILD.
13565   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13566   if (SrcVT == MVT::i32) {
13567     SDValue WordOff = DAG.getConstant(4, getPointerTy());
13568     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
13569                                      getPointerTy(), StackSlot, WordOff);
13570     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13571                                   StackSlot, MachinePointerInfo(),
13572                                   false, false, 0);
13573     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
13574                                   OffsetSlot, MachinePointerInfo(),
13575                                   false, false, 0);
13576     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13577     return Fild;
13578   }
13579
13580   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13581   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13582                                StackSlot, MachinePointerInfo(),
13583                                false, false, 0);
13584   // For i64 source, we need to add the appropriate power of 2 if the input
13585   // was negative.  This is the same as the optimization in
13586   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13587   // we must be careful to do the computation in x87 extended precision, not
13588   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13589   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13590   MachineMemOperand *MMO =
13591     DAG.getMachineFunction()
13592     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13593                           MachineMemOperand::MOLoad, 8, 8);
13594
13595   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13596   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13597   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13598                                          MVT::i64, MMO);
13599
13600   APInt FF(32, 0x5F800000ULL);
13601
13602   // Check whether the sign bit is set.
13603   SDValue SignSet = DAG.getSetCC(dl,
13604                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
13605                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
13606                                  ISD::SETLT);
13607
13608   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13609   SDValue FudgePtr = DAG.getConstantPool(
13610                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
13611                                          getPointerTy());
13612
13613   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13614   SDValue Zero = DAG.getIntPtrConstant(0);
13615   SDValue Four = DAG.getIntPtrConstant(4);
13616   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13617                                Zero, Four);
13618   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
13619
13620   // Load the value out, extending it from f32 to f80.
13621   // FIXME: Avoid the extend by constructing the right constant pool?
13622   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
13623                                  FudgePtr, MachinePointerInfo::getConstantPool(),
13624                                  MVT::f32, false, false, false, 4);
13625   // Extend everything to 80 bits to force it to be done on x87.
13626   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13627   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
13628 }
13629
13630 std::pair<SDValue,SDValue>
13631 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13632                                     bool IsSigned, bool IsReplace) const {
13633   SDLoc DL(Op);
13634
13635   EVT DstTy = Op.getValueType();
13636
13637   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
13638     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13639     DstTy = MVT::i64;
13640   }
13641
13642   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13643          DstTy.getSimpleVT() >= MVT::i16 &&
13644          "Unknown FP_TO_INT to lower!");
13645
13646   // These are really Legal.
13647   if (DstTy == MVT::i32 &&
13648       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13649     return std::make_pair(SDValue(), SDValue());
13650   if (Subtarget->is64Bit() &&
13651       DstTy == MVT::i64 &&
13652       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13653     return std::make_pair(SDValue(), SDValue());
13654
13655   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
13656   // stack slot, or into the FTOL runtime function.
13657   MachineFunction &MF = DAG.getMachineFunction();
13658   unsigned MemSize = DstTy.getSizeInBits()/8;
13659   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13660   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13661
13662   unsigned Opc;
13663   if (!IsSigned && isIntegerTypeFTOL(DstTy))
13664     Opc = X86ISD::WIN_FTOL;
13665   else
13666     switch (DstTy.getSimpleVT().SimpleTy) {
13667     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13668     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13669     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13670     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13671     }
13672
13673   SDValue Chain = DAG.getEntryNode();
13674   SDValue Value = Op.getOperand(0);
13675   EVT TheVT = Op.getOperand(0).getValueType();
13676   // FIXME This causes a redundant load/store if the SSE-class value is already
13677   // in memory, such as if it is on the callstack.
13678   if (isScalarFPTypeInSSEReg(TheVT)) {
13679     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13680     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13681                          MachinePointerInfo::getFixedStack(SSFI),
13682                          false, false, 0);
13683     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13684     SDValue Ops[] = {
13685       Chain, StackSlot, DAG.getValueType(TheVT)
13686     };
13687
13688     MachineMemOperand *MMO =
13689       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13690                               MachineMemOperand::MOLoad, MemSize, MemSize);
13691     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13692     Chain = Value.getValue(1);
13693     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13694     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13695   }
13696
13697   MachineMemOperand *MMO =
13698     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13699                             MachineMemOperand::MOStore, MemSize, MemSize);
13700
13701   if (Opc != X86ISD::WIN_FTOL) {
13702     // Build the FP_TO_INT*_IN_MEM
13703     SDValue Ops[] = { Chain, Value, StackSlot };
13704     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13705                                            Ops, DstTy, MMO);
13706     return std::make_pair(FIST, StackSlot);
13707   } else {
13708     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
13709       DAG.getVTList(MVT::Other, MVT::Glue),
13710       Chain, Value);
13711     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
13712       MVT::i32, ftol.getValue(1));
13713     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
13714       MVT::i32, eax.getValue(2));
13715     SDValue Ops[] = { eax, edx };
13716     SDValue pair = IsReplace
13717       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
13718       : DAG.getMergeValues(Ops, DL);
13719     return std::make_pair(pair, SDValue());
13720   }
13721 }
13722
13723 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13724                               const X86Subtarget *Subtarget) {
13725   MVT VT = Op->getSimpleValueType(0);
13726   SDValue In = Op->getOperand(0);
13727   MVT InVT = In.getSimpleValueType();
13728   SDLoc dl(Op);
13729
13730   // Optimize vectors in AVX mode:
13731   //
13732   //   v8i16 -> v8i32
13733   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13734   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13735   //   Concat upper and lower parts.
13736   //
13737   //   v4i32 -> v4i64
13738   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13739   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13740   //   Concat upper and lower parts.
13741   //
13742
13743   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13744       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13745       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13746     return SDValue();
13747
13748   if (Subtarget->hasInt256())
13749     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13750
13751   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13752   SDValue Undef = DAG.getUNDEF(InVT);
13753   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13754   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13755   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13756
13757   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13758                              VT.getVectorNumElements()/2);
13759
13760   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
13761   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
13762
13763   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13764 }
13765
13766 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13767                                         SelectionDAG &DAG) {
13768   MVT VT = Op->getSimpleValueType(0);
13769   SDValue In = Op->getOperand(0);
13770   MVT InVT = In.getSimpleValueType();
13771   SDLoc DL(Op);
13772   unsigned int NumElts = VT.getVectorNumElements();
13773   if (NumElts != 8 && NumElts != 16)
13774     return SDValue();
13775
13776   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13777     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13778
13779   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
13780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13781   // Now we have only mask extension
13782   assert(InVT.getVectorElementType() == MVT::i1);
13783   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
13784   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
13785   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13786   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13787   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
13788                            MachinePointerInfo::getConstantPool(),
13789                            false, false, false, Alignment);
13790
13791   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
13792   if (VT.is512BitVector())
13793     return Brcst;
13794   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
13795 }
13796
13797 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13798                                SelectionDAG &DAG) {
13799   if (Subtarget->hasFp256()) {
13800     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
13801     if (Res.getNode())
13802       return Res;
13803   }
13804
13805   return SDValue();
13806 }
13807
13808 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13809                                 SelectionDAG &DAG) {
13810   SDLoc DL(Op);
13811   MVT VT = Op.getSimpleValueType();
13812   SDValue In = Op.getOperand(0);
13813   MVT SVT = In.getSimpleValueType();
13814
13815   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13816     return LowerZERO_EXTEND_AVX512(Op, DAG);
13817
13818   if (Subtarget->hasFp256()) {
13819     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
13820     if (Res.getNode())
13821       return Res;
13822   }
13823
13824   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13825          VT.getVectorNumElements() != SVT.getVectorNumElements());
13826   return SDValue();
13827 }
13828
13829 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13830   SDLoc DL(Op);
13831   MVT VT = Op.getSimpleValueType();
13832   SDValue In = Op.getOperand(0);
13833   MVT InVT = In.getSimpleValueType();
13834
13835   if (VT == MVT::i1) {
13836     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13837            "Invalid scalar TRUNCATE operation");
13838     if (InVT.getSizeInBits() >= 32)
13839       return SDValue();
13840     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13841     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13842   }
13843   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13844          "Invalid TRUNCATE operation");
13845
13846   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
13847     if (VT.getVectorElementType().getSizeInBits() >=8)
13848       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13849
13850     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13851     unsigned NumElts = InVT.getVectorNumElements();
13852     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13853     if (InVT.getSizeInBits() < 512) {
13854       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13855       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13856       InVT = ExtVT;
13857     }
13858     
13859     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
13860     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
13861     SDValue CP = DAG.getConstantPool(C, getPointerTy());
13862     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13863     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
13864                            MachinePointerInfo::getConstantPool(),
13865                            false, false, false, Alignment);
13866     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
13867     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13868     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13869   }
13870
13871   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13872     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13873     if (Subtarget->hasInt256()) {
13874       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13875       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
13876       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13877                                 ShufMask);
13878       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13879                          DAG.getIntPtrConstant(0));
13880     }
13881
13882     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13883                                DAG.getIntPtrConstant(0));
13884     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13885                                DAG.getIntPtrConstant(2));
13886     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
13887     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
13888     static const int ShufMask[] = {0, 2, 4, 6};
13889     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13890   }
13891
13892   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13893     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13894     if (Subtarget->hasInt256()) {
13895       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
13896
13897       SmallVector<SDValue,32> pshufbMask;
13898       for (unsigned i = 0; i < 2; ++i) {
13899         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13900         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13901         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13902         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13903         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13904         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13905         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13906         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13907         for (unsigned j = 0; j < 8; ++j)
13908           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13909       }
13910       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13911       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13912       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
13913
13914       static const int ShufMask[] = {0,  2,  -1,  -1};
13915       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13916                                 &ShufMask[0]);
13917       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13918                        DAG.getIntPtrConstant(0));
13919       return DAG.getNode(ISD::BITCAST, DL, VT, In);
13920     }
13921
13922     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13923                                DAG.getIntPtrConstant(0));
13924
13925     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13926                                DAG.getIntPtrConstant(4));
13927
13928     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
13929     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
13930
13931     // The PSHUFB mask:
13932     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13933                                    -1, -1, -1, -1, -1, -1, -1, -1};
13934
13935     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13936     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13937     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13938
13939     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
13940     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
13941
13942     // The MOVLHPS Mask:
13943     static const int ShufMask2[] = {0, 1, 4, 5};
13944     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13945     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
13946   }
13947
13948   // Handle truncation of V256 to V128 using shuffles.
13949   if (!VT.is128BitVector() || !InVT.is256BitVector())
13950     return SDValue();
13951
13952   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13953
13954   unsigned NumElems = VT.getVectorNumElements();
13955   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13956
13957   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13958   // Prepare truncation shuffle mask
13959   for (unsigned i = 0; i != NumElems; ++i)
13960     MaskVec[i] = i * 2;
13961   SDValue V = DAG.getVectorShuffle(NVT, DL,
13962                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
13963                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13964   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13965                      DAG.getIntPtrConstant(0));
13966 }
13967
13968 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13969                                            SelectionDAG &DAG) const {
13970   assert(!Op.getSimpleValueType().isVector());
13971
13972   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13973     /*IsSigned=*/ true, /*IsReplace=*/ false);
13974   SDValue FIST = Vals.first, StackSlot = Vals.second;
13975   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13976   if (!FIST.getNode()) return Op;
13977
13978   if (StackSlot.getNode())
13979     // Load the result.
13980     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13981                        FIST, StackSlot, MachinePointerInfo(),
13982                        false, false, false, 0);
13983
13984   // The node is the result.
13985   return FIST;
13986 }
13987
13988 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13989                                            SelectionDAG &DAG) const {
13990   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13991     /*IsSigned=*/ false, /*IsReplace=*/ false);
13992   SDValue FIST = Vals.first, StackSlot = Vals.second;
13993   assert(FIST.getNode() && "Unexpected failure");
13994
13995   if (StackSlot.getNode())
13996     // Load the result.
13997     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13998                        FIST, StackSlot, MachinePointerInfo(),
13999                        false, false, false, 0);
14000
14001   // The node is the result.
14002   return FIST;
14003 }
14004
14005 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
14006   SDLoc DL(Op);
14007   MVT VT = Op.getSimpleValueType();
14008   SDValue In = Op.getOperand(0);
14009   MVT SVT = In.getSimpleValueType();
14010
14011   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
14012
14013   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
14014                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
14015                                  In, DAG.getUNDEF(SVT)));
14016 }
14017
14018 /// The only differences between FABS and FNEG are the mask and the logic op.
14019 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
14020 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
14021   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
14022          "Wrong opcode for lowering FABS or FNEG.");
14023
14024   bool IsFABS = (Op.getOpcode() == ISD::FABS);
14025
14026   // If this is a FABS and it has an FNEG user, bail out to fold the combination
14027   // into an FNABS. We'll lower the FABS after that if it is still in use.
14028   if (IsFABS)
14029     for (SDNode *User : Op->uses())
14030       if (User->getOpcode() == ISD::FNEG)
14031         return Op;
14032
14033   SDValue Op0 = Op.getOperand(0);
14034   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
14035
14036   SDLoc dl(Op);
14037   MVT VT = Op.getSimpleValueType();
14038   // Assume scalar op for initialization; update for vector if needed.
14039   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
14040   // generate a 16-byte vector constant and logic op even for the scalar case.
14041   // Using a 16-byte mask allows folding the load of the mask with
14042   // the logic op, so it can save (~4 bytes) on code size.
14043   MVT EltVT = VT;
14044   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
14045   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
14046   // decide if we should generate a 16-byte constant mask when we only need 4 or
14047   // 8 bytes for the scalar case.
14048   if (VT.isVector()) {
14049     EltVT = VT.getVectorElementType();
14050     NumElts = VT.getVectorNumElements();
14051   }
14052   
14053   unsigned EltBits = EltVT.getSizeInBits();
14054   LLVMContext *Context = DAG.getContext();
14055   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
14056   APInt MaskElt =
14057     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
14058   Constant *C = ConstantInt::get(*Context, MaskElt);
14059   C = ConstantVector::getSplat(NumElts, C);
14060   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14061   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
14062   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14063   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14064                              MachinePointerInfo::getConstantPool(),
14065                              false, false, false, Alignment);
14066
14067   if (VT.isVector()) {
14068     // For a vector, cast operands to a vector type, perform the logic op,
14069     // and cast the result back to the original value type.
14070     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
14071     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
14072     SDValue Operand = IsFNABS ?
14073       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
14074       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
14075     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
14076     return DAG.getNode(ISD::BITCAST, dl, VT,
14077                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
14078   }
14079   
14080   // If not vector, then scalar.
14081   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
14082   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
14083   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
14084 }
14085
14086 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
14087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14088   LLVMContext *Context = DAG.getContext();
14089   SDValue Op0 = Op.getOperand(0);
14090   SDValue Op1 = Op.getOperand(1);
14091   SDLoc dl(Op);
14092   MVT VT = Op.getSimpleValueType();
14093   MVT SrcVT = Op1.getSimpleValueType();
14094
14095   // If second operand is smaller, extend it first.
14096   if (SrcVT.bitsLT(VT)) {
14097     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
14098     SrcVT = VT;
14099   }
14100   // And if it is bigger, shrink it first.
14101   if (SrcVT.bitsGT(VT)) {
14102     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
14103     SrcVT = VT;
14104   }
14105
14106   // At this point the operands and the result should have the same
14107   // type, and that won't be f80 since that is not custom lowered.
14108
14109   // First get the sign bit of second operand.
14110   SmallVector<Constant*,4> CV;
14111   if (SrcVT == MVT::f64) {
14112     const fltSemantics &Sem = APFloat::IEEEdouble;
14113     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
14114     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
14115   } else {
14116     const fltSemantics &Sem = APFloat::IEEEsingle;
14117     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
14118     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14119     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14120     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14121   }
14122   Constant *C = ConstantVector::get(CV);
14123   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14124   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
14125                               MachinePointerInfo::getConstantPool(),
14126                               false, false, false, 16);
14127   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
14128
14129   // Shift sign bit right or left if the two operands have different types.
14130   if (SrcVT.bitsGT(VT)) {
14131     // Op0 is MVT::f32, Op1 is MVT::f64.
14132     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
14133     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
14134                           DAG.getConstant(32, MVT::i32));
14135     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
14136     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
14137                           DAG.getIntPtrConstant(0));
14138   }
14139
14140   // Clear first operand sign bit.
14141   CV.clear();
14142   if (VT == MVT::f64) {
14143     const fltSemantics &Sem = APFloat::IEEEdouble;
14144     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
14145                                                    APInt(64, ~(1ULL << 63)))));
14146     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
14147   } else {
14148     const fltSemantics &Sem = APFloat::IEEEsingle;
14149     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
14150                                                    APInt(32, ~(1U << 31)))));
14151     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14152     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14153     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14154   }
14155   C = ConstantVector::get(CV);
14156   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14157   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14158                               MachinePointerInfo::getConstantPool(),
14159                               false, false, false, 16);
14160   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
14161
14162   // Or the value with the sign bit.
14163   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
14164 }
14165
14166 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
14167   SDValue N0 = Op.getOperand(0);
14168   SDLoc dl(Op);
14169   MVT VT = Op.getSimpleValueType();
14170
14171   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
14172   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
14173                                   DAG.getConstant(1, VT));
14174   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
14175 }
14176
14177 // Check whether an OR'd tree is PTEST-able.
14178 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
14179                                       SelectionDAG &DAG) {
14180   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
14181
14182   if (!Subtarget->hasSSE41())
14183     return SDValue();
14184
14185   if (!Op->hasOneUse())
14186     return SDValue();
14187
14188   SDNode *N = Op.getNode();
14189   SDLoc DL(N);
14190
14191   SmallVector<SDValue, 8> Opnds;
14192   DenseMap<SDValue, unsigned> VecInMap;
14193   SmallVector<SDValue, 8> VecIns;
14194   EVT VT = MVT::Other;
14195
14196   // Recognize a special case where a vector is casted into wide integer to
14197   // test all 0s.
14198   Opnds.push_back(N->getOperand(0));
14199   Opnds.push_back(N->getOperand(1));
14200
14201   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14202     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
14203     // BFS traverse all OR'd operands.
14204     if (I->getOpcode() == ISD::OR) {
14205       Opnds.push_back(I->getOperand(0));
14206       Opnds.push_back(I->getOperand(1));
14207       // Re-evaluate the number of nodes to be traversed.
14208       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14209       continue;
14210     }
14211
14212     // Quit if a non-EXTRACT_VECTOR_ELT
14213     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14214       return SDValue();
14215
14216     // Quit if without a constant index.
14217     SDValue Idx = I->getOperand(1);
14218     if (!isa<ConstantSDNode>(Idx))
14219       return SDValue();
14220
14221     SDValue ExtractedFromVec = I->getOperand(0);
14222     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
14223     if (M == VecInMap.end()) {
14224       VT = ExtractedFromVec.getValueType();
14225       // Quit if not 128/256-bit vector.
14226       if (!VT.is128BitVector() && !VT.is256BitVector())
14227         return SDValue();
14228       // Quit if not the same type.
14229       if (VecInMap.begin() != VecInMap.end() &&
14230           VT != VecInMap.begin()->first.getValueType())
14231         return SDValue();
14232       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
14233       VecIns.push_back(ExtractedFromVec);
14234     }
14235     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14236   }
14237
14238   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14239          "Not extracted from 128-/256-bit vector.");
14240
14241   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
14242
14243   for (DenseMap<SDValue, unsigned>::const_iterator
14244         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
14245     // Quit if not all elements are used.
14246     if (I->second != FullMask)
14247       return SDValue();
14248   }
14249
14250   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
14251
14252   // Cast all vectors into TestVT for PTEST.
14253   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
14254     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
14255
14256   // If more than one full vectors are evaluated, OR them first before PTEST.
14257   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
14258     // Each iteration will OR 2 nodes and append the result until there is only
14259     // 1 node left, i.e. the final OR'd value of all vectors.
14260     SDValue LHS = VecIns[Slot];
14261     SDValue RHS = VecIns[Slot + 1];
14262     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
14263   }
14264
14265   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
14266                      VecIns.back(), VecIns.back());
14267 }
14268
14269 /// \brief return true if \c Op has a use that doesn't just read flags.
14270 static bool hasNonFlagsUse(SDValue Op) {
14271   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
14272        ++UI) {
14273     SDNode *User = *UI;
14274     unsigned UOpNo = UI.getOperandNo();
14275     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
14276       // Look pass truncate.
14277       UOpNo = User->use_begin().getOperandNo();
14278       User = *User->use_begin();
14279     }
14280
14281     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
14282         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
14283       return true;
14284   }
14285   return false;
14286 }
14287
14288 /// Emit nodes that will be selected as "test Op0,Op0", or something
14289 /// equivalent.
14290 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
14291                                     SelectionDAG &DAG) const {
14292   if (Op.getValueType() == MVT::i1)
14293     // KORTEST instruction should be selected
14294     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14295                        DAG.getConstant(0, Op.getValueType()));
14296
14297   // CF and OF aren't always set the way we want. Determine which
14298   // of these we need.
14299   bool NeedCF = false;
14300   bool NeedOF = false;
14301   switch (X86CC) {
14302   default: break;
14303   case X86::COND_A: case X86::COND_AE:
14304   case X86::COND_B: case X86::COND_BE:
14305     NeedCF = true;
14306     break;
14307   case X86::COND_G: case X86::COND_GE:
14308   case X86::COND_L: case X86::COND_LE:
14309   case X86::COND_O: case X86::COND_NO: {
14310     // Check if we really need to set the
14311     // Overflow flag. If NoSignedWrap is present
14312     // that is not actually needed.
14313     switch (Op->getOpcode()) {
14314     case ISD::ADD:
14315     case ISD::SUB:
14316     case ISD::MUL:
14317     case ISD::SHL: {
14318       const BinaryWithFlagsSDNode *BinNode =
14319           cast<BinaryWithFlagsSDNode>(Op.getNode());
14320       if (BinNode->hasNoSignedWrap())
14321         break;
14322     }
14323     default:
14324       NeedOF = true;
14325       break;
14326     }
14327     break;
14328   }
14329   }
14330   // See if we can use the EFLAGS value from the operand instead of
14331   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14332   // we prove that the arithmetic won't overflow, we can't use OF or CF.
14333   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14334     // Emit a CMP with 0, which is the TEST pattern.
14335     //if (Op.getValueType() == MVT::i1)
14336     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14337     //                     DAG.getConstant(0, MVT::i1));
14338     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14339                        DAG.getConstant(0, Op.getValueType()));
14340   }
14341   unsigned Opcode = 0;
14342   unsigned NumOperands = 0;
14343
14344   // Truncate operations may prevent the merge of the SETCC instruction
14345   // and the arithmetic instruction before it. Attempt to truncate the operands
14346   // of the arithmetic instruction and use a reduced bit-width instruction.
14347   bool NeedTruncation = false;
14348   SDValue ArithOp = Op;
14349   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14350     SDValue Arith = Op->getOperand(0);
14351     // Both the trunc and the arithmetic op need to have one user each.
14352     if (Arith->hasOneUse())
14353       switch (Arith.getOpcode()) {
14354         default: break;
14355         case ISD::ADD:
14356         case ISD::SUB:
14357         case ISD::AND:
14358         case ISD::OR:
14359         case ISD::XOR: {
14360           NeedTruncation = true;
14361           ArithOp = Arith;
14362         }
14363       }
14364   }
14365
14366   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14367   // which may be the result of a CAST.  We use the variable 'Op', which is the
14368   // non-casted variable when we check for possible users.
14369   switch (ArithOp.getOpcode()) {
14370   case ISD::ADD:
14371     // Due to an isel shortcoming, be conservative if this add is likely to be
14372     // selected as part of a load-modify-store instruction. When the root node
14373     // in a match is a store, isel doesn't know how to remap non-chain non-flag
14374     // uses of other nodes in the match, such as the ADD in this case. This
14375     // leads to the ADD being left around and reselected, with the result being
14376     // two adds in the output.  Alas, even if none our users are stores, that
14377     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
14378     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
14379     // climbing the DAG back to the root, and it doesn't seem to be worth the
14380     // effort.
14381     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14382          UE = Op.getNode()->use_end(); UI != UE; ++UI)
14383       if (UI->getOpcode() != ISD::CopyToReg &&
14384           UI->getOpcode() != ISD::SETCC &&
14385           UI->getOpcode() != ISD::STORE)
14386         goto default_case;
14387
14388     if (ConstantSDNode *C =
14389         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14390       // An add of one will be selected as an INC.
14391       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
14392         Opcode = X86ISD::INC;
14393         NumOperands = 1;
14394         break;
14395       }
14396
14397       // An add of negative one (subtract of one) will be selected as a DEC.
14398       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
14399         Opcode = X86ISD::DEC;
14400         NumOperands = 1;
14401         break;
14402       }
14403     }
14404
14405     // Otherwise use a regular EFLAGS-setting add.
14406     Opcode = X86ISD::ADD;
14407     NumOperands = 2;
14408     break;
14409   case ISD::SHL:
14410   case ISD::SRL:
14411     // If we have a constant logical shift that's only used in a comparison
14412     // against zero turn it into an equivalent AND. This allows turning it into
14413     // a TEST instruction later.
14414     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14415         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14416       EVT VT = Op.getValueType();
14417       unsigned BitWidth = VT.getSizeInBits();
14418       unsigned ShAmt = Op->getConstantOperandVal(1);
14419       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14420         break;
14421       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14422                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14423                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14424       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14425         break;
14426       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14427                                 DAG.getConstant(Mask, VT));
14428       DAG.ReplaceAllUsesWith(Op, New);
14429       Op = New;
14430     }
14431     break;
14432
14433   case ISD::AND:
14434     // If the primary and result isn't used, don't bother using X86ISD::AND,
14435     // because a TEST instruction will be better.
14436     if (!hasNonFlagsUse(Op))
14437       break;
14438     // FALL THROUGH
14439   case ISD::SUB:
14440   case ISD::OR:
14441   case ISD::XOR:
14442     // Due to the ISEL shortcoming noted above, be conservative if this op is
14443     // likely to be selected as part of a load-modify-store instruction.
14444     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14445            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14446       if (UI->getOpcode() == ISD::STORE)
14447         goto default_case;
14448
14449     // Otherwise use a regular EFLAGS-setting instruction.
14450     switch (ArithOp.getOpcode()) {
14451     default: llvm_unreachable("unexpected operator!");
14452     case ISD::SUB: Opcode = X86ISD::SUB; break;
14453     case ISD::XOR: Opcode = X86ISD::XOR; break;
14454     case ISD::AND: Opcode = X86ISD::AND; break;
14455     case ISD::OR: {
14456       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14457         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14458         if (EFLAGS.getNode())
14459           return EFLAGS;
14460       }
14461       Opcode = X86ISD::OR;
14462       break;
14463     }
14464     }
14465
14466     NumOperands = 2;
14467     break;
14468   case X86ISD::ADD:
14469   case X86ISD::SUB:
14470   case X86ISD::INC:
14471   case X86ISD::DEC:
14472   case X86ISD::OR:
14473   case X86ISD::XOR:
14474   case X86ISD::AND:
14475     return SDValue(Op.getNode(), 1);
14476   default:
14477   default_case:
14478     break;
14479   }
14480
14481   // If we found that truncation is beneficial, perform the truncation and
14482   // update 'Op'.
14483   if (NeedTruncation) {
14484     EVT VT = Op.getValueType();
14485     SDValue WideVal = Op->getOperand(0);
14486     EVT WideVT = WideVal.getValueType();
14487     unsigned ConvertedOp = 0;
14488     // Use a target machine opcode to prevent further DAGCombine
14489     // optimizations that may separate the arithmetic operations
14490     // from the setcc node.
14491     switch (WideVal.getOpcode()) {
14492       default: break;
14493       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14494       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14495       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14496       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14497       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14498     }
14499
14500     if (ConvertedOp) {
14501       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14502       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14503         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14504         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14505         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14506       }
14507     }
14508   }
14509
14510   if (Opcode == 0)
14511     // Emit a CMP with 0, which is the TEST pattern.
14512     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14513                        DAG.getConstant(0, Op.getValueType()));
14514
14515   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14516   SmallVector<SDValue, 4> Ops;
14517   for (unsigned i = 0; i != NumOperands; ++i)
14518     Ops.push_back(Op.getOperand(i));
14519
14520   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14521   DAG.ReplaceAllUsesWith(Op, New);
14522   return SDValue(New.getNode(), 1);
14523 }
14524
14525 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14526 /// equivalent.
14527 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14528                                    SDLoc dl, SelectionDAG &DAG) const {
14529   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
14530     if (C->getAPIntValue() == 0)
14531       return EmitTest(Op0, X86CC, dl, DAG);
14532
14533      if (Op0.getValueType() == MVT::i1)
14534        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
14535   }
14536  
14537   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14538        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14539     // Do the comparison at i32 if it's smaller, besides the Atom case. 
14540     // This avoids subregister aliasing issues. Keep the smaller reference 
14541     // if we're optimizing for size, however, as that'll allow better folding 
14542     // of memory operations.
14543     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14544         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
14545              AttributeSet::FunctionIndex, Attribute::MinSize) &&
14546         !Subtarget->isAtom()) {
14547       unsigned ExtendOp =
14548           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14549       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14550       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14551     }
14552     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14553     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14554     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14555                               Op0, Op1);
14556     return SDValue(Sub.getNode(), 1);
14557   }
14558   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14559 }
14560
14561 /// Convert a comparison if required by the subtarget.
14562 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14563                                                  SelectionDAG &DAG) const {
14564   // If the subtarget does not support the FUCOMI instruction, floating-point
14565   // comparisons have to be converted.
14566   if (Subtarget->hasCMov() ||
14567       Cmp.getOpcode() != X86ISD::CMP ||
14568       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14569       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14570     return Cmp;
14571
14572   // The instruction selector will select an FUCOM instruction instead of
14573   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14574   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14575   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14576   SDLoc dl(Cmp);
14577   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14578   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14579   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14580                             DAG.getConstant(8, MVT::i8));
14581   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14582   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14583 }
14584
14585 /// The minimum architected relative accuracy is 2^-12. We need one
14586 /// Newton-Raphson step to have a good float result (24 bits of precision).
14587 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14588                                             DAGCombinerInfo &DCI,
14589                                             unsigned &RefinementSteps,
14590                                             bool &UseOneConstNR) const {
14591   // FIXME: We should use instruction latency models to calculate the cost of
14592   // each potential sequence, but this is very hard to do reliably because
14593   // at least Intel's Core* chips have variable timing based on the number of
14594   // significant digits in the divisor and/or sqrt operand.
14595   if (!Subtarget->useSqrtEst())
14596     return SDValue();
14597
14598   EVT VT = Op.getValueType();
14599   
14600   // SSE1 has rsqrtss and rsqrtps.
14601   // TODO: Add support for AVX512 (v16f32).
14602   // It is likely not profitable to do this for f64 because a double-precision
14603   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14604   // instructions: convert to single, rsqrtss, convert back to double, refine
14605   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14606   // along with FMA, this could be a throughput win.
14607   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14608       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14609     RefinementSteps = 1;
14610     UseOneConstNR = false;
14611     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14612   }
14613   return SDValue();
14614 }
14615
14616 /// The minimum architected relative accuracy is 2^-12. We need one
14617 /// Newton-Raphson step to have a good float result (24 bits of precision).
14618 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14619                                             DAGCombinerInfo &DCI,
14620                                             unsigned &RefinementSteps) const {
14621   // FIXME: We should use instruction latency models to calculate the cost of
14622   // each potential sequence, but this is very hard to do reliably because
14623   // at least Intel's Core* chips have variable timing based on the number of
14624   // significant digits in the divisor.
14625   if (!Subtarget->useReciprocalEst())
14626     return SDValue();
14627   
14628   EVT VT = Op.getValueType();
14629   
14630   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14631   // TODO: Add support for AVX512 (v16f32).
14632   // It is likely not profitable to do this for f64 because a double-precision
14633   // reciprocal estimate with refinement on x86 prior to FMA requires
14634   // 15 instructions: convert to single, rcpss, convert back to double, refine
14635   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14636   // along with FMA, this could be a throughput win.
14637   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14638       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14639     RefinementSteps = ReciprocalEstimateRefinementSteps;
14640     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14641   }
14642   return SDValue();
14643 }
14644
14645 static bool isAllOnes(SDValue V) {
14646   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
14647   return C && C->isAllOnesValue();
14648 }
14649
14650 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14651 /// if it's possible.
14652 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14653                                      SDLoc dl, SelectionDAG &DAG) const {
14654   SDValue Op0 = And.getOperand(0);
14655   SDValue Op1 = And.getOperand(1);
14656   if (Op0.getOpcode() == ISD::TRUNCATE)
14657     Op0 = Op0.getOperand(0);
14658   if (Op1.getOpcode() == ISD::TRUNCATE)
14659     Op1 = Op1.getOperand(0);
14660
14661   SDValue LHS, RHS;
14662   if (Op1.getOpcode() == ISD::SHL)
14663     std::swap(Op0, Op1);
14664   if (Op0.getOpcode() == ISD::SHL) {
14665     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
14666       if (And00C->getZExtValue() == 1) {
14667         // If we looked past a truncate, check that it's only truncating away
14668         // known zeros.
14669         unsigned BitWidth = Op0.getValueSizeInBits();
14670         unsigned AndBitWidth = And.getValueSizeInBits();
14671         if (BitWidth > AndBitWidth) {
14672           APInt Zeros, Ones;
14673           DAG.computeKnownBits(Op0, Zeros, Ones);
14674           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14675             return SDValue();
14676         }
14677         LHS = Op1;
14678         RHS = Op0.getOperand(1);
14679       }
14680   } else if (Op1.getOpcode() == ISD::Constant) {
14681     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14682     uint64_t AndRHSVal = AndRHS->getZExtValue();
14683     SDValue AndLHS = Op0;
14684
14685     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14686       LHS = AndLHS.getOperand(0);
14687       RHS = AndLHS.getOperand(1);
14688     }
14689
14690     // Use BT if the immediate can't be encoded in a TEST instruction.
14691     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14692       LHS = AndLHS;
14693       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
14694     }
14695   }
14696
14697   if (LHS.getNode()) {
14698     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14699     // instruction.  Since the shift amount is in-range-or-undefined, we know
14700     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14701     // the encoding for the i16 version is larger than the i32 version.
14702     // Also promote i16 to i32 for performance / code size reason.
14703     if (LHS.getValueType() == MVT::i8 ||
14704         LHS.getValueType() == MVT::i16)
14705       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14706
14707     // If the operand types disagree, extend the shift amount to match.  Since
14708     // BT ignores high bits (like shifts) we can use anyextend.
14709     if (LHS.getValueType() != RHS.getValueType())
14710       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14711
14712     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14713     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14714     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14715                        DAG.getConstant(Cond, MVT::i8), BT);
14716   }
14717
14718   return SDValue();
14719 }
14720
14721 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14722 /// mask CMPs.
14723 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14724                               SDValue &Op1) {
14725   unsigned SSECC;
14726   bool Swap = false;
14727
14728   // SSE Condition code mapping:
14729   //  0 - EQ
14730   //  1 - LT
14731   //  2 - LE
14732   //  3 - UNORD
14733   //  4 - NEQ
14734   //  5 - NLT
14735   //  6 - NLE
14736   //  7 - ORD
14737   switch (SetCCOpcode) {
14738   default: llvm_unreachable("Unexpected SETCC condition");
14739   case ISD::SETOEQ:
14740   case ISD::SETEQ:  SSECC = 0; break;
14741   case ISD::SETOGT:
14742   case ISD::SETGT:  Swap = true; // Fallthrough
14743   case ISD::SETLT:
14744   case ISD::SETOLT: SSECC = 1; break;
14745   case ISD::SETOGE:
14746   case ISD::SETGE:  Swap = true; // Fallthrough
14747   case ISD::SETLE:
14748   case ISD::SETOLE: SSECC = 2; break;
14749   case ISD::SETUO:  SSECC = 3; break;
14750   case ISD::SETUNE:
14751   case ISD::SETNE:  SSECC = 4; break;
14752   case ISD::SETULE: Swap = true; // Fallthrough
14753   case ISD::SETUGE: SSECC = 5; break;
14754   case ISD::SETULT: Swap = true; // Fallthrough
14755   case ISD::SETUGT: SSECC = 6; break;
14756   case ISD::SETO:   SSECC = 7; break;
14757   case ISD::SETUEQ:
14758   case ISD::SETONE: SSECC = 8; break;
14759   }
14760   if (Swap)
14761     std::swap(Op0, Op1);
14762
14763   return SSECC;
14764 }
14765
14766 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14767 // ones, and then concatenate the result back.
14768 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14769   MVT VT = Op.getSimpleValueType();
14770
14771   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14772          "Unsupported value type for operation");
14773
14774   unsigned NumElems = VT.getVectorNumElements();
14775   SDLoc dl(Op);
14776   SDValue CC = Op.getOperand(2);
14777
14778   // Extract the LHS vectors
14779   SDValue LHS = Op.getOperand(0);
14780   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14781   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14782
14783   // Extract the RHS vectors
14784   SDValue RHS = Op.getOperand(1);
14785   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14786   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14787
14788   // Issue the operation on the smaller types and concatenate the result back
14789   MVT EltVT = VT.getVectorElementType();
14790   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14791   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14792                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14793                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14794 }
14795
14796 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14797                                      const X86Subtarget *Subtarget) {
14798   SDValue Op0 = Op.getOperand(0);
14799   SDValue Op1 = Op.getOperand(1);
14800   SDValue CC = Op.getOperand(2);
14801   MVT VT = Op.getSimpleValueType();
14802   SDLoc dl(Op);
14803
14804   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14805          Op.getValueType().getScalarType() == MVT::i1 &&
14806          "Cannot set masked compare for this operation");
14807
14808   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14809   unsigned  Opc = 0;
14810   bool Unsigned = false;
14811   bool Swap = false;
14812   unsigned SSECC;
14813   switch (SetCCOpcode) {
14814   default: llvm_unreachable("Unexpected SETCC condition");
14815   case ISD::SETNE:  SSECC = 4; break;
14816   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14817   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14818   case ISD::SETLT:  Swap = true; //fall-through
14819   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14820   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14821   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14822   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14823   case ISD::SETULE: Unsigned = true; //fall-through
14824   case ISD::SETLE:  SSECC = 2; break;
14825   }
14826
14827   if (Swap)
14828     std::swap(Op0, Op1);
14829   if (Opc)
14830     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14831   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14832   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14833                      DAG.getConstant(SSECC, MVT::i8));
14834 }
14835
14836 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14837 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14838 /// return an empty value.
14839 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14840 {
14841   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14842   if (!BV)
14843     return SDValue();
14844
14845   MVT VT = Op1.getSimpleValueType();
14846   MVT EVT = VT.getVectorElementType();
14847   unsigned n = VT.getVectorNumElements();
14848   SmallVector<SDValue, 8> ULTOp1;
14849
14850   for (unsigned i = 0; i < n; ++i) {
14851     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14852     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14853       return SDValue();
14854
14855     // Avoid underflow.
14856     APInt Val = Elt->getAPIntValue();
14857     if (Val == 0)
14858       return SDValue();
14859
14860     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
14861   }
14862
14863   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14864 }
14865
14866 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14867                            SelectionDAG &DAG) {
14868   SDValue Op0 = Op.getOperand(0);
14869   SDValue Op1 = Op.getOperand(1);
14870   SDValue CC = Op.getOperand(2);
14871   MVT VT = Op.getSimpleValueType();
14872   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14873   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14874   SDLoc dl(Op);
14875
14876   if (isFP) {
14877 #ifndef NDEBUG
14878     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14879     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14880 #endif
14881
14882     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14883     unsigned Opc = X86ISD::CMPP;
14884     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14885       assert(VT.getVectorNumElements() <= 16);
14886       Opc = X86ISD::CMPM;
14887     }
14888     // In the two special cases we can't handle, emit two comparisons.
14889     if (SSECC == 8) {
14890       unsigned CC0, CC1;
14891       unsigned CombineOpc;
14892       if (SetCCOpcode == ISD::SETUEQ) {
14893         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14894       } else {
14895         assert(SetCCOpcode == ISD::SETONE);
14896         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14897       }
14898
14899       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14900                                  DAG.getConstant(CC0, MVT::i8));
14901       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14902                                  DAG.getConstant(CC1, MVT::i8));
14903       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14904     }
14905     // Handle all other FP comparisons here.
14906     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14907                        DAG.getConstant(SSECC, MVT::i8));
14908   }
14909
14910   // Break 256-bit integer vector compare into smaller ones.
14911   if (VT.is256BitVector() && !Subtarget->hasInt256())
14912     return Lower256IntVSETCC(Op, DAG);
14913
14914   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14915   EVT OpVT = Op1.getValueType();
14916   if (Subtarget->hasAVX512()) {
14917     if (Op1.getValueType().is512BitVector() ||
14918         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14919         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14920       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14921
14922     // In AVX-512 architecture setcc returns mask with i1 elements,
14923     // But there is no compare instruction for i8 and i16 elements in KNL.
14924     // We are not talking about 512-bit operands in this case, these
14925     // types are illegal.
14926     if (MaskResult &&
14927         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14928          OpVT.getVectorElementType().getSizeInBits() >= 8))
14929       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14930                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14931   }
14932
14933   // We are handling one of the integer comparisons here.  Since SSE only has
14934   // GT and EQ comparisons for integer, swapping operands and multiple
14935   // operations may be required for some comparisons.
14936   unsigned Opc;
14937   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14938   bool Subus = false;
14939
14940   switch (SetCCOpcode) {
14941   default: llvm_unreachable("Unexpected SETCC condition");
14942   case ISD::SETNE:  Invert = true;
14943   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14944   case ISD::SETLT:  Swap = true;
14945   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14946   case ISD::SETGE:  Swap = true;
14947   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14948                     Invert = true; break;
14949   case ISD::SETULT: Swap = true;
14950   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14951                     FlipSigns = true; break;
14952   case ISD::SETUGE: Swap = true;
14953   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14954                     FlipSigns = true; Invert = true; break;
14955   }
14956
14957   // Special case: Use min/max operations for SETULE/SETUGE
14958   MVT VET = VT.getVectorElementType();
14959   bool hasMinMax =
14960        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14961     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14962
14963   if (hasMinMax) {
14964     switch (SetCCOpcode) {
14965     default: break;
14966     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
14967     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
14968     }
14969
14970     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14971   }
14972
14973   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14974   if (!MinMax && hasSubus) {
14975     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14976     // Op0 u<= Op1:
14977     //   t = psubus Op0, Op1
14978     //   pcmpeq t, <0..0>
14979     switch (SetCCOpcode) {
14980     default: break;
14981     case ISD::SETULT: {
14982       // If the comparison is against a constant we can turn this into a
14983       // setule.  With psubus, setule does not require a swap.  This is
14984       // beneficial because the constant in the register is no longer
14985       // destructed as the destination so it can be hoisted out of a loop.
14986       // Only do this pre-AVX since vpcmp* is no longer destructive.
14987       if (Subtarget->hasAVX())
14988         break;
14989       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14990       if (ULEOp1.getNode()) {
14991         Op1 = ULEOp1;
14992         Subus = true; Invert = false; Swap = false;
14993       }
14994       break;
14995     }
14996     // Psubus is better than flip-sign because it requires no inversion.
14997     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14998     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14999     }
15000
15001     if (Subus) {
15002       Opc = X86ISD::SUBUS;
15003       FlipSigns = false;
15004     }
15005   }
15006
15007   if (Swap)
15008     std::swap(Op0, Op1);
15009
15010   // Check that the operation in question is available (most are plain SSE2,
15011   // but PCMPGTQ and PCMPEQQ have different requirements).
15012   if (VT == MVT::v2i64) {
15013     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
15014       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
15015
15016       // First cast everything to the right type.
15017       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15018       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15019
15020       // Since SSE has no unsigned integer comparisons, we need to flip the sign
15021       // bits of the inputs before performing those operations. The lower
15022       // compare is always unsigned.
15023       SDValue SB;
15024       if (FlipSigns) {
15025         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
15026       } else {
15027         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
15028         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
15029         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
15030                          Sign, Zero, Sign, Zero);
15031       }
15032       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
15033       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
15034
15035       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
15036       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
15037       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
15038
15039       // Create masks for only the low parts/high parts of the 64 bit integers.
15040       static const int MaskHi[] = { 1, 1, 3, 3 };
15041       static const int MaskLo[] = { 0, 0, 2, 2 };
15042       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
15043       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
15044       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
15045
15046       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
15047       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
15048
15049       if (Invert)
15050         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15051
15052       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15053     }
15054
15055     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
15056       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
15057       // pcmpeqd + pshufd + pand.
15058       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
15059
15060       // First cast everything to the right type.
15061       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15062       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15063
15064       // Do the compare.
15065       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
15066
15067       // Make sure the lower and upper halves are both all-ones.
15068       static const int Mask[] = { 1, 0, 3, 2 };
15069       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
15070       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
15071
15072       if (Invert)
15073         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15074
15075       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15076     }
15077   }
15078
15079   // Since SSE has no unsigned integer comparisons, we need to flip the sign
15080   // bits of the inputs before performing those operations.
15081   if (FlipSigns) {
15082     EVT EltVT = VT.getVectorElementType();
15083     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
15084     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
15085     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
15086   }
15087
15088   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
15089
15090   // If the logical-not of the result is required, perform that now.
15091   if (Invert)
15092     Result = DAG.getNOT(dl, Result, VT);
15093
15094   if (MinMax)
15095     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
15096
15097   if (Subus)
15098     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
15099                          getZeroVector(VT, Subtarget, DAG, dl));
15100
15101   return Result;
15102 }
15103
15104 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
15105
15106   MVT VT = Op.getSimpleValueType();
15107
15108   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
15109
15110   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
15111          && "SetCC type must be 8-bit or 1-bit integer");
15112   SDValue Op0 = Op.getOperand(0);
15113   SDValue Op1 = Op.getOperand(1);
15114   SDLoc dl(Op);
15115   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
15116
15117   // Optimize to BT if possible.
15118   // Lower (X & (1 << N)) == 0 to BT(X, N).
15119   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
15120   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
15121   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
15122       Op1.getOpcode() == ISD::Constant &&
15123       cast<ConstantSDNode>(Op1)->isNullValue() &&
15124       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15125     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
15126     if (NewSetCC.getNode())
15127       return NewSetCC;
15128   }
15129
15130   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
15131   // these.
15132   if (Op1.getOpcode() == ISD::Constant &&
15133       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
15134        cast<ConstantSDNode>(Op1)->isNullValue()) &&
15135       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15136
15137     // If the input is a setcc, then reuse the input setcc or use a new one with
15138     // the inverted condition.
15139     if (Op0.getOpcode() == X86ISD::SETCC) {
15140       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
15141       bool Invert = (CC == ISD::SETNE) ^
15142         cast<ConstantSDNode>(Op1)->isNullValue();
15143       if (!Invert)
15144         return Op0;
15145
15146       CCode = X86::GetOppositeBranchCondition(CCode);
15147       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15148                                   DAG.getConstant(CCode, MVT::i8),
15149                                   Op0.getOperand(1));
15150       if (VT == MVT::i1)
15151         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15152       return SetCC;
15153     }
15154   }
15155   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
15156       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
15157       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15158
15159     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
15160     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
15161   }
15162
15163   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
15164   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
15165   if (X86CC == X86::COND_INVALID)
15166     return SDValue();
15167
15168   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
15169   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
15170   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15171                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
15172   if (VT == MVT::i1)
15173     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15174   return SetCC;
15175 }
15176
15177 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
15178 static bool isX86LogicalCmp(SDValue Op) {
15179   unsigned Opc = Op.getNode()->getOpcode();
15180   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
15181       Opc == X86ISD::SAHF)
15182     return true;
15183   if (Op.getResNo() == 1 &&
15184       (Opc == X86ISD::ADD ||
15185        Opc == X86ISD::SUB ||
15186        Opc == X86ISD::ADC ||
15187        Opc == X86ISD::SBB ||
15188        Opc == X86ISD::SMUL ||
15189        Opc == X86ISD::UMUL ||
15190        Opc == X86ISD::INC ||
15191        Opc == X86ISD::DEC ||
15192        Opc == X86ISD::OR ||
15193        Opc == X86ISD::XOR ||
15194        Opc == X86ISD::AND))
15195     return true;
15196
15197   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15198     return true;
15199
15200   return false;
15201 }
15202
15203 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15204   if (V.getOpcode() != ISD::TRUNCATE)
15205     return false;
15206
15207   SDValue VOp0 = V.getOperand(0);
15208   unsigned InBits = VOp0.getValueSizeInBits();
15209   unsigned Bits = V.getValueSizeInBits();
15210   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15211 }
15212
15213 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15214   bool addTest = true;
15215   SDValue Cond  = Op.getOperand(0);
15216   SDValue Op1 = Op.getOperand(1);
15217   SDValue Op2 = Op.getOperand(2);
15218   SDLoc DL(Op);
15219   EVT VT = Op1.getValueType();
15220   SDValue CC;
15221
15222   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15223   // are available. Otherwise fp cmovs get lowered into a less efficient branch
15224   // sequence later on.
15225   if (Cond.getOpcode() == ISD::SETCC &&
15226       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15227        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15228       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
15229     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15230     int SSECC = translateX86FSETCC(
15231         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15232
15233     if (SSECC != 8) {
15234       if (Subtarget->hasAVX512()) {
15235         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15236                                   DAG.getConstant(SSECC, MVT::i8));
15237         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15238       }
15239       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15240                                 DAG.getConstant(SSECC, MVT::i8));
15241       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15242       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15243       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15244     }
15245   }
15246
15247   if (Cond.getOpcode() == ISD::SETCC) {
15248     SDValue NewCond = LowerSETCC(Cond, DAG);
15249     if (NewCond.getNode())
15250       Cond = NewCond;
15251   }
15252
15253   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15254   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15255   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15256   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15257   if (Cond.getOpcode() == X86ISD::SETCC &&
15258       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15259       isZero(Cond.getOperand(1).getOperand(1))) {
15260     SDValue Cmp = Cond.getOperand(1);
15261
15262     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15263
15264     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
15265         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15266       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
15267
15268       SDValue CmpOp0 = Cmp.getOperand(0);
15269       // Apply further optimizations for special cases
15270       // (select (x != 0), -1, 0) -> neg & sbb
15271       // (select (x == 0), 0, -1) -> neg & sbb
15272       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
15273         if (YC->isNullValue() &&
15274             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
15275           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15276           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15277                                     DAG.getConstant(0, CmpOp0.getValueType()),
15278                                     CmpOp0);
15279           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15280                                     DAG.getConstant(X86::COND_B, MVT::i8),
15281                                     SDValue(Neg.getNode(), 1));
15282           return Res;
15283         }
15284
15285       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15286                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
15287       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15288
15289       SDValue Res =   // Res = 0 or -1.
15290         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15291                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
15292
15293       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
15294         Res = DAG.getNOT(DL, Res, Res.getValueType());
15295
15296       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
15297       if (!N2C || !N2C->isNullValue())
15298         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15299       return Res;
15300     }
15301   }
15302
15303   // Look past (and (setcc_carry (cmp ...)), 1).
15304   if (Cond.getOpcode() == ISD::AND &&
15305       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15306     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15307     if (C && C->getAPIntValue() == 1)
15308       Cond = Cond.getOperand(0);
15309   }
15310
15311   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15312   // setting operand in place of the X86ISD::SETCC.
15313   unsigned CondOpcode = Cond.getOpcode();
15314   if (CondOpcode == X86ISD::SETCC ||
15315       CondOpcode == X86ISD::SETCC_CARRY) {
15316     CC = Cond.getOperand(0);
15317
15318     SDValue Cmp = Cond.getOperand(1);
15319     unsigned Opc = Cmp.getOpcode();
15320     MVT VT = Op.getSimpleValueType();
15321
15322     bool IllegalFPCMov = false;
15323     if (VT.isFloatingPoint() && !VT.isVector() &&
15324         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15325       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15326
15327     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15328         Opc == X86ISD::BT) { // FIXME
15329       Cond = Cmp;
15330       addTest = false;
15331     }
15332   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15333              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15334              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15335               Cond.getOperand(0).getValueType() != MVT::i8)) {
15336     SDValue LHS = Cond.getOperand(0);
15337     SDValue RHS = Cond.getOperand(1);
15338     unsigned X86Opcode;
15339     unsigned X86Cond;
15340     SDVTList VTs;
15341     switch (CondOpcode) {
15342     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15343     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15344     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15345     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15346     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15347     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15348     default: llvm_unreachable("unexpected overflowing operator");
15349     }
15350     if (CondOpcode == ISD::UMULO)
15351       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15352                           MVT::i32);
15353     else
15354       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15355
15356     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15357
15358     if (CondOpcode == ISD::UMULO)
15359       Cond = X86Op.getValue(2);
15360     else
15361       Cond = X86Op.getValue(1);
15362
15363     CC = DAG.getConstant(X86Cond, MVT::i8);
15364     addTest = false;
15365   }
15366
15367   if (addTest) {
15368     // Look pass the truncate if the high bits are known zero.
15369     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15370         Cond = Cond.getOperand(0);
15371
15372     // We know the result of AND is compared against zero. Try to match
15373     // it to BT.
15374     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15375       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
15376       if (NewSetCC.getNode()) {
15377         CC = NewSetCC.getOperand(0);
15378         Cond = NewSetCC.getOperand(1);
15379         addTest = false;
15380       }
15381     }
15382   }
15383
15384   if (addTest) {
15385     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15386     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15387   }
15388
15389   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15390   // a <  b ?  0 : -1 -> RES = setcc_carry
15391   // a >= b ? -1 :  0 -> RES = setcc_carry
15392   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15393   if (Cond.getOpcode() == X86ISD::SUB) {
15394     Cond = ConvertCmpIfNecessary(Cond, DAG);
15395     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15396
15397     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15398         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
15399       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15400                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
15401       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
15402         return DAG.getNOT(DL, Res, Res.getValueType());
15403       return Res;
15404     }
15405   }
15406
15407   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15408   // widen the cmov and push the truncate through. This avoids introducing a new
15409   // branch during isel and doesn't add any extensions.
15410   if (Op.getValueType() == MVT::i8 &&
15411       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15412     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15413     if (T1.getValueType() == T2.getValueType() &&
15414         // Blacklist CopyFromReg to avoid partial register stalls.
15415         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15416       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15417       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15418       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15419     }
15420   }
15421
15422   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15423   // condition is true.
15424   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15425   SDValue Ops[] = { Op2, Op1, CC, Cond };
15426   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15427 }
15428
15429 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
15430                                        SelectionDAG &DAG) {
15431   MVT VT = Op->getSimpleValueType(0);
15432   SDValue In = Op->getOperand(0);
15433   MVT InVT = In.getSimpleValueType();
15434   MVT VTElt = VT.getVectorElementType();
15435   MVT InVTElt = InVT.getVectorElementType();
15436   SDLoc dl(Op);
15437
15438   // SKX processor
15439   if ((InVTElt == MVT::i1) &&
15440       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15441         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15442
15443        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15444         VTElt.getSizeInBits() <= 16)) ||
15445
15446        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15447         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15448     
15449        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15450         VTElt.getSizeInBits() >= 32))))
15451     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15452     
15453   unsigned int NumElts = VT.getVectorNumElements();
15454
15455   if (NumElts != 8 && NumElts != 16)
15456     return SDValue();
15457
15458   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
15459     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15460
15461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15462   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15463
15464   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
15465   Constant *C = ConstantInt::get(*DAG.getContext(),
15466     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
15467
15468   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
15469   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
15470   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
15471                           MachinePointerInfo::getConstantPool(),
15472                           false, false, false, Alignment);
15473   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
15474   if (VT.is512BitVector())
15475     return Brcst;
15476   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
15477 }
15478
15479 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15480                                 SelectionDAG &DAG) {
15481   MVT VT = Op->getSimpleValueType(0);
15482   SDValue In = Op->getOperand(0);
15483   MVT InVT = In.getSimpleValueType();
15484   SDLoc dl(Op);
15485
15486   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15487     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15488
15489   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15490       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15491       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15492     return SDValue();
15493
15494   if (Subtarget->hasInt256())
15495     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15496
15497   // Optimize vectors in AVX mode
15498   // Sign extend  v8i16 to v8i32 and
15499   //              v4i32 to v4i64
15500   //
15501   // Divide input vector into two parts
15502   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15503   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15504   // concat the vectors to original VT
15505
15506   unsigned NumElems = InVT.getVectorNumElements();
15507   SDValue Undef = DAG.getUNDEF(InVT);
15508
15509   SmallVector<int,8> ShufMask1(NumElems, -1);
15510   for (unsigned i = 0; i != NumElems/2; ++i)
15511     ShufMask1[i] = i;
15512
15513   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15514
15515   SmallVector<int,8> ShufMask2(NumElems, -1);
15516   for (unsigned i = 0; i != NumElems/2; ++i)
15517     ShufMask2[i] = i + NumElems/2;
15518
15519   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15520
15521   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15522                                 VT.getVectorNumElements()/2);
15523
15524   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15525   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15526
15527   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15528 }
15529
15530 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15531 // may emit an illegal shuffle but the expansion is still better than scalar
15532 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15533 // we'll emit a shuffle and a arithmetic shift.
15534 // TODO: It is possible to support ZExt by zeroing the undef values during
15535 // the shuffle phase or after the shuffle.
15536 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15537                                  SelectionDAG &DAG) {
15538   MVT RegVT = Op.getSimpleValueType();
15539   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15540   assert(RegVT.isInteger() &&
15541          "We only custom lower integer vector sext loads.");
15542
15543   // Nothing useful we can do without SSE2 shuffles.
15544   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15545
15546   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15547   SDLoc dl(Ld);
15548   EVT MemVT = Ld->getMemoryVT();
15549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15550   unsigned RegSz = RegVT.getSizeInBits();
15551
15552   ISD::LoadExtType Ext = Ld->getExtensionType();
15553
15554   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15555          && "Only anyext and sext are currently implemented.");
15556   assert(MemVT != RegVT && "Cannot extend to the same type");
15557   assert(MemVT.isVector() && "Must load a vector from memory");
15558
15559   unsigned NumElems = RegVT.getVectorNumElements();
15560   unsigned MemSz = MemVT.getSizeInBits();
15561   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15562
15563   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15564     // The only way in which we have a legal 256-bit vector result but not the
15565     // integer 256-bit operations needed to directly lower a sextload is if we
15566     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15567     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15568     // correctly legalized. We do this late to allow the canonical form of
15569     // sextload to persist throughout the rest of the DAG combiner -- it wants
15570     // to fold together any extensions it can, and so will fuse a sign_extend
15571     // of an sextload into a sextload targeting a wider value.
15572     SDValue Load;
15573     if (MemSz == 128) {
15574       // Just switch this to a normal load.
15575       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15576                                        "it must be a legal 128-bit vector "
15577                                        "type!");
15578       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15579                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15580                   Ld->isInvariant(), Ld->getAlignment());
15581     } else {
15582       assert(MemSz < 128 &&
15583              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15584       // Do an sext load to a 128-bit vector type. We want to use the same
15585       // number of elements, but elements half as wide. This will end up being
15586       // recursively lowered by this routine, but will succeed as we definitely
15587       // have all the necessary features if we're using AVX1.
15588       EVT HalfEltVT =
15589           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15590       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15591       Load =
15592           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15593                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15594                          Ld->isNonTemporal(), Ld->isInvariant(),
15595                          Ld->getAlignment());
15596     }
15597
15598     // Replace chain users with the new chain.
15599     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15600     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15601
15602     // Finally, do a normal sign-extend to the desired register.
15603     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15604   }
15605
15606   // All sizes must be a power of two.
15607   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15608          "Non-power-of-two elements are not custom lowered!");
15609
15610   // Attempt to load the original value using scalar loads.
15611   // Find the largest scalar type that divides the total loaded size.
15612   MVT SclrLoadTy = MVT::i8;
15613   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15614        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15615     MVT Tp = (MVT::SimpleValueType)tp;
15616     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15617       SclrLoadTy = Tp;
15618     }
15619   }
15620
15621   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15622   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15623       (64 <= MemSz))
15624     SclrLoadTy = MVT::f64;
15625
15626   // Calculate the number of scalar loads that we need to perform
15627   // in order to load our vector from memory.
15628   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15629
15630   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15631          "Can only lower sext loads with a single scalar load!");
15632
15633   unsigned loadRegZize = RegSz;
15634   if (Ext == ISD::SEXTLOAD && RegSz == 256)
15635     loadRegZize /= 2;
15636
15637   // Represent our vector as a sequence of elements which are the
15638   // largest scalar that we can load.
15639   EVT LoadUnitVecVT = EVT::getVectorVT(
15640       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15641
15642   // Represent the data using the same element type that is stored in
15643   // memory. In practice, we ''widen'' MemVT.
15644   EVT WideVecVT =
15645       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15646                        loadRegZize / MemVT.getScalarType().getSizeInBits());
15647
15648   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15649          "Invalid vector type");
15650
15651   // We can't shuffle using an illegal type.
15652   assert(TLI.isTypeLegal(WideVecVT) &&
15653          "We only lower types that form legal widened vector types");
15654
15655   SmallVector<SDValue, 8> Chains;
15656   SDValue Ptr = Ld->getBasePtr();
15657   SDValue Increment =
15658       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
15659   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15660
15661   for (unsigned i = 0; i < NumLoads; ++i) {
15662     // Perform a single load.
15663     SDValue ScalarLoad =
15664         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15665                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15666                     Ld->getAlignment());
15667     Chains.push_back(ScalarLoad.getValue(1));
15668     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15669     // another round of DAGCombining.
15670     if (i == 0)
15671       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15672     else
15673       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15674                         ScalarLoad, DAG.getIntPtrConstant(i));
15675
15676     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15677   }
15678
15679   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15680
15681   // Bitcast the loaded value to a vector of the original element type, in
15682   // the size of the target vector type.
15683   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15684   unsigned SizeRatio = RegSz / MemSz;
15685
15686   if (Ext == ISD::SEXTLOAD) {
15687     // If we have SSE4.1, we can directly emit a VSEXT node.
15688     if (Subtarget->hasSSE41()) {
15689       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15690       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15691       return Sext;
15692     }
15693
15694     // Otherwise we'll shuffle the small elements in the high bits of the
15695     // larger type and perform an arithmetic shift. If the shift is not legal
15696     // it's better to scalarize.
15697     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
15698            "We can't implement a sext load without an arithmetic right shift!");
15699
15700     // Redistribute the loaded elements into the different locations.
15701     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15702     for (unsigned i = 0; i != NumElems; ++i)
15703       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
15704
15705     SDValue Shuff = DAG.getVectorShuffle(
15706         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15707
15708     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15709
15710     // Build the arithmetic shift.
15711     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
15712                    MemVT.getVectorElementType().getSizeInBits();
15713     Shuff =
15714         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
15715
15716     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15717     return Shuff;
15718   }
15719
15720   // Redistribute the loaded elements into the different locations.
15721   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15722   for (unsigned i = 0; i != NumElems; ++i)
15723     ShuffleVec[i * SizeRatio] = i;
15724
15725   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15726                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15727
15728   // Bitcast to the requested type.
15729   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15730   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15731   return Shuff;
15732 }
15733
15734 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15735 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15736 // from the AND / OR.
15737 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15738   Opc = Op.getOpcode();
15739   if (Opc != ISD::OR && Opc != ISD::AND)
15740     return false;
15741   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15742           Op.getOperand(0).hasOneUse() &&
15743           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15744           Op.getOperand(1).hasOneUse());
15745 }
15746
15747 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15748 // 1 and that the SETCC node has a single use.
15749 static bool isXor1OfSetCC(SDValue Op) {
15750   if (Op.getOpcode() != ISD::XOR)
15751     return false;
15752   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15753   if (N1C && N1C->getAPIntValue() == 1) {
15754     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15755       Op.getOperand(0).hasOneUse();
15756   }
15757   return false;
15758 }
15759
15760 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15761   bool addTest = true;
15762   SDValue Chain = Op.getOperand(0);
15763   SDValue Cond  = Op.getOperand(1);
15764   SDValue Dest  = Op.getOperand(2);
15765   SDLoc dl(Op);
15766   SDValue CC;
15767   bool Inverted = false;
15768
15769   if (Cond.getOpcode() == ISD::SETCC) {
15770     // Check for setcc([su]{add,sub,mul}o == 0).
15771     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15772         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15773         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15774         Cond.getOperand(0).getResNo() == 1 &&
15775         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15776          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15777          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15778          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15779          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15780          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15781       Inverted = true;
15782       Cond = Cond.getOperand(0);
15783     } else {
15784       SDValue NewCond = LowerSETCC(Cond, DAG);
15785       if (NewCond.getNode())
15786         Cond = NewCond;
15787     }
15788   }
15789 #if 0
15790   // FIXME: LowerXALUO doesn't handle these!!
15791   else if (Cond.getOpcode() == X86ISD::ADD  ||
15792            Cond.getOpcode() == X86ISD::SUB  ||
15793            Cond.getOpcode() == X86ISD::SMUL ||
15794            Cond.getOpcode() == X86ISD::UMUL)
15795     Cond = LowerXALUO(Cond, DAG);
15796 #endif
15797
15798   // Look pass (and (setcc_carry (cmp ...)), 1).
15799   if (Cond.getOpcode() == ISD::AND &&
15800       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15801     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15802     if (C && C->getAPIntValue() == 1)
15803       Cond = Cond.getOperand(0);
15804   }
15805
15806   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15807   // setting operand in place of the X86ISD::SETCC.
15808   unsigned CondOpcode = Cond.getOpcode();
15809   if (CondOpcode == X86ISD::SETCC ||
15810       CondOpcode == X86ISD::SETCC_CARRY) {
15811     CC = Cond.getOperand(0);
15812
15813     SDValue Cmp = Cond.getOperand(1);
15814     unsigned Opc = Cmp.getOpcode();
15815     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15816     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15817       Cond = Cmp;
15818       addTest = false;
15819     } else {
15820       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15821       default: break;
15822       case X86::COND_O:
15823       case X86::COND_B:
15824         // These can only come from an arithmetic instruction with overflow,
15825         // e.g. SADDO, UADDO.
15826         Cond = Cond.getNode()->getOperand(1);
15827         addTest = false;
15828         break;
15829       }
15830     }
15831   }
15832   CondOpcode = Cond.getOpcode();
15833   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15834       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15835       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15836        Cond.getOperand(0).getValueType() != MVT::i8)) {
15837     SDValue LHS = Cond.getOperand(0);
15838     SDValue RHS = Cond.getOperand(1);
15839     unsigned X86Opcode;
15840     unsigned X86Cond;
15841     SDVTList VTs;
15842     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15843     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15844     // X86ISD::INC).
15845     switch (CondOpcode) {
15846     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15847     case ISD::SADDO:
15848       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15849         if (C->isOne()) {
15850           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15851           break;
15852         }
15853       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15854     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15855     case ISD::SSUBO:
15856       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15857         if (C->isOne()) {
15858           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15859           break;
15860         }
15861       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15862     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15863     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15864     default: llvm_unreachable("unexpected overflowing operator");
15865     }
15866     if (Inverted)
15867       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15868     if (CondOpcode == ISD::UMULO)
15869       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15870                           MVT::i32);
15871     else
15872       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15873
15874     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15875
15876     if (CondOpcode == ISD::UMULO)
15877       Cond = X86Op.getValue(2);
15878     else
15879       Cond = X86Op.getValue(1);
15880
15881     CC = DAG.getConstant(X86Cond, MVT::i8);
15882     addTest = false;
15883   } else {
15884     unsigned CondOpc;
15885     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15886       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15887       if (CondOpc == ISD::OR) {
15888         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15889         // two branches instead of an explicit OR instruction with a
15890         // separate test.
15891         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15892             isX86LogicalCmp(Cmp)) {
15893           CC = Cond.getOperand(0).getOperand(0);
15894           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15895                               Chain, Dest, CC, Cmp);
15896           CC = Cond.getOperand(1).getOperand(0);
15897           Cond = Cmp;
15898           addTest = false;
15899         }
15900       } else { // ISD::AND
15901         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15902         // two branches instead of an explicit AND instruction with a
15903         // separate test. However, we only do this if this block doesn't
15904         // have a fall-through edge, because this requires an explicit
15905         // jmp when the condition is false.
15906         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15907             isX86LogicalCmp(Cmp) &&
15908             Op.getNode()->hasOneUse()) {
15909           X86::CondCode CCode =
15910             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15911           CCode = X86::GetOppositeBranchCondition(CCode);
15912           CC = DAG.getConstant(CCode, MVT::i8);
15913           SDNode *User = *Op.getNode()->use_begin();
15914           // Look for an unconditional branch following this conditional branch.
15915           // We need this because we need to reverse the successors in order
15916           // to implement FCMP_OEQ.
15917           if (User->getOpcode() == ISD::BR) {
15918             SDValue FalseBB = User->getOperand(1);
15919             SDNode *NewBR =
15920               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15921             assert(NewBR == User);
15922             (void)NewBR;
15923             Dest = FalseBB;
15924
15925             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15926                                 Chain, Dest, CC, Cmp);
15927             X86::CondCode CCode =
15928               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15929             CCode = X86::GetOppositeBranchCondition(CCode);
15930             CC = DAG.getConstant(CCode, MVT::i8);
15931             Cond = Cmp;
15932             addTest = false;
15933           }
15934         }
15935       }
15936     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15937       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15938       // It should be transformed during dag combiner except when the condition
15939       // is set by a arithmetics with overflow node.
15940       X86::CondCode CCode =
15941         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15942       CCode = X86::GetOppositeBranchCondition(CCode);
15943       CC = DAG.getConstant(CCode, MVT::i8);
15944       Cond = Cond.getOperand(0).getOperand(1);
15945       addTest = false;
15946     } else if (Cond.getOpcode() == ISD::SETCC &&
15947                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15948       // For FCMP_OEQ, we can emit
15949       // two branches instead of an explicit AND instruction with a
15950       // separate test. However, we only do this if this block doesn't
15951       // have a fall-through edge, because this requires an explicit
15952       // jmp when the condition is false.
15953       if (Op.getNode()->hasOneUse()) {
15954         SDNode *User = *Op.getNode()->use_begin();
15955         // Look for an unconditional branch following this conditional branch.
15956         // We need this because we need to reverse the successors in order
15957         // to implement FCMP_OEQ.
15958         if (User->getOpcode() == ISD::BR) {
15959           SDValue FalseBB = User->getOperand(1);
15960           SDNode *NewBR =
15961             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15962           assert(NewBR == User);
15963           (void)NewBR;
15964           Dest = FalseBB;
15965
15966           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15967                                     Cond.getOperand(0), Cond.getOperand(1));
15968           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15969           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15970           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15971                               Chain, Dest, CC, Cmp);
15972           CC = DAG.getConstant(X86::COND_P, MVT::i8);
15973           Cond = Cmp;
15974           addTest = false;
15975         }
15976       }
15977     } else if (Cond.getOpcode() == ISD::SETCC &&
15978                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15979       // For FCMP_UNE, we can emit
15980       // two branches instead of an explicit AND instruction with a
15981       // separate test. However, we only do this if this block doesn't
15982       // have a fall-through edge, because this requires an explicit
15983       // jmp when the condition is false.
15984       if (Op.getNode()->hasOneUse()) {
15985         SDNode *User = *Op.getNode()->use_begin();
15986         // Look for an unconditional branch following this conditional branch.
15987         // We need this because we need to reverse the successors in order
15988         // to implement FCMP_UNE.
15989         if (User->getOpcode() == ISD::BR) {
15990           SDValue FalseBB = User->getOperand(1);
15991           SDNode *NewBR =
15992             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15993           assert(NewBR == User);
15994           (void)NewBR;
15995
15996           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15997                                     Cond.getOperand(0), Cond.getOperand(1));
15998           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15999           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16000           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16001                               Chain, Dest, CC, Cmp);
16002           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
16003           Cond = Cmp;
16004           addTest = false;
16005           Dest = FalseBB;
16006         }
16007       }
16008     }
16009   }
16010
16011   if (addTest) {
16012     // Look pass the truncate if the high bits are known zero.
16013     if (isTruncWithZeroHighBitsInput(Cond, DAG))
16014         Cond = Cond.getOperand(0);
16015
16016     // We know the result of AND is compared against zero. Try to match
16017     // it to BT.
16018     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
16019       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
16020       if (NewSetCC.getNode()) {
16021         CC = NewSetCC.getOperand(0);
16022         Cond = NewSetCC.getOperand(1);
16023         addTest = false;
16024       }
16025     }
16026   }
16027
16028   if (addTest) {
16029     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
16030     CC = DAG.getConstant(X86Cond, MVT::i8);
16031     Cond = EmitTest(Cond, X86Cond, dl, DAG);
16032   }
16033   Cond = ConvertCmpIfNecessary(Cond, DAG);
16034   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16035                      Chain, Dest, CC, Cond);
16036 }
16037
16038 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
16039 // Calls to _alloca are needed to probe the stack when allocating more than 4k
16040 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
16041 // that the guard pages used by the OS virtual memory manager are allocated in
16042 // correct sequence.
16043 SDValue
16044 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
16045                                            SelectionDAG &DAG) const {
16046   MachineFunction &MF = DAG.getMachineFunction();
16047   bool SplitStack = MF.shouldSplitStack();
16048   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
16049                SplitStack;
16050   SDLoc dl(Op);
16051
16052   if (!Lower) {
16053     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16054     SDNode* Node = Op.getNode();
16055
16056     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
16057     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
16058         " not tell us which reg is the stack pointer!");
16059     EVT VT = Node->getValueType(0);
16060     SDValue Tmp1 = SDValue(Node, 0);
16061     SDValue Tmp2 = SDValue(Node, 1);
16062     SDValue Tmp3 = Node->getOperand(2);
16063     SDValue Chain = Tmp1.getOperand(0);
16064
16065     // Chain the dynamic stack allocation so that it doesn't modify the stack
16066     // pointer when other instructions are using the stack.
16067     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
16068         SDLoc(Node));
16069
16070     SDValue Size = Tmp2.getOperand(1);
16071     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
16072     Chain = SP.getValue(1);
16073     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
16074     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
16075     unsigned StackAlign = TFI.getStackAlignment();
16076     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
16077     if (Align > StackAlign)
16078       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
16079           DAG.getConstant(-(uint64_t)Align, VT));
16080     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
16081
16082     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
16083         DAG.getIntPtrConstant(0, true), SDValue(),
16084         SDLoc(Node));
16085
16086     SDValue Ops[2] = { Tmp1, Tmp2 };
16087     return DAG.getMergeValues(Ops, dl);
16088   }
16089
16090   // Get the inputs.
16091   SDValue Chain = Op.getOperand(0);
16092   SDValue Size  = Op.getOperand(1);
16093   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16094   EVT VT = Op.getNode()->getValueType(0);
16095
16096   bool Is64Bit = Subtarget->is64Bit();
16097   EVT SPTy = getPointerTy();
16098
16099   if (SplitStack) {
16100     MachineRegisterInfo &MRI = MF.getRegInfo();
16101
16102     if (Is64Bit) {
16103       // The 64 bit implementation of segmented stacks needs to clobber both r10
16104       // r11. This makes it impossible to use it along with nested parameters.
16105       const Function *F = MF.getFunction();
16106
16107       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16108            I != E; ++I)
16109         if (I->hasNestAttr())
16110           report_fatal_error("Cannot use segmented stacks with functions that "
16111                              "have nested arguments.");
16112     }
16113
16114     const TargetRegisterClass *AddrRegClass =
16115       getRegClassFor(getPointerTy());
16116     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16117     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16118     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16119                                 DAG.getRegister(Vreg, SPTy));
16120     SDValue Ops1[2] = { Value, Chain };
16121     return DAG.getMergeValues(Ops1, dl);
16122   } else {
16123     SDValue Flag;
16124     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16125
16126     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16127     Flag = Chain.getValue(1);
16128     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16129
16130     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16131
16132     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16133         DAG.getSubtarget().getRegisterInfo());
16134     unsigned SPReg = RegInfo->getStackRegister();
16135     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16136     Chain = SP.getValue(1);
16137
16138     if (Align) {
16139       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16140                        DAG.getConstant(-(uint64_t)Align, VT));
16141       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16142     }
16143
16144     SDValue Ops1[2] = { SP, Chain };
16145     return DAG.getMergeValues(Ops1, dl);
16146   }
16147 }
16148
16149 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16150   MachineFunction &MF = DAG.getMachineFunction();
16151   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16152
16153   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16154   SDLoc DL(Op);
16155
16156   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
16157     // vastart just stores the address of the VarArgsFrameIndex slot into the
16158     // memory location argument.
16159     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16160                                    getPointerTy());
16161     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16162                         MachinePointerInfo(SV), false, false, 0);
16163   }
16164
16165   // __va_list_tag:
16166   //   gp_offset         (0 - 6 * 8)
16167   //   fp_offset         (48 - 48 + 8 * 16)
16168   //   overflow_arg_area (point to parameters coming in memory).
16169   //   reg_save_area
16170   SmallVector<SDValue, 8> MemOps;
16171   SDValue FIN = Op.getOperand(1);
16172   // Store gp_offset
16173   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16174                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16175                                                MVT::i32),
16176                                FIN, MachinePointerInfo(SV), false, false, 0);
16177   MemOps.push_back(Store);
16178
16179   // Store fp_offset
16180   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16181                     FIN, DAG.getIntPtrConstant(4));
16182   Store = DAG.getStore(Op.getOperand(0), DL,
16183                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
16184                                        MVT::i32),
16185                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16186   MemOps.push_back(Store);
16187
16188   // Store ptr to overflow_arg_area
16189   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16190                     FIN, DAG.getIntPtrConstant(4));
16191   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16192                                     getPointerTy());
16193   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16194                        MachinePointerInfo(SV, 8),
16195                        false, false, 0);
16196   MemOps.push_back(Store);
16197
16198   // Store ptr to reg_save_area.
16199   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16200                     FIN, DAG.getIntPtrConstant(8));
16201   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
16202                                     getPointerTy());
16203   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
16204                        MachinePointerInfo(SV, 16), false, false, 0);
16205   MemOps.push_back(Store);
16206   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16207 }
16208
16209 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16210   assert(Subtarget->is64Bit() &&
16211          "LowerVAARG only handles 64-bit va_arg!");
16212   assert((Subtarget->isTargetLinux() ||
16213           Subtarget->isTargetDarwin()) &&
16214           "Unhandled target in LowerVAARG");
16215   assert(Op.getNode()->getNumOperands() == 4);
16216   SDValue Chain = Op.getOperand(0);
16217   SDValue SrcPtr = Op.getOperand(1);
16218   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16219   unsigned Align = Op.getConstantOperandVal(3);
16220   SDLoc dl(Op);
16221
16222   EVT ArgVT = Op.getNode()->getValueType(0);
16223   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16224   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
16225   uint8_t ArgMode;
16226
16227   // Decide which area this value should be read from.
16228   // TODO: Implement the AMD64 ABI in its entirety. This simple
16229   // selection mechanism works only for the basic types.
16230   if (ArgVT == MVT::f80) {
16231     llvm_unreachable("va_arg for f80 not yet implemented");
16232   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16233     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16234   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16235     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16236   } else {
16237     llvm_unreachable("Unhandled argument type in LowerVAARG");
16238   }
16239
16240   if (ArgMode == 2) {
16241     // Sanity Check: Make sure using fp_offset makes sense.
16242     assert(!DAG.getTarget().Options.UseSoftFloat &&
16243            !(DAG.getMachineFunction()
16244                 .getFunction()->getAttributes()
16245                 .hasAttribute(AttributeSet::FunctionIndex,
16246                               Attribute::NoImplicitFloat)) &&
16247            Subtarget->hasSSE1());
16248   }
16249
16250   // Insert VAARG_64 node into the DAG
16251   // VAARG_64 returns two values: Variable Argument Address, Chain
16252   SmallVector<SDValue, 11> InstOps;
16253   InstOps.push_back(Chain);
16254   InstOps.push_back(SrcPtr);
16255   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
16256   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
16257   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
16258   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
16259   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16260                                           VTs, InstOps, MVT::i64,
16261                                           MachinePointerInfo(SV),
16262                                           /*Align=*/0,
16263                                           /*Volatile=*/false,
16264                                           /*ReadMem=*/true,
16265                                           /*WriteMem=*/true);
16266   Chain = VAARG.getValue(1);
16267
16268   // Load the next argument and return it
16269   return DAG.getLoad(ArgVT, dl,
16270                      Chain,
16271                      VAARG,
16272                      MachinePointerInfo(),
16273                      false, false, false, 0);
16274 }
16275
16276 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16277                            SelectionDAG &DAG) {
16278   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
16279   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16280   SDValue Chain = Op.getOperand(0);
16281   SDValue DstPtr = Op.getOperand(1);
16282   SDValue SrcPtr = Op.getOperand(2);
16283   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16284   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16285   SDLoc DL(Op);
16286
16287   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16288                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
16289                        false,
16290                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16291 }
16292
16293 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16294 // amount is a constant. Takes immediate version of shift as input.
16295 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16296                                           SDValue SrcOp, uint64_t ShiftAmt,
16297                                           SelectionDAG &DAG) {
16298   MVT ElementType = VT.getVectorElementType();
16299
16300   // Fold this packed shift into its first operand if ShiftAmt is 0.
16301   if (ShiftAmt == 0)
16302     return SrcOp;
16303
16304   // Check for ShiftAmt >= element width
16305   if (ShiftAmt >= ElementType.getSizeInBits()) {
16306     if (Opc == X86ISD::VSRAI)
16307       ShiftAmt = ElementType.getSizeInBits() - 1;
16308     else
16309       return DAG.getConstant(0, VT);
16310   }
16311
16312   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16313          && "Unknown target vector shift-by-constant node");
16314
16315   // Fold this packed vector shift into a build vector if SrcOp is a
16316   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16317   if (VT == SrcOp.getSimpleValueType() &&
16318       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16319     SmallVector<SDValue, 8> Elts;
16320     unsigned NumElts = SrcOp->getNumOperands();
16321     ConstantSDNode *ND;
16322
16323     switch(Opc) {
16324     default: llvm_unreachable(nullptr);
16325     case X86ISD::VSHLI:
16326       for (unsigned i=0; i!=NumElts; ++i) {
16327         SDValue CurrentOp = SrcOp->getOperand(i);
16328         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16329           Elts.push_back(CurrentOp);
16330           continue;
16331         }
16332         ND = cast<ConstantSDNode>(CurrentOp);
16333         const APInt &C = ND->getAPIntValue();
16334         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
16335       }
16336       break;
16337     case X86ISD::VSRLI:
16338       for (unsigned i=0; i!=NumElts; ++i) {
16339         SDValue CurrentOp = SrcOp->getOperand(i);
16340         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16341           Elts.push_back(CurrentOp);
16342           continue;
16343         }
16344         ND = cast<ConstantSDNode>(CurrentOp);
16345         const APInt &C = ND->getAPIntValue();
16346         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
16347       }
16348       break;
16349     case X86ISD::VSRAI:
16350       for (unsigned i=0; i!=NumElts; ++i) {
16351         SDValue CurrentOp = SrcOp->getOperand(i);
16352         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16353           Elts.push_back(CurrentOp);
16354           continue;
16355         }
16356         ND = cast<ConstantSDNode>(CurrentOp);
16357         const APInt &C = ND->getAPIntValue();
16358         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
16359       }
16360       break;
16361     }
16362
16363     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16364   }
16365
16366   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
16367 }
16368
16369 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16370 // may or may not be a constant. Takes immediate version of shift as input.
16371 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16372                                    SDValue SrcOp, SDValue ShAmt,
16373                                    SelectionDAG &DAG) {
16374   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
16375
16376   // Catch shift-by-constant.
16377   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16378     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16379                                       CShAmt->getZExtValue(), DAG);
16380
16381   // Change opcode to non-immediate version
16382   switch (Opc) {
16383     default: llvm_unreachable("Unknown target vector shift node");
16384     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16385     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16386     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16387   }
16388
16389   // Need to build a vector containing shift amount
16390   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
16391   SDValue ShOps[4];
16392   ShOps[0] = ShAmt;
16393   ShOps[1] = DAG.getConstant(0, MVT::i32);
16394   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
16395   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
16396
16397   // The return type has to be a 128-bit type with the same element
16398   // type as the input type.
16399   MVT EltVT = VT.getVectorElementType();
16400   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16401
16402   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
16403   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16404 }
16405
16406 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16407 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16408 /// necessary casting for \p Mask when lowering masking intrinsics.
16409 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16410                                     SDValue PreservedSrc,
16411                                     const X86Subtarget *Subtarget,
16412                                     SelectionDAG &DAG) {
16413     EVT VT = Op.getValueType();
16414     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16415                                   MVT::i1, VT.getVectorNumElements());
16416     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16417                                      Mask.getValueType().getSizeInBits());
16418     SDLoc dl(Op);
16419
16420     assert(MaskVT.isSimple() && "invalid mask type");
16421
16422     if (isAllOnes(Mask))
16423       return Op;
16424
16425     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16426     // are extracted by EXTRACT_SUBVECTOR.
16427     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16428                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
16429                               DAG.getIntPtrConstant(0));
16430
16431     switch (Op.getOpcode()) {
16432       default: break;
16433       case X86ISD::PCMPEQM:
16434       case X86ISD::PCMPGTM:
16435       case X86ISD::CMPM:
16436       case X86ISD::CMPMU:
16437         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16438     }
16439     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16440       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16441     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
16442 }
16443
16444 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
16445     switch (IntNo) {
16446     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16447     case Intrinsic::x86_fma_vfmadd_ps:
16448     case Intrinsic::x86_fma_vfmadd_pd:
16449     case Intrinsic::x86_fma_vfmadd_ps_256:
16450     case Intrinsic::x86_fma_vfmadd_pd_256:
16451     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
16452     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
16453       return X86ISD::FMADD;
16454     case Intrinsic::x86_fma_vfmsub_ps:
16455     case Intrinsic::x86_fma_vfmsub_pd:
16456     case Intrinsic::x86_fma_vfmsub_ps_256:
16457     case Intrinsic::x86_fma_vfmsub_pd_256:
16458     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
16459     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
16460       return X86ISD::FMSUB;
16461     case Intrinsic::x86_fma_vfnmadd_ps:
16462     case Intrinsic::x86_fma_vfnmadd_pd:
16463     case Intrinsic::x86_fma_vfnmadd_ps_256:
16464     case Intrinsic::x86_fma_vfnmadd_pd_256:
16465     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
16466     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
16467       return X86ISD::FNMADD;
16468     case Intrinsic::x86_fma_vfnmsub_ps:
16469     case Intrinsic::x86_fma_vfnmsub_pd:
16470     case Intrinsic::x86_fma_vfnmsub_ps_256:
16471     case Intrinsic::x86_fma_vfnmsub_pd_256:
16472     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
16473     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
16474       return X86ISD::FNMSUB;
16475     case Intrinsic::x86_fma_vfmaddsub_ps:
16476     case Intrinsic::x86_fma_vfmaddsub_pd:
16477     case Intrinsic::x86_fma_vfmaddsub_ps_256:
16478     case Intrinsic::x86_fma_vfmaddsub_pd_256:
16479     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
16480     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
16481       return X86ISD::FMADDSUB;
16482     case Intrinsic::x86_fma_vfmsubadd_ps:
16483     case Intrinsic::x86_fma_vfmsubadd_pd:
16484     case Intrinsic::x86_fma_vfmsubadd_ps_256:
16485     case Intrinsic::x86_fma_vfmsubadd_pd_256:
16486     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
16487     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
16488       return X86ISD::FMSUBADD;
16489     }
16490 }
16491
16492 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16493                                        SelectionDAG &DAG) {
16494   SDLoc dl(Op);
16495   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16496   EVT VT = Op.getValueType();
16497   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16498   if (IntrData) {
16499     switch(IntrData->Type) {
16500     case INTR_TYPE_1OP:
16501       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16502     case INTR_TYPE_2OP:
16503       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16504         Op.getOperand(2));
16505     case INTR_TYPE_3OP:
16506       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16507         Op.getOperand(2), Op.getOperand(3));
16508     case INTR_TYPE_1OP_MASK_RM: {
16509       SDValue Src = Op.getOperand(1);
16510       SDValue Src0 = Op.getOperand(2);
16511       SDValue Mask = Op.getOperand(3);
16512       SDValue RoundingMode = Op.getOperand(4);
16513       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16514                                               RoundingMode),
16515                                   Mask, Src0, Subtarget, DAG);
16516     }
16517                                               
16518     case CMP_MASK:
16519     case CMP_MASK_CC: {
16520       // Comparison intrinsics with masks.
16521       // Example of transformation:
16522       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16523       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16524       // (i8 (bitcast
16525       //   (v8i1 (insert_subvector undef,
16526       //           (v2i1 (and (PCMPEQM %a, %b),
16527       //                      (extract_subvector
16528       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16529       EVT VT = Op.getOperand(1).getValueType();
16530       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16531                                     VT.getVectorNumElements());
16532       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16533       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16534                                        Mask.getValueType().getSizeInBits());
16535       SDValue Cmp;
16536       if (IntrData->Type == CMP_MASK_CC) {
16537         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16538                     Op.getOperand(2), Op.getOperand(3));
16539       } else {
16540         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16541         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16542                     Op.getOperand(2));
16543       }
16544       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16545                                              DAG.getTargetConstant(0, MaskVT),
16546                                              Subtarget, DAG);
16547       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16548                                 DAG.getUNDEF(BitcastVT), CmpMask,
16549                                 DAG.getIntPtrConstant(0));
16550       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
16551     }
16552     case COMI: { // Comparison intrinsics
16553       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16554       SDValue LHS = Op.getOperand(1);
16555       SDValue RHS = Op.getOperand(2);
16556       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
16557       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16558       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16559       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16560                                   DAG.getConstant(X86CC, MVT::i8), Cond);
16561       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16562     }
16563     case VSHIFT:
16564       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16565                                  Op.getOperand(1), Op.getOperand(2), DAG);
16566     case VSHIFT_MASK:
16567       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16568                                                       Op.getOperand(1), Op.getOperand(2), DAG),
16569                                   Op.getOperand(4), Op.getOperand(3), Subtarget, DAG);;
16570     default:
16571       break;
16572     }
16573   }
16574
16575   switch (IntNo) {
16576   default: return SDValue();    // Don't custom lower most intrinsics.
16577
16578   // Arithmetic intrinsics.
16579   case Intrinsic::x86_sse2_pmulu_dq:
16580   case Intrinsic::x86_avx2_pmulu_dq:
16581     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
16582                        Op.getOperand(1), Op.getOperand(2));
16583
16584   case Intrinsic::x86_sse41_pmuldq:
16585   case Intrinsic::x86_avx2_pmul_dq:
16586     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
16587                        Op.getOperand(1), Op.getOperand(2));
16588
16589   case Intrinsic::x86_sse2_pmulhu_w:
16590   case Intrinsic::x86_avx2_pmulhu_w:
16591     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
16592                        Op.getOperand(1), Op.getOperand(2));
16593
16594   case Intrinsic::x86_sse2_pmulh_w:
16595   case Intrinsic::x86_avx2_pmulh_w:
16596     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
16597                        Op.getOperand(1), Op.getOperand(2));
16598
16599   // SSE/SSE2/AVX floating point max/min intrinsics.
16600   case Intrinsic::x86_sse_max_ps:
16601   case Intrinsic::x86_sse2_max_pd:
16602   case Intrinsic::x86_avx_max_ps_256:
16603   case Intrinsic::x86_avx_max_pd_256:
16604   case Intrinsic::x86_sse_min_ps:
16605   case Intrinsic::x86_sse2_min_pd:
16606   case Intrinsic::x86_avx_min_ps_256:
16607   case Intrinsic::x86_avx_min_pd_256: {
16608     unsigned Opcode;
16609     switch (IntNo) {
16610     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16611     case Intrinsic::x86_sse_max_ps:
16612     case Intrinsic::x86_sse2_max_pd:
16613     case Intrinsic::x86_avx_max_ps_256:
16614     case Intrinsic::x86_avx_max_pd_256:
16615       Opcode = X86ISD::FMAX;
16616       break;
16617     case Intrinsic::x86_sse_min_ps:
16618     case Intrinsic::x86_sse2_min_pd:
16619     case Intrinsic::x86_avx_min_ps_256:
16620     case Intrinsic::x86_avx_min_pd_256:
16621       Opcode = X86ISD::FMIN;
16622       break;
16623     }
16624     return DAG.getNode(Opcode, dl, Op.getValueType(),
16625                        Op.getOperand(1), Op.getOperand(2));
16626   }
16627
16628   // AVX2 variable shift intrinsics
16629   case Intrinsic::x86_avx2_psllv_d:
16630   case Intrinsic::x86_avx2_psllv_q:
16631   case Intrinsic::x86_avx2_psllv_d_256:
16632   case Intrinsic::x86_avx2_psllv_q_256:
16633   case Intrinsic::x86_avx2_psrlv_d:
16634   case Intrinsic::x86_avx2_psrlv_q:
16635   case Intrinsic::x86_avx2_psrlv_d_256:
16636   case Intrinsic::x86_avx2_psrlv_q_256:
16637   case Intrinsic::x86_avx2_psrav_d:
16638   case Intrinsic::x86_avx2_psrav_d_256: {
16639     unsigned Opcode;
16640     switch (IntNo) {
16641     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16642     case Intrinsic::x86_avx2_psllv_d:
16643     case Intrinsic::x86_avx2_psllv_q:
16644     case Intrinsic::x86_avx2_psllv_d_256:
16645     case Intrinsic::x86_avx2_psllv_q_256:
16646       Opcode = ISD::SHL;
16647       break;
16648     case Intrinsic::x86_avx2_psrlv_d:
16649     case Intrinsic::x86_avx2_psrlv_q:
16650     case Intrinsic::x86_avx2_psrlv_d_256:
16651     case Intrinsic::x86_avx2_psrlv_q_256:
16652       Opcode = ISD::SRL;
16653       break;
16654     case Intrinsic::x86_avx2_psrav_d:
16655     case Intrinsic::x86_avx2_psrav_d_256:
16656       Opcode = ISD::SRA;
16657       break;
16658     }
16659     return DAG.getNode(Opcode, dl, Op.getValueType(),
16660                        Op.getOperand(1), Op.getOperand(2));
16661   }
16662
16663   case Intrinsic::x86_sse2_packssdw_128:
16664   case Intrinsic::x86_sse2_packsswb_128:
16665   case Intrinsic::x86_avx2_packssdw:
16666   case Intrinsic::x86_avx2_packsswb:
16667     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
16668                        Op.getOperand(1), Op.getOperand(2));
16669
16670   case Intrinsic::x86_sse2_packuswb_128:
16671   case Intrinsic::x86_sse41_packusdw:
16672   case Intrinsic::x86_avx2_packuswb:
16673   case Intrinsic::x86_avx2_packusdw:
16674     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
16675                        Op.getOperand(1), Op.getOperand(2));
16676
16677   case Intrinsic::x86_ssse3_pshuf_b_128:
16678   case Intrinsic::x86_avx2_pshuf_b:
16679     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
16680                        Op.getOperand(1), Op.getOperand(2));
16681
16682   case Intrinsic::x86_sse2_pshuf_d:
16683     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
16684                        Op.getOperand(1), Op.getOperand(2));
16685
16686   case Intrinsic::x86_sse2_pshufl_w:
16687     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
16688                        Op.getOperand(1), Op.getOperand(2));
16689
16690   case Intrinsic::x86_sse2_pshufh_w:
16691     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
16692                        Op.getOperand(1), Op.getOperand(2));
16693
16694   case Intrinsic::x86_ssse3_psign_b_128:
16695   case Intrinsic::x86_ssse3_psign_w_128:
16696   case Intrinsic::x86_ssse3_psign_d_128:
16697   case Intrinsic::x86_avx2_psign_b:
16698   case Intrinsic::x86_avx2_psign_w:
16699   case Intrinsic::x86_avx2_psign_d:
16700     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
16701                        Op.getOperand(1), Op.getOperand(2));
16702
16703   case Intrinsic::x86_avx2_permd:
16704   case Intrinsic::x86_avx2_permps:
16705     // Operands intentionally swapped. Mask is last operand to intrinsic,
16706     // but second operand for node/instruction.
16707     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16708                        Op.getOperand(2), Op.getOperand(1));
16709
16710   case Intrinsic::x86_avx512_mask_valign_q_512:
16711   case Intrinsic::x86_avx512_mask_valign_d_512:
16712     // Vector source operands are swapped.
16713     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
16714                                             Op.getValueType(), Op.getOperand(2),
16715                                             Op.getOperand(1),
16716                                             Op.getOperand(3)),
16717                                 Op.getOperand(5), Op.getOperand(4),
16718                                 Subtarget, DAG);
16719
16720   // ptest and testp intrinsics. The intrinsic these come from are designed to
16721   // return an integer value, not just an instruction so lower it to the ptest
16722   // or testp pattern and a setcc for the result.
16723   case Intrinsic::x86_sse41_ptestz:
16724   case Intrinsic::x86_sse41_ptestc:
16725   case Intrinsic::x86_sse41_ptestnzc:
16726   case Intrinsic::x86_avx_ptestz_256:
16727   case Intrinsic::x86_avx_ptestc_256:
16728   case Intrinsic::x86_avx_ptestnzc_256:
16729   case Intrinsic::x86_avx_vtestz_ps:
16730   case Intrinsic::x86_avx_vtestc_ps:
16731   case Intrinsic::x86_avx_vtestnzc_ps:
16732   case Intrinsic::x86_avx_vtestz_pd:
16733   case Intrinsic::x86_avx_vtestc_pd:
16734   case Intrinsic::x86_avx_vtestnzc_pd:
16735   case Intrinsic::x86_avx_vtestz_ps_256:
16736   case Intrinsic::x86_avx_vtestc_ps_256:
16737   case Intrinsic::x86_avx_vtestnzc_ps_256:
16738   case Intrinsic::x86_avx_vtestz_pd_256:
16739   case Intrinsic::x86_avx_vtestc_pd_256:
16740   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16741     bool IsTestPacked = false;
16742     unsigned X86CC;
16743     switch (IntNo) {
16744     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16745     case Intrinsic::x86_avx_vtestz_ps:
16746     case Intrinsic::x86_avx_vtestz_pd:
16747     case Intrinsic::x86_avx_vtestz_ps_256:
16748     case Intrinsic::x86_avx_vtestz_pd_256:
16749       IsTestPacked = true; // Fallthrough
16750     case Intrinsic::x86_sse41_ptestz:
16751     case Intrinsic::x86_avx_ptestz_256:
16752       // ZF = 1
16753       X86CC = X86::COND_E;
16754       break;
16755     case Intrinsic::x86_avx_vtestc_ps:
16756     case Intrinsic::x86_avx_vtestc_pd:
16757     case Intrinsic::x86_avx_vtestc_ps_256:
16758     case Intrinsic::x86_avx_vtestc_pd_256:
16759       IsTestPacked = true; // Fallthrough
16760     case Intrinsic::x86_sse41_ptestc:
16761     case Intrinsic::x86_avx_ptestc_256:
16762       // CF = 1
16763       X86CC = X86::COND_B;
16764       break;
16765     case Intrinsic::x86_avx_vtestnzc_ps:
16766     case Intrinsic::x86_avx_vtestnzc_pd:
16767     case Intrinsic::x86_avx_vtestnzc_ps_256:
16768     case Intrinsic::x86_avx_vtestnzc_pd_256:
16769       IsTestPacked = true; // Fallthrough
16770     case Intrinsic::x86_sse41_ptestnzc:
16771     case Intrinsic::x86_avx_ptestnzc_256:
16772       // ZF and CF = 0
16773       X86CC = X86::COND_A;
16774       break;
16775     }
16776
16777     SDValue LHS = Op.getOperand(1);
16778     SDValue RHS = Op.getOperand(2);
16779     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16780     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16781     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
16782     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16783     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16784   }
16785   case Intrinsic::x86_avx512_kortestz_w:
16786   case Intrinsic::x86_avx512_kortestc_w: {
16787     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16788     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
16789     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
16790     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
16791     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16792     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16793     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16794   }
16795
16796   case Intrinsic::x86_sse42_pcmpistria128:
16797   case Intrinsic::x86_sse42_pcmpestria128:
16798   case Intrinsic::x86_sse42_pcmpistric128:
16799   case Intrinsic::x86_sse42_pcmpestric128:
16800   case Intrinsic::x86_sse42_pcmpistrio128:
16801   case Intrinsic::x86_sse42_pcmpestrio128:
16802   case Intrinsic::x86_sse42_pcmpistris128:
16803   case Intrinsic::x86_sse42_pcmpestris128:
16804   case Intrinsic::x86_sse42_pcmpistriz128:
16805   case Intrinsic::x86_sse42_pcmpestriz128: {
16806     unsigned Opcode;
16807     unsigned X86CC;
16808     switch (IntNo) {
16809     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16810     case Intrinsic::x86_sse42_pcmpistria128:
16811       Opcode = X86ISD::PCMPISTRI;
16812       X86CC = X86::COND_A;
16813       break;
16814     case Intrinsic::x86_sse42_pcmpestria128:
16815       Opcode = X86ISD::PCMPESTRI;
16816       X86CC = X86::COND_A;
16817       break;
16818     case Intrinsic::x86_sse42_pcmpistric128:
16819       Opcode = X86ISD::PCMPISTRI;
16820       X86CC = X86::COND_B;
16821       break;
16822     case Intrinsic::x86_sse42_pcmpestric128:
16823       Opcode = X86ISD::PCMPESTRI;
16824       X86CC = X86::COND_B;
16825       break;
16826     case Intrinsic::x86_sse42_pcmpistrio128:
16827       Opcode = X86ISD::PCMPISTRI;
16828       X86CC = X86::COND_O;
16829       break;
16830     case Intrinsic::x86_sse42_pcmpestrio128:
16831       Opcode = X86ISD::PCMPESTRI;
16832       X86CC = X86::COND_O;
16833       break;
16834     case Intrinsic::x86_sse42_pcmpistris128:
16835       Opcode = X86ISD::PCMPISTRI;
16836       X86CC = X86::COND_S;
16837       break;
16838     case Intrinsic::x86_sse42_pcmpestris128:
16839       Opcode = X86ISD::PCMPESTRI;
16840       X86CC = X86::COND_S;
16841       break;
16842     case Intrinsic::x86_sse42_pcmpistriz128:
16843       Opcode = X86ISD::PCMPISTRI;
16844       X86CC = X86::COND_E;
16845       break;
16846     case Intrinsic::x86_sse42_pcmpestriz128:
16847       Opcode = X86ISD::PCMPESTRI;
16848       X86CC = X86::COND_E;
16849       break;
16850     }
16851     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16852     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16853     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16854     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16855                                 DAG.getConstant(X86CC, MVT::i8),
16856                                 SDValue(PCMP.getNode(), 1));
16857     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16858   }
16859
16860   case Intrinsic::x86_sse42_pcmpistri128:
16861   case Intrinsic::x86_sse42_pcmpestri128: {
16862     unsigned Opcode;
16863     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16864       Opcode = X86ISD::PCMPISTRI;
16865     else
16866       Opcode = X86ISD::PCMPESTRI;
16867
16868     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16869     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16870     return DAG.getNode(Opcode, dl, VTs, NewOps);
16871   }
16872
16873   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
16874   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
16875   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
16876   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
16877   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
16878   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
16879   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
16880   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
16881   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
16882   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
16883   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
16884   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
16885     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
16886     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
16887       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
16888                                               dl, Op.getValueType(),
16889                                               Op.getOperand(1),
16890                                               Op.getOperand(2),
16891                                               Op.getOperand(3)),
16892                                   Op.getOperand(4), Op.getOperand(1),
16893                                   Subtarget, DAG);
16894     else
16895       return SDValue();
16896   }
16897
16898   case Intrinsic::x86_fma_vfmadd_ps:
16899   case Intrinsic::x86_fma_vfmadd_pd:
16900   case Intrinsic::x86_fma_vfmsub_ps:
16901   case Intrinsic::x86_fma_vfmsub_pd:
16902   case Intrinsic::x86_fma_vfnmadd_ps:
16903   case Intrinsic::x86_fma_vfnmadd_pd:
16904   case Intrinsic::x86_fma_vfnmsub_ps:
16905   case Intrinsic::x86_fma_vfnmsub_pd:
16906   case Intrinsic::x86_fma_vfmaddsub_ps:
16907   case Intrinsic::x86_fma_vfmaddsub_pd:
16908   case Intrinsic::x86_fma_vfmsubadd_ps:
16909   case Intrinsic::x86_fma_vfmsubadd_pd:
16910   case Intrinsic::x86_fma_vfmadd_ps_256:
16911   case Intrinsic::x86_fma_vfmadd_pd_256:
16912   case Intrinsic::x86_fma_vfmsub_ps_256:
16913   case Intrinsic::x86_fma_vfmsub_pd_256:
16914   case Intrinsic::x86_fma_vfnmadd_ps_256:
16915   case Intrinsic::x86_fma_vfnmadd_pd_256:
16916   case Intrinsic::x86_fma_vfnmsub_ps_256:
16917   case Intrinsic::x86_fma_vfnmsub_pd_256:
16918   case Intrinsic::x86_fma_vfmaddsub_ps_256:
16919   case Intrinsic::x86_fma_vfmaddsub_pd_256:
16920   case Intrinsic::x86_fma_vfmsubadd_ps_256:
16921   case Intrinsic::x86_fma_vfmsubadd_pd_256:
16922     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
16923                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
16924   }
16925 }
16926
16927 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16928                               SDValue Src, SDValue Mask, SDValue Base,
16929                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16930                               const X86Subtarget * Subtarget) {
16931   SDLoc dl(Op);
16932   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16933   assert(C && "Invalid scale type");
16934   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
16935   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16936                              Index.getSimpleValueType().getVectorNumElements());
16937   SDValue MaskInReg;
16938   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16939   if (MaskC)
16940     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
16941   else
16942     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
16943   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16944   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
16945   SDValue Segment = DAG.getRegister(0, MVT::i32);
16946   if (Src.getOpcode() == ISD::UNDEF)
16947     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16948   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16949   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16950   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16951   return DAG.getMergeValues(RetOps, dl);
16952 }
16953
16954 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16955                                SDValue Src, SDValue Mask, SDValue Base,
16956                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16957   SDLoc dl(Op);
16958   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16959   assert(C && "Invalid scale type");
16960   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
16961   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
16962   SDValue Segment = DAG.getRegister(0, MVT::i32);
16963   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16964                              Index.getSimpleValueType().getVectorNumElements());
16965   SDValue MaskInReg;
16966   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16967   if (MaskC)
16968     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
16969   else
16970     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
16971   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16972   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16973   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16974   return SDValue(Res, 1);
16975 }
16976
16977 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16978                                SDValue Mask, SDValue Base, SDValue Index,
16979                                SDValue ScaleOp, SDValue Chain) {
16980   SDLoc dl(Op);
16981   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16982   assert(C && "Invalid scale type");
16983   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
16984   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
16985   SDValue Segment = DAG.getRegister(0, MVT::i32);
16986   EVT MaskVT =
16987     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16988   SDValue MaskInReg;
16989   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16990   if (MaskC)
16991     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
16992   else
16993     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
16994   //SDVTList VTs = DAG.getVTList(MVT::Other);
16995   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16996   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16997   return SDValue(Res, 0);
16998 }
16999
17000 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17001 // read performance monitor counters (x86_rdpmc).
17002 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17003                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17004                               SmallVectorImpl<SDValue> &Results) {
17005   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17006   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17007   SDValue LO, HI;
17008
17009   // The ECX register is used to select the index of the performance counter
17010   // to read.
17011   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17012                                    N->getOperand(2));
17013   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17014
17015   // Reads the content of a 64-bit performance counter and returns it in the
17016   // registers EDX:EAX.
17017   if (Subtarget->is64Bit()) {
17018     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17019     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17020                             LO.getValue(2));
17021   } else {
17022     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17023     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17024                             LO.getValue(2));
17025   }
17026   Chain = HI.getValue(1);
17027
17028   if (Subtarget->is64Bit()) {
17029     // The EAX register is loaded with the low-order 32 bits. The EDX register
17030     // is loaded with the supported high-order bits of the counter.
17031     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17032                               DAG.getConstant(32, MVT::i8));
17033     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17034     Results.push_back(Chain);
17035     return;
17036   }
17037
17038   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17039   SDValue Ops[] = { LO, HI };
17040   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17041   Results.push_back(Pair);
17042   Results.push_back(Chain);
17043 }
17044
17045 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17046 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17047 // also used to custom lower READCYCLECOUNTER nodes.
17048 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17049                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17050                               SmallVectorImpl<SDValue> &Results) {
17051   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17052   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17053   SDValue LO, HI;
17054
17055   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17056   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17057   // and the EAX register is loaded with the low-order 32 bits.
17058   if (Subtarget->is64Bit()) {
17059     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17060     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17061                             LO.getValue(2));
17062   } else {
17063     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17064     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17065                             LO.getValue(2));
17066   }
17067   SDValue Chain = HI.getValue(1);
17068
17069   if (Opcode == X86ISD::RDTSCP_DAG) {
17070     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17071
17072     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17073     // the ECX register. Add 'ecx' explicitly to the chain.
17074     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17075                                      HI.getValue(2));
17076     // Explicitly store the content of ECX at the location passed in input
17077     // to the 'rdtscp' intrinsic.
17078     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17079                          MachinePointerInfo(), false, false, 0);
17080   }
17081
17082   if (Subtarget->is64Bit()) {
17083     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17084     // the EAX register is loaded with the low-order 32 bits.
17085     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17086                               DAG.getConstant(32, MVT::i8));
17087     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17088     Results.push_back(Chain);
17089     return;
17090   }
17091
17092   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17093   SDValue Ops[] = { LO, HI };
17094   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17095   Results.push_back(Pair);
17096   Results.push_back(Chain);
17097 }
17098
17099 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17100                                      SelectionDAG &DAG) {
17101   SmallVector<SDValue, 2> Results;
17102   SDLoc DL(Op);
17103   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17104                           Results);
17105   return DAG.getMergeValues(Results, DL);
17106 }
17107
17108
17109 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17110                                       SelectionDAG &DAG) {
17111   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17112
17113   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17114   if (!IntrData)
17115     return SDValue();
17116
17117   SDLoc dl(Op);
17118   switch(IntrData->Type) {
17119   default:
17120     llvm_unreachable("Unknown Intrinsic Type");
17121     break;    
17122   case RDSEED:
17123   case RDRAND: {
17124     // Emit the node with the right value type.
17125     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17126     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17127
17128     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17129     // Otherwise return the value from Rand, which is always 0, casted to i32.
17130     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17131                       DAG.getConstant(1, Op->getValueType(1)),
17132                       DAG.getConstant(X86::COND_B, MVT::i32),
17133                       SDValue(Result.getNode(), 1) };
17134     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17135                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17136                                   Ops);
17137
17138     // Return { result, isValid, chain }.
17139     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17140                        SDValue(Result.getNode(), 2));
17141   }
17142   case GATHER: {
17143   //gather(v1, mask, index, base, scale);
17144     SDValue Chain = Op.getOperand(0);
17145     SDValue Src   = Op.getOperand(2);
17146     SDValue Base  = Op.getOperand(3);
17147     SDValue Index = Op.getOperand(4);
17148     SDValue Mask  = Op.getOperand(5);
17149     SDValue Scale = Op.getOperand(6);
17150     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
17151                           Subtarget);
17152   }
17153   case SCATTER: {
17154   //scatter(base, mask, index, v1, scale);
17155     SDValue Chain = Op.getOperand(0);
17156     SDValue Base  = Op.getOperand(2);
17157     SDValue Mask  = Op.getOperand(3);
17158     SDValue Index = Op.getOperand(4);
17159     SDValue Src   = Op.getOperand(5);
17160     SDValue Scale = Op.getOperand(6);
17161     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
17162   }
17163   case PREFETCH: {
17164     SDValue Hint = Op.getOperand(6);
17165     unsigned HintVal;
17166     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
17167         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
17168       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
17169     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17170     SDValue Chain = Op.getOperand(0);
17171     SDValue Mask  = Op.getOperand(2);
17172     SDValue Index = Op.getOperand(3);
17173     SDValue Base  = Op.getOperand(4);
17174     SDValue Scale = Op.getOperand(5);
17175     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17176   }
17177   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17178   case RDTSC: {
17179     SmallVector<SDValue, 2> Results;
17180     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
17181     return DAG.getMergeValues(Results, dl);
17182   }
17183   // Read Performance Monitoring Counters.
17184   case RDPMC: {
17185     SmallVector<SDValue, 2> Results;
17186     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17187     return DAG.getMergeValues(Results, dl);
17188   }
17189   // XTEST intrinsics.
17190   case XTEST: {
17191     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17192     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17193     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17194                                 DAG.getConstant(X86::COND_NE, MVT::i8),
17195                                 InTrans);
17196     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17197     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17198                        Ret, SDValue(InTrans.getNode(), 1));
17199   }
17200   // ADC/ADCX/SBB
17201   case ADX: {
17202     SmallVector<SDValue, 2> Results;
17203     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17204     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17205     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17206                                 DAG.getConstant(-1, MVT::i8));
17207     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17208                               Op.getOperand(4), GenCF.getValue(1));
17209     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17210                                  Op.getOperand(5), MachinePointerInfo(),
17211                                  false, false, 0);
17212     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17213                                 DAG.getConstant(X86::COND_B, MVT::i8),
17214                                 Res.getValue(1));
17215     Results.push_back(SetCC);
17216     Results.push_back(Store);
17217     return DAG.getMergeValues(Results, dl);
17218   }
17219   }
17220 }
17221
17222 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17223                                            SelectionDAG &DAG) const {
17224   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17225   MFI->setReturnAddressIsTaken(true);
17226
17227   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17228     return SDValue();
17229
17230   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17231   SDLoc dl(Op);
17232   EVT PtrVT = getPointerTy();
17233
17234   if (Depth > 0) {
17235     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17236     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17237         DAG.getSubtarget().getRegisterInfo());
17238     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
17239     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17240                        DAG.getNode(ISD::ADD, dl, PtrVT,
17241                                    FrameAddr, Offset),
17242                        MachinePointerInfo(), false, false, false, 0);
17243   }
17244
17245   // Just load the return address.
17246   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17247   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17248                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17249 }
17250
17251 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17252   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17253   MFI->setFrameAddressIsTaken(true);
17254
17255   EVT VT = Op.getValueType();
17256   SDLoc dl(Op);  // FIXME probably not meaningful
17257   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17258   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17259       DAG.getSubtarget().getRegisterInfo());
17260   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17261   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17262           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17263          "Invalid Frame Register!");
17264   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17265   while (Depth--)
17266     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17267                             MachinePointerInfo(),
17268                             false, false, false, 0);
17269   return FrameAddr;
17270 }
17271
17272 // FIXME? Maybe this could be a TableGen attribute on some registers and
17273 // this table could be generated automatically from RegInfo.
17274 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
17275                                               EVT VT) const {
17276   unsigned Reg = StringSwitch<unsigned>(RegName)
17277                        .Case("esp", X86::ESP)
17278                        .Case("rsp", X86::RSP)
17279                        .Default(0);
17280   if (Reg)
17281     return Reg;
17282   report_fatal_error("Invalid register name global variable");
17283 }
17284
17285 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17286                                                      SelectionDAG &DAG) const {
17287   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17288       DAG.getSubtarget().getRegisterInfo());
17289   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
17290 }
17291
17292 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17293   SDValue Chain     = Op.getOperand(0);
17294   SDValue Offset    = Op.getOperand(1);
17295   SDValue Handler   = Op.getOperand(2);
17296   SDLoc dl      (Op);
17297
17298   EVT PtrVT = getPointerTy();
17299   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17300       DAG.getSubtarget().getRegisterInfo());
17301   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17302   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17303           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17304          "Invalid Frame Register!");
17305   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17306   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17307
17308   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17309                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
17310   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17311   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17312                        false, false, 0);
17313   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17314
17315   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17316                      DAG.getRegister(StoreAddrReg, PtrVT));
17317 }
17318
17319 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17320                                                SelectionDAG &DAG) const {
17321   SDLoc DL(Op);
17322   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17323                      DAG.getVTList(MVT::i32, MVT::Other),
17324                      Op.getOperand(0), Op.getOperand(1));
17325 }
17326
17327 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17328                                                 SelectionDAG &DAG) const {
17329   SDLoc DL(Op);
17330   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17331                      Op.getOperand(0), Op.getOperand(1));
17332 }
17333
17334 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17335   return Op.getOperand(0);
17336 }
17337
17338 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17339                                                 SelectionDAG &DAG) const {
17340   SDValue Root = Op.getOperand(0);
17341   SDValue Trmp = Op.getOperand(1); // trampoline
17342   SDValue FPtr = Op.getOperand(2); // nested function
17343   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17344   SDLoc dl (Op);
17345
17346   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17347   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
17348
17349   if (Subtarget->is64Bit()) {
17350     SDValue OutChains[6];
17351
17352     // Large code-model.
17353     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17354     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17355
17356     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17357     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17358
17359     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17360
17361     // Load the pointer to the nested function into R11.
17362     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17363     SDValue Addr = Trmp;
17364     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17365                                 Addr, MachinePointerInfo(TrmpAddr),
17366                                 false, false, 0);
17367
17368     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17369                        DAG.getConstant(2, MVT::i64));
17370     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17371                                 MachinePointerInfo(TrmpAddr, 2),
17372                                 false, false, 2);
17373
17374     // Load the 'nest' parameter value into R10.
17375     // R10 is specified in X86CallingConv.td
17376     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17377     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17378                        DAG.getConstant(10, MVT::i64));
17379     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17380                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17381                                 false, false, 0);
17382
17383     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17384                        DAG.getConstant(12, MVT::i64));
17385     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17386                                 MachinePointerInfo(TrmpAddr, 12),
17387                                 false, false, 2);
17388
17389     // Jump to the nested function.
17390     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17391     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17392                        DAG.getConstant(20, MVT::i64));
17393     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17394                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17395                                 false, false, 0);
17396
17397     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17398     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17399                        DAG.getConstant(22, MVT::i64));
17400     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
17401                                 MachinePointerInfo(TrmpAddr, 22),
17402                                 false, false, 0);
17403
17404     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17405   } else {
17406     const Function *Func =
17407       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17408     CallingConv::ID CC = Func->getCallingConv();
17409     unsigned NestReg;
17410
17411     switch (CC) {
17412     default:
17413       llvm_unreachable("Unsupported calling convention");
17414     case CallingConv::C:
17415     case CallingConv::X86_StdCall: {
17416       // Pass 'nest' parameter in ECX.
17417       // Must be kept in sync with X86CallingConv.td
17418       NestReg = X86::ECX;
17419
17420       // Check that ECX wasn't needed by an 'inreg' parameter.
17421       FunctionType *FTy = Func->getFunctionType();
17422       const AttributeSet &Attrs = Func->getAttributes();
17423
17424       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17425         unsigned InRegCount = 0;
17426         unsigned Idx = 1;
17427
17428         for (FunctionType::param_iterator I = FTy->param_begin(),
17429              E = FTy->param_end(); I != E; ++I, ++Idx)
17430           if (Attrs.hasAttribute(Idx, Attribute::InReg))
17431             // FIXME: should only count parameters that are lowered to integers.
17432             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
17433
17434         if (InRegCount > 2) {
17435           report_fatal_error("Nest register in use - reduce number of inreg"
17436                              " parameters!");
17437         }
17438       }
17439       break;
17440     }
17441     case CallingConv::X86_FastCall:
17442     case CallingConv::X86_ThisCall:
17443     case CallingConv::Fast:
17444       // Pass 'nest' parameter in EAX.
17445       // Must be kept in sync with X86CallingConv.td
17446       NestReg = X86::EAX;
17447       break;
17448     }
17449
17450     SDValue OutChains[4];
17451     SDValue Addr, Disp;
17452
17453     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17454                        DAG.getConstant(10, MVT::i32));
17455     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17456
17457     // This is storing the opcode for MOV32ri.
17458     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17459     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17460     OutChains[0] = DAG.getStore(Root, dl,
17461                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
17462                                 Trmp, MachinePointerInfo(TrmpAddr),
17463                                 false, false, 0);
17464
17465     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17466                        DAG.getConstant(1, MVT::i32));
17467     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17468                                 MachinePointerInfo(TrmpAddr, 1),
17469                                 false, false, 1);
17470
17471     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17472     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17473                        DAG.getConstant(5, MVT::i32));
17474     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
17475                                 MachinePointerInfo(TrmpAddr, 5),
17476                                 false, false, 1);
17477
17478     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17479                        DAG.getConstant(6, MVT::i32));
17480     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17481                                 MachinePointerInfo(TrmpAddr, 6),
17482                                 false, false, 1);
17483
17484     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17485   }
17486 }
17487
17488 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17489                                             SelectionDAG &DAG) const {
17490   /*
17491    The rounding mode is in bits 11:10 of FPSR, and has the following
17492    settings:
17493      00 Round to nearest
17494      01 Round to -inf
17495      10 Round to +inf
17496      11 Round to 0
17497
17498   FLT_ROUNDS, on the other hand, expects the following:
17499     -1 Undefined
17500      0 Round to 0
17501      1 Round to nearest
17502      2 Round to +inf
17503      3 Round to -inf
17504
17505   To perform the conversion, we do:
17506     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17507   */
17508
17509   MachineFunction &MF = DAG.getMachineFunction();
17510   const TargetMachine &TM = MF.getTarget();
17511   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
17512   unsigned StackAlignment = TFI.getStackAlignment();
17513   MVT VT = Op.getSimpleValueType();
17514   SDLoc DL(Op);
17515
17516   // Save FP Control Word to stack slot
17517   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17518   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
17519
17520   MachineMemOperand *MMO =
17521    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
17522                            MachineMemOperand::MOStore, 2, 2);
17523
17524   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17525   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17526                                           DAG.getVTList(MVT::Other),
17527                                           Ops, MVT::i16, MMO);
17528
17529   // Load FP Control Word from stack slot
17530   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17531                             MachinePointerInfo(), false, false, false, 0);
17532
17533   // Transform as necessary
17534   SDValue CWD1 =
17535     DAG.getNode(ISD::SRL, DL, MVT::i16,
17536                 DAG.getNode(ISD::AND, DL, MVT::i16,
17537                             CWD, DAG.getConstant(0x800, MVT::i16)),
17538                 DAG.getConstant(11, MVT::i8));
17539   SDValue CWD2 =
17540     DAG.getNode(ISD::SRL, DL, MVT::i16,
17541                 DAG.getNode(ISD::AND, DL, MVT::i16,
17542                             CWD, DAG.getConstant(0x400, MVT::i16)),
17543                 DAG.getConstant(9, MVT::i8));
17544
17545   SDValue RetVal =
17546     DAG.getNode(ISD::AND, DL, MVT::i16,
17547                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17548                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17549                             DAG.getConstant(1, MVT::i16)),
17550                 DAG.getConstant(3, MVT::i16));
17551
17552   return DAG.getNode((VT.getSizeInBits() < 16 ?
17553                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17554 }
17555
17556 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17557   MVT VT = Op.getSimpleValueType();
17558   EVT OpVT = VT;
17559   unsigned NumBits = VT.getSizeInBits();
17560   SDLoc dl(Op);
17561
17562   Op = Op.getOperand(0);
17563   if (VT == MVT::i8) {
17564     // Zero extend to i32 since there is not an i8 bsr.
17565     OpVT = MVT::i32;
17566     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17567   }
17568
17569   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17570   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17571   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17572
17573   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17574   SDValue Ops[] = {
17575     Op,
17576     DAG.getConstant(NumBits+NumBits-1, OpVT),
17577     DAG.getConstant(X86::COND_E, MVT::i8),
17578     Op.getValue(1)
17579   };
17580   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17581
17582   // Finally xor with NumBits-1.
17583   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17584
17585   if (VT == MVT::i8)
17586     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17587   return Op;
17588 }
17589
17590 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17591   MVT VT = Op.getSimpleValueType();
17592   EVT OpVT = VT;
17593   unsigned NumBits = VT.getSizeInBits();
17594   SDLoc dl(Op);
17595
17596   Op = Op.getOperand(0);
17597   if (VT == MVT::i8) {
17598     // Zero extend to i32 since there is not an i8 bsr.
17599     OpVT = MVT::i32;
17600     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17601   }
17602
17603   // Issue a bsr (scan bits in reverse).
17604   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17605   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17606
17607   // And xor with NumBits-1.
17608   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17609
17610   if (VT == MVT::i8)
17611     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17612   return Op;
17613 }
17614
17615 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17616   MVT VT = Op.getSimpleValueType();
17617   unsigned NumBits = VT.getSizeInBits();
17618   SDLoc dl(Op);
17619   Op = Op.getOperand(0);
17620
17621   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17622   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17623   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17624
17625   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17626   SDValue Ops[] = {
17627     Op,
17628     DAG.getConstant(NumBits, VT),
17629     DAG.getConstant(X86::COND_E, MVT::i8),
17630     Op.getValue(1)
17631   };
17632   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17633 }
17634
17635 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17636 // ones, and then concatenate the result back.
17637 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17638   MVT VT = Op.getSimpleValueType();
17639
17640   assert(VT.is256BitVector() && VT.isInteger() &&
17641          "Unsupported value type for operation");
17642
17643   unsigned NumElems = VT.getVectorNumElements();
17644   SDLoc dl(Op);
17645
17646   // Extract the LHS vectors
17647   SDValue LHS = Op.getOperand(0);
17648   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17649   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17650
17651   // Extract the RHS vectors
17652   SDValue RHS = Op.getOperand(1);
17653   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17654   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17655
17656   MVT EltVT = VT.getVectorElementType();
17657   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17658
17659   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17660                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17661                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17662 }
17663
17664 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17665   assert(Op.getSimpleValueType().is256BitVector() &&
17666          Op.getSimpleValueType().isInteger() &&
17667          "Only handle AVX 256-bit vector integer operation");
17668   return Lower256IntArith(Op, DAG);
17669 }
17670
17671 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17672   assert(Op.getSimpleValueType().is256BitVector() &&
17673          Op.getSimpleValueType().isInteger() &&
17674          "Only handle AVX 256-bit vector integer operation");
17675   return Lower256IntArith(Op, DAG);
17676 }
17677
17678 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17679                         SelectionDAG &DAG) {
17680   SDLoc dl(Op);
17681   MVT VT = Op.getSimpleValueType();
17682
17683   // Decompose 256-bit ops into smaller 128-bit ops.
17684   if (VT.is256BitVector() && !Subtarget->hasInt256())
17685     return Lower256IntArith(Op, DAG);
17686
17687   SDValue A = Op.getOperand(0);
17688   SDValue B = Op.getOperand(1);
17689
17690   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17691   if (VT == MVT::v4i32) {
17692     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17693            "Should not custom lower when pmuldq is available!");
17694
17695     // Extract the odd parts.
17696     static const int UnpackMask[] = { 1, -1, 3, -1 };
17697     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17698     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17699
17700     // Multiply the even parts.
17701     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17702     // Now multiply odd parts.
17703     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17704
17705     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
17706     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
17707
17708     // Merge the two vectors back together with a shuffle. This expands into 2
17709     // shuffles.
17710     static const int ShufMask[] = { 0, 4, 2, 6 };
17711     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17712   }
17713
17714   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17715          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17716
17717   //  Ahi = psrlqi(a, 32);
17718   //  Bhi = psrlqi(b, 32);
17719   //
17720   //  AloBlo = pmuludq(a, b);
17721   //  AloBhi = pmuludq(a, Bhi);
17722   //  AhiBlo = pmuludq(Ahi, b);
17723
17724   //  AloBhi = psllqi(AloBhi, 32);
17725   //  AhiBlo = psllqi(AhiBlo, 32);
17726   //  return AloBlo + AloBhi + AhiBlo;
17727
17728   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17729   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17730
17731   // Bit cast to 32-bit vectors for MULUDQ
17732   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17733                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17734   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
17735   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
17736   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
17737   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
17738
17739   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17740   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17741   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17742
17743   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17744   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17745
17746   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17747   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17748 }
17749
17750 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17751   assert(Subtarget->isTargetWin64() && "Unexpected target");
17752   EVT VT = Op.getValueType();
17753   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17754          "Unexpected return type for lowering");
17755
17756   RTLIB::Libcall LC;
17757   bool isSigned;
17758   switch (Op->getOpcode()) {
17759   default: llvm_unreachable("Unexpected request for libcall!");
17760   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17761   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17762   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17763   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17764   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17765   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17766   }
17767
17768   SDLoc dl(Op);
17769   SDValue InChain = DAG.getEntryNode();
17770
17771   TargetLowering::ArgListTy Args;
17772   TargetLowering::ArgListEntry Entry;
17773   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17774     EVT ArgVT = Op->getOperand(i).getValueType();
17775     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17776            "Unexpected argument type for lowering");
17777     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17778     Entry.Node = StackPtr;
17779     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17780                            false, false, 16);
17781     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17782     Entry.Ty = PointerType::get(ArgTy,0);
17783     Entry.isSExt = false;
17784     Entry.isZExt = false;
17785     Args.push_back(Entry);
17786   }
17787
17788   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17789                                          getPointerTy());
17790
17791   TargetLowering::CallLoweringInfo CLI(DAG);
17792   CLI.setDebugLoc(dl).setChain(InChain)
17793     .setCallee(getLibcallCallingConv(LC),
17794                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17795                Callee, std::move(Args), 0)
17796     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17797
17798   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17799   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
17800 }
17801
17802 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17803                              SelectionDAG &DAG) {
17804   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17805   EVT VT = Op0.getValueType();
17806   SDLoc dl(Op);
17807
17808   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17809          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17810
17811   // PMULxD operations multiply each even value (starting at 0) of LHS with
17812   // the related value of RHS and produce a widen result.
17813   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17814   // => <2 x i64> <ae|cg>
17815   //
17816   // In other word, to have all the results, we need to perform two PMULxD:
17817   // 1. one with the even values.
17818   // 2. one with the odd values.
17819   // To achieve #2, with need to place the odd values at an even position.
17820   //
17821   // Place the odd value at an even position (basically, shift all values 1
17822   // step to the left):
17823   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17824   // <a|b|c|d> => <b|undef|d|undef>
17825   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17826   // <e|f|g|h> => <f|undef|h|undef>
17827   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17828
17829   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17830   // ints.
17831   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17832   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17833   unsigned Opcode =
17834       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17835   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17836   // => <2 x i64> <ae|cg>
17837   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
17838                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17839   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17840   // => <2 x i64> <bf|dh>
17841   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
17842                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17843
17844   // Shuffle it back into the right order.
17845   SDValue Highs, Lows;
17846   if (VT == MVT::v8i32) {
17847     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17848     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17849     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17850     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17851   } else {
17852     const int HighMask[] = {1, 5, 3, 7};
17853     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17854     const int LowMask[] = {0, 4, 2, 6};
17855     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17856   }
17857
17858   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17859   // unsigned multiply.
17860   if (IsSigned && !Subtarget->hasSSE41()) {
17861     SDValue ShAmt =
17862         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
17863     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17864                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17865     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17866                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17867
17868     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17869     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17870   }
17871
17872   // The first result of MUL_LOHI is actually the low value, followed by the
17873   // high value.
17874   SDValue Ops[] = {Lows, Highs};
17875   return DAG.getMergeValues(Ops, dl);
17876 }
17877
17878 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17879                                          const X86Subtarget *Subtarget) {
17880   MVT VT = Op.getSimpleValueType();
17881   SDLoc dl(Op);
17882   SDValue R = Op.getOperand(0);
17883   SDValue Amt = Op.getOperand(1);
17884
17885   // Optimize shl/srl/sra with constant shift amount.
17886   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17887     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17888       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17889
17890       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
17891           (Subtarget->hasInt256() &&
17892            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
17893           (Subtarget->hasAVX512() &&
17894            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
17895         if (Op.getOpcode() == ISD::SHL)
17896           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
17897                                             DAG);
17898         if (Op.getOpcode() == ISD::SRL)
17899           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
17900                                             DAG);
17901         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
17902           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
17903                                             DAG);
17904       }
17905
17906       if (VT == MVT::v16i8) {
17907         if (Op.getOpcode() == ISD::SHL) {
17908           // Make a large shift.
17909           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
17910                                                    MVT::v8i16, R, ShiftAmt,
17911                                                    DAG);
17912           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
17913           // Zero out the rightmost bits.
17914           SmallVector<SDValue, 16> V(16,
17915                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
17916                                                      MVT::i8));
17917           return DAG.getNode(ISD::AND, dl, VT, SHL,
17918                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17919         }
17920         if (Op.getOpcode() == ISD::SRL) {
17921           // Make a large shift.
17922           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
17923                                                    MVT::v8i16, R, ShiftAmt,
17924                                                    DAG);
17925           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
17926           // Zero out the leftmost bits.
17927           SmallVector<SDValue, 16> V(16,
17928                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
17929                                                      MVT::i8));
17930           return DAG.getNode(ISD::AND, dl, VT, SRL,
17931                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17932         }
17933         if (Op.getOpcode() == ISD::SRA) {
17934           if (ShiftAmt == 7) {
17935             // R s>> 7  ===  R s< 0
17936             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17937             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17938           }
17939
17940           // R s>> a === ((R u>> a) ^ m) - m
17941           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17942           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
17943                                                          MVT::i8));
17944           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17945           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17946           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17947           return Res;
17948         }
17949         llvm_unreachable("Unknown shift opcode.");
17950       }
17951
17952       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
17953         if (Op.getOpcode() == ISD::SHL) {
17954           // Make a large shift.
17955           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
17956                                                    MVT::v16i16, R, ShiftAmt,
17957                                                    DAG);
17958           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
17959           // Zero out the rightmost bits.
17960           SmallVector<SDValue, 32> V(32,
17961                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
17962                                                      MVT::i8));
17963           return DAG.getNode(ISD::AND, dl, VT, SHL,
17964                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17965         }
17966         if (Op.getOpcode() == ISD::SRL) {
17967           // Make a large shift.
17968           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
17969                                                    MVT::v16i16, R, ShiftAmt,
17970                                                    DAG);
17971           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
17972           // Zero out the leftmost bits.
17973           SmallVector<SDValue, 32> V(32,
17974                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
17975                                                      MVT::i8));
17976           return DAG.getNode(ISD::AND, dl, VT, SRL,
17977                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17978         }
17979         if (Op.getOpcode() == ISD::SRA) {
17980           if (ShiftAmt == 7) {
17981             // R s>> 7  ===  R s< 0
17982             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17983             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17984           }
17985
17986           // R s>> a === ((R u>> a) ^ m) - m
17987           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17988           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
17989                                                          MVT::i8));
17990           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17991           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17992           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17993           return Res;
17994         }
17995         llvm_unreachable("Unknown shift opcode.");
17996       }
17997     }
17998   }
17999
18000   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18001   if (!Subtarget->is64Bit() &&
18002       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18003       Amt.getOpcode() == ISD::BITCAST &&
18004       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18005     Amt = Amt.getOperand(0);
18006     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18007                      VT.getVectorNumElements();
18008     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18009     uint64_t ShiftAmt = 0;
18010     for (unsigned i = 0; i != Ratio; ++i) {
18011       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
18012       if (!C)
18013         return SDValue();
18014       // 6 == Log2(64)
18015       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18016     }
18017     // Check remaining shift amounts.
18018     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18019       uint64_t ShAmt = 0;
18020       for (unsigned j = 0; j != Ratio; ++j) {
18021         ConstantSDNode *C =
18022           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18023         if (!C)
18024           return SDValue();
18025         // 6 == Log2(64)
18026         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18027       }
18028       if (ShAmt != ShiftAmt)
18029         return SDValue();
18030     }
18031     switch (Op.getOpcode()) {
18032     default:
18033       llvm_unreachable("Unknown shift opcode!");
18034     case ISD::SHL:
18035       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18036                                         DAG);
18037     case ISD::SRL:
18038       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18039                                         DAG);
18040     case ISD::SRA:
18041       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18042                                         DAG);
18043     }
18044   }
18045
18046   return SDValue();
18047 }
18048
18049 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18050                                         const X86Subtarget* Subtarget) {
18051   MVT VT = Op.getSimpleValueType();
18052   SDLoc dl(Op);
18053   SDValue R = Op.getOperand(0);
18054   SDValue Amt = Op.getOperand(1);
18055
18056   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
18057       VT == MVT::v4i32 || VT == MVT::v8i16 ||
18058       (Subtarget->hasInt256() &&
18059        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
18060         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18061        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18062     SDValue BaseShAmt;
18063     EVT EltVT = VT.getVectorElementType();
18064
18065     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18066       unsigned NumElts = VT.getVectorNumElements();
18067       unsigned i, j;
18068       for (i = 0; i != NumElts; ++i) {
18069         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
18070           continue;
18071         break;
18072       }
18073       for (j = i; j != NumElts; ++j) {
18074         SDValue Arg = Amt.getOperand(j);
18075         if (Arg.getOpcode() == ISD::UNDEF) continue;
18076         if (Arg != Amt.getOperand(i))
18077           break;
18078       }
18079       if (i != NumElts && j == NumElts)
18080         BaseShAmt = Amt.getOperand(i);
18081     } else {
18082       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18083         Amt = Amt.getOperand(0);
18084       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
18085                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
18086         SDValue InVec = Amt.getOperand(0);
18087         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18088           unsigned NumElts = InVec.getValueType().getVectorNumElements();
18089           unsigned i = 0;
18090           for (; i != NumElts; ++i) {
18091             SDValue Arg = InVec.getOperand(i);
18092             if (Arg.getOpcode() == ISD::UNDEF) continue;
18093             BaseShAmt = Arg;
18094             break;
18095           }
18096         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18097            if (ConstantSDNode *C =
18098                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18099              unsigned SplatIdx =
18100                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
18101              if (C->getZExtValue() == SplatIdx)
18102                BaseShAmt = InVec.getOperand(1);
18103            }
18104         }
18105         if (!BaseShAmt.getNode())
18106           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
18107                                   DAG.getIntPtrConstant(0));
18108       }
18109     }
18110
18111     if (BaseShAmt.getNode()) {
18112       if (EltVT.bitsGT(MVT::i32))
18113         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
18114       else if (EltVT.bitsLT(MVT::i32))
18115         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18116
18117       switch (Op.getOpcode()) {
18118       default:
18119         llvm_unreachable("Unknown shift opcode!");
18120       case ISD::SHL:
18121         switch (VT.SimpleTy) {
18122         default: return SDValue();
18123         case MVT::v2i64:
18124         case MVT::v4i32:
18125         case MVT::v8i16:
18126         case MVT::v4i64:
18127         case MVT::v8i32:
18128         case MVT::v16i16:
18129         case MVT::v16i32:
18130         case MVT::v8i64:
18131           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
18132         }
18133       case ISD::SRA:
18134         switch (VT.SimpleTy) {
18135         default: return SDValue();
18136         case MVT::v4i32:
18137         case MVT::v8i16:
18138         case MVT::v8i32:
18139         case MVT::v16i16:
18140         case MVT::v16i32:
18141         case MVT::v8i64:
18142           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
18143         }
18144       case ISD::SRL:
18145         switch (VT.SimpleTy) {
18146         default: return SDValue();
18147         case MVT::v2i64:
18148         case MVT::v4i32:
18149         case MVT::v8i16:
18150         case MVT::v4i64:
18151         case MVT::v8i32:
18152         case MVT::v16i16:
18153         case MVT::v16i32:
18154         case MVT::v8i64:
18155           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
18156         }
18157       }
18158     }
18159   }
18160
18161   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18162   if (!Subtarget->is64Bit() &&
18163       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
18164       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
18165       Amt.getOpcode() == ISD::BITCAST &&
18166       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18167     Amt = Amt.getOperand(0);
18168     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18169                      VT.getVectorNumElements();
18170     std::vector<SDValue> Vals(Ratio);
18171     for (unsigned i = 0; i != Ratio; ++i)
18172       Vals[i] = Amt.getOperand(i);
18173     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18174       for (unsigned j = 0; j != Ratio; ++j)
18175         if (Vals[j] != Amt.getOperand(i + j))
18176           return SDValue();
18177     }
18178     switch (Op.getOpcode()) {
18179     default:
18180       llvm_unreachable("Unknown shift opcode!");
18181     case ISD::SHL:
18182       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
18183     case ISD::SRL:
18184       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
18185     case ISD::SRA:
18186       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
18187     }
18188   }
18189
18190   return SDValue();
18191 }
18192
18193 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18194                           SelectionDAG &DAG) {
18195   MVT VT = Op.getSimpleValueType();
18196   SDLoc dl(Op);
18197   SDValue R = Op.getOperand(0);
18198   SDValue Amt = Op.getOperand(1);
18199   SDValue V;
18200
18201   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18202   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18203
18204   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
18205   if (V.getNode())
18206     return V;
18207
18208   V = LowerScalarVariableShift(Op, DAG, Subtarget);
18209   if (V.getNode())
18210       return V;
18211
18212   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
18213     return Op;
18214   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
18215   if (Subtarget->hasInt256()) {
18216     if (Op.getOpcode() == ISD::SRL &&
18217         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18218          VT == MVT::v4i64 || VT == MVT::v8i32))
18219       return Op;
18220     if (Op.getOpcode() == ISD::SHL &&
18221         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18222          VT == MVT::v4i64 || VT == MVT::v8i32))
18223       return Op;
18224     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
18225       return Op;
18226   }
18227
18228   // If possible, lower this packed shift into a vector multiply instead of
18229   // expanding it into a sequence of scalar shifts.
18230   // Do this only if the vector shift count is a constant build_vector.
18231   if (Op.getOpcode() == ISD::SHL && 
18232       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18233        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18234       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18235     SmallVector<SDValue, 8> Elts;
18236     EVT SVT = VT.getScalarType();
18237     unsigned SVTBits = SVT.getSizeInBits();
18238     const APInt &One = APInt(SVTBits, 1);
18239     unsigned NumElems = VT.getVectorNumElements();
18240
18241     for (unsigned i=0; i !=NumElems; ++i) {
18242       SDValue Op = Amt->getOperand(i);
18243       if (Op->getOpcode() == ISD::UNDEF) {
18244         Elts.push_back(Op);
18245         continue;
18246       }
18247
18248       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18249       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18250       uint64_t ShAmt = C.getZExtValue();
18251       if (ShAmt >= SVTBits) {
18252         Elts.push_back(DAG.getUNDEF(SVT));
18253         continue;
18254       }
18255       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
18256     }
18257     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18258     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18259   }
18260
18261   // Lower SHL with variable shift amount.
18262   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18263     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
18264
18265     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
18266     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
18267     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18268     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18269   }
18270
18271   // If possible, lower this shift as a sequence of two shifts by
18272   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18273   // Example:
18274   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18275   //
18276   // Could be rewritten as:
18277   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18278   //
18279   // The advantage is that the two shifts from the example would be
18280   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18281   // the vector shift into four scalar shifts plus four pairs of vector
18282   // insert/extract.
18283   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18284       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18285     unsigned TargetOpcode = X86ISD::MOVSS;
18286     bool CanBeSimplified;
18287     // The splat value for the first packed shift (the 'X' from the example).
18288     SDValue Amt1 = Amt->getOperand(0);
18289     // The splat value for the second packed shift (the 'Y' from the example).
18290     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18291                                         Amt->getOperand(2);
18292
18293     // See if it is possible to replace this node with a sequence of
18294     // two shifts followed by a MOVSS/MOVSD
18295     if (VT == MVT::v4i32) {
18296       // Check if it is legal to use a MOVSS.
18297       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18298                         Amt2 == Amt->getOperand(3);
18299       if (!CanBeSimplified) {
18300         // Otherwise, check if we can still simplify this node using a MOVSD.
18301         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18302                           Amt->getOperand(2) == Amt->getOperand(3);
18303         TargetOpcode = X86ISD::MOVSD;
18304         Amt2 = Amt->getOperand(2);
18305       }
18306     } else {
18307       // Do similar checks for the case where the machine value type
18308       // is MVT::v8i16.
18309       CanBeSimplified = Amt1 == Amt->getOperand(1);
18310       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18311         CanBeSimplified = Amt2 == Amt->getOperand(i);
18312
18313       if (!CanBeSimplified) {
18314         TargetOpcode = X86ISD::MOVSD;
18315         CanBeSimplified = true;
18316         Amt2 = Amt->getOperand(4);
18317         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18318           CanBeSimplified = Amt1 == Amt->getOperand(i);
18319         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18320           CanBeSimplified = Amt2 == Amt->getOperand(j);
18321       }
18322     }
18323     
18324     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18325         isa<ConstantSDNode>(Amt2)) {
18326       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18327       EVT CastVT = MVT::v4i32;
18328       SDValue Splat1 = 
18329         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
18330       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18331       SDValue Splat2 = 
18332         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
18333       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18334       if (TargetOpcode == X86ISD::MOVSD)
18335         CastVT = MVT::v2i64;
18336       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
18337       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
18338       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18339                                             BitCast1, DAG);
18340       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
18341     }
18342   }
18343
18344   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
18345     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
18346
18347     // a = a << 5;
18348     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
18349     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
18350
18351     // Turn 'a' into a mask suitable for VSELECT
18352     SDValue VSelM = DAG.getConstant(0x80, VT);
18353     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18354     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18355
18356     SDValue CM1 = DAG.getConstant(0x0f, VT);
18357     SDValue CM2 = DAG.getConstant(0x3f, VT);
18358
18359     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
18360     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
18361     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
18362     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18363     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18364
18365     // a += a
18366     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18367     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18368     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18369
18370     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
18371     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
18372     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
18373     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18374     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18375
18376     // a += a
18377     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18378     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18379     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18380
18381     // return VSELECT(r, r+r, a);
18382     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
18383                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
18384     return R;
18385   }
18386
18387   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18388   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18389   // solution better.
18390   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18391     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
18392     unsigned ExtOpc =
18393         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18394     R = DAG.getNode(ExtOpc, dl, NewVT, R);
18395     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
18396     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18397                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
18398     }
18399
18400   // Decompose 256-bit shifts into smaller 128-bit shifts.
18401   if (VT.is256BitVector()) {
18402     unsigned NumElems = VT.getVectorNumElements();
18403     MVT EltVT = VT.getVectorElementType();
18404     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18405
18406     // Extract the two vectors
18407     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18408     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18409
18410     // Recreate the shift amount vectors
18411     SDValue Amt1, Amt2;
18412     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18413       // Constant shift amount
18414       SmallVector<SDValue, 4> Amt1Csts;
18415       SmallVector<SDValue, 4> Amt2Csts;
18416       for (unsigned i = 0; i != NumElems/2; ++i)
18417         Amt1Csts.push_back(Amt->getOperand(i));
18418       for (unsigned i = NumElems/2; i != NumElems; ++i)
18419         Amt2Csts.push_back(Amt->getOperand(i));
18420
18421       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18422       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18423     } else {
18424       // Variable shift amount
18425       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18426       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18427     }
18428
18429     // Issue new vector shifts for the smaller types
18430     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18431     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18432
18433     // Concatenate the result back
18434     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18435   }
18436
18437   return SDValue();
18438 }
18439
18440 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18441   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18442   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18443   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18444   // has only one use.
18445   SDNode *N = Op.getNode();
18446   SDValue LHS = N->getOperand(0);
18447   SDValue RHS = N->getOperand(1);
18448   unsigned BaseOp = 0;
18449   unsigned Cond = 0;
18450   SDLoc DL(Op);
18451   switch (Op.getOpcode()) {
18452   default: llvm_unreachable("Unknown ovf instruction!");
18453   case ISD::SADDO:
18454     // A subtract of one will be selected as a INC. Note that INC doesn't
18455     // set CF, so we can't do this for UADDO.
18456     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18457       if (C->isOne()) {
18458         BaseOp = X86ISD::INC;
18459         Cond = X86::COND_O;
18460         break;
18461       }
18462     BaseOp = X86ISD::ADD;
18463     Cond = X86::COND_O;
18464     break;
18465   case ISD::UADDO:
18466     BaseOp = X86ISD::ADD;
18467     Cond = X86::COND_B;
18468     break;
18469   case ISD::SSUBO:
18470     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18471     // set CF, so we can't do this for USUBO.
18472     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18473       if (C->isOne()) {
18474         BaseOp = X86ISD::DEC;
18475         Cond = X86::COND_O;
18476         break;
18477       }
18478     BaseOp = X86ISD::SUB;
18479     Cond = X86::COND_O;
18480     break;
18481   case ISD::USUBO:
18482     BaseOp = X86ISD::SUB;
18483     Cond = X86::COND_B;
18484     break;
18485   case ISD::SMULO:
18486     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18487     Cond = X86::COND_O;
18488     break;
18489   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18490     if (N->getValueType(0) == MVT::i8) {
18491       BaseOp = X86ISD::UMUL8;
18492       Cond = X86::COND_O;
18493       break;
18494     }
18495     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18496                                  MVT::i32);
18497     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18498
18499     SDValue SetCC =
18500       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18501                   DAG.getConstant(X86::COND_O, MVT::i32),
18502                   SDValue(Sum.getNode(), 2));
18503
18504     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18505   }
18506   }
18507
18508   // Also sets EFLAGS.
18509   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18510   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18511
18512   SDValue SetCC =
18513     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18514                 DAG.getConstant(Cond, MVT::i32),
18515                 SDValue(Sum.getNode(), 1));
18516
18517   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18518 }
18519
18520 // Sign extension of the low part of vector elements. This may be used either
18521 // when sign extend instructions are not available or if the vector element
18522 // sizes already match the sign-extended size. If the vector elements are in
18523 // their pre-extended size and sign extend instructions are available, that will
18524 // be handled by LowerSIGN_EXTEND.
18525 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
18526                                                   SelectionDAG &DAG) const {
18527   SDLoc dl(Op);
18528   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
18529   MVT VT = Op.getSimpleValueType();
18530
18531   if (!Subtarget->hasSSE2() || !VT.isVector())
18532     return SDValue();
18533
18534   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
18535                       ExtraVT.getScalarType().getSizeInBits();
18536
18537   switch (VT.SimpleTy) {
18538     default: return SDValue();
18539     case MVT::v8i32:
18540     case MVT::v16i16:
18541       if (!Subtarget->hasFp256())
18542         return SDValue();
18543       if (!Subtarget->hasInt256()) {
18544         // needs to be split
18545         unsigned NumElems = VT.getVectorNumElements();
18546
18547         // Extract the LHS vectors
18548         SDValue LHS = Op.getOperand(0);
18549         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18550         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18551
18552         MVT EltVT = VT.getVectorElementType();
18553         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18554
18555         EVT ExtraEltVT = ExtraVT.getVectorElementType();
18556         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
18557         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
18558                                    ExtraNumElems/2);
18559         SDValue Extra = DAG.getValueType(ExtraVT);
18560
18561         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
18562         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
18563
18564         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
18565       }
18566       // fall through
18567     case MVT::v4i32:
18568     case MVT::v8i16: {
18569       SDValue Op0 = Op.getOperand(0);
18570
18571       // This is a sign extension of some low part of vector elements without
18572       // changing the size of the vector elements themselves:
18573       // Shift-Left + Shift-Right-Algebraic.
18574       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
18575                                                BitsDiff, DAG);
18576       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
18577                                         DAG);
18578     }
18579   }
18580 }
18581
18582 /// Returns true if the operand type is exactly twice the native width, and
18583 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18584 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18585 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18586 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
18587   const X86Subtarget &Subtarget =
18588       getTargetMachine().getSubtarget<X86Subtarget>();
18589   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18590
18591   if (OpWidth == 64)
18592     return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18593   else if (OpWidth == 128)
18594     return Subtarget.hasCmpxchg16b();
18595   else
18596     return false;
18597 }
18598
18599 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18600   return needsCmpXchgNb(SI->getValueOperand()->getType());
18601 }
18602
18603 // Note: this turns large loads into lock cmpxchg8b/16b.
18604 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18605 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18606   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18607   return needsCmpXchgNb(PTy->getElementType());
18608 }
18609
18610 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18611   const X86Subtarget &Subtarget =
18612       getTargetMachine().getSubtarget<X86Subtarget>();
18613   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
18614   const Type *MemType = AI->getType();
18615
18616   // If the operand is too big, we must see if cmpxchg8/16b is available
18617   // and default to library calls otherwise.
18618   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18619     return needsCmpXchgNb(MemType);
18620
18621   AtomicRMWInst::BinOp Op = AI->getOperation();
18622   switch (Op) {
18623   default:
18624     llvm_unreachable("Unknown atomic operation");
18625   case AtomicRMWInst::Xchg:
18626   case AtomicRMWInst::Add:
18627   case AtomicRMWInst::Sub:
18628     // It's better to use xadd, xsub or xchg for these in all cases.
18629     return false;
18630   case AtomicRMWInst::Or:
18631   case AtomicRMWInst::And:
18632   case AtomicRMWInst::Xor:
18633     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18634     // prefix to a normal instruction for these operations.
18635     return !AI->use_empty();
18636   case AtomicRMWInst::Nand:
18637   case AtomicRMWInst::Max:
18638   case AtomicRMWInst::Min:
18639   case AtomicRMWInst::UMax:
18640   case AtomicRMWInst::UMin:
18641     // These always require a non-trivial set of data operations on x86. We must
18642     // use a cmpxchg loop.
18643     return true;
18644   }
18645 }
18646
18647 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18648   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18649   // no-sse2). There isn't any reason to disable it if the target processor
18650   // supports it.
18651   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18652 }
18653
18654 LoadInst *
18655 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18656   const X86Subtarget &Subtarget =
18657       getTargetMachine().getSubtarget<X86Subtarget>();
18658   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
18659   const Type *MemType = AI->getType();
18660   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18661   // there is no benefit in turning such RMWs into loads, and it is actually
18662   // harmful as it introduces a mfence.
18663   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18664     return nullptr;
18665
18666   auto Builder = IRBuilder<>(AI);
18667   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18668   auto SynchScope = AI->getSynchScope();
18669   // We must restrict the ordering to avoid generating loads with Release or
18670   // ReleaseAcquire orderings.
18671   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18672   auto Ptr = AI->getPointerOperand();
18673
18674   // Before the load we need a fence. Here is an example lifted from
18675   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18676   // is required:
18677   // Thread 0:
18678   //   x.store(1, relaxed);
18679   //   r1 = y.fetch_add(0, release);
18680   // Thread 1:
18681   //   y.fetch_add(42, acquire);
18682   //   r2 = x.load(relaxed);
18683   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18684   // lowered to just a load without a fence. A mfence flushes the store buffer,
18685   // making the optimization clearly correct.
18686   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18687   // otherwise, we might be able to be more agressive on relaxed idempotent
18688   // rmw. In practice, they do not look useful, so we don't try to be
18689   // especially clever.
18690   if (SynchScope == SingleThread) {
18691     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18692     // the IR level, so we must wrap it in an intrinsic.
18693     return nullptr;
18694   } else if (hasMFENCE(Subtarget)) {
18695     Function *MFence = llvm::Intrinsic::getDeclaration(M,
18696             Intrinsic::x86_sse2_mfence);
18697     Builder.CreateCall(MFence);
18698   } else {
18699     // FIXME: it might make sense to use a locked operation here but on a
18700     // different cache-line to prevent cache-line bouncing. In practice it
18701     // is probably a small win, and x86 processors without mfence are rare
18702     // enough that we do not bother.
18703     return nullptr;
18704   }
18705
18706   // Finally we can emit the atomic load.
18707   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18708           AI->getType()->getPrimitiveSizeInBits());
18709   Loaded->setAtomic(Order, SynchScope);
18710   AI->replaceAllUsesWith(Loaded);
18711   AI->eraseFromParent();
18712   return Loaded;
18713 }
18714
18715 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18716                                  SelectionDAG &DAG) {
18717   SDLoc dl(Op);
18718   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18719     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18720   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18721     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18722
18723   // The only fence that needs an instruction is a sequentially-consistent
18724   // cross-thread fence.
18725   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18726     if (hasMFENCE(*Subtarget))
18727       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18728
18729     SDValue Chain = Op.getOperand(0);
18730     SDValue Zero = DAG.getConstant(0, MVT::i32);
18731     SDValue Ops[] = {
18732       DAG.getRegister(X86::ESP, MVT::i32), // Base
18733       DAG.getTargetConstant(1, MVT::i8),   // Scale
18734       DAG.getRegister(0, MVT::i32),        // Index
18735       DAG.getTargetConstant(0, MVT::i32),  // Disp
18736       DAG.getRegister(0, MVT::i32),        // Segment.
18737       Zero,
18738       Chain
18739     };
18740     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18741     return SDValue(Res, 0);
18742   }
18743
18744   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18745   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18746 }
18747
18748 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18749                              SelectionDAG &DAG) {
18750   MVT T = Op.getSimpleValueType();
18751   SDLoc DL(Op);
18752   unsigned Reg = 0;
18753   unsigned size = 0;
18754   switch(T.SimpleTy) {
18755   default: llvm_unreachable("Invalid value type!");
18756   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18757   case MVT::i16: Reg = X86::AX;  size = 2; break;
18758   case MVT::i32: Reg = X86::EAX; size = 4; break;
18759   case MVT::i64:
18760     assert(Subtarget->is64Bit() && "Node not type legal!");
18761     Reg = X86::RAX; size = 8;
18762     break;
18763   }
18764   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18765                                   Op.getOperand(2), SDValue());
18766   SDValue Ops[] = { cpIn.getValue(0),
18767                     Op.getOperand(1),
18768                     Op.getOperand(3),
18769                     DAG.getTargetConstant(size, MVT::i8),
18770                     cpIn.getValue(1) };
18771   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18772   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18773   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18774                                            Ops, T, MMO);
18775
18776   SDValue cpOut =
18777     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18778   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18779                                       MVT::i32, cpOut.getValue(2));
18780   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18781                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
18782
18783   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18784   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18785   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18786   return SDValue();
18787 }
18788
18789 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18790                             SelectionDAG &DAG) {
18791   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18792   MVT DstVT = Op.getSimpleValueType();
18793
18794   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18795     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18796     if (DstVT != MVT::f64)
18797       // This conversion needs to be expanded.
18798       return SDValue();
18799
18800     SDValue InVec = Op->getOperand(0);
18801     SDLoc dl(Op);
18802     unsigned NumElts = SrcVT.getVectorNumElements();
18803     EVT SVT = SrcVT.getVectorElementType();
18804
18805     // Widen the vector in input in the case of MVT::v2i32.
18806     // Example: from MVT::v2i32 to MVT::v4i32.
18807     SmallVector<SDValue, 16> Elts;
18808     for (unsigned i = 0, e = NumElts; i != e; ++i)
18809       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18810                                  DAG.getIntPtrConstant(i)));
18811
18812     // Explicitly mark the extra elements as Undef.
18813     SDValue Undef = DAG.getUNDEF(SVT);
18814     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
18815       Elts.push_back(Undef);
18816
18817     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18818     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18819     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
18820     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18821                        DAG.getIntPtrConstant(0));
18822   }
18823
18824   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18825          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18826   assert((DstVT == MVT::i64 ||
18827           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18828          "Unexpected custom BITCAST");
18829   // i64 <=> MMX conversions are Legal.
18830   if (SrcVT==MVT::i64 && DstVT.isVector())
18831     return Op;
18832   if (DstVT==MVT::i64 && SrcVT.isVector())
18833     return Op;
18834   // MMX <=> MMX conversions are Legal.
18835   if (SrcVT.isVector() && DstVT.isVector())
18836     return Op;
18837   // All other conversions need to be expanded.
18838   return SDValue();
18839 }
18840
18841 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18842   SDNode *Node = Op.getNode();
18843   SDLoc dl(Node);
18844   EVT T = Node->getValueType(0);
18845   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18846                               DAG.getConstant(0, T), Node->getOperand(2));
18847   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18848                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18849                        Node->getOperand(0),
18850                        Node->getOperand(1), negOp,
18851                        cast<AtomicSDNode>(Node)->getMemOperand(),
18852                        cast<AtomicSDNode>(Node)->getOrdering(),
18853                        cast<AtomicSDNode>(Node)->getSynchScope());
18854 }
18855
18856 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18857   SDNode *Node = Op.getNode();
18858   SDLoc dl(Node);
18859   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18860
18861   // Convert seq_cst store -> xchg
18862   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18863   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18864   //        (The only way to get a 16-byte store is cmpxchg16b)
18865   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18866   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18867       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18868     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18869                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18870                                  Node->getOperand(0),
18871                                  Node->getOperand(1), Node->getOperand(2),
18872                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18873                                  cast<AtomicSDNode>(Node)->getOrdering(),
18874                                  cast<AtomicSDNode>(Node)->getSynchScope());
18875     return Swap.getValue(1);
18876   }
18877   // Other atomic stores have a simple pattern.
18878   return Op;
18879 }
18880
18881 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18882   EVT VT = Op.getNode()->getSimpleValueType(0);
18883
18884   // Let legalize expand this if it isn't a legal type yet.
18885   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18886     return SDValue();
18887
18888   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18889
18890   unsigned Opc;
18891   bool ExtraOp = false;
18892   switch (Op.getOpcode()) {
18893   default: llvm_unreachable("Invalid code");
18894   case ISD::ADDC: Opc = X86ISD::ADD; break;
18895   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18896   case ISD::SUBC: Opc = X86ISD::SUB; break;
18897   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18898   }
18899
18900   if (!ExtraOp)
18901     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18902                        Op.getOperand(1));
18903   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18904                      Op.getOperand(1), Op.getOperand(2));
18905 }
18906
18907 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18908                             SelectionDAG &DAG) {
18909   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18910
18911   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18912   // which returns the values as { float, float } (in XMM0) or
18913   // { double, double } (which is returned in XMM0, XMM1).
18914   SDLoc dl(Op);
18915   SDValue Arg = Op.getOperand(0);
18916   EVT ArgVT = Arg.getValueType();
18917   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18918
18919   TargetLowering::ArgListTy Args;
18920   TargetLowering::ArgListEntry Entry;
18921
18922   Entry.Node = Arg;
18923   Entry.Ty = ArgTy;
18924   Entry.isSExt = false;
18925   Entry.isZExt = false;
18926   Args.push_back(Entry);
18927
18928   bool isF64 = ArgVT == MVT::f64;
18929   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18930   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18931   // the results are returned via SRet in memory.
18932   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18933   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18934   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
18935
18936   Type *RetTy = isF64
18937     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
18938     : (Type*)VectorType::get(ArgTy, 4);
18939
18940   TargetLowering::CallLoweringInfo CLI(DAG);
18941   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18942     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18943
18944   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18945
18946   if (isF64)
18947     // Returned in xmm0 and xmm1.
18948     return CallResult.first;
18949
18950   // Returned in bits 0:31 and 32:64 xmm0.
18951   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18952                                CallResult.first, DAG.getIntPtrConstant(0));
18953   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18954                                CallResult.first, DAG.getIntPtrConstant(1));
18955   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18956   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18957 }
18958
18959 /// LowerOperation - Provide custom lowering hooks for some operations.
18960 ///
18961 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18962   switch (Op.getOpcode()) {
18963   default: llvm_unreachable("Should not custom lower this!");
18964   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
18965   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18966   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18967     return LowerCMP_SWAP(Op, Subtarget, DAG);
18968   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18969   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18970   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18971   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
18972   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
18973   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18974   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18975   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18976   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18977   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18978   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18979   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18980   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18981   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18982   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18983   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18984   case ISD::SHL_PARTS:
18985   case ISD::SRA_PARTS:
18986   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18987   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18988   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18989   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18990   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18991   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18992   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18993   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18994   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18995   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18996   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18997   case ISD::FABS:
18998   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18999   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19000   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19001   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19002   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19003   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19004   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19005   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19006   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19007   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19008   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19009   case ISD::INTRINSIC_VOID:
19010   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19011   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19012   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19013   case ISD::FRAME_TO_ARGS_OFFSET:
19014                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19015   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19016   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19017   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19018   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19019   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19020   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19021   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19022   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19023   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19024   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
19025   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19026   case ISD::UMUL_LOHI:
19027   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19028   case ISD::SRA:
19029   case ISD::SRL:
19030   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19031   case ISD::SADDO:
19032   case ISD::UADDO:
19033   case ISD::SSUBO:
19034   case ISD::USUBO:
19035   case ISD::SMULO:
19036   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19037   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19038   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19039   case ISD::ADDC:
19040   case ISD::ADDE:
19041   case ISD::SUBC:
19042   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19043   case ISD::ADD:                return LowerADD(Op, DAG);
19044   case ISD::SUB:                return LowerSUB(Op, DAG);
19045   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19046   }
19047 }
19048
19049 /// ReplaceNodeResults - Replace a node with an illegal result type
19050 /// with a new node built out of custom code.
19051 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19052                                            SmallVectorImpl<SDValue>&Results,
19053                                            SelectionDAG &DAG) const {
19054   SDLoc dl(N);
19055   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19056   switch (N->getOpcode()) {
19057   default:
19058     llvm_unreachable("Do not know how to custom type legalize this operation!");
19059   case ISD::SIGN_EXTEND_INREG:
19060   case ISD::ADDC:
19061   case ISD::ADDE:
19062   case ISD::SUBC:
19063   case ISD::SUBE:
19064     // We don't want to expand or promote these.
19065     return;
19066   case ISD::SDIV:
19067   case ISD::UDIV:
19068   case ISD::SREM:
19069   case ISD::UREM:
19070   case ISD::SDIVREM:
19071   case ISD::UDIVREM: {
19072     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19073     Results.push_back(V);
19074     return;
19075   }
19076   case ISD::FP_TO_SINT:
19077   case ISD::FP_TO_UINT: {
19078     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19079
19080     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
19081       return;
19082
19083     std::pair<SDValue,SDValue> Vals =
19084         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19085     SDValue FIST = Vals.first, StackSlot = Vals.second;
19086     if (FIST.getNode()) {
19087       EVT VT = N->getValueType(0);
19088       // Return a load from the stack slot.
19089       if (StackSlot.getNode())
19090         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19091                                       MachinePointerInfo(),
19092                                       false, false, false, 0));
19093       else
19094         Results.push_back(FIST);
19095     }
19096     return;
19097   }
19098   case ISD::UINT_TO_FP: {
19099     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19100     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19101         N->getValueType(0) != MVT::v2f32)
19102       return;
19103     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19104                                  N->getOperand(0));
19105     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
19106                                      MVT::f64);
19107     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19108     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19109                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
19110     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
19111     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19112     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19113     return;
19114   }
19115   case ISD::FP_ROUND: {
19116     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19117         return;
19118     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19119     Results.push_back(V);
19120     return;
19121   }
19122   case ISD::INTRINSIC_W_CHAIN: {
19123     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19124     switch (IntNo) {
19125     default : llvm_unreachable("Do not know how to custom type "
19126                                "legalize this intrinsic operation!");
19127     case Intrinsic::x86_rdtsc:
19128       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19129                                      Results);
19130     case Intrinsic::x86_rdtscp:
19131       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19132                                      Results);
19133     case Intrinsic::x86_rdpmc:
19134       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19135     }
19136   }
19137   case ISD::READCYCLECOUNTER: {
19138     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19139                                    Results);
19140   }
19141   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19142     EVT T = N->getValueType(0);
19143     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19144     bool Regs64bit = T == MVT::i128;
19145     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19146     SDValue cpInL, cpInH;
19147     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19148                         DAG.getConstant(0, HalfT));
19149     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19150                         DAG.getConstant(1, HalfT));
19151     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19152                              Regs64bit ? X86::RAX : X86::EAX,
19153                              cpInL, SDValue());
19154     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19155                              Regs64bit ? X86::RDX : X86::EDX,
19156                              cpInH, cpInL.getValue(1));
19157     SDValue swapInL, swapInH;
19158     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19159                           DAG.getConstant(0, HalfT));
19160     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19161                           DAG.getConstant(1, HalfT));
19162     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19163                                Regs64bit ? X86::RBX : X86::EBX,
19164                                swapInL, cpInH.getValue(1));
19165     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19166                                Regs64bit ? X86::RCX : X86::ECX,
19167                                swapInH, swapInL.getValue(1));
19168     SDValue Ops[] = { swapInH.getValue(0),
19169                       N->getOperand(1),
19170                       swapInH.getValue(1) };
19171     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19172     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19173     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19174                                   X86ISD::LCMPXCHG8_DAG;
19175     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19176     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19177                                         Regs64bit ? X86::RAX : X86::EAX,
19178                                         HalfT, Result.getValue(1));
19179     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19180                                         Regs64bit ? X86::RDX : X86::EDX,
19181                                         HalfT, cpOutL.getValue(2));
19182     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19183
19184     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19185                                         MVT::i32, cpOutH.getValue(2));
19186     SDValue Success =
19187         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19188                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19189     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19190
19191     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19192     Results.push_back(Success);
19193     Results.push_back(EFLAGS.getValue(1));
19194     return;
19195   }
19196   case ISD::ATOMIC_SWAP:
19197   case ISD::ATOMIC_LOAD_ADD:
19198   case ISD::ATOMIC_LOAD_SUB:
19199   case ISD::ATOMIC_LOAD_AND:
19200   case ISD::ATOMIC_LOAD_OR:
19201   case ISD::ATOMIC_LOAD_XOR:
19202   case ISD::ATOMIC_LOAD_NAND:
19203   case ISD::ATOMIC_LOAD_MIN:
19204   case ISD::ATOMIC_LOAD_MAX:
19205   case ISD::ATOMIC_LOAD_UMIN:
19206   case ISD::ATOMIC_LOAD_UMAX:
19207   case ISD::ATOMIC_LOAD: {
19208     // Delegate to generic TypeLegalization. Situations we can really handle
19209     // should have already been dealt with by AtomicExpandPass.cpp.
19210     break;
19211   }
19212   case ISD::BITCAST: {
19213     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19214     EVT DstVT = N->getValueType(0);
19215     EVT SrcVT = N->getOperand(0)->getValueType(0);
19216
19217     if (SrcVT != MVT::f64 ||
19218         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19219       return;
19220
19221     unsigned NumElts = DstVT.getVectorNumElements();
19222     EVT SVT = DstVT.getVectorElementType();
19223     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19224     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19225                                    MVT::v2f64, N->getOperand(0));
19226     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
19227
19228     if (ExperimentalVectorWideningLegalization) {
19229       // If we are legalizing vectors by widening, we already have the desired
19230       // legal vector type, just return it.
19231       Results.push_back(ToVecInt);
19232       return;
19233     }
19234
19235     SmallVector<SDValue, 8> Elts;
19236     for (unsigned i = 0, e = NumElts; i != e; ++i)
19237       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19238                                    ToVecInt, DAG.getIntPtrConstant(i)));
19239
19240     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19241   }
19242   }
19243 }
19244
19245 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19246   switch (Opcode) {
19247   default: return nullptr;
19248   case X86ISD::BSF:                return "X86ISD::BSF";
19249   case X86ISD::BSR:                return "X86ISD::BSR";
19250   case X86ISD::SHLD:               return "X86ISD::SHLD";
19251   case X86ISD::SHRD:               return "X86ISD::SHRD";
19252   case X86ISD::FAND:               return "X86ISD::FAND";
19253   case X86ISD::FANDN:              return "X86ISD::FANDN";
19254   case X86ISD::FOR:                return "X86ISD::FOR";
19255   case X86ISD::FXOR:               return "X86ISD::FXOR";
19256   case X86ISD::FSRL:               return "X86ISD::FSRL";
19257   case X86ISD::FILD:               return "X86ISD::FILD";
19258   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19259   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19260   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19261   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19262   case X86ISD::FLD:                return "X86ISD::FLD";
19263   case X86ISD::FST:                return "X86ISD::FST";
19264   case X86ISD::CALL:               return "X86ISD::CALL";
19265   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19266   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19267   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19268   case X86ISD::BT:                 return "X86ISD::BT";
19269   case X86ISD::CMP:                return "X86ISD::CMP";
19270   case X86ISD::COMI:               return "X86ISD::COMI";
19271   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19272   case X86ISD::CMPM:               return "X86ISD::CMPM";
19273   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19274   case X86ISD::SETCC:              return "X86ISD::SETCC";
19275   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19276   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19277   case X86ISD::CMOV:               return "X86ISD::CMOV";
19278   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19279   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19280   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19281   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19282   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19283   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19284   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19285   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19286   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19287   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19288   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19289   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19290   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19291   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19292   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19293   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19294   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19295   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19296   case X86ISD::HADD:               return "X86ISD::HADD";
19297   case X86ISD::HSUB:               return "X86ISD::HSUB";
19298   case X86ISD::FHADD:              return "X86ISD::FHADD";
19299   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19300   case X86ISD::UMAX:               return "X86ISD::UMAX";
19301   case X86ISD::UMIN:               return "X86ISD::UMIN";
19302   case X86ISD::SMAX:               return "X86ISD::SMAX";
19303   case X86ISD::SMIN:               return "X86ISD::SMIN";
19304   case X86ISD::FMAX:               return "X86ISD::FMAX";
19305   case X86ISD::FMIN:               return "X86ISD::FMIN";
19306   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19307   case X86ISD::FMINC:              return "X86ISD::FMINC";
19308   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19309   case X86ISD::FRCP:               return "X86ISD::FRCP";
19310   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19311   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19312   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19313   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19314   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19315   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19316   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19317   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19318   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19319   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19320   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19321   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19322   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19323   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19324   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19325   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19326   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19327   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
19328   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19329   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19330   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19331   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19332   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19333   case X86ISD::VSHL:               return "X86ISD::VSHL";
19334   case X86ISD::VSRL:               return "X86ISD::VSRL";
19335   case X86ISD::VSRA:               return "X86ISD::VSRA";
19336   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19337   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19338   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19339   case X86ISD::CMPP:               return "X86ISD::CMPP";
19340   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19341   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19342   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19343   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19344   case X86ISD::ADD:                return "X86ISD::ADD";
19345   case X86ISD::SUB:                return "X86ISD::SUB";
19346   case X86ISD::ADC:                return "X86ISD::ADC";
19347   case X86ISD::SBB:                return "X86ISD::SBB";
19348   case X86ISD::SMUL:               return "X86ISD::SMUL";
19349   case X86ISD::UMUL:               return "X86ISD::UMUL";
19350   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19351   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19352   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19353   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19354   case X86ISD::INC:                return "X86ISD::INC";
19355   case X86ISD::DEC:                return "X86ISD::DEC";
19356   case X86ISD::OR:                 return "X86ISD::OR";
19357   case X86ISD::XOR:                return "X86ISD::XOR";
19358   case X86ISD::AND:                return "X86ISD::AND";
19359   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19360   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19361   case X86ISD::PTEST:              return "X86ISD::PTEST";
19362   case X86ISD::TESTP:              return "X86ISD::TESTP";
19363   case X86ISD::TESTM:              return "X86ISD::TESTM";
19364   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19365   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19366   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19367   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19368   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19369   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19370   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19371   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19372   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19373   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19374   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19375   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19376   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19377   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19378   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19379   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19380   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19381   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19382   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19383   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19384   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19385   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19386   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19387   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
19388   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19389   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19390   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19391   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19392   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19393   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19394   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19395   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19396   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19397   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19398   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19399   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19400   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19401   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19402   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19403   case X86ISD::SAHF:               return "X86ISD::SAHF";
19404   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19405   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19406   case X86ISD::FMADD:              return "X86ISD::FMADD";
19407   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19408   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19409   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19410   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19411   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19412   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19413   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19414   case X86ISD::XTEST:              return "X86ISD::XTEST";
19415   }
19416 }
19417
19418 // isLegalAddressingMode - Return true if the addressing mode represented
19419 // by AM is legal for this target, for a load/store of the specified type.
19420 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
19421                                               Type *Ty) const {
19422   // X86 supports extremely general addressing modes.
19423   CodeModel::Model M = getTargetMachine().getCodeModel();
19424   Reloc::Model R = getTargetMachine().getRelocationModel();
19425
19426   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19427   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19428     return false;
19429
19430   if (AM.BaseGV) {
19431     unsigned GVFlags =
19432       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19433
19434     // If a reference to this global requires an extra load, we can't fold it.
19435     if (isGlobalStubReference(GVFlags))
19436       return false;
19437
19438     // If BaseGV requires a register for the PIC base, we cannot also have a
19439     // BaseReg specified.
19440     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19441       return false;
19442
19443     // If lower 4G is not available, then we must use rip-relative addressing.
19444     if ((M != CodeModel::Small || R != Reloc::Static) &&
19445         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19446       return false;
19447   }
19448
19449   switch (AM.Scale) {
19450   case 0:
19451   case 1:
19452   case 2:
19453   case 4:
19454   case 8:
19455     // These scales always work.
19456     break;
19457   case 3:
19458   case 5:
19459   case 9:
19460     // These scales are formed with basereg+scalereg.  Only accept if there is
19461     // no basereg yet.
19462     if (AM.HasBaseReg)
19463       return false;
19464     break;
19465   default:  // Other stuff never works.
19466     return false;
19467   }
19468
19469   return true;
19470 }
19471
19472 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19473   unsigned Bits = Ty->getScalarSizeInBits();
19474
19475   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19476   // particularly cheaper than those without.
19477   if (Bits == 8)
19478     return false;
19479
19480   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19481   // variable shifts just as cheap as scalar ones.
19482   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19483     return false;
19484
19485   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19486   // fully general vector.
19487   return true;
19488 }
19489
19490 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19491   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19492     return false;
19493   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19494   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19495   return NumBits1 > NumBits2;
19496 }
19497
19498 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19499   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19500     return false;
19501
19502   if (!isTypeLegal(EVT::getEVT(Ty1)))
19503     return false;
19504
19505   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19506
19507   // Assuming the caller doesn't have a zeroext or signext return parameter,
19508   // truncation all the way down to i1 is valid.
19509   return true;
19510 }
19511
19512 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19513   return isInt<32>(Imm);
19514 }
19515
19516 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19517   // Can also use sub to handle negated immediates.
19518   return isInt<32>(Imm);
19519 }
19520
19521 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19522   if (!VT1.isInteger() || !VT2.isInteger())
19523     return false;
19524   unsigned NumBits1 = VT1.getSizeInBits();
19525   unsigned NumBits2 = VT2.getSizeInBits();
19526   return NumBits1 > NumBits2;
19527 }
19528
19529 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19530   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19531   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19532 }
19533
19534 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19535   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19536   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19537 }
19538
19539 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19540   EVT VT1 = Val.getValueType();
19541   if (isZExtFree(VT1, VT2))
19542     return true;
19543
19544   if (Val.getOpcode() != ISD::LOAD)
19545     return false;
19546
19547   if (!VT1.isSimple() || !VT1.isInteger() ||
19548       !VT2.isSimple() || !VT2.isInteger())
19549     return false;
19550
19551   switch (VT1.getSimpleVT().SimpleTy) {
19552   default: break;
19553   case MVT::i8:
19554   case MVT::i16:
19555   case MVT::i32:
19556     // X86 has 8, 16, and 32-bit zero-extending loads.
19557     return true;
19558   }
19559
19560   return false;
19561 }
19562
19563 bool
19564 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19565   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
19566     return false;
19567
19568   VT = VT.getScalarType();
19569
19570   if (!VT.isSimple())
19571     return false;
19572
19573   switch (VT.getSimpleVT().SimpleTy) {
19574   case MVT::f32:
19575   case MVT::f64:
19576     return true;
19577   default:
19578     break;
19579   }
19580
19581   return false;
19582 }
19583
19584 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19585   // i16 instructions are longer (0x66 prefix) and potentially slower.
19586   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19587 }
19588
19589 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19590 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19591 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19592 /// are assumed to be legal.
19593 bool
19594 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19595                                       EVT VT) const {
19596   if (!VT.isSimple())
19597     return false;
19598
19599   MVT SVT = VT.getSimpleVT();
19600
19601   // Very little shuffling can be done for 64-bit vectors right now.
19602   if (VT.getSizeInBits() == 64)
19603     return false;
19604
19605   // If this is a single-input shuffle with no 128 bit lane crossings we can
19606   // lower it into pshufb.
19607   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
19608       (SVT.is256BitVector() && Subtarget->hasInt256())) {
19609     bool isLegal = true;
19610     for (unsigned I = 0, E = M.size(); I != E; ++I) {
19611       if (M[I] >= (int)SVT.getVectorNumElements() ||
19612           ShuffleCrosses128bitLane(SVT, I, M[I])) {
19613         isLegal = false;
19614         break;
19615       }
19616     }
19617     if (isLegal)
19618       return true;
19619   }
19620
19621   // FIXME: blends, shifts.
19622   return (SVT.getVectorNumElements() == 2 ||
19623           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
19624           isMOVLMask(M, SVT) ||
19625           isMOVHLPSMask(M, SVT) ||
19626           isSHUFPMask(M, SVT) ||
19627           isPSHUFDMask(M, SVT) ||
19628           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
19629           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
19630           isPALIGNRMask(M, SVT, Subtarget) ||
19631           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
19632           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
19633           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
19634           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
19635           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()) ||
19636           (Subtarget->hasSSE41() && isINSERTPSMask(M, SVT)));
19637 }
19638
19639 bool
19640 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19641                                           EVT VT) const {
19642   if (!VT.isSimple())
19643     return false;
19644
19645   MVT SVT = VT.getSimpleVT();
19646   unsigned NumElts = SVT.getVectorNumElements();
19647   // FIXME: This collection of masks seems suspect.
19648   if (NumElts == 2)
19649     return true;
19650   if (NumElts == 4 && SVT.is128BitVector()) {
19651     return (isMOVLMask(Mask, SVT)  ||
19652             isCommutedMOVLMask(Mask, SVT, true) ||
19653             isSHUFPMask(Mask, SVT) ||
19654             isSHUFPMask(Mask, SVT, /* Commuted */ true) ||
19655             isBlendMask(Mask, SVT, Subtarget->hasSSE41(),
19656                         Subtarget->hasInt256()));
19657   }
19658   return false;
19659 }
19660
19661 //===----------------------------------------------------------------------===//
19662 //                           X86 Scheduler Hooks
19663 //===----------------------------------------------------------------------===//
19664
19665 /// Utility function to emit xbegin specifying the start of an RTM region.
19666 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19667                                      const TargetInstrInfo *TII) {
19668   DebugLoc DL = MI->getDebugLoc();
19669
19670   const BasicBlock *BB = MBB->getBasicBlock();
19671   MachineFunction::iterator I = MBB;
19672   ++I;
19673
19674   // For the v = xbegin(), we generate
19675   //
19676   // thisMBB:
19677   //  xbegin sinkMBB
19678   //
19679   // mainMBB:
19680   //  eax = -1
19681   //
19682   // sinkMBB:
19683   //  v = eax
19684
19685   MachineBasicBlock *thisMBB = MBB;
19686   MachineFunction *MF = MBB->getParent();
19687   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19688   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19689   MF->insert(I, mainMBB);
19690   MF->insert(I, sinkMBB);
19691
19692   // Transfer the remainder of BB and its successor edges to sinkMBB.
19693   sinkMBB->splice(sinkMBB->begin(), MBB,
19694                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19695   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19696
19697   // thisMBB:
19698   //  xbegin sinkMBB
19699   //  # fallthrough to mainMBB
19700   //  # abortion to sinkMBB
19701   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19702   thisMBB->addSuccessor(mainMBB);
19703   thisMBB->addSuccessor(sinkMBB);
19704
19705   // mainMBB:
19706   //  EAX = -1
19707   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19708   mainMBB->addSuccessor(sinkMBB);
19709
19710   // sinkMBB:
19711   // EAX is live into the sinkMBB
19712   sinkMBB->addLiveIn(X86::EAX);
19713   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19714           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19715     .addReg(X86::EAX);
19716
19717   MI->eraseFromParent();
19718   return sinkMBB;
19719 }
19720
19721 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19722 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19723 // in the .td file.
19724 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19725                                        const TargetInstrInfo *TII) {
19726   unsigned Opc;
19727   switch (MI->getOpcode()) {
19728   default: llvm_unreachable("illegal opcode!");
19729   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19730   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19731   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19732   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19733   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19734   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19735   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19736   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19737   }
19738
19739   DebugLoc dl = MI->getDebugLoc();
19740   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19741
19742   unsigned NumArgs = MI->getNumOperands();
19743   for (unsigned i = 1; i < NumArgs; ++i) {
19744     MachineOperand &Op = MI->getOperand(i);
19745     if (!(Op.isReg() && Op.isImplicit()))
19746       MIB.addOperand(Op);
19747   }
19748   if (MI->hasOneMemOperand())
19749     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19750
19751   BuildMI(*BB, MI, dl,
19752     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19753     .addReg(X86::XMM0);
19754
19755   MI->eraseFromParent();
19756   return BB;
19757 }
19758
19759 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19760 // defs in an instruction pattern
19761 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19762                                        const TargetInstrInfo *TII) {
19763   unsigned Opc;
19764   switch (MI->getOpcode()) {
19765   default: llvm_unreachable("illegal opcode!");
19766   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19767   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19768   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19769   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19770   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19771   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19772   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19773   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19774   }
19775
19776   DebugLoc dl = MI->getDebugLoc();
19777   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19778
19779   unsigned NumArgs = MI->getNumOperands(); // remove the results
19780   for (unsigned i = 1; i < NumArgs; ++i) {
19781     MachineOperand &Op = MI->getOperand(i);
19782     if (!(Op.isReg() && Op.isImplicit()))
19783       MIB.addOperand(Op);
19784   }
19785   if (MI->hasOneMemOperand())
19786     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19787
19788   BuildMI(*BB, MI, dl,
19789     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19790     .addReg(X86::ECX);
19791
19792   MI->eraseFromParent();
19793   return BB;
19794 }
19795
19796 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19797                                        const TargetInstrInfo *TII,
19798                                        const X86Subtarget* Subtarget) {
19799   DebugLoc dl = MI->getDebugLoc();
19800
19801   // Address into RAX/EAX, other two args into ECX, EDX.
19802   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19803   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19804   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19805   for (int i = 0; i < X86::AddrNumOperands; ++i)
19806     MIB.addOperand(MI->getOperand(i));
19807
19808   unsigned ValOps = X86::AddrNumOperands;
19809   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19810     .addReg(MI->getOperand(ValOps).getReg());
19811   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19812     .addReg(MI->getOperand(ValOps+1).getReg());
19813
19814   // The instruction doesn't actually take any operands though.
19815   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19816
19817   MI->eraseFromParent(); // The pseudo is gone now.
19818   return BB;
19819 }
19820
19821 MachineBasicBlock *
19822 X86TargetLowering::EmitVAARG64WithCustomInserter(
19823                    MachineInstr *MI,
19824                    MachineBasicBlock *MBB) const {
19825   // Emit va_arg instruction on X86-64.
19826
19827   // Operands to this pseudo-instruction:
19828   // 0  ) Output        : destination address (reg)
19829   // 1-5) Input         : va_list address (addr, i64mem)
19830   // 6  ) ArgSize       : Size (in bytes) of vararg type
19831   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19832   // 8  ) Align         : Alignment of type
19833   // 9  ) EFLAGS (implicit-def)
19834
19835   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19836   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
19837
19838   unsigned DestReg = MI->getOperand(0).getReg();
19839   MachineOperand &Base = MI->getOperand(1);
19840   MachineOperand &Scale = MI->getOperand(2);
19841   MachineOperand &Index = MI->getOperand(3);
19842   MachineOperand &Disp = MI->getOperand(4);
19843   MachineOperand &Segment = MI->getOperand(5);
19844   unsigned ArgSize = MI->getOperand(6).getImm();
19845   unsigned ArgMode = MI->getOperand(7).getImm();
19846   unsigned Align = MI->getOperand(8).getImm();
19847
19848   // Memory Reference
19849   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19850   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19851   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19852
19853   // Machine Information
19854   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
19855   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19856   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19857   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19858   DebugLoc DL = MI->getDebugLoc();
19859
19860   // struct va_list {
19861   //   i32   gp_offset
19862   //   i32   fp_offset
19863   //   i64   overflow_area (address)
19864   //   i64   reg_save_area (address)
19865   // }
19866   // sizeof(va_list) = 24
19867   // alignment(va_list) = 8
19868
19869   unsigned TotalNumIntRegs = 6;
19870   unsigned TotalNumXMMRegs = 8;
19871   bool UseGPOffset = (ArgMode == 1);
19872   bool UseFPOffset = (ArgMode == 2);
19873   unsigned MaxOffset = TotalNumIntRegs * 8 +
19874                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19875
19876   /* Align ArgSize to a multiple of 8 */
19877   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19878   bool NeedsAlign = (Align > 8);
19879
19880   MachineBasicBlock *thisMBB = MBB;
19881   MachineBasicBlock *overflowMBB;
19882   MachineBasicBlock *offsetMBB;
19883   MachineBasicBlock *endMBB;
19884
19885   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19886   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19887   unsigned OffsetReg = 0;
19888
19889   if (!UseGPOffset && !UseFPOffset) {
19890     // If we only pull from the overflow region, we don't create a branch.
19891     // We don't need to alter control flow.
19892     OffsetDestReg = 0; // unused
19893     OverflowDestReg = DestReg;
19894
19895     offsetMBB = nullptr;
19896     overflowMBB = thisMBB;
19897     endMBB = thisMBB;
19898   } else {
19899     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19900     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19901     // If not, pull from overflow_area. (branch to overflowMBB)
19902     //
19903     //       thisMBB
19904     //         |     .
19905     //         |        .
19906     //     offsetMBB   overflowMBB
19907     //         |        .
19908     //         |     .
19909     //        endMBB
19910
19911     // Registers for the PHI in endMBB
19912     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19913     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19914
19915     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19916     MachineFunction *MF = MBB->getParent();
19917     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19918     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19919     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19920
19921     MachineFunction::iterator MBBIter = MBB;
19922     ++MBBIter;
19923
19924     // Insert the new basic blocks
19925     MF->insert(MBBIter, offsetMBB);
19926     MF->insert(MBBIter, overflowMBB);
19927     MF->insert(MBBIter, endMBB);
19928
19929     // Transfer the remainder of MBB and its successor edges to endMBB.
19930     endMBB->splice(endMBB->begin(), thisMBB,
19931                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19932     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19933
19934     // Make offsetMBB and overflowMBB successors of thisMBB
19935     thisMBB->addSuccessor(offsetMBB);
19936     thisMBB->addSuccessor(overflowMBB);
19937
19938     // endMBB is a successor of both offsetMBB and overflowMBB
19939     offsetMBB->addSuccessor(endMBB);
19940     overflowMBB->addSuccessor(endMBB);
19941
19942     // Load the offset value into a register
19943     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19944     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19945       .addOperand(Base)
19946       .addOperand(Scale)
19947       .addOperand(Index)
19948       .addDisp(Disp, UseFPOffset ? 4 : 0)
19949       .addOperand(Segment)
19950       .setMemRefs(MMOBegin, MMOEnd);
19951
19952     // Check if there is enough room left to pull this argument.
19953     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19954       .addReg(OffsetReg)
19955       .addImm(MaxOffset + 8 - ArgSizeA8);
19956
19957     // Branch to "overflowMBB" if offset >= max
19958     // Fall through to "offsetMBB" otherwise
19959     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19960       .addMBB(overflowMBB);
19961   }
19962
19963   // In offsetMBB, emit code to use the reg_save_area.
19964   if (offsetMBB) {
19965     assert(OffsetReg != 0);
19966
19967     // Read the reg_save_area address.
19968     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19969     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19970       .addOperand(Base)
19971       .addOperand(Scale)
19972       .addOperand(Index)
19973       .addDisp(Disp, 16)
19974       .addOperand(Segment)
19975       .setMemRefs(MMOBegin, MMOEnd);
19976
19977     // Zero-extend the offset
19978     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19979       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19980         .addImm(0)
19981         .addReg(OffsetReg)
19982         .addImm(X86::sub_32bit);
19983
19984     // Add the offset to the reg_save_area to get the final address.
19985     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19986       .addReg(OffsetReg64)
19987       .addReg(RegSaveReg);
19988
19989     // Compute the offset for the next argument
19990     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19991     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19992       .addReg(OffsetReg)
19993       .addImm(UseFPOffset ? 16 : 8);
19994
19995     // Store it back into the va_list.
19996     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19997       .addOperand(Base)
19998       .addOperand(Scale)
19999       .addOperand(Index)
20000       .addDisp(Disp, UseFPOffset ? 4 : 0)
20001       .addOperand(Segment)
20002       .addReg(NextOffsetReg)
20003       .setMemRefs(MMOBegin, MMOEnd);
20004
20005     // Jump to endMBB
20006     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
20007       .addMBB(endMBB);
20008   }
20009
20010   //
20011   // Emit code to use overflow area
20012   //
20013
20014   // Load the overflow_area address into a register.
20015   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20016   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20017     .addOperand(Base)
20018     .addOperand(Scale)
20019     .addOperand(Index)
20020     .addDisp(Disp, 8)
20021     .addOperand(Segment)
20022     .setMemRefs(MMOBegin, MMOEnd);
20023
20024   // If we need to align it, do so. Otherwise, just copy the address
20025   // to OverflowDestReg.
20026   if (NeedsAlign) {
20027     // Align the overflow address
20028     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20029     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20030
20031     // aligned_addr = (addr + (align-1)) & ~(align-1)
20032     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20033       .addReg(OverflowAddrReg)
20034       .addImm(Align-1);
20035
20036     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20037       .addReg(TmpReg)
20038       .addImm(~(uint64_t)(Align-1));
20039   } else {
20040     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20041       .addReg(OverflowAddrReg);
20042   }
20043
20044   // Compute the next overflow address after this argument.
20045   // (the overflow address should be kept 8-byte aligned)
20046   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20047   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20048     .addReg(OverflowDestReg)
20049     .addImm(ArgSizeA8);
20050
20051   // Store the new overflow address.
20052   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20053     .addOperand(Base)
20054     .addOperand(Scale)
20055     .addOperand(Index)
20056     .addDisp(Disp, 8)
20057     .addOperand(Segment)
20058     .addReg(NextAddrReg)
20059     .setMemRefs(MMOBegin, MMOEnd);
20060
20061   // If we branched, emit the PHI to the front of endMBB.
20062   if (offsetMBB) {
20063     BuildMI(*endMBB, endMBB->begin(), DL,
20064             TII->get(X86::PHI), DestReg)
20065       .addReg(OffsetDestReg).addMBB(offsetMBB)
20066       .addReg(OverflowDestReg).addMBB(overflowMBB);
20067   }
20068
20069   // Erase the pseudo instruction
20070   MI->eraseFromParent();
20071
20072   return endMBB;
20073 }
20074
20075 MachineBasicBlock *
20076 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20077                                                  MachineInstr *MI,
20078                                                  MachineBasicBlock *MBB) const {
20079   // Emit code to save XMM registers to the stack. The ABI says that the
20080   // number of registers to save is given in %al, so it's theoretically
20081   // possible to do an indirect jump trick to avoid saving all of them,
20082   // however this code takes a simpler approach and just executes all
20083   // of the stores if %al is non-zero. It's less code, and it's probably
20084   // easier on the hardware branch predictor, and stores aren't all that
20085   // expensive anyway.
20086
20087   // Create the new basic blocks. One block contains all the XMM stores,
20088   // and one block is the final destination regardless of whether any
20089   // stores were performed.
20090   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20091   MachineFunction *F = MBB->getParent();
20092   MachineFunction::iterator MBBIter = MBB;
20093   ++MBBIter;
20094   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20095   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20096   F->insert(MBBIter, XMMSaveMBB);
20097   F->insert(MBBIter, EndMBB);
20098
20099   // Transfer the remainder of MBB and its successor edges to EndMBB.
20100   EndMBB->splice(EndMBB->begin(), MBB,
20101                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20102   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20103
20104   // The original block will now fall through to the XMM save block.
20105   MBB->addSuccessor(XMMSaveMBB);
20106   // The XMMSaveMBB will fall through to the end block.
20107   XMMSaveMBB->addSuccessor(EndMBB);
20108
20109   // Now add the instructions.
20110   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20111   DebugLoc DL = MI->getDebugLoc();
20112
20113   unsigned CountReg = MI->getOperand(0).getReg();
20114   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20115   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20116
20117   if (!Subtarget->isTargetWin64()) {
20118     // If %al is 0, branch around the XMM save block.
20119     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20120     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
20121     MBB->addSuccessor(EndMBB);
20122   }
20123
20124   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20125   // that was just emitted, but clearly shouldn't be "saved".
20126   assert((MI->getNumOperands() <= 3 ||
20127           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20128           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20129          && "Expected last argument to be EFLAGS");
20130   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20131   // In the XMM save block, save all the XMM argument registers.
20132   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20133     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20134     MachineMemOperand *MMO =
20135       F->getMachineMemOperand(
20136           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
20137         MachineMemOperand::MOStore,
20138         /*Size=*/16, /*Align=*/16);
20139     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20140       .addFrameIndex(RegSaveFrameIndex)
20141       .addImm(/*Scale=*/1)
20142       .addReg(/*IndexReg=*/0)
20143       .addImm(/*Disp=*/Offset)
20144       .addReg(/*Segment=*/0)
20145       .addReg(MI->getOperand(i).getReg())
20146       .addMemOperand(MMO);
20147   }
20148
20149   MI->eraseFromParent();   // The pseudo instruction is gone now.
20150
20151   return EndMBB;
20152 }
20153
20154 // The EFLAGS operand of SelectItr might be missing a kill marker
20155 // because there were multiple uses of EFLAGS, and ISel didn't know
20156 // which to mark. Figure out whether SelectItr should have had a
20157 // kill marker, and set it if it should. Returns the correct kill
20158 // marker value.
20159 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20160                                      MachineBasicBlock* BB,
20161                                      const TargetRegisterInfo* TRI) {
20162   // Scan forward through BB for a use/def of EFLAGS.
20163   MachineBasicBlock::iterator miI(std::next(SelectItr));
20164   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20165     const MachineInstr& mi = *miI;
20166     if (mi.readsRegister(X86::EFLAGS))
20167       return false;
20168     if (mi.definesRegister(X86::EFLAGS))
20169       break; // Should have kill-flag - update below.
20170   }
20171
20172   // If we hit the end of the block, check whether EFLAGS is live into a
20173   // successor.
20174   if (miI == BB->end()) {
20175     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20176                                           sEnd = BB->succ_end();
20177          sItr != sEnd; ++sItr) {
20178       MachineBasicBlock* succ = *sItr;
20179       if (succ->isLiveIn(X86::EFLAGS))
20180         return false;
20181     }
20182   }
20183
20184   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20185   // out. SelectMI should have a kill flag on EFLAGS.
20186   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20187   return true;
20188 }
20189
20190 MachineBasicBlock *
20191 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20192                                      MachineBasicBlock *BB) const {
20193   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20194   DebugLoc DL = MI->getDebugLoc();
20195
20196   // To "insert" a SELECT_CC instruction, we actually have to insert the
20197   // diamond control-flow pattern.  The incoming instruction knows the
20198   // destination vreg to set, the condition code register to branch on, the
20199   // true/false values to select between, and a branch opcode to use.
20200   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20201   MachineFunction::iterator It = BB;
20202   ++It;
20203
20204   //  thisMBB:
20205   //  ...
20206   //   TrueVal = ...
20207   //   cmpTY ccX, r1, r2
20208   //   bCC copy1MBB
20209   //   fallthrough --> copy0MBB
20210   MachineBasicBlock *thisMBB = BB;
20211   MachineFunction *F = BB->getParent();
20212   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20213   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20214   F->insert(It, copy0MBB);
20215   F->insert(It, sinkMBB);
20216
20217   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20218   // live into the sink and copy blocks.
20219   const TargetRegisterInfo *TRI =
20220       BB->getParent()->getSubtarget().getRegisterInfo();
20221   if (!MI->killsRegister(X86::EFLAGS) &&
20222       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
20223     copy0MBB->addLiveIn(X86::EFLAGS);
20224     sinkMBB->addLiveIn(X86::EFLAGS);
20225   }
20226
20227   // Transfer the remainder of BB and its successor edges to sinkMBB.
20228   sinkMBB->splice(sinkMBB->begin(), BB,
20229                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
20230   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20231
20232   // Add the true and fallthrough blocks as its successors.
20233   BB->addSuccessor(copy0MBB);
20234   BB->addSuccessor(sinkMBB);
20235
20236   // Create the conditional branch instruction.
20237   unsigned Opc =
20238     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20239   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20240
20241   //  copy0MBB:
20242   //   %FalseValue = ...
20243   //   # fallthrough to sinkMBB
20244   copy0MBB->addSuccessor(sinkMBB);
20245
20246   //  sinkMBB:
20247   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20248   //  ...
20249   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20250           TII->get(X86::PHI), MI->getOperand(0).getReg())
20251     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20252     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20253
20254   MI->eraseFromParent();   // The pseudo instruction is gone now.
20255   return sinkMBB;
20256 }
20257
20258 MachineBasicBlock *
20259 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20260                                         MachineBasicBlock *BB) const {
20261   MachineFunction *MF = BB->getParent();
20262   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20263   DebugLoc DL = MI->getDebugLoc();
20264   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20265
20266   assert(MF->shouldSplitStack());
20267
20268   const bool Is64Bit = Subtarget->is64Bit();
20269   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20270
20271   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20272   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20273
20274   // BB:
20275   //  ... [Till the alloca]
20276   // If stacklet is not large enough, jump to mallocMBB
20277   //
20278   // bumpMBB:
20279   //  Allocate by subtracting from RSP
20280   //  Jump to continueMBB
20281   //
20282   // mallocMBB:
20283   //  Allocate by call to runtime
20284   //
20285   // continueMBB:
20286   //  ...
20287   //  [rest of original BB]
20288   //
20289
20290   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20291   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20292   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20293
20294   MachineRegisterInfo &MRI = MF->getRegInfo();
20295   const TargetRegisterClass *AddrRegClass =
20296     getRegClassFor(getPointerTy());
20297
20298   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20299     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20300     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20301     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20302     sizeVReg = MI->getOperand(1).getReg(),
20303     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20304
20305   MachineFunction::iterator MBBIter = BB;
20306   ++MBBIter;
20307
20308   MF->insert(MBBIter, bumpMBB);
20309   MF->insert(MBBIter, mallocMBB);
20310   MF->insert(MBBIter, continueMBB);
20311
20312   continueMBB->splice(continueMBB->begin(), BB,
20313                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20314   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20315
20316   // Add code to the main basic block to check if the stack limit has been hit,
20317   // and if so, jump to mallocMBB otherwise to bumpMBB.
20318   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20319   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20320     .addReg(tmpSPVReg).addReg(sizeVReg);
20321   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20322     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20323     .addReg(SPLimitVReg);
20324   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
20325
20326   // bumpMBB simply decreases the stack pointer, since we know the current
20327   // stacklet has enough space.
20328   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20329     .addReg(SPLimitVReg);
20330   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20331     .addReg(SPLimitVReg);
20332   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20333
20334   // Calls into a routine in libgcc to allocate more space from the heap.
20335   const uint32_t *RegMask = MF->getTarget()
20336                                 .getSubtargetImpl()
20337                                 ->getRegisterInfo()
20338                                 ->getCallPreservedMask(CallingConv::C);
20339   if (IsLP64) {
20340     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20341       .addReg(sizeVReg);
20342     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20343       .addExternalSymbol("__morestack_allocate_stack_space")
20344       .addRegMask(RegMask)
20345       .addReg(X86::RDI, RegState::Implicit)
20346       .addReg(X86::RAX, RegState::ImplicitDefine);
20347   } else if (Is64Bit) {
20348     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20349       .addReg(sizeVReg);
20350     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20351       .addExternalSymbol("__morestack_allocate_stack_space")
20352       .addRegMask(RegMask)
20353       .addReg(X86::EDI, RegState::Implicit)
20354       .addReg(X86::EAX, RegState::ImplicitDefine);
20355   } else {
20356     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20357       .addImm(12);
20358     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20359     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20360       .addExternalSymbol("__morestack_allocate_stack_space")
20361       .addRegMask(RegMask)
20362       .addReg(X86::EAX, RegState::ImplicitDefine);
20363   }
20364
20365   if (!Is64Bit)
20366     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20367       .addImm(16);
20368
20369   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20370     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20371   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20372
20373   // Set up the CFG correctly.
20374   BB->addSuccessor(bumpMBB);
20375   BB->addSuccessor(mallocMBB);
20376   mallocMBB->addSuccessor(continueMBB);
20377   bumpMBB->addSuccessor(continueMBB);
20378
20379   // Take care of the PHI nodes.
20380   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20381           MI->getOperand(0).getReg())
20382     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20383     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20384
20385   // Delete the original pseudo instruction.
20386   MI->eraseFromParent();
20387
20388   // And we're done.
20389   return continueMBB;
20390 }
20391
20392 MachineBasicBlock *
20393 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20394                                         MachineBasicBlock *BB) const {
20395   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20396   DebugLoc DL = MI->getDebugLoc();
20397
20398   assert(!Subtarget->isTargetMacho());
20399
20400   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
20401   // non-trivial part is impdef of ESP.
20402
20403   if (Subtarget->isTargetWin64()) {
20404     if (Subtarget->isTargetCygMing()) {
20405       // ___chkstk(Mingw64):
20406       // Clobbers R10, R11, RAX and EFLAGS.
20407       // Updates RSP.
20408       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20409         .addExternalSymbol("___chkstk")
20410         .addReg(X86::RAX, RegState::Implicit)
20411         .addReg(X86::RSP, RegState::Implicit)
20412         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
20413         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
20414         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20415     } else {
20416       // __chkstk(MSVCRT): does not update stack pointer.
20417       // Clobbers R10, R11 and EFLAGS.
20418       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20419         .addExternalSymbol("__chkstk")
20420         .addReg(X86::RAX, RegState::Implicit)
20421         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20422       // RAX has the offset to be subtracted from RSP.
20423       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
20424         .addReg(X86::RSP)
20425         .addReg(X86::RAX);
20426     }
20427   } else {
20428     const char *StackProbeSymbol =
20429       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
20430
20431     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
20432       .addExternalSymbol(StackProbeSymbol)
20433       .addReg(X86::EAX, RegState::Implicit)
20434       .addReg(X86::ESP, RegState::Implicit)
20435       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
20436       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
20437       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20438   }
20439
20440   MI->eraseFromParent();   // The pseudo instruction is gone now.
20441   return BB;
20442 }
20443
20444 MachineBasicBlock *
20445 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20446                                       MachineBasicBlock *BB) const {
20447   // This is pretty easy.  We're taking the value that we received from
20448   // our load from the relocation, sticking it in either RDI (x86-64)
20449   // or EAX and doing an indirect call.  The return value will then
20450   // be in the normal return register.
20451   MachineFunction *F = BB->getParent();
20452   const X86InstrInfo *TII =
20453       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
20454   DebugLoc DL = MI->getDebugLoc();
20455
20456   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20457   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20458
20459   // Get a register mask for the lowered call.
20460   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20461   // proper register mask.
20462   const uint32_t *RegMask = F->getTarget()
20463                                 .getSubtargetImpl()
20464                                 ->getRegisterInfo()
20465                                 ->getCallPreservedMask(CallingConv::C);
20466   if (Subtarget->is64Bit()) {
20467     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20468                                       TII->get(X86::MOV64rm), X86::RDI)
20469     .addReg(X86::RIP)
20470     .addImm(0).addReg(0)
20471     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20472                       MI->getOperand(3).getTargetFlags())
20473     .addReg(0);
20474     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20475     addDirectMem(MIB, X86::RDI);
20476     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20477   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20478     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20479                                       TII->get(X86::MOV32rm), X86::EAX)
20480     .addReg(0)
20481     .addImm(0).addReg(0)
20482     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20483                       MI->getOperand(3).getTargetFlags())
20484     .addReg(0);
20485     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20486     addDirectMem(MIB, X86::EAX);
20487     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20488   } else {
20489     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20490                                       TII->get(X86::MOV32rm), X86::EAX)
20491     .addReg(TII->getGlobalBaseReg(F))
20492     .addImm(0).addReg(0)
20493     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20494                       MI->getOperand(3).getTargetFlags())
20495     .addReg(0);
20496     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20497     addDirectMem(MIB, X86::EAX);
20498     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20499   }
20500
20501   MI->eraseFromParent(); // The pseudo instruction is gone now.
20502   return BB;
20503 }
20504
20505 MachineBasicBlock *
20506 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20507                                     MachineBasicBlock *MBB) const {
20508   DebugLoc DL = MI->getDebugLoc();
20509   MachineFunction *MF = MBB->getParent();
20510   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20511   MachineRegisterInfo &MRI = MF->getRegInfo();
20512
20513   const BasicBlock *BB = MBB->getBasicBlock();
20514   MachineFunction::iterator I = MBB;
20515   ++I;
20516
20517   // Memory Reference
20518   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20519   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20520
20521   unsigned DstReg;
20522   unsigned MemOpndSlot = 0;
20523
20524   unsigned CurOp = 0;
20525
20526   DstReg = MI->getOperand(CurOp++).getReg();
20527   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20528   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20529   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20530   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20531
20532   MemOpndSlot = CurOp;
20533
20534   MVT PVT = getPointerTy();
20535   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20536          "Invalid Pointer Size!");
20537
20538   // For v = setjmp(buf), we generate
20539   //
20540   // thisMBB:
20541   //  buf[LabelOffset] = restoreMBB
20542   //  SjLjSetup restoreMBB
20543   //
20544   // mainMBB:
20545   //  v_main = 0
20546   //
20547   // sinkMBB:
20548   //  v = phi(main, restore)
20549   //
20550   // restoreMBB:
20551   //  v_restore = 1
20552
20553   MachineBasicBlock *thisMBB = MBB;
20554   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20555   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20556   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20557   MF->insert(I, mainMBB);
20558   MF->insert(I, sinkMBB);
20559   MF->push_back(restoreMBB);
20560
20561   MachineInstrBuilder MIB;
20562
20563   // Transfer the remainder of BB and its successor edges to sinkMBB.
20564   sinkMBB->splice(sinkMBB->begin(), MBB,
20565                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20566   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20567
20568   // thisMBB:
20569   unsigned PtrStoreOpc = 0;
20570   unsigned LabelReg = 0;
20571   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20572   Reloc::Model RM = MF->getTarget().getRelocationModel();
20573   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20574                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20575
20576   // Prepare IP either in reg or imm.
20577   if (!UseImmLabel) {
20578     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20579     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20580     LabelReg = MRI.createVirtualRegister(PtrRC);
20581     if (Subtarget->is64Bit()) {
20582       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20583               .addReg(X86::RIP)
20584               .addImm(0)
20585               .addReg(0)
20586               .addMBB(restoreMBB)
20587               .addReg(0);
20588     } else {
20589       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20590       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20591               .addReg(XII->getGlobalBaseReg(MF))
20592               .addImm(0)
20593               .addReg(0)
20594               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20595               .addReg(0);
20596     }
20597   } else
20598     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20599   // Store IP
20600   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20601   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20602     if (i == X86::AddrDisp)
20603       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20604     else
20605       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20606   }
20607   if (!UseImmLabel)
20608     MIB.addReg(LabelReg);
20609   else
20610     MIB.addMBB(restoreMBB);
20611   MIB.setMemRefs(MMOBegin, MMOEnd);
20612   // Setup
20613   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20614           .addMBB(restoreMBB);
20615
20616   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
20617       MF->getSubtarget().getRegisterInfo());
20618   MIB.addRegMask(RegInfo->getNoPreservedMask());
20619   thisMBB->addSuccessor(mainMBB);
20620   thisMBB->addSuccessor(restoreMBB);
20621
20622   // mainMBB:
20623   //  EAX = 0
20624   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20625   mainMBB->addSuccessor(sinkMBB);
20626
20627   // sinkMBB:
20628   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20629           TII->get(X86::PHI), DstReg)
20630     .addReg(mainDstReg).addMBB(mainMBB)
20631     .addReg(restoreDstReg).addMBB(restoreMBB);
20632
20633   // restoreMBB:
20634   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20635   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
20636   restoreMBB->addSuccessor(sinkMBB);
20637
20638   MI->eraseFromParent();
20639   return sinkMBB;
20640 }
20641
20642 MachineBasicBlock *
20643 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20644                                      MachineBasicBlock *MBB) const {
20645   DebugLoc DL = MI->getDebugLoc();
20646   MachineFunction *MF = MBB->getParent();
20647   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20648   MachineRegisterInfo &MRI = MF->getRegInfo();
20649
20650   // Memory Reference
20651   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20652   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20653
20654   MVT PVT = getPointerTy();
20655   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20656          "Invalid Pointer Size!");
20657
20658   const TargetRegisterClass *RC =
20659     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20660   unsigned Tmp = MRI.createVirtualRegister(RC);
20661   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20662   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
20663       MF->getSubtarget().getRegisterInfo());
20664   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20665   unsigned SP = RegInfo->getStackRegister();
20666
20667   MachineInstrBuilder MIB;
20668
20669   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20670   const int64_t SPOffset = 2 * PVT.getStoreSize();
20671
20672   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20673   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20674
20675   // Reload FP
20676   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20677   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20678     MIB.addOperand(MI->getOperand(i));
20679   MIB.setMemRefs(MMOBegin, MMOEnd);
20680   // Reload IP
20681   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20682   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20683     if (i == X86::AddrDisp)
20684       MIB.addDisp(MI->getOperand(i), LabelOffset);
20685     else
20686       MIB.addOperand(MI->getOperand(i));
20687   }
20688   MIB.setMemRefs(MMOBegin, MMOEnd);
20689   // Reload SP
20690   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20691   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20692     if (i == X86::AddrDisp)
20693       MIB.addDisp(MI->getOperand(i), SPOffset);
20694     else
20695       MIB.addOperand(MI->getOperand(i));
20696   }
20697   MIB.setMemRefs(MMOBegin, MMOEnd);
20698   // Jump
20699   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20700
20701   MI->eraseFromParent();
20702   return MBB;
20703 }
20704
20705 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20706 // accumulator loops. Writing back to the accumulator allows the coalescer
20707 // to remove extra copies in the loop.   
20708 MachineBasicBlock *
20709 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20710                                  MachineBasicBlock *MBB) const {
20711   MachineOperand &AddendOp = MI->getOperand(3);
20712
20713   // Bail out early if the addend isn't a register - we can't switch these.
20714   if (!AddendOp.isReg())
20715     return MBB;
20716
20717   MachineFunction &MF = *MBB->getParent();
20718   MachineRegisterInfo &MRI = MF.getRegInfo();
20719
20720   // Check whether the addend is defined by a PHI:
20721   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20722   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20723   if (!AddendDef.isPHI())
20724     return MBB;
20725
20726   // Look for the following pattern:
20727   // loop:
20728   //   %addend = phi [%entry, 0], [%loop, %result]
20729   //   ...
20730   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20731
20732   // Replace with:
20733   //   loop:
20734   //   %addend = phi [%entry, 0], [%loop, %result]
20735   //   ...
20736   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20737
20738   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20739     assert(AddendDef.getOperand(i).isReg());
20740     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20741     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20742     if (&PHISrcInst == MI) {
20743       // Found a matching instruction.
20744       unsigned NewFMAOpc = 0;
20745       switch (MI->getOpcode()) {
20746         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20747         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20748         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20749         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20750         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20751         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20752         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20753         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20754         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20755         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20756         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20757         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20758         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20759         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20760         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20761         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20762         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20763         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20764         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20765         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20766
20767         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20768         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20769         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20770         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20771         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20772         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20773         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20774         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20775         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20776         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20777         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20778         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20779         default: llvm_unreachable("Unrecognized FMA variant.");
20780       }
20781
20782       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
20783       MachineInstrBuilder MIB =
20784         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20785         .addOperand(MI->getOperand(0))
20786         .addOperand(MI->getOperand(3))
20787         .addOperand(MI->getOperand(2))
20788         .addOperand(MI->getOperand(1));
20789       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20790       MI->eraseFromParent();
20791     }
20792   }
20793
20794   return MBB;
20795 }
20796
20797 MachineBasicBlock *
20798 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20799                                                MachineBasicBlock *BB) const {
20800   switch (MI->getOpcode()) {
20801   default: llvm_unreachable("Unexpected instr type to insert");
20802   case X86::TAILJMPd64:
20803   case X86::TAILJMPr64:
20804   case X86::TAILJMPm64:
20805     llvm_unreachable("TAILJMP64 would not be touched here.");
20806   case X86::TCRETURNdi64:
20807   case X86::TCRETURNri64:
20808   case X86::TCRETURNmi64:
20809     return BB;
20810   case X86::WIN_ALLOCA:
20811     return EmitLoweredWinAlloca(MI, BB);
20812   case X86::SEG_ALLOCA_32:
20813   case X86::SEG_ALLOCA_64:
20814     return EmitLoweredSegAlloca(MI, BB);
20815   case X86::TLSCall_32:
20816   case X86::TLSCall_64:
20817     return EmitLoweredTLSCall(MI, BB);
20818   case X86::CMOV_GR8:
20819   case X86::CMOV_FR32:
20820   case X86::CMOV_FR64:
20821   case X86::CMOV_V4F32:
20822   case X86::CMOV_V2F64:
20823   case X86::CMOV_V2I64:
20824   case X86::CMOV_V8F32:
20825   case X86::CMOV_V4F64:
20826   case X86::CMOV_V4I64:
20827   case X86::CMOV_V16F32:
20828   case X86::CMOV_V8F64:
20829   case X86::CMOV_V8I64:
20830   case X86::CMOV_GR16:
20831   case X86::CMOV_GR32:
20832   case X86::CMOV_RFP32:
20833   case X86::CMOV_RFP64:
20834   case X86::CMOV_RFP80:
20835     return EmitLoweredSelect(MI, BB);
20836
20837   case X86::FP32_TO_INT16_IN_MEM:
20838   case X86::FP32_TO_INT32_IN_MEM:
20839   case X86::FP32_TO_INT64_IN_MEM:
20840   case X86::FP64_TO_INT16_IN_MEM:
20841   case X86::FP64_TO_INT32_IN_MEM:
20842   case X86::FP64_TO_INT64_IN_MEM:
20843   case X86::FP80_TO_INT16_IN_MEM:
20844   case X86::FP80_TO_INT32_IN_MEM:
20845   case X86::FP80_TO_INT64_IN_MEM: {
20846     MachineFunction *F = BB->getParent();
20847     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
20848     DebugLoc DL = MI->getDebugLoc();
20849
20850     // Change the floating point control register to use "round towards zero"
20851     // mode when truncating to an integer value.
20852     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20853     addFrameReference(BuildMI(*BB, MI, DL,
20854                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20855
20856     // Load the old value of the high byte of the control word...
20857     unsigned OldCW =
20858       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20859     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20860                       CWFrameIdx);
20861
20862     // Set the high part to be round to zero...
20863     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20864       .addImm(0xC7F);
20865
20866     // Reload the modified control word now...
20867     addFrameReference(BuildMI(*BB, MI, DL,
20868                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20869
20870     // Restore the memory image of control word to original value
20871     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20872       .addReg(OldCW);
20873
20874     // Get the X86 opcode to use.
20875     unsigned Opc;
20876     switch (MI->getOpcode()) {
20877     default: llvm_unreachable("illegal opcode!");
20878     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20879     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20880     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20881     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20882     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20883     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20884     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20885     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20886     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20887     }
20888
20889     X86AddressMode AM;
20890     MachineOperand &Op = MI->getOperand(0);
20891     if (Op.isReg()) {
20892       AM.BaseType = X86AddressMode::RegBase;
20893       AM.Base.Reg = Op.getReg();
20894     } else {
20895       AM.BaseType = X86AddressMode::FrameIndexBase;
20896       AM.Base.FrameIndex = Op.getIndex();
20897     }
20898     Op = MI->getOperand(1);
20899     if (Op.isImm())
20900       AM.Scale = Op.getImm();
20901     Op = MI->getOperand(2);
20902     if (Op.isImm())
20903       AM.IndexReg = Op.getImm();
20904     Op = MI->getOperand(3);
20905     if (Op.isGlobal()) {
20906       AM.GV = Op.getGlobal();
20907     } else {
20908       AM.Disp = Op.getImm();
20909     }
20910     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20911                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20912
20913     // Reload the original control word now.
20914     addFrameReference(BuildMI(*BB, MI, DL,
20915                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20916
20917     MI->eraseFromParent();   // The pseudo instruction is gone now.
20918     return BB;
20919   }
20920     // String/text processing lowering.
20921   case X86::PCMPISTRM128REG:
20922   case X86::VPCMPISTRM128REG:
20923   case X86::PCMPISTRM128MEM:
20924   case X86::VPCMPISTRM128MEM:
20925   case X86::PCMPESTRM128REG:
20926   case X86::VPCMPESTRM128REG:
20927   case X86::PCMPESTRM128MEM:
20928   case X86::VPCMPESTRM128MEM:
20929     assert(Subtarget->hasSSE42() &&
20930            "Target must have SSE4.2 or AVX features enabled");
20931     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
20932
20933   // String/text processing lowering.
20934   case X86::PCMPISTRIREG:
20935   case X86::VPCMPISTRIREG:
20936   case X86::PCMPISTRIMEM:
20937   case X86::VPCMPISTRIMEM:
20938   case X86::PCMPESTRIREG:
20939   case X86::VPCMPESTRIREG:
20940   case X86::PCMPESTRIMEM:
20941   case X86::VPCMPESTRIMEM:
20942     assert(Subtarget->hasSSE42() &&
20943            "Target must have SSE4.2 or AVX features enabled");
20944     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
20945
20946   // Thread synchronization.
20947   case X86::MONITOR:
20948     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
20949                        Subtarget);
20950
20951   // xbegin
20952   case X86::XBEGIN:
20953     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
20954
20955   case X86::VASTART_SAVE_XMM_REGS:
20956     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20957
20958   case X86::VAARG_64:
20959     return EmitVAARG64WithCustomInserter(MI, BB);
20960
20961   case X86::EH_SjLj_SetJmp32:
20962   case X86::EH_SjLj_SetJmp64:
20963     return emitEHSjLjSetJmp(MI, BB);
20964
20965   case X86::EH_SjLj_LongJmp32:
20966   case X86::EH_SjLj_LongJmp64:
20967     return emitEHSjLjLongJmp(MI, BB);
20968
20969   case TargetOpcode::STACKMAP:
20970   case TargetOpcode::PATCHPOINT:
20971     return emitPatchPoint(MI, BB);
20972
20973   case X86::VFMADDPDr213r:
20974   case X86::VFMADDPSr213r:
20975   case X86::VFMADDSDr213r:
20976   case X86::VFMADDSSr213r:
20977   case X86::VFMSUBPDr213r:
20978   case X86::VFMSUBPSr213r:
20979   case X86::VFMSUBSDr213r:
20980   case X86::VFMSUBSSr213r:
20981   case X86::VFNMADDPDr213r:
20982   case X86::VFNMADDPSr213r:
20983   case X86::VFNMADDSDr213r:
20984   case X86::VFNMADDSSr213r:
20985   case X86::VFNMSUBPDr213r:
20986   case X86::VFNMSUBPSr213r:
20987   case X86::VFNMSUBSDr213r:
20988   case X86::VFNMSUBSSr213r:
20989   case X86::VFMADDSUBPDr213r:
20990   case X86::VFMADDSUBPSr213r:
20991   case X86::VFMSUBADDPDr213r:
20992   case X86::VFMSUBADDPSr213r:
20993   case X86::VFMADDPDr213rY:
20994   case X86::VFMADDPSr213rY:
20995   case X86::VFMSUBPDr213rY:
20996   case X86::VFMSUBPSr213rY:
20997   case X86::VFNMADDPDr213rY:
20998   case X86::VFNMADDPSr213rY:
20999   case X86::VFNMSUBPDr213rY:
21000   case X86::VFNMSUBPSr213rY:
21001   case X86::VFMADDSUBPDr213rY:
21002   case X86::VFMADDSUBPSr213rY:
21003   case X86::VFMSUBADDPDr213rY:
21004   case X86::VFMSUBADDPSr213rY:
21005     return emitFMA3Instr(MI, BB);
21006   }
21007 }
21008
21009 //===----------------------------------------------------------------------===//
21010 //                           X86 Optimization Hooks
21011 //===----------------------------------------------------------------------===//
21012
21013 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21014                                                       APInt &KnownZero,
21015                                                       APInt &KnownOne,
21016                                                       const SelectionDAG &DAG,
21017                                                       unsigned Depth) const {
21018   unsigned BitWidth = KnownZero.getBitWidth();
21019   unsigned Opc = Op.getOpcode();
21020   assert((Opc >= ISD::BUILTIN_OP_END ||
21021           Opc == ISD::INTRINSIC_WO_CHAIN ||
21022           Opc == ISD::INTRINSIC_W_CHAIN ||
21023           Opc == ISD::INTRINSIC_VOID) &&
21024          "Should use MaskedValueIsZero if you don't know whether Op"
21025          " is a target node!");
21026
21027   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21028   switch (Opc) {
21029   default: break;
21030   case X86ISD::ADD:
21031   case X86ISD::SUB:
21032   case X86ISD::ADC:
21033   case X86ISD::SBB:
21034   case X86ISD::SMUL:
21035   case X86ISD::UMUL:
21036   case X86ISD::INC:
21037   case X86ISD::DEC:
21038   case X86ISD::OR:
21039   case X86ISD::XOR:
21040   case X86ISD::AND:
21041     // These nodes' second result is a boolean.
21042     if (Op.getResNo() == 0)
21043       break;
21044     // Fallthrough
21045   case X86ISD::SETCC:
21046     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21047     break;
21048   case ISD::INTRINSIC_WO_CHAIN: {
21049     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21050     unsigned NumLoBits = 0;
21051     switch (IntId) {
21052     default: break;
21053     case Intrinsic::x86_sse_movmsk_ps:
21054     case Intrinsic::x86_avx_movmsk_ps_256:
21055     case Intrinsic::x86_sse2_movmsk_pd:
21056     case Intrinsic::x86_avx_movmsk_pd_256:
21057     case Intrinsic::x86_mmx_pmovmskb:
21058     case Intrinsic::x86_sse2_pmovmskb_128:
21059     case Intrinsic::x86_avx2_pmovmskb: {
21060       // High bits of movmskp{s|d}, pmovmskb are known zero.
21061       switch (IntId) {
21062         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21063         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21064         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21065         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21066         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21067         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21068         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21069         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21070       }
21071       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21072       break;
21073     }
21074     }
21075     break;
21076   }
21077   }
21078 }
21079
21080 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21081   SDValue Op,
21082   const SelectionDAG &,
21083   unsigned Depth) const {
21084   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21085   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21086     return Op.getValueType().getScalarType().getSizeInBits();
21087
21088   // Fallback case.
21089   return 1;
21090 }
21091
21092 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21093 /// node is a GlobalAddress + offset.
21094 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21095                                        const GlobalValue* &GA,
21096                                        int64_t &Offset) const {
21097   if (N->getOpcode() == X86ISD::Wrapper) {
21098     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21099       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21100       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21101       return true;
21102     }
21103   }
21104   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21105 }
21106
21107 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21108 /// same as extracting the high 128-bit part of 256-bit vector and then
21109 /// inserting the result into the low part of a new 256-bit vector
21110 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21111   EVT VT = SVOp->getValueType(0);
21112   unsigned NumElems = VT.getVectorNumElements();
21113
21114   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21115   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21116     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21117         SVOp->getMaskElt(j) >= 0)
21118       return false;
21119
21120   return true;
21121 }
21122
21123 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21124 /// same as extracting the low 128-bit part of 256-bit vector and then
21125 /// inserting the result into the high part of a new 256-bit vector
21126 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21127   EVT VT = SVOp->getValueType(0);
21128   unsigned NumElems = VT.getVectorNumElements();
21129
21130   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21131   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21132     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21133         SVOp->getMaskElt(j) >= 0)
21134       return false;
21135
21136   return true;
21137 }
21138
21139 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21140 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21141                                         TargetLowering::DAGCombinerInfo &DCI,
21142                                         const X86Subtarget* Subtarget) {
21143   SDLoc dl(N);
21144   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21145   SDValue V1 = SVOp->getOperand(0);
21146   SDValue V2 = SVOp->getOperand(1);
21147   EVT VT = SVOp->getValueType(0);
21148   unsigned NumElems = VT.getVectorNumElements();
21149
21150   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21151       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21152     //
21153     //                   0,0,0,...
21154     //                      |
21155     //    V      UNDEF    BUILD_VECTOR    UNDEF
21156     //     \      /           \           /
21157     //  CONCAT_VECTOR         CONCAT_VECTOR
21158     //         \                  /
21159     //          \                /
21160     //          RESULT: V + zero extended
21161     //
21162     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21163         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21164         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21165       return SDValue();
21166
21167     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21168       return SDValue();
21169
21170     // To match the shuffle mask, the first half of the mask should
21171     // be exactly the first vector, and all the rest a splat with the
21172     // first element of the second one.
21173     for (unsigned i = 0; i != NumElems/2; ++i)
21174       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21175           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21176         return SDValue();
21177
21178     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21179     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21180       if (Ld->hasNUsesOfValue(1, 0)) {
21181         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21182         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21183         SDValue ResNode =
21184           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21185                                   Ld->getMemoryVT(),
21186                                   Ld->getPointerInfo(),
21187                                   Ld->getAlignment(),
21188                                   false/*isVolatile*/, true/*ReadMem*/,
21189                                   false/*WriteMem*/);
21190
21191         // Make sure the newly-created LOAD is in the same position as Ld in
21192         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21193         // and update uses of Ld's output chain to use the TokenFactor.
21194         if (Ld->hasAnyUseOfValue(1)) {
21195           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21196                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21197           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21198           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21199                                  SDValue(ResNode.getNode(), 1));
21200         }
21201
21202         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
21203       }
21204     }
21205
21206     // Emit a zeroed vector and insert the desired subvector on its
21207     // first half.
21208     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21209     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21210     return DCI.CombineTo(N, InsV);
21211   }
21212
21213   //===--------------------------------------------------------------------===//
21214   // Combine some shuffles into subvector extracts and inserts:
21215   //
21216
21217   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21218   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21219     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21220     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21221     return DCI.CombineTo(N, InsV);
21222   }
21223
21224   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21225   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21226     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21227     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21228     return DCI.CombineTo(N, InsV);
21229   }
21230
21231   return SDValue();
21232 }
21233
21234 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21235 /// possible.
21236 ///
21237 /// This is the leaf of the recursive combinine below. When we have found some
21238 /// chain of single-use x86 shuffle instructions and accumulated the combined
21239 /// shuffle mask represented by them, this will try to pattern match that mask
21240 /// into either a single instruction if there is a special purpose instruction
21241 /// for this operation, or into a PSHUFB instruction which is a fully general
21242 /// instruction but should only be used to replace chains over a certain depth.
21243 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21244                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21245                                    TargetLowering::DAGCombinerInfo &DCI,
21246                                    const X86Subtarget *Subtarget) {
21247   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21248
21249   // Find the operand that enters the chain. Note that multiple uses are OK
21250   // here, we're not going to remove the operand we find.
21251   SDValue Input = Op.getOperand(0);
21252   while (Input.getOpcode() == ISD::BITCAST)
21253     Input = Input.getOperand(0);
21254
21255   MVT VT = Input.getSimpleValueType();
21256   MVT RootVT = Root.getSimpleValueType();
21257   SDLoc DL(Root);
21258
21259   // Just remove no-op shuffle masks.
21260   if (Mask.size() == 1) {
21261     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
21262                   /*AddTo*/ true);
21263     return true;
21264   }
21265
21266   // Use the float domain if the operand type is a floating point type.
21267   bool FloatDomain = VT.isFloatingPoint();
21268
21269   // For floating point shuffles, we don't have free copies in the shuffle
21270   // instructions or the ability to load as part of the instruction, so
21271   // canonicalize their shuffles to UNPCK or MOV variants.
21272   //
21273   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21274   // vectors because it can have a load folded into it that UNPCK cannot. This
21275   // doesn't preclude something switching to the shorter encoding post-RA.
21276   if (FloatDomain) {
21277     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
21278       bool Lo = Mask.equals(0, 0);
21279       unsigned Shuffle;
21280       MVT ShuffleVT;
21281       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21282       // is no slower than UNPCKLPD but has the option to fold the input operand
21283       // into even an unaligned memory load.
21284       if (Lo && Subtarget->hasSSE3()) {
21285         Shuffle = X86ISD::MOVDDUP;
21286         ShuffleVT = MVT::v2f64;
21287       } else {
21288         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21289         // than the UNPCK variants.
21290         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21291         ShuffleVT = MVT::v4f32;
21292       }
21293       if (Depth == 1 && Root->getOpcode() == Shuffle)
21294         return false; // Nothing to do!
21295       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21296       DCI.AddToWorklist(Op.getNode());
21297       if (Shuffle == X86ISD::MOVDDUP)
21298         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21299       else
21300         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21301       DCI.AddToWorklist(Op.getNode());
21302       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21303                     /*AddTo*/ true);
21304       return true;
21305     }
21306     if (Subtarget->hasSSE3() &&
21307         (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
21308       bool Lo = Mask.equals(0, 0, 2, 2);
21309       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21310       MVT ShuffleVT = MVT::v4f32;
21311       if (Depth == 1 && Root->getOpcode() == Shuffle)
21312         return false; // Nothing to do!
21313       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21314       DCI.AddToWorklist(Op.getNode());
21315       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21316       DCI.AddToWorklist(Op.getNode());
21317       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21318                     /*AddTo*/ true);
21319       return true;
21320     }
21321     if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
21322       bool Lo = Mask.equals(0, 0, 1, 1);
21323       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21324       MVT ShuffleVT = MVT::v4f32;
21325       if (Depth == 1 && Root->getOpcode() == Shuffle)
21326         return false; // Nothing to do!
21327       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21328       DCI.AddToWorklist(Op.getNode());
21329       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21330       DCI.AddToWorklist(Op.getNode());
21331       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21332                     /*AddTo*/ true);
21333       return true;
21334     }
21335   }
21336
21337   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21338   // variants as none of these have single-instruction variants that are
21339   // superior to the UNPCK formulation.
21340   if (!FloatDomain &&
21341       (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
21342        Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
21343        Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
21344        Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
21345                    15))) {
21346     bool Lo = Mask[0] == 0;
21347     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21348     if (Depth == 1 && Root->getOpcode() == Shuffle)
21349       return false; // Nothing to do!
21350     MVT ShuffleVT;
21351     switch (Mask.size()) {
21352     case 8:
21353       ShuffleVT = MVT::v8i16;
21354       break;
21355     case 16:
21356       ShuffleVT = MVT::v16i8;
21357       break;
21358     default:
21359       llvm_unreachable("Impossible mask size!");
21360     };
21361     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21362     DCI.AddToWorklist(Op.getNode());
21363     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21364     DCI.AddToWorklist(Op.getNode());
21365     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21366                   /*AddTo*/ true);
21367     return true;
21368   }
21369
21370   // Don't try to re-form single instruction chains under any circumstances now
21371   // that we've done encoding canonicalization for them.
21372   if (Depth < 2)
21373     return false;
21374
21375   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21376   // can replace them with a single PSHUFB instruction profitably. Intel's
21377   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21378   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21379   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21380     SmallVector<SDValue, 16> PSHUFBMask;
21381     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
21382     int Ratio = 16 / Mask.size();
21383     for (unsigned i = 0; i < 16; ++i) {
21384       if (Mask[i / Ratio] == SM_SentinelUndef) {
21385         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21386         continue;
21387       }
21388       int M = Mask[i / Ratio] != SM_SentinelZero
21389                   ? Ratio * Mask[i / Ratio] + i % Ratio
21390                   : 255;
21391       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
21392     }
21393     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
21394     DCI.AddToWorklist(Op.getNode());
21395     SDValue PSHUFBMaskOp =
21396         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
21397     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21398     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
21399     DCI.AddToWorklist(Op.getNode());
21400     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21401                   /*AddTo*/ true);
21402     return true;
21403   }
21404
21405   // Failed to find any combines.
21406   return false;
21407 }
21408
21409 /// \brief Fully generic combining of x86 shuffle instructions.
21410 ///
21411 /// This should be the last combine run over the x86 shuffle instructions. Once
21412 /// they have been fully optimized, this will recursively consider all chains
21413 /// of single-use shuffle instructions, build a generic model of the cumulative
21414 /// shuffle operation, and check for simpler instructions which implement this
21415 /// operation. We use this primarily for two purposes:
21416 ///
21417 /// 1) Collapse generic shuffles to specialized single instructions when
21418 ///    equivalent. In most cases, this is just an encoding size win, but
21419 ///    sometimes we will collapse multiple generic shuffles into a single
21420 ///    special-purpose shuffle.
21421 /// 2) Look for sequences of shuffle instructions with 3 or more total
21422 ///    instructions, and replace them with the slightly more expensive SSSE3
21423 ///    PSHUFB instruction if available. We do this as the last combining step
21424 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21425 ///    a suitable short sequence of other instructions. The PHUFB will either
21426 ///    use a register or have to read from memory and so is slightly (but only
21427 ///    slightly) more expensive than the other shuffle instructions.
21428 ///
21429 /// Because this is inherently a quadratic operation (for each shuffle in
21430 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21431 /// This should never be an issue in practice as the shuffle lowering doesn't
21432 /// produce sequences of more than 8 instructions.
21433 ///
21434 /// FIXME: We will currently miss some cases where the redundant shuffling
21435 /// would simplify under the threshold for PSHUFB formation because of
21436 /// combine-ordering. To fix this, we should do the redundant instruction
21437 /// combining in this recursive walk.
21438 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21439                                           ArrayRef<int> RootMask,
21440                                           int Depth, bool HasPSHUFB,
21441                                           SelectionDAG &DAG,
21442                                           TargetLowering::DAGCombinerInfo &DCI,
21443                                           const X86Subtarget *Subtarget) {
21444   // Bound the depth of our recursive combine because this is ultimately
21445   // quadratic in nature.
21446   if (Depth > 8)
21447     return false;
21448
21449   // Directly rip through bitcasts to find the underlying operand.
21450   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21451     Op = Op.getOperand(0);
21452
21453   MVT VT = Op.getSimpleValueType();
21454   if (!VT.isVector())
21455     return false; // Bail if we hit a non-vector.
21456   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
21457   // version should be added.
21458   if (VT.getSizeInBits() != 128)
21459     return false;
21460
21461   assert(Root.getSimpleValueType().isVector() &&
21462          "Shuffles operate on vector types!");
21463   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21464          "Can only combine shuffles of the same vector register size.");
21465
21466   if (!isTargetShuffle(Op.getOpcode()))
21467     return false;
21468   SmallVector<int, 16> OpMask;
21469   bool IsUnary;
21470   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21471   // We only can combine unary shuffles which we can decode the mask for.
21472   if (!HaveMask || !IsUnary)
21473     return false;
21474
21475   assert(VT.getVectorNumElements() == OpMask.size() &&
21476          "Different mask size from vector size!");
21477   assert(((RootMask.size() > OpMask.size() &&
21478            RootMask.size() % OpMask.size() == 0) ||
21479           (OpMask.size() > RootMask.size() &&
21480            OpMask.size() % RootMask.size() == 0) ||
21481           OpMask.size() == RootMask.size()) &&
21482          "The smaller number of elements must divide the larger.");
21483   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21484   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21485   assert(((RootRatio == 1 && OpRatio == 1) ||
21486           (RootRatio == 1) != (OpRatio == 1)) &&
21487          "Must not have a ratio for both incoming and op masks!");
21488
21489   SmallVector<int, 16> Mask;
21490   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21491
21492   // Merge this shuffle operation's mask into our accumulated mask. Note that
21493   // this shuffle's mask will be the first applied to the input, followed by the
21494   // root mask to get us all the way to the root value arrangement. The reason
21495   // for this order is that we are recursing up the operation chain.
21496   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21497     int RootIdx = i / RootRatio;
21498     if (RootMask[RootIdx] < 0) {
21499       // This is a zero or undef lane, we're done.
21500       Mask.push_back(RootMask[RootIdx]);
21501       continue;
21502     }
21503
21504     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21505     int OpIdx = RootMaskedIdx / OpRatio;
21506     if (OpMask[OpIdx] < 0) {
21507       // The incoming lanes are zero or undef, it doesn't matter which ones we
21508       // are using.
21509       Mask.push_back(OpMask[OpIdx]);
21510       continue;
21511     }
21512
21513     // Ok, we have non-zero lanes, map them through.
21514     Mask.push_back(OpMask[OpIdx] * OpRatio +
21515                    RootMaskedIdx % OpRatio);
21516   }
21517
21518   // See if we can recurse into the operand to combine more things.
21519   switch (Op.getOpcode()) {
21520     case X86ISD::PSHUFB:
21521       HasPSHUFB = true;
21522     case X86ISD::PSHUFD:
21523     case X86ISD::PSHUFHW:
21524     case X86ISD::PSHUFLW:
21525       if (Op.getOperand(0).hasOneUse() &&
21526           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21527                                         HasPSHUFB, DAG, DCI, Subtarget))
21528         return true;
21529       break;
21530
21531     case X86ISD::UNPCKL:
21532     case X86ISD::UNPCKH:
21533       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21534       // We can't check for single use, we have to check that this shuffle is the only user.
21535       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21536           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21537                                         HasPSHUFB, DAG, DCI, Subtarget))
21538           return true;
21539       break;
21540   }
21541
21542   // Minor canonicalization of the accumulated shuffle mask to make it easier
21543   // to match below. All this does is detect masks with squential pairs of
21544   // elements, and shrink them to the half-width mask. It does this in a loop
21545   // so it will reduce the size of the mask to the minimal width mask which
21546   // performs an equivalent shuffle.
21547   SmallVector<int, 16> WidenedMask;
21548   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21549     Mask = std::move(WidenedMask);
21550     WidenedMask.clear();
21551   }
21552
21553   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21554                                 Subtarget);
21555 }
21556
21557 /// \brief Get the PSHUF-style mask from PSHUF node.
21558 ///
21559 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21560 /// PSHUF-style masks that can be reused with such instructions.
21561 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21562   SmallVector<int, 4> Mask;
21563   bool IsUnary;
21564   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
21565   (void)HaveMask;
21566   assert(HaveMask);
21567
21568   switch (N.getOpcode()) {
21569   case X86ISD::PSHUFD:
21570     return Mask;
21571   case X86ISD::PSHUFLW:
21572     Mask.resize(4);
21573     return Mask;
21574   case X86ISD::PSHUFHW:
21575     Mask.erase(Mask.begin(), Mask.begin() + 4);
21576     for (int &M : Mask)
21577       M -= 4;
21578     return Mask;
21579   default:
21580     llvm_unreachable("No valid shuffle instruction found!");
21581   }
21582 }
21583
21584 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21585 ///
21586 /// We walk up the chain and look for a combinable shuffle, skipping over
21587 /// shuffles that we could hoist this shuffle's transformation past without
21588 /// altering anything.
21589 static SDValue
21590 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21591                              SelectionDAG &DAG,
21592                              TargetLowering::DAGCombinerInfo &DCI) {
21593   assert(N.getOpcode() == X86ISD::PSHUFD &&
21594          "Called with something other than an x86 128-bit half shuffle!");
21595   SDLoc DL(N);
21596
21597   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21598   // of the shuffles in the chain so that we can form a fresh chain to replace
21599   // this one.
21600   SmallVector<SDValue, 8> Chain;
21601   SDValue V = N.getOperand(0);
21602   for (; V.hasOneUse(); V = V.getOperand(0)) {
21603     switch (V.getOpcode()) {
21604     default:
21605       return SDValue(); // Nothing combined!
21606
21607     case ISD::BITCAST:
21608       // Skip bitcasts as we always know the type for the target specific
21609       // instructions.
21610       continue;
21611
21612     case X86ISD::PSHUFD:
21613       // Found another dword shuffle.
21614       break;
21615
21616     case X86ISD::PSHUFLW:
21617       // Check that the low words (being shuffled) are the identity in the
21618       // dword shuffle, and the high words are self-contained.
21619       if (Mask[0] != 0 || Mask[1] != 1 ||
21620           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21621         return SDValue();
21622
21623       Chain.push_back(V);
21624       continue;
21625
21626     case X86ISD::PSHUFHW:
21627       // Check that the high words (being shuffled) are the identity in the
21628       // dword shuffle, and the low words are self-contained.
21629       if (Mask[2] != 2 || Mask[3] != 3 ||
21630           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21631         return SDValue();
21632
21633       Chain.push_back(V);
21634       continue;
21635
21636     case X86ISD::UNPCKL:
21637     case X86ISD::UNPCKH:
21638       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21639       // shuffle into a preceding word shuffle.
21640       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
21641         return SDValue();
21642
21643       // Search for a half-shuffle which we can combine with.
21644       unsigned CombineOp =
21645           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21646       if (V.getOperand(0) != V.getOperand(1) ||
21647           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21648         return SDValue();
21649       Chain.push_back(V);
21650       V = V.getOperand(0);
21651       do {
21652         switch (V.getOpcode()) {
21653         default:
21654           return SDValue(); // Nothing to combine.
21655
21656         case X86ISD::PSHUFLW:
21657         case X86ISD::PSHUFHW:
21658           if (V.getOpcode() == CombineOp)
21659             break;
21660
21661           Chain.push_back(V);
21662
21663           // Fallthrough!
21664         case ISD::BITCAST:
21665           V = V.getOperand(0);
21666           continue;
21667         }
21668         break;
21669       } while (V.hasOneUse());
21670       break;
21671     }
21672     // Break out of the loop if we break out of the switch.
21673     break;
21674   }
21675
21676   if (!V.hasOneUse())
21677     // We fell out of the loop without finding a viable combining instruction.
21678     return SDValue();
21679
21680   // Merge this node's mask and our incoming mask.
21681   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21682   for (int &M : Mask)
21683     M = VMask[M];
21684   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21685                   getV4X86ShuffleImm8ForMask(Mask, DAG));
21686
21687   // Rebuild the chain around this new shuffle.
21688   while (!Chain.empty()) {
21689     SDValue W = Chain.pop_back_val();
21690
21691     if (V.getValueType() != W.getOperand(0).getValueType())
21692       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
21693
21694     switch (W.getOpcode()) {
21695     default:
21696       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21697
21698     case X86ISD::UNPCKL:
21699     case X86ISD::UNPCKH:
21700       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21701       break;
21702
21703     case X86ISD::PSHUFD:
21704     case X86ISD::PSHUFLW:
21705     case X86ISD::PSHUFHW:
21706       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21707       break;
21708     }
21709   }
21710   if (V.getValueType() != N.getValueType())
21711     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
21712
21713   // Return the new chain to replace N.
21714   return V;
21715 }
21716
21717 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21718 ///
21719 /// We walk up the chain, skipping shuffles of the other half and looking
21720 /// through shuffles which switch halves trying to find a shuffle of the same
21721 /// pair of dwords.
21722 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21723                                         SelectionDAG &DAG,
21724                                         TargetLowering::DAGCombinerInfo &DCI) {
21725   assert(
21726       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21727       "Called with something other than an x86 128-bit half shuffle!");
21728   SDLoc DL(N);
21729   unsigned CombineOpcode = N.getOpcode();
21730
21731   // Walk up a single-use chain looking for a combinable shuffle.
21732   SDValue V = N.getOperand(0);
21733   for (; V.hasOneUse(); V = V.getOperand(0)) {
21734     switch (V.getOpcode()) {
21735     default:
21736       return false; // Nothing combined!
21737
21738     case ISD::BITCAST:
21739       // Skip bitcasts as we always know the type for the target specific
21740       // instructions.
21741       continue;
21742
21743     case X86ISD::PSHUFLW:
21744     case X86ISD::PSHUFHW:
21745       if (V.getOpcode() == CombineOpcode)
21746         break;
21747
21748       // Other-half shuffles are no-ops.
21749       continue;
21750     }
21751     // Break out of the loop if we break out of the switch.
21752     break;
21753   }
21754
21755   if (!V.hasOneUse())
21756     // We fell out of the loop without finding a viable combining instruction.
21757     return false;
21758
21759   // Combine away the bottom node as its shuffle will be accumulated into
21760   // a preceding shuffle.
21761   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21762
21763   // Record the old value.
21764   SDValue Old = V;
21765
21766   // Merge this node's mask and our incoming mask (adjusted to account for all
21767   // the pshufd instructions encountered).
21768   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21769   for (int &M : Mask)
21770     M = VMask[M];
21771   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21772                   getV4X86ShuffleImm8ForMask(Mask, DAG));
21773
21774   // Check that the shuffles didn't cancel each other out. If not, we need to
21775   // combine to the new one.
21776   if (Old != V)
21777     // Replace the combinable shuffle with the combined one, updating all users
21778     // so that we re-evaluate the chain here.
21779     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21780
21781   return true;
21782 }
21783
21784 /// \brief Try to combine x86 target specific shuffles.
21785 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21786                                            TargetLowering::DAGCombinerInfo &DCI,
21787                                            const X86Subtarget *Subtarget) {
21788   SDLoc DL(N);
21789   MVT VT = N.getSimpleValueType();
21790   SmallVector<int, 4> Mask;
21791
21792   switch (N.getOpcode()) {
21793   case X86ISD::PSHUFD:
21794   case X86ISD::PSHUFLW:
21795   case X86ISD::PSHUFHW:
21796     Mask = getPSHUFShuffleMask(N);
21797     assert(Mask.size() == 4);
21798     break;
21799   default:
21800     return SDValue();
21801   }
21802
21803   // Nuke no-op shuffles that show up after combining.
21804   if (isNoopShuffleMask(Mask))
21805     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21806
21807   // Look for simplifications involving one or two shuffle instructions.
21808   SDValue V = N.getOperand(0);
21809   switch (N.getOpcode()) {
21810   default:
21811     break;
21812   case X86ISD::PSHUFLW:
21813   case X86ISD::PSHUFHW:
21814     assert(VT == MVT::v8i16);
21815     (void)VT;
21816
21817     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21818       return SDValue(); // We combined away this shuffle, so we're done.
21819
21820     // See if this reduces to a PSHUFD which is no more expensive and can
21821     // combine with more operations. Note that it has to at least flip the
21822     // dwords as otherwise it would have been removed as a no-op.
21823     if (Mask[0] == 2 && Mask[1] == 3 && Mask[2] == 0 && Mask[3] == 1) {
21824       int DMask[] = {0, 1, 2, 3};
21825       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21826       DMask[DOffset + 0] = DOffset + 1;
21827       DMask[DOffset + 1] = DOffset + 0;
21828       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
21829       DCI.AddToWorklist(V.getNode());
21830       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
21831                       getV4X86ShuffleImm8ForMask(DMask, DAG));
21832       DCI.AddToWorklist(V.getNode());
21833       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
21834     }
21835
21836     // Look for shuffle patterns which can be implemented as a single unpack.
21837     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21838     // only works when we have a PSHUFD followed by two half-shuffles.
21839     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21840         (V.getOpcode() == X86ISD::PSHUFLW ||
21841          V.getOpcode() == X86ISD::PSHUFHW) &&
21842         V.getOpcode() != N.getOpcode() &&
21843         V.hasOneUse()) {
21844       SDValue D = V.getOperand(0);
21845       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21846         D = D.getOperand(0);
21847       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21848         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21849         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21850         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21851         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21852         int WordMask[8];
21853         for (int i = 0; i < 4; ++i) {
21854           WordMask[i + NOffset] = Mask[i] + NOffset;
21855           WordMask[i + VOffset] = VMask[i] + VOffset;
21856         }
21857         // Map the word mask through the DWord mask.
21858         int MappedMask[8];
21859         for (int i = 0; i < 8; ++i)
21860           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21861         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
21862         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
21863         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
21864                        std::begin(UnpackLoMask)) ||
21865             std::equal(std::begin(MappedMask), std::end(MappedMask),
21866                        std::begin(UnpackHiMask))) {
21867           // We can replace all three shuffles with an unpack.
21868           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
21869           DCI.AddToWorklist(V.getNode());
21870           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21871                                                 : X86ISD::UNPCKH,
21872                              DL, MVT::v8i16, V, V);
21873         }
21874       }
21875     }
21876
21877     break;
21878
21879   case X86ISD::PSHUFD:
21880     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21881       return NewN;
21882
21883     break;
21884   }
21885
21886   return SDValue();
21887 }
21888
21889 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21890 ///
21891 /// We combine this directly on the abstract vector shuffle nodes so it is
21892 /// easier to generically match. We also insert dummy vector shuffle nodes for
21893 /// the operands which explicitly discard the lanes which are unused by this
21894 /// operation to try to flow through the rest of the combiner the fact that
21895 /// they're unused.
21896 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21897   SDLoc DL(N);
21898   EVT VT = N->getValueType(0);
21899
21900   // We only handle target-independent shuffles.
21901   // FIXME: It would be easy and harmless to use the target shuffle mask
21902   // extraction tool to support more.
21903   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21904     return SDValue();
21905
21906   auto *SVN = cast<ShuffleVectorSDNode>(N);
21907   ArrayRef<int> Mask = SVN->getMask();
21908   SDValue V1 = N->getOperand(0);
21909   SDValue V2 = N->getOperand(1);
21910
21911   // We require the first shuffle operand to be the SUB node, and the second to
21912   // be the ADD node.
21913   // FIXME: We should support the commuted patterns.
21914   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21915     return SDValue();
21916
21917   // If there are other uses of these operations we can't fold them.
21918   if (!V1->hasOneUse() || !V2->hasOneUse())
21919     return SDValue();
21920
21921   // Ensure that both operations have the same operands. Note that we can
21922   // commute the FADD operands.
21923   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21924   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21925       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21926     return SDValue();
21927
21928   // We're looking for blends between FADD and FSUB nodes. We insist on these
21929   // nodes being lined up in a specific expected pattern.
21930   if (!(isShuffleEquivalent(Mask, 0, 3) ||
21931         isShuffleEquivalent(Mask, 0, 5, 2, 7) ||
21932         isShuffleEquivalent(Mask, 0, 9, 2, 11, 4, 13, 6, 15)))
21933     return SDValue();
21934
21935   // Only specific types are legal at this point, assert so we notice if and
21936   // when these change.
21937   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21938           VT == MVT::v4f64) &&
21939          "Unknown vector type encountered!");
21940
21941   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21942 }
21943
21944 /// PerformShuffleCombine - Performs several different shuffle combines.
21945 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21946                                      TargetLowering::DAGCombinerInfo &DCI,
21947                                      const X86Subtarget *Subtarget) {
21948   SDLoc dl(N);
21949   SDValue N0 = N->getOperand(0);
21950   SDValue N1 = N->getOperand(1);
21951   EVT VT = N->getValueType(0);
21952
21953   // Don't create instructions with illegal types after legalize types has run.
21954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21955   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21956     return SDValue();
21957
21958   // If we have legalized the vector types, look for blends of FADD and FSUB
21959   // nodes that we can fuse into an ADDSUB node.
21960   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21961     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21962       return AddSub;
21963
21964   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21965   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21966       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21967     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21968
21969   // During Type Legalization, when promoting illegal vector types,
21970   // the backend might introduce new shuffle dag nodes and bitcasts.
21971   //
21972   // This code performs the following transformation:
21973   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21974   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21975   //
21976   // We do this only if both the bitcast and the BINOP dag nodes have
21977   // one use. Also, perform this transformation only if the new binary
21978   // operation is legal. This is to avoid introducing dag nodes that
21979   // potentially need to be further expanded (or custom lowered) into a
21980   // less optimal sequence of dag nodes.
21981   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21982       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21983       N0.getOpcode() == ISD::BITCAST) {
21984     SDValue BC0 = N0.getOperand(0);
21985     EVT SVT = BC0.getValueType();
21986     unsigned Opcode = BC0.getOpcode();
21987     unsigned NumElts = VT.getVectorNumElements();
21988     
21989     if (BC0.hasOneUse() && SVT.isVector() &&
21990         SVT.getVectorNumElements() * 2 == NumElts &&
21991         TLI.isOperationLegal(Opcode, VT)) {
21992       bool CanFold = false;
21993       switch (Opcode) {
21994       default : break;
21995       case ISD::ADD :
21996       case ISD::FADD :
21997       case ISD::SUB :
21998       case ISD::FSUB :
21999       case ISD::MUL :
22000       case ISD::FMUL :
22001         CanFold = true;
22002       }
22003
22004       unsigned SVTNumElts = SVT.getVectorNumElements();
22005       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22006       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22007         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22008       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22009         CanFold = SVOp->getMaskElt(i) < 0;
22010
22011       if (CanFold) {
22012         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
22013         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
22014         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22015         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22016       }
22017     }
22018   }
22019
22020   // Only handle 128 wide vector from here on.
22021   if (!VT.is128BitVector())
22022     return SDValue();
22023
22024   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22025   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22026   // consecutive, non-overlapping, and in the right order.
22027   SmallVector<SDValue, 16> Elts;
22028   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22029     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22030
22031   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
22032   if (LD.getNode())
22033     return LD;
22034
22035   if (isTargetShuffle(N->getOpcode())) {
22036     SDValue Shuffle =
22037         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22038     if (Shuffle.getNode())
22039       return Shuffle;
22040
22041     // Try recursively combining arbitrary sequences of x86 shuffle
22042     // instructions into higher-order shuffles. We do this after combining
22043     // specific PSHUF instruction sequences into their minimal form so that we
22044     // can evaluate how many specialized shuffle instructions are involved in
22045     // a particular chain.
22046     SmallVector<int, 1> NonceMask; // Just a placeholder.
22047     NonceMask.push_back(0);
22048     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22049                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22050                                       DCI, Subtarget))
22051       return SDValue(); // This routine will use CombineTo to replace N.
22052   }
22053
22054   return SDValue();
22055 }
22056
22057 /// PerformTruncateCombine - Converts truncate operation to
22058 /// a sequence of vector shuffle operations.
22059 /// It is possible when we truncate 256-bit vector to 128-bit vector
22060 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
22061                                       TargetLowering::DAGCombinerInfo &DCI,
22062                                       const X86Subtarget *Subtarget)  {
22063   return SDValue();
22064 }
22065
22066 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22067 /// specific shuffle of a load can be folded into a single element load.
22068 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22069 /// shuffles have been custom lowered so we need to handle those here.
22070 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22071                                          TargetLowering::DAGCombinerInfo &DCI) {
22072   if (DCI.isBeforeLegalizeOps())
22073     return SDValue();
22074
22075   SDValue InVec = N->getOperand(0);
22076   SDValue EltNo = N->getOperand(1);
22077
22078   if (!isa<ConstantSDNode>(EltNo))
22079     return SDValue();
22080
22081   EVT OriginalVT = InVec.getValueType();
22082
22083   if (InVec.getOpcode() == ISD::BITCAST) {
22084     // Don't duplicate a load with other uses.
22085     if (!InVec.hasOneUse())
22086       return SDValue();
22087     EVT BCVT = InVec.getOperand(0).getValueType();
22088     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22089       return SDValue();
22090     InVec = InVec.getOperand(0);
22091   }
22092
22093   EVT CurrentVT = InVec.getValueType();
22094
22095   if (!isTargetShuffle(InVec.getOpcode()))
22096     return SDValue();
22097
22098   // Don't duplicate a load with other uses.
22099   if (!InVec.hasOneUse())
22100     return SDValue();
22101
22102   SmallVector<int, 16> ShuffleMask;
22103   bool UnaryShuffle;
22104   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22105                             ShuffleMask, UnaryShuffle))
22106     return SDValue();
22107
22108   // Select the input vector, guarding against out of range extract vector.
22109   unsigned NumElems = CurrentVT.getVectorNumElements();
22110   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22111   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22112   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22113                                          : InVec.getOperand(1);
22114
22115   // If inputs to shuffle are the same for both ops, then allow 2 uses
22116   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22117
22118   if (LdNode.getOpcode() == ISD::BITCAST) {
22119     // Don't duplicate a load with other uses.
22120     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22121       return SDValue();
22122
22123     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22124     LdNode = LdNode.getOperand(0);
22125   }
22126
22127   if (!ISD::isNormalLoad(LdNode.getNode()))
22128     return SDValue();
22129
22130   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22131
22132   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22133     return SDValue();
22134
22135   EVT EltVT = N->getValueType(0);
22136   // If there's a bitcast before the shuffle, check if the load type and
22137   // alignment is valid.
22138   unsigned Align = LN0->getAlignment();
22139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22140   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
22141       EltVT.getTypeForEVT(*DAG.getContext()));
22142
22143   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22144     return SDValue();
22145
22146   // All checks match so transform back to vector_shuffle so that DAG combiner
22147   // can finish the job
22148   SDLoc dl(N);
22149
22150   // Create shuffle node taking into account the case that its a unary shuffle
22151   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22152                                    : InVec.getOperand(1);
22153   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22154                                  InVec.getOperand(0), Shuffle,
22155                                  &ShuffleMask[0]);
22156   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
22157   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22158                      EltNo);
22159 }
22160
22161 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22162 /// generation and convert it from being a bunch of shuffles and extracts
22163 /// to a simple store and scalar loads to extract the elements.
22164 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22165                                          TargetLowering::DAGCombinerInfo &DCI) {
22166   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
22167   if (NewOp.getNode())
22168     return NewOp;
22169
22170   SDValue InputVector = N->getOperand(0);
22171
22172   // Detect whether we are trying to convert from mmx to i32 and the bitcast
22173   // from mmx to v2i32 has a single usage.
22174   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
22175       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
22176       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
22177     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22178                        N->getValueType(0),
22179                        InputVector.getNode()->getOperand(0));
22180
22181   // Only operate on vectors of 4 elements, where the alternative shuffling
22182   // gets to be more expensive.
22183   if (InputVector.getValueType() != MVT::v4i32)
22184     return SDValue();
22185
22186   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22187   // single use which is a sign-extend or zero-extend, and all elements are
22188   // used.
22189   SmallVector<SDNode *, 4> Uses;
22190   unsigned ExtractedElements = 0;
22191   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22192        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22193     if (UI.getUse().getResNo() != InputVector.getResNo())
22194       return SDValue();
22195
22196     SDNode *Extract = *UI;
22197     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22198       return SDValue();
22199
22200     if (Extract->getValueType(0) != MVT::i32)
22201       return SDValue();
22202     if (!Extract->hasOneUse())
22203       return SDValue();
22204     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22205         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22206       return SDValue();
22207     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22208       return SDValue();
22209
22210     // Record which element was extracted.
22211     ExtractedElements |=
22212       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22213
22214     Uses.push_back(Extract);
22215   }
22216
22217   // If not all the elements were used, this may not be worthwhile.
22218   if (ExtractedElements != 15)
22219     return SDValue();
22220
22221   // Ok, we've now decided to do the transformation.
22222   SDLoc dl(InputVector);
22223
22224   // Store the value to a temporary stack slot.
22225   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22226   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22227                             MachinePointerInfo(), false, false, 0);
22228
22229   // Replace each use (extract) with a load of the appropriate element.
22230   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22231        UE = Uses.end(); UI != UE; ++UI) {
22232     SDNode *Extract = *UI;
22233
22234     // cOMpute the element's address.
22235     SDValue Idx = Extract->getOperand(1);
22236     unsigned EltSize =
22237         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
22238     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
22239     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22240     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
22241
22242     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
22243                                      StackPtr, OffsetVal);
22244
22245     // Load the scalar.
22246     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
22247                                      ScalarAddr, MachinePointerInfo(),
22248                                      false, false, false, 0);
22249
22250     // Replace the exact with the load.
22251     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
22252   }
22253
22254   // The replacement was made in place; don't return anything.
22255   return SDValue();
22256 }
22257
22258 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22259 static std::pair<unsigned, bool>
22260 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22261                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22262   if (!VT.isVector())
22263     return std::make_pair(0, false);
22264
22265   bool NeedSplit = false;
22266   switch (VT.getSimpleVT().SimpleTy) {
22267   default: return std::make_pair(0, false);
22268   case MVT::v32i8:
22269   case MVT::v16i16:
22270   case MVT::v8i32:
22271     if (!Subtarget->hasAVX2())
22272       NeedSplit = true;
22273     if (!Subtarget->hasAVX())
22274       return std::make_pair(0, false);
22275     break;
22276   case MVT::v16i8:
22277   case MVT::v8i16:
22278   case MVT::v4i32:
22279     if (!Subtarget->hasSSE2())
22280       return std::make_pair(0, false);
22281   }
22282
22283   // SSE2 has only a small subset of the operations.
22284   bool hasUnsigned = Subtarget->hasSSE41() ||
22285                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22286   bool hasSigned = Subtarget->hasSSE41() ||
22287                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22288
22289   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22290
22291   unsigned Opc = 0;
22292   // Check for x CC y ? x : y.
22293   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22294       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22295     switch (CC) {
22296     default: break;
22297     case ISD::SETULT:
22298     case ISD::SETULE:
22299       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22300     case ISD::SETUGT:
22301     case ISD::SETUGE:
22302       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22303     case ISD::SETLT:
22304     case ISD::SETLE:
22305       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22306     case ISD::SETGT:
22307     case ISD::SETGE:
22308       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22309     }
22310   // Check for x CC y ? y : x -- a min/max with reversed arms.
22311   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22312              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22313     switch (CC) {
22314     default: break;
22315     case ISD::SETULT:
22316     case ISD::SETULE:
22317       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22318     case ISD::SETUGT:
22319     case ISD::SETUGE:
22320       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22321     case ISD::SETLT:
22322     case ISD::SETLE:
22323       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22324     case ISD::SETGT:
22325     case ISD::SETGE:
22326       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22327     }
22328   }
22329
22330   return std::make_pair(Opc, NeedSplit);
22331 }
22332
22333 static SDValue
22334 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22335                                       const X86Subtarget *Subtarget) {
22336   SDLoc dl(N);
22337   SDValue Cond = N->getOperand(0);
22338   SDValue LHS = N->getOperand(1);
22339   SDValue RHS = N->getOperand(2);
22340
22341   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22342     SDValue CondSrc = Cond->getOperand(0);
22343     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22344       Cond = CondSrc->getOperand(0);
22345   }
22346
22347   MVT VT = N->getSimpleValueType(0);
22348   MVT EltVT = VT.getVectorElementType();
22349   unsigned NumElems = VT.getVectorNumElements();
22350   // There is no blend with immediate in AVX-512.
22351   if (VT.is512BitVector())
22352     return SDValue();
22353
22354   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
22355     return SDValue();
22356   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
22357     return SDValue();
22358
22359   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22360     return SDValue();
22361
22362   // A vselect where all conditions and data are constants can be optimized into
22363   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22364   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22365       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22366     return SDValue();
22367
22368   unsigned MaskValue = 0;
22369   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22370     return SDValue();
22371
22372   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22373   for (unsigned i = 0; i < NumElems; ++i) {
22374     // Be sure we emit undef where we can.
22375     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22376       ShuffleMask[i] = -1;
22377     else
22378       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22379   }
22380
22381   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22382 }
22383
22384 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22385 /// nodes.
22386 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22387                                     TargetLowering::DAGCombinerInfo &DCI,
22388                                     const X86Subtarget *Subtarget) {
22389   SDLoc DL(N);
22390   SDValue Cond = N->getOperand(0);
22391   // Get the LHS/RHS of the select.
22392   SDValue LHS = N->getOperand(1);
22393   SDValue RHS = N->getOperand(2);
22394   EVT VT = LHS.getValueType();
22395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22396
22397   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22398   // instructions match the semantics of the common C idiom x<y?x:y but not
22399   // x<=y?x:y, because of how they handle negative zero (which can be
22400   // ignored in unsafe-math mode).
22401   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22402       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
22403       (Subtarget->hasSSE2() ||
22404        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22405     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22406
22407     unsigned Opcode = 0;
22408     // Check for x CC y ? x : y.
22409     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22410         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22411       switch (CC) {
22412       default: break;
22413       case ISD::SETULT:
22414         // Converting this to a min would handle NaNs incorrectly, and swapping
22415         // the operands would cause it to handle comparisons between positive
22416         // and negative zero incorrectly.
22417         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22418           if (!DAG.getTarget().Options.UnsafeFPMath &&
22419               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22420             break;
22421           std::swap(LHS, RHS);
22422         }
22423         Opcode = X86ISD::FMIN;
22424         break;
22425       case ISD::SETOLE:
22426         // Converting this to a min would handle comparisons between positive
22427         // and negative zero incorrectly.
22428         if (!DAG.getTarget().Options.UnsafeFPMath &&
22429             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22430           break;
22431         Opcode = X86ISD::FMIN;
22432         break;
22433       case ISD::SETULE:
22434         // Converting this to a min would handle both negative zeros and NaNs
22435         // incorrectly, but we can swap the operands to fix both.
22436         std::swap(LHS, RHS);
22437       case ISD::SETOLT:
22438       case ISD::SETLT:
22439       case ISD::SETLE:
22440         Opcode = X86ISD::FMIN;
22441         break;
22442
22443       case ISD::SETOGE:
22444         // Converting this to a max would handle comparisons between positive
22445         // and negative zero incorrectly.
22446         if (!DAG.getTarget().Options.UnsafeFPMath &&
22447             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22448           break;
22449         Opcode = X86ISD::FMAX;
22450         break;
22451       case ISD::SETUGT:
22452         // Converting this to a max would handle NaNs incorrectly, and swapping
22453         // the operands would cause it to handle comparisons between positive
22454         // and negative zero incorrectly.
22455         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22456           if (!DAG.getTarget().Options.UnsafeFPMath &&
22457               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22458             break;
22459           std::swap(LHS, RHS);
22460         }
22461         Opcode = X86ISD::FMAX;
22462         break;
22463       case ISD::SETUGE:
22464         // Converting this to a max would handle both negative zeros and NaNs
22465         // incorrectly, but we can swap the operands to fix both.
22466         std::swap(LHS, RHS);
22467       case ISD::SETOGT:
22468       case ISD::SETGT:
22469       case ISD::SETGE:
22470         Opcode = X86ISD::FMAX;
22471         break;
22472       }
22473     // Check for x CC y ? y : x -- a min/max with reversed arms.
22474     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22475                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22476       switch (CC) {
22477       default: break;
22478       case ISD::SETOGE:
22479         // Converting this to a min would handle comparisons between positive
22480         // and negative zero incorrectly, and swapping the operands would
22481         // cause it to handle NaNs incorrectly.
22482         if (!DAG.getTarget().Options.UnsafeFPMath &&
22483             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22484           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22485             break;
22486           std::swap(LHS, RHS);
22487         }
22488         Opcode = X86ISD::FMIN;
22489         break;
22490       case ISD::SETUGT:
22491         // Converting this to a min would handle NaNs incorrectly.
22492         if (!DAG.getTarget().Options.UnsafeFPMath &&
22493             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22494           break;
22495         Opcode = X86ISD::FMIN;
22496         break;
22497       case ISD::SETUGE:
22498         // Converting this to a min would handle both negative zeros and NaNs
22499         // incorrectly, but we can swap the operands to fix both.
22500         std::swap(LHS, RHS);
22501       case ISD::SETOGT:
22502       case ISD::SETGT:
22503       case ISD::SETGE:
22504         Opcode = X86ISD::FMIN;
22505         break;
22506
22507       case ISD::SETULT:
22508         // Converting this to a max would handle NaNs incorrectly.
22509         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22510           break;
22511         Opcode = X86ISD::FMAX;
22512         break;
22513       case ISD::SETOLE:
22514         // Converting this to a max would handle comparisons between positive
22515         // and negative zero incorrectly, and swapping the operands would
22516         // cause it to handle NaNs incorrectly.
22517         if (!DAG.getTarget().Options.UnsafeFPMath &&
22518             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22519           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22520             break;
22521           std::swap(LHS, RHS);
22522         }
22523         Opcode = X86ISD::FMAX;
22524         break;
22525       case ISD::SETULE:
22526         // Converting this to a max would handle both negative zeros and NaNs
22527         // incorrectly, but we can swap the operands to fix both.
22528         std::swap(LHS, RHS);
22529       case ISD::SETOLT:
22530       case ISD::SETLT:
22531       case ISD::SETLE:
22532         Opcode = X86ISD::FMAX;
22533         break;
22534       }
22535     }
22536
22537     if (Opcode)
22538       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22539   }
22540
22541   EVT CondVT = Cond.getValueType();
22542   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22543       CondVT.getVectorElementType() == MVT::i1) {
22544     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22545     // lowering on KNL. In this case we convert it to
22546     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22547     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22548     // Since SKX these selects have a proper lowering.
22549     EVT OpVT = LHS.getValueType();
22550     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22551         (OpVT.getVectorElementType() == MVT::i8 ||
22552          OpVT.getVectorElementType() == MVT::i16) &&
22553         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22554       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22555       DCI.AddToWorklist(Cond.getNode());
22556       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22557     }
22558   }
22559   // If this is a select between two integer constants, try to do some
22560   // optimizations.
22561   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22562     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22563       // Don't do this for crazy integer types.
22564       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22565         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22566         // so that TrueC (the true value) is larger than FalseC.
22567         bool NeedsCondInvert = false;
22568
22569         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22570             // Efficiently invertible.
22571             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22572              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22573               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22574           NeedsCondInvert = true;
22575           std::swap(TrueC, FalseC);
22576         }
22577
22578         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22579         if (FalseC->getAPIntValue() == 0 &&
22580             TrueC->getAPIntValue().isPowerOf2()) {
22581           if (NeedsCondInvert) // Invert the condition if needed.
22582             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22583                                DAG.getConstant(1, Cond.getValueType()));
22584
22585           // Zero extend the condition if needed.
22586           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22587
22588           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22589           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22590                              DAG.getConstant(ShAmt, MVT::i8));
22591         }
22592
22593         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22594         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22595           if (NeedsCondInvert) // Invert the condition if needed.
22596             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22597                                DAG.getConstant(1, Cond.getValueType()));
22598
22599           // Zero extend the condition if needed.
22600           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22601                              FalseC->getValueType(0), Cond);
22602           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22603                              SDValue(FalseC, 0));
22604         }
22605
22606         // Optimize cases that will turn into an LEA instruction.  This requires
22607         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22608         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22609           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22610           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22611
22612           bool isFastMultiplier = false;
22613           if (Diff < 10) {
22614             switch ((unsigned char)Diff) {
22615               default: break;
22616               case 1:  // result = add base, cond
22617               case 2:  // result = lea base(    , cond*2)
22618               case 3:  // result = lea base(cond, cond*2)
22619               case 4:  // result = lea base(    , cond*4)
22620               case 5:  // result = lea base(cond, cond*4)
22621               case 8:  // result = lea base(    , cond*8)
22622               case 9:  // result = lea base(cond, cond*8)
22623                 isFastMultiplier = true;
22624                 break;
22625             }
22626           }
22627
22628           if (isFastMultiplier) {
22629             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22630             if (NeedsCondInvert) // Invert the condition if needed.
22631               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22632                                  DAG.getConstant(1, Cond.getValueType()));
22633
22634             // Zero extend the condition if needed.
22635             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22636                                Cond);
22637             // Scale the condition by the difference.
22638             if (Diff != 1)
22639               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22640                                  DAG.getConstant(Diff, Cond.getValueType()));
22641
22642             // Add the base if non-zero.
22643             if (FalseC->getAPIntValue() != 0)
22644               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22645                                  SDValue(FalseC, 0));
22646             return Cond;
22647           }
22648         }
22649       }
22650   }
22651
22652   // Canonicalize max and min:
22653   // (x > y) ? x : y -> (x >= y) ? x : y
22654   // (x < y) ? x : y -> (x <= y) ? x : y
22655   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22656   // the need for an extra compare
22657   // against zero. e.g.
22658   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22659   // subl   %esi, %edi
22660   // testl  %edi, %edi
22661   // movl   $0, %eax
22662   // cmovgl %edi, %eax
22663   // =>
22664   // xorl   %eax, %eax
22665   // subl   %esi, $edi
22666   // cmovsl %eax, %edi
22667   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22668       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22669       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22670     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22671     switch (CC) {
22672     default: break;
22673     case ISD::SETLT:
22674     case ISD::SETGT: {
22675       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22676       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22677                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22678       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22679     }
22680     }
22681   }
22682
22683   // Early exit check
22684   if (!TLI.isTypeLegal(VT))
22685     return SDValue();
22686
22687   // Match VSELECTs into subs with unsigned saturation.
22688   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22689       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22690       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22691        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22692     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22693
22694     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22695     // left side invert the predicate to simplify logic below.
22696     SDValue Other;
22697     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22698       Other = RHS;
22699       CC = ISD::getSetCCInverse(CC, true);
22700     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22701       Other = LHS;
22702     }
22703
22704     if (Other.getNode() && Other->getNumOperands() == 2 &&
22705         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22706       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22707       SDValue CondRHS = Cond->getOperand(1);
22708
22709       // Look for a general sub with unsigned saturation first.
22710       // x >= y ? x-y : 0 --> subus x, y
22711       // x >  y ? x-y : 0 --> subus x, y
22712       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22713           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22714         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22715
22716       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22717         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22718           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22719             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22720               // If the RHS is a constant we have to reverse the const
22721               // canonicalization.
22722               // x > C-1 ? x+-C : 0 --> subus x, C
22723               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22724                   CondRHSConst->getAPIntValue() ==
22725                       (-OpRHSConst->getAPIntValue() - 1))
22726                 return DAG.getNode(
22727                     X86ISD::SUBUS, DL, VT, OpLHS,
22728                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
22729
22730           // Another special case: If C was a sign bit, the sub has been
22731           // canonicalized into a xor.
22732           // FIXME: Would it be better to use computeKnownBits to determine
22733           //        whether it's safe to decanonicalize the xor?
22734           // x s< 0 ? x^C : 0 --> subus x, C
22735           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22736               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22737               OpRHSConst->getAPIntValue().isSignBit())
22738             // Note that we have to rebuild the RHS constant here to ensure we
22739             // don't rely on particular values of undef lanes.
22740             return DAG.getNode(
22741                 X86ISD::SUBUS, DL, VT, OpLHS,
22742                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
22743         }
22744     }
22745   }
22746
22747   // Try to match a min/max vector operation.
22748   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22749     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22750     unsigned Opc = ret.first;
22751     bool NeedSplit = ret.second;
22752
22753     if (Opc && NeedSplit) {
22754       unsigned NumElems = VT.getVectorNumElements();
22755       // Extract the LHS vectors
22756       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22757       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22758
22759       // Extract the RHS vectors
22760       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22761       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22762
22763       // Create min/max for each subvector
22764       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22765       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22766
22767       // Merge the result
22768       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22769     } else if (Opc)
22770       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22771   }
22772
22773   // Simplify vector selection if condition value type matches vselect
22774   // operand type
22775   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22776     assert(Cond.getValueType().isVector() &&
22777            "vector select expects a vector selector!");
22778
22779     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22780     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22781
22782     // Try invert the condition if true value is not all 1s and false value
22783     // is not all 0s.
22784     if (!TValIsAllOnes && !FValIsAllZeros &&
22785         // Check if the selector will be produced by CMPP*/PCMP*
22786         Cond.getOpcode() == ISD::SETCC &&
22787         // Check if SETCC has already been promoted
22788         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
22789       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22790       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22791
22792       if (TValIsAllZeros || FValIsAllOnes) {
22793         SDValue CC = Cond.getOperand(2);
22794         ISD::CondCode NewCC =
22795           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22796                                Cond.getOperand(0).getValueType().isInteger());
22797         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22798         std::swap(LHS, RHS);
22799         TValIsAllOnes = FValIsAllOnes;
22800         FValIsAllZeros = TValIsAllZeros;
22801       }
22802     }
22803
22804     if (TValIsAllOnes || FValIsAllZeros) {
22805       SDValue Ret;
22806
22807       if (TValIsAllOnes && FValIsAllZeros)
22808         Ret = Cond;
22809       else if (TValIsAllOnes)
22810         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
22811                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
22812       else if (FValIsAllZeros)
22813         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22814                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
22815
22816       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
22817     }
22818   }
22819
22820   // Try to fold this VSELECT into a MOVSS/MOVSD
22821   if (N->getOpcode() == ISD::VSELECT &&
22822       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
22823     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
22824         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
22825       bool CanFold = false;
22826       unsigned NumElems = Cond.getNumOperands();
22827       SDValue A = LHS;
22828       SDValue B = RHS;
22829       
22830       if (isZero(Cond.getOperand(0))) {
22831         CanFold = true;
22832
22833         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
22834         // fold (vselect <0,-1> -> (movsd A, B)
22835         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
22836           CanFold = isAllOnes(Cond.getOperand(i));
22837       } else if (isAllOnes(Cond.getOperand(0))) {
22838         CanFold = true;
22839         std::swap(A, B);
22840
22841         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
22842         // fold (vselect <-1,0> -> (movsd B, A)
22843         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
22844           CanFold = isZero(Cond.getOperand(i));
22845       }
22846
22847       if (CanFold) {
22848         if (VT == MVT::v4i32 || VT == MVT::v4f32)
22849           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
22850         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
22851       }
22852
22853       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
22854         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
22855         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
22856         //                             (v2i64 (bitcast B)))))
22857         //
22858         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
22859         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
22860         //                             (v2f64 (bitcast B)))))
22861         //
22862         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
22863         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
22864         //                             (v2i64 (bitcast A)))))
22865         //
22866         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
22867         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
22868         //                             (v2f64 (bitcast A)))))
22869
22870         CanFold = (isZero(Cond.getOperand(0)) &&
22871                    isZero(Cond.getOperand(1)) &&
22872                    isAllOnes(Cond.getOperand(2)) &&
22873                    isAllOnes(Cond.getOperand(3)));
22874
22875         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
22876             isAllOnes(Cond.getOperand(1)) &&
22877             isZero(Cond.getOperand(2)) &&
22878             isZero(Cond.getOperand(3))) {
22879           CanFold = true;
22880           std::swap(LHS, RHS);
22881         }
22882
22883         if (CanFold) {
22884           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
22885           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
22886           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
22887           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
22888                                                 NewB, DAG);
22889           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
22890         }
22891       }
22892     }
22893   }
22894
22895   // If we know that this node is legal then we know that it is going to be
22896   // matched by one of the SSE/AVX BLEND instructions. These instructions only
22897   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
22898   // to simplify previous instructions.
22899   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22900       !DCI.isBeforeLegalize() &&
22901       // We explicitly check against v8i16 and v16i16 because, although
22902       // they're marked as Custom, they might only be legal when Cond is a
22903       // build_vector of constants. This will be taken care in a later
22904       // condition.
22905       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
22906        VT != MVT::v8i16) &&
22907       // Don't optimize vector of constants. Those are handled by
22908       // the generic code and all the bits must be properly set for
22909       // the generic optimizer.
22910       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22911     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22912
22913     // Don't optimize vector selects that map to mask-registers.
22914     if (BitWidth == 1)
22915       return SDValue();
22916
22917     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22918     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22919
22920     APInt KnownZero, KnownOne;
22921     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22922                                           DCI.isBeforeLegalizeOps());
22923     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22924         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22925                                  TLO)) {
22926       // If we changed the computation somewhere in the DAG, this change
22927       // will affect all users of Cond.
22928       // Make sure it is fine and update all the nodes so that we do not
22929       // use the generic VSELECT anymore. Otherwise, we may perform
22930       // wrong optimizations as we messed up with the actual expectation
22931       // for the vector boolean values.
22932       if (Cond != TLO.Old) {
22933         // Check all uses of that condition operand to check whether it will be
22934         // consumed by non-BLEND instructions, which may depend on all bits are
22935         // set properly.
22936         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22937              I != E; ++I)
22938           if (I->getOpcode() != ISD::VSELECT)
22939             // TODO: Add other opcodes eventually lowered into BLEND.
22940             return SDValue();
22941
22942         // Update all the users of the condition, before committing the change,
22943         // so that the VSELECT optimizations that expect the correct vector
22944         // boolean value will not be triggered.
22945         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22946              I != E; ++I)
22947           DAG.ReplaceAllUsesOfValueWith(
22948               SDValue(*I, 0),
22949               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22950                           Cond, I->getOperand(1), I->getOperand(2)));
22951         DCI.CommitTargetLoweringOpt(TLO);
22952         return SDValue();
22953       }
22954       // At this point, only Cond is changed. Change the condition
22955       // just for N to keep the opportunity to optimize all other
22956       // users their own way.
22957       DAG.ReplaceAllUsesOfValueWith(
22958           SDValue(N, 0),
22959           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22960                       TLO.New, N->getOperand(1), N->getOperand(2)));
22961       return SDValue();
22962     }
22963   }
22964
22965   // We should generate an X86ISD::BLENDI from a vselect if its argument
22966   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22967   // constants. This specific pattern gets generated when we split a
22968   // selector for a 512 bit vector in a machine without AVX512 (but with
22969   // 256-bit vectors), during legalization:
22970   //
22971   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22972   //
22973   // Iff we find this pattern and the build_vectors are built from
22974   // constants, we translate the vselect into a shuffle_vector that we
22975   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22976   if ((N->getOpcode() == ISD::VSELECT ||
22977        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22978       !DCI.isBeforeLegalize()) {
22979     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22980     if (Shuffle.getNode())
22981       return Shuffle;
22982   }
22983
22984   return SDValue();
22985 }
22986
22987 // Check whether a boolean test is testing a boolean value generated by
22988 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22989 // code.
22990 //
22991 // Simplify the following patterns:
22992 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22993 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22994 // to (Op EFLAGS Cond)
22995 //
22996 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22997 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22998 // to (Op EFLAGS !Cond)
22999 //
23000 // where Op could be BRCOND or CMOV.
23001 //
23002 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23003   // Quit if not CMP and SUB with its value result used.
23004   if (Cmp.getOpcode() != X86ISD::CMP &&
23005       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23006       return SDValue();
23007
23008   // Quit if not used as a boolean value.
23009   if (CC != X86::COND_E && CC != X86::COND_NE)
23010     return SDValue();
23011
23012   // Check CMP operands. One of them should be 0 or 1 and the other should be
23013   // an SetCC or extended from it.
23014   SDValue Op1 = Cmp.getOperand(0);
23015   SDValue Op2 = Cmp.getOperand(1);
23016
23017   SDValue SetCC;
23018   const ConstantSDNode* C = nullptr;
23019   bool needOppositeCond = (CC == X86::COND_E);
23020   bool checkAgainstTrue = false; // Is it a comparison against 1?
23021
23022   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23023     SetCC = Op2;
23024   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23025     SetCC = Op1;
23026   else // Quit if all operands are not constants.
23027     return SDValue();
23028
23029   if (C->getZExtValue() == 1) {
23030     needOppositeCond = !needOppositeCond;
23031     checkAgainstTrue = true;
23032   } else if (C->getZExtValue() != 0)
23033     // Quit if the constant is neither 0 or 1.
23034     return SDValue();
23035
23036   bool truncatedToBoolWithAnd = false;
23037   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23038   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23039          SetCC.getOpcode() == ISD::TRUNCATE ||
23040          SetCC.getOpcode() == ISD::AND) {
23041     if (SetCC.getOpcode() == ISD::AND) {
23042       int OpIdx = -1;
23043       ConstantSDNode *CS;
23044       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23045           CS->getZExtValue() == 1)
23046         OpIdx = 1;
23047       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23048           CS->getZExtValue() == 1)
23049         OpIdx = 0;
23050       if (OpIdx == -1)
23051         break;
23052       SetCC = SetCC.getOperand(OpIdx);
23053       truncatedToBoolWithAnd = true;
23054     } else
23055       SetCC = SetCC.getOperand(0);
23056   }
23057
23058   switch (SetCC.getOpcode()) {
23059   case X86ISD::SETCC_CARRY:
23060     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23061     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23062     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23063     // truncated to i1 using 'and'.
23064     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23065       break;
23066     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23067            "Invalid use of SETCC_CARRY!");
23068     // FALL THROUGH
23069   case X86ISD::SETCC:
23070     // Set the condition code or opposite one if necessary.
23071     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23072     if (needOppositeCond)
23073       CC = X86::GetOppositeBranchCondition(CC);
23074     return SetCC.getOperand(1);
23075   case X86ISD::CMOV: {
23076     // Check whether false/true value has canonical one, i.e. 0 or 1.
23077     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23078     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23079     // Quit if true value is not a constant.
23080     if (!TVal)
23081       return SDValue();
23082     // Quit if false value is not a constant.
23083     if (!FVal) {
23084       SDValue Op = SetCC.getOperand(0);
23085       // Skip 'zext' or 'trunc' node.
23086       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23087           Op.getOpcode() == ISD::TRUNCATE)
23088         Op = Op.getOperand(0);
23089       // A special case for rdrand/rdseed, where 0 is set if false cond is
23090       // found.
23091       if ((Op.getOpcode() != X86ISD::RDRAND &&
23092            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23093         return SDValue();
23094     }
23095     // Quit if false value is not the constant 0 or 1.
23096     bool FValIsFalse = true;
23097     if (FVal && FVal->getZExtValue() != 0) {
23098       if (FVal->getZExtValue() != 1)
23099         return SDValue();
23100       // If FVal is 1, opposite cond is needed.
23101       needOppositeCond = !needOppositeCond;
23102       FValIsFalse = false;
23103     }
23104     // Quit if TVal is not the constant opposite of FVal.
23105     if (FValIsFalse && TVal->getZExtValue() != 1)
23106       return SDValue();
23107     if (!FValIsFalse && TVal->getZExtValue() != 0)
23108       return SDValue();
23109     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23110     if (needOppositeCond)
23111       CC = X86::GetOppositeBranchCondition(CC);
23112     return SetCC.getOperand(3);
23113   }
23114   }
23115
23116   return SDValue();
23117 }
23118
23119 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23120 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23121                                   TargetLowering::DAGCombinerInfo &DCI,
23122                                   const X86Subtarget *Subtarget) {
23123   SDLoc DL(N);
23124
23125   // If the flag operand isn't dead, don't touch this CMOV.
23126   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23127     return SDValue();
23128
23129   SDValue FalseOp = N->getOperand(0);
23130   SDValue TrueOp = N->getOperand(1);
23131   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23132   SDValue Cond = N->getOperand(3);
23133
23134   if (CC == X86::COND_E || CC == X86::COND_NE) {
23135     switch (Cond.getOpcode()) {
23136     default: break;
23137     case X86ISD::BSR:
23138     case X86ISD::BSF:
23139       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23140       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23141         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23142     }
23143   }
23144
23145   SDValue Flags;
23146
23147   Flags = checkBoolTestSetCCCombine(Cond, CC);
23148   if (Flags.getNode() &&
23149       // Extra check as FCMOV only supports a subset of X86 cond.
23150       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23151     SDValue Ops[] = { FalseOp, TrueOp,
23152                       DAG.getConstant(CC, MVT::i8), Flags };
23153     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23154   }
23155
23156   // If this is a select between two integer constants, try to do some
23157   // optimizations.  Note that the operands are ordered the opposite of SELECT
23158   // operands.
23159   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23160     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23161       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23162       // larger than FalseC (the false value).
23163       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23164         CC = X86::GetOppositeBranchCondition(CC);
23165         std::swap(TrueC, FalseC);
23166         std::swap(TrueOp, FalseOp);
23167       }
23168
23169       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23170       // This is efficient for any integer data type (including i8/i16) and
23171       // shift amount.
23172       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23173         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23174                            DAG.getConstant(CC, MVT::i8), Cond);
23175
23176         // Zero extend the condition if needed.
23177         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23178
23179         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23180         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23181                            DAG.getConstant(ShAmt, MVT::i8));
23182         if (N->getNumValues() == 2)  // Dead flag value?
23183           return DCI.CombineTo(N, Cond, SDValue());
23184         return Cond;
23185       }
23186
23187       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23188       // for any integer data type, including i8/i16.
23189       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23190         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23191                            DAG.getConstant(CC, MVT::i8), Cond);
23192
23193         // Zero extend the condition if needed.
23194         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23195                            FalseC->getValueType(0), Cond);
23196         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23197                            SDValue(FalseC, 0));
23198
23199         if (N->getNumValues() == 2)  // Dead flag value?
23200           return DCI.CombineTo(N, Cond, SDValue());
23201         return Cond;
23202       }
23203
23204       // Optimize cases that will turn into an LEA instruction.  This requires
23205       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23206       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23207         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23208         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23209
23210         bool isFastMultiplier = false;
23211         if (Diff < 10) {
23212           switch ((unsigned char)Diff) {
23213           default: break;
23214           case 1:  // result = add base, cond
23215           case 2:  // result = lea base(    , cond*2)
23216           case 3:  // result = lea base(cond, cond*2)
23217           case 4:  // result = lea base(    , cond*4)
23218           case 5:  // result = lea base(cond, cond*4)
23219           case 8:  // result = lea base(    , cond*8)
23220           case 9:  // result = lea base(cond, cond*8)
23221             isFastMultiplier = true;
23222             break;
23223           }
23224         }
23225
23226         if (isFastMultiplier) {
23227           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23228           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23229                              DAG.getConstant(CC, MVT::i8), Cond);
23230           // Zero extend the condition if needed.
23231           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23232                              Cond);
23233           // Scale the condition by the difference.
23234           if (Diff != 1)
23235             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23236                                DAG.getConstant(Diff, Cond.getValueType()));
23237
23238           // Add the base if non-zero.
23239           if (FalseC->getAPIntValue() != 0)
23240             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23241                                SDValue(FalseC, 0));
23242           if (N->getNumValues() == 2)  // Dead flag value?
23243             return DCI.CombineTo(N, Cond, SDValue());
23244           return Cond;
23245         }
23246       }
23247     }
23248   }
23249
23250   // Handle these cases:
23251   //   (select (x != c), e, c) -> select (x != c), e, x),
23252   //   (select (x == c), c, e) -> select (x == c), x, e)
23253   // where the c is an integer constant, and the "select" is the combination
23254   // of CMOV and CMP.
23255   //
23256   // The rationale for this change is that the conditional-move from a constant
23257   // needs two instructions, however, conditional-move from a register needs
23258   // only one instruction.
23259   //
23260   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23261   //  some instruction-combining opportunities. This opt needs to be
23262   //  postponed as late as possible.
23263   //
23264   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23265     // the DCI.xxxx conditions are provided to postpone the optimization as
23266     // late as possible.
23267
23268     ConstantSDNode *CmpAgainst = nullptr;
23269     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23270         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23271         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23272
23273       if (CC == X86::COND_NE &&
23274           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23275         CC = X86::GetOppositeBranchCondition(CC);
23276         std::swap(TrueOp, FalseOp);
23277       }
23278
23279       if (CC == X86::COND_E &&
23280           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23281         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23282                           DAG.getConstant(CC, MVT::i8), Cond };
23283         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23284       }
23285     }
23286   }
23287
23288   return SDValue();
23289 }
23290
23291 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23292                                                 const X86Subtarget *Subtarget) {
23293   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23294   switch (IntNo) {
23295   default: return SDValue();
23296   // SSE/AVX/AVX2 blend intrinsics.
23297   case Intrinsic::x86_avx2_pblendvb:
23298   case Intrinsic::x86_avx2_pblendw:
23299   case Intrinsic::x86_avx2_pblendd_128:
23300   case Intrinsic::x86_avx2_pblendd_256:
23301     // Don't try to simplify this intrinsic if we don't have AVX2.
23302     if (!Subtarget->hasAVX2())
23303       return SDValue();
23304     // FALL-THROUGH
23305   case Intrinsic::x86_avx_blend_pd_256:
23306   case Intrinsic::x86_avx_blend_ps_256:
23307   case Intrinsic::x86_avx_blendv_pd_256:
23308   case Intrinsic::x86_avx_blendv_ps_256:
23309     // Don't try to simplify this intrinsic if we don't have AVX.
23310     if (!Subtarget->hasAVX())
23311       return SDValue();
23312     // FALL-THROUGH
23313   case Intrinsic::x86_sse41_pblendw:
23314   case Intrinsic::x86_sse41_blendpd:
23315   case Intrinsic::x86_sse41_blendps:
23316   case Intrinsic::x86_sse41_blendvps:
23317   case Intrinsic::x86_sse41_blendvpd:
23318   case Intrinsic::x86_sse41_pblendvb: {
23319     SDValue Op0 = N->getOperand(1);
23320     SDValue Op1 = N->getOperand(2);
23321     SDValue Mask = N->getOperand(3);
23322
23323     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23324     if (!Subtarget->hasSSE41())
23325       return SDValue();
23326
23327     // fold (blend A, A, Mask) -> A
23328     if (Op0 == Op1)
23329       return Op0;
23330     // fold (blend A, B, allZeros) -> A
23331     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23332       return Op0;
23333     // fold (blend A, B, allOnes) -> B
23334     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23335       return Op1;
23336     
23337     // Simplify the case where the mask is a constant i32 value.
23338     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23339       if (C->isNullValue())
23340         return Op0;
23341       if (C->isAllOnesValue())
23342         return Op1;
23343     }
23344
23345     return SDValue();
23346   }
23347
23348   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23349   case Intrinsic::x86_sse2_psrai_w:
23350   case Intrinsic::x86_sse2_psrai_d:
23351   case Intrinsic::x86_avx2_psrai_w:
23352   case Intrinsic::x86_avx2_psrai_d:
23353   case Intrinsic::x86_sse2_psra_w:
23354   case Intrinsic::x86_sse2_psra_d:
23355   case Intrinsic::x86_avx2_psra_w:
23356   case Intrinsic::x86_avx2_psra_d: {
23357     SDValue Op0 = N->getOperand(1);
23358     SDValue Op1 = N->getOperand(2);
23359     EVT VT = Op0.getValueType();
23360     assert(VT.isVector() && "Expected a vector type!");
23361
23362     if (isa<BuildVectorSDNode>(Op1))
23363       Op1 = Op1.getOperand(0);
23364
23365     if (!isa<ConstantSDNode>(Op1))
23366       return SDValue();
23367
23368     EVT SVT = VT.getVectorElementType();
23369     unsigned SVTBits = SVT.getSizeInBits();
23370
23371     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23372     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23373     uint64_t ShAmt = C.getZExtValue();
23374
23375     // Don't try to convert this shift into a ISD::SRA if the shift
23376     // count is bigger than or equal to the element size.
23377     if (ShAmt >= SVTBits)
23378       return SDValue();
23379
23380     // Trivial case: if the shift count is zero, then fold this
23381     // into the first operand.
23382     if (ShAmt == 0)
23383       return Op0;
23384
23385     // Replace this packed shift intrinsic with a target independent
23386     // shift dag node.
23387     SDValue Splat = DAG.getConstant(C, VT);
23388     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
23389   }
23390   }
23391 }
23392
23393 /// PerformMulCombine - Optimize a single multiply with constant into two
23394 /// in order to implement it with two cheaper instructions, e.g.
23395 /// LEA + SHL, LEA + LEA.
23396 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23397                                  TargetLowering::DAGCombinerInfo &DCI) {
23398   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23399     return SDValue();
23400
23401   EVT VT = N->getValueType(0);
23402   if (VT != MVT::i64)
23403     return SDValue();
23404
23405   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23406   if (!C)
23407     return SDValue();
23408   uint64_t MulAmt = C->getZExtValue();
23409   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23410     return SDValue();
23411
23412   uint64_t MulAmt1 = 0;
23413   uint64_t MulAmt2 = 0;
23414   if ((MulAmt % 9) == 0) {
23415     MulAmt1 = 9;
23416     MulAmt2 = MulAmt / 9;
23417   } else if ((MulAmt % 5) == 0) {
23418     MulAmt1 = 5;
23419     MulAmt2 = MulAmt / 5;
23420   } else if ((MulAmt % 3) == 0) {
23421     MulAmt1 = 3;
23422     MulAmt2 = MulAmt / 3;
23423   }
23424   if (MulAmt2 &&
23425       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23426     SDLoc DL(N);
23427
23428     if (isPowerOf2_64(MulAmt2) &&
23429         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23430       // If second multiplifer is pow2, issue it first. We want the multiply by
23431       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23432       // is an add.
23433       std::swap(MulAmt1, MulAmt2);
23434
23435     SDValue NewMul;
23436     if (isPowerOf2_64(MulAmt1))
23437       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23438                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
23439     else
23440       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23441                            DAG.getConstant(MulAmt1, VT));
23442
23443     if (isPowerOf2_64(MulAmt2))
23444       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23445                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
23446     else
23447       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23448                            DAG.getConstant(MulAmt2, VT));
23449
23450     // Do not add new nodes to DAG combiner worklist.
23451     DCI.CombineTo(N, NewMul, false);
23452   }
23453   return SDValue();
23454 }
23455
23456 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23457   SDValue N0 = N->getOperand(0);
23458   SDValue N1 = N->getOperand(1);
23459   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23460   EVT VT = N0.getValueType();
23461
23462   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23463   // since the result of setcc_c is all zero's or all ones.
23464   if (VT.isInteger() && !VT.isVector() &&
23465       N1C && N0.getOpcode() == ISD::AND &&
23466       N0.getOperand(1).getOpcode() == ISD::Constant) {
23467     SDValue N00 = N0.getOperand(0);
23468     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23469         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23470           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23471          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23472       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23473       APInt ShAmt = N1C->getAPIntValue();
23474       Mask = Mask.shl(ShAmt);
23475       if (Mask != 0)
23476         return DAG.getNode(ISD::AND, SDLoc(N), VT,
23477                            N00, DAG.getConstant(Mask, VT));
23478     }
23479   }
23480
23481   // Hardware support for vector shifts is sparse which makes us scalarize the
23482   // vector operations in many cases. Also, on sandybridge ADD is faster than
23483   // shl.
23484   // (shl V, 1) -> add V,V
23485   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23486     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23487       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23488       // We shift all of the values by one. In many cases we do not have
23489       // hardware support for this operation. This is better expressed as an ADD
23490       // of two values.
23491       if (N1SplatC->getZExtValue() == 1)
23492         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23493     }
23494
23495   return SDValue();
23496 }
23497
23498 /// \brief Returns a vector of 0s if the node in input is a vector logical
23499 /// shift by a constant amount which is known to be bigger than or equal
23500 /// to the vector element size in bits.
23501 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23502                                       const X86Subtarget *Subtarget) {
23503   EVT VT = N->getValueType(0);
23504
23505   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23506       (!Subtarget->hasInt256() ||
23507        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23508     return SDValue();
23509
23510   SDValue Amt = N->getOperand(1);
23511   SDLoc DL(N);
23512   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23513     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23514       APInt ShiftAmt = AmtSplat->getAPIntValue();
23515       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23516
23517       // SSE2/AVX2 logical shifts always return a vector of 0s
23518       // if the shift amount is bigger than or equal to
23519       // the element size. The constant shift amount will be
23520       // encoded as a 8-bit immediate.
23521       if (ShiftAmt.trunc(8).uge(MaxAmount))
23522         return getZeroVector(VT, Subtarget, DAG, DL);
23523     }
23524
23525   return SDValue();
23526 }
23527
23528 /// PerformShiftCombine - Combine shifts.
23529 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23530                                    TargetLowering::DAGCombinerInfo &DCI,
23531                                    const X86Subtarget *Subtarget) {
23532   if (N->getOpcode() == ISD::SHL) {
23533     SDValue V = PerformSHLCombine(N, DAG);
23534     if (V.getNode()) return V;
23535   }
23536
23537   if (N->getOpcode() != ISD::SRA) {
23538     // Try to fold this logical shift into a zero vector.
23539     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
23540     if (V.getNode()) return V;
23541   }
23542
23543   return SDValue();
23544 }
23545
23546 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23547 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23548 // and friends.  Likewise for OR -> CMPNEQSS.
23549 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23550                             TargetLowering::DAGCombinerInfo &DCI,
23551                             const X86Subtarget *Subtarget) {
23552   unsigned opcode;
23553
23554   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23555   // we're requiring SSE2 for both.
23556   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23557     SDValue N0 = N->getOperand(0);
23558     SDValue N1 = N->getOperand(1);
23559     SDValue CMP0 = N0->getOperand(1);
23560     SDValue CMP1 = N1->getOperand(1);
23561     SDLoc DL(N);
23562
23563     // The SETCCs should both refer to the same CMP.
23564     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23565       return SDValue();
23566
23567     SDValue CMP00 = CMP0->getOperand(0);
23568     SDValue CMP01 = CMP0->getOperand(1);
23569     EVT     VT    = CMP00.getValueType();
23570
23571     if (VT == MVT::f32 || VT == MVT::f64) {
23572       bool ExpectingFlags = false;
23573       // Check for any users that want flags:
23574       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23575            !ExpectingFlags && UI != UE; ++UI)
23576         switch (UI->getOpcode()) {
23577         default:
23578         case ISD::BR_CC:
23579         case ISD::BRCOND:
23580         case ISD::SELECT:
23581           ExpectingFlags = true;
23582           break;
23583         case ISD::CopyToReg:
23584         case ISD::SIGN_EXTEND:
23585         case ISD::ZERO_EXTEND:
23586         case ISD::ANY_EXTEND:
23587           break;
23588         }
23589
23590       if (!ExpectingFlags) {
23591         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23592         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23593
23594         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23595           X86::CondCode tmp = cc0;
23596           cc0 = cc1;
23597           cc1 = tmp;
23598         }
23599
23600         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23601             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23602           // FIXME: need symbolic constants for these magic numbers.
23603           // See X86ATTInstPrinter.cpp:printSSECC().
23604           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23605           if (Subtarget->hasAVX512()) {
23606             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23607                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
23608             if (N->getValueType(0) != MVT::i1)
23609               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23610                                  FSetCC);
23611             return FSetCC;
23612           }
23613           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23614                                               CMP00.getValueType(), CMP00, CMP01,
23615                                               DAG.getConstant(x86cc, MVT::i8));
23616
23617           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23618           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23619
23620           if (is64BitFP && !Subtarget->is64Bit()) {
23621             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23622             // 64-bit integer, since that's not a legal type. Since
23623             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23624             // bits, but can do this little dance to extract the lowest 32 bits
23625             // and work with those going forward.
23626             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23627                                            OnesOrZeroesF);
23628             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
23629                                            Vector64);
23630             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23631                                         Vector32, DAG.getIntPtrConstant(0));
23632             IntVT = MVT::i32;
23633           }
23634
23635           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
23636           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23637                                       DAG.getConstant(1, IntVT));
23638           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
23639           return OneBitOfTruth;
23640         }
23641       }
23642     }
23643   }
23644   return SDValue();
23645 }
23646
23647 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23648 /// so it can be folded inside ANDNP.
23649 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23650   EVT VT = N->getValueType(0);
23651
23652   // Match direct AllOnes for 128 and 256-bit vectors
23653   if (ISD::isBuildVectorAllOnes(N))
23654     return true;
23655
23656   // Look through a bit convert.
23657   if (N->getOpcode() == ISD::BITCAST)
23658     N = N->getOperand(0).getNode();
23659
23660   // Sometimes the operand may come from a insert_subvector building a 256-bit
23661   // allones vector
23662   if (VT.is256BitVector() &&
23663       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23664     SDValue V1 = N->getOperand(0);
23665     SDValue V2 = N->getOperand(1);
23666
23667     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23668         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23669         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23670         ISD::isBuildVectorAllOnes(V2.getNode()))
23671       return true;
23672   }
23673
23674   return false;
23675 }
23676
23677 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23678 // register. In most cases we actually compare or select YMM-sized registers
23679 // and mixing the two types creates horrible code. This method optimizes
23680 // some of the transition sequences.
23681 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23682                                  TargetLowering::DAGCombinerInfo &DCI,
23683                                  const X86Subtarget *Subtarget) {
23684   EVT VT = N->getValueType(0);
23685   if (!VT.is256BitVector())
23686     return SDValue();
23687
23688   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23689           N->getOpcode() == ISD::ZERO_EXTEND ||
23690           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23691
23692   SDValue Narrow = N->getOperand(0);
23693   EVT NarrowVT = Narrow->getValueType(0);
23694   if (!NarrowVT.is128BitVector())
23695     return SDValue();
23696
23697   if (Narrow->getOpcode() != ISD::XOR &&
23698       Narrow->getOpcode() != ISD::AND &&
23699       Narrow->getOpcode() != ISD::OR)
23700     return SDValue();
23701
23702   SDValue N0  = Narrow->getOperand(0);
23703   SDValue N1  = Narrow->getOperand(1);
23704   SDLoc DL(Narrow);
23705
23706   // The Left side has to be a trunc.
23707   if (N0.getOpcode() != ISD::TRUNCATE)
23708     return SDValue();
23709
23710   // The type of the truncated inputs.
23711   EVT WideVT = N0->getOperand(0)->getValueType(0);
23712   if (WideVT != VT)
23713     return SDValue();
23714
23715   // The right side has to be a 'trunc' or a constant vector.
23716   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23717   ConstantSDNode *RHSConstSplat = nullptr;
23718   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23719     RHSConstSplat = RHSBV->getConstantSplatNode();
23720   if (!RHSTrunc && !RHSConstSplat)
23721     return SDValue();
23722
23723   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23724
23725   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23726     return SDValue();
23727
23728   // Set N0 and N1 to hold the inputs to the new wide operation.
23729   N0 = N0->getOperand(0);
23730   if (RHSConstSplat) {
23731     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23732                      SDValue(RHSConstSplat, 0));
23733     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23734     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23735   } else if (RHSTrunc) {
23736     N1 = N1->getOperand(0);
23737   }
23738
23739   // Generate the wide operation.
23740   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23741   unsigned Opcode = N->getOpcode();
23742   switch (Opcode) {
23743   case ISD::ANY_EXTEND:
23744     return Op;
23745   case ISD::ZERO_EXTEND: {
23746     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23747     APInt Mask = APInt::getAllOnesValue(InBits);
23748     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23749     return DAG.getNode(ISD::AND, DL, VT,
23750                        Op, DAG.getConstant(Mask, VT));
23751   }
23752   case ISD::SIGN_EXTEND:
23753     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23754                        Op, DAG.getValueType(NarrowVT));
23755   default:
23756     llvm_unreachable("Unexpected opcode");
23757   }
23758 }
23759
23760 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23761                                  TargetLowering::DAGCombinerInfo &DCI,
23762                                  const X86Subtarget *Subtarget) {
23763   EVT VT = N->getValueType(0);
23764   if (DCI.isBeforeLegalizeOps())
23765     return SDValue();
23766
23767   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
23768   if (R.getNode())
23769     return R;
23770
23771   // Create BEXTR instructions
23772   // BEXTR is ((X >> imm) & (2**size-1))
23773   if (VT == MVT::i32 || VT == MVT::i64) {
23774     SDValue N0 = N->getOperand(0);
23775     SDValue N1 = N->getOperand(1);
23776     SDLoc DL(N);
23777
23778     // Check for BEXTR.
23779     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23780         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23781       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23782       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23783       if (MaskNode && ShiftNode) {
23784         uint64_t Mask = MaskNode->getZExtValue();
23785         uint64_t Shift = ShiftNode->getZExtValue();
23786         if (isMask_64(Mask)) {
23787           uint64_t MaskSize = CountPopulation_64(Mask);
23788           if (Shift + MaskSize <= VT.getSizeInBits())
23789             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23790                                DAG.getConstant(Shift | (MaskSize << 8), VT));
23791         }
23792       }
23793     } // BEXTR
23794
23795     return SDValue();
23796   }
23797
23798   // Want to form ANDNP nodes:
23799   // 1) In the hopes of then easily combining them with OR and AND nodes
23800   //    to form PBLEND/PSIGN.
23801   // 2) To match ANDN packed intrinsics
23802   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23803     return SDValue();
23804
23805   SDValue N0 = N->getOperand(0);
23806   SDValue N1 = N->getOperand(1);
23807   SDLoc DL(N);
23808
23809   // Check LHS for vnot
23810   if (N0.getOpcode() == ISD::XOR &&
23811       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23812       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23813     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23814
23815   // Check RHS for vnot
23816   if (N1.getOpcode() == ISD::XOR &&
23817       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23818       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23819     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23820
23821   return SDValue();
23822 }
23823
23824 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23825                                 TargetLowering::DAGCombinerInfo &DCI,
23826                                 const X86Subtarget *Subtarget) {
23827   if (DCI.isBeforeLegalizeOps())
23828     return SDValue();
23829
23830   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
23831   if (R.getNode())
23832     return R;
23833
23834   SDValue N0 = N->getOperand(0);
23835   SDValue N1 = N->getOperand(1);
23836   EVT VT = N->getValueType(0);
23837
23838   // look for psign/blend
23839   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23840     if (!Subtarget->hasSSSE3() ||
23841         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23842       return SDValue();
23843
23844     // Canonicalize pandn to RHS
23845     if (N0.getOpcode() == X86ISD::ANDNP)
23846       std::swap(N0, N1);
23847     // or (and (m, y), (pandn m, x))
23848     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23849       SDValue Mask = N1.getOperand(0);
23850       SDValue X    = N1.getOperand(1);
23851       SDValue Y;
23852       if (N0.getOperand(0) == Mask)
23853         Y = N0.getOperand(1);
23854       if (N0.getOperand(1) == Mask)
23855         Y = N0.getOperand(0);
23856
23857       // Check to see if the mask appeared in both the AND and ANDNP and
23858       if (!Y.getNode())
23859         return SDValue();
23860
23861       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23862       // Look through mask bitcast.
23863       if (Mask.getOpcode() == ISD::BITCAST)
23864         Mask = Mask.getOperand(0);
23865       if (X.getOpcode() == ISD::BITCAST)
23866         X = X.getOperand(0);
23867       if (Y.getOpcode() == ISD::BITCAST)
23868         Y = Y.getOperand(0);
23869
23870       EVT MaskVT = Mask.getValueType();
23871
23872       // Validate that the Mask operand is a vector sra node.
23873       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23874       // there is no psrai.b
23875       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23876       unsigned SraAmt = ~0;
23877       if (Mask.getOpcode() == ISD::SRA) {
23878         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23879           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23880             SraAmt = AmtConst->getZExtValue();
23881       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23882         SDValue SraC = Mask.getOperand(1);
23883         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23884       }
23885       if ((SraAmt + 1) != EltBits)
23886         return SDValue();
23887
23888       SDLoc DL(N);
23889
23890       // Now we know we at least have a plendvb with the mask val.  See if
23891       // we can form a psignb/w/d.
23892       // psign = x.type == y.type == mask.type && y = sub(0, x);
23893       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23894           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23895           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23896         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23897                "Unsupported VT for PSIGN");
23898         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23899         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
23900       }
23901       // PBLENDVB only available on SSE 4.1
23902       if (!Subtarget->hasSSE41())
23903         return SDValue();
23904
23905       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23906
23907       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
23908       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
23909       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
23910       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23911       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
23912     }
23913   }
23914
23915   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23916     return SDValue();
23917
23918   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23919   MachineFunction &MF = DAG.getMachineFunction();
23920   bool OptForSize = MF.getFunction()->getAttributes().
23921     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
23922
23923   // SHLD/SHRD instructions have lower register pressure, but on some
23924   // platforms they have higher latency than the equivalent
23925   // series of shifts/or that would otherwise be generated.
23926   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23927   // have higher latencies and we are not optimizing for size.
23928   if (!OptForSize && Subtarget->isSHLDSlow())
23929     return SDValue();
23930
23931   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23932     std::swap(N0, N1);
23933   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23934     return SDValue();
23935   if (!N0.hasOneUse() || !N1.hasOneUse())
23936     return SDValue();
23937
23938   SDValue ShAmt0 = N0.getOperand(1);
23939   if (ShAmt0.getValueType() != MVT::i8)
23940     return SDValue();
23941   SDValue ShAmt1 = N1.getOperand(1);
23942   if (ShAmt1.getValueType() != MVT::i8)
23943     return SDValue();
23944   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23945     ShAmt0 = ShAmt0.getOperand(0);
23946   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23947     ShAmt1 = ShAmt1.getOperand(0);
23948
23949   SDLoc DL(N);
23950   unsigned Opc = X86ISD::SHLD;
23951   SDValue Op0 = N0.getOperand(0);
23952   SDValue Op1 = N1.getOperand(0);
23953   if (ShAmt0.getOpcode() == ISD::SUB) {
23954     Opc = X86ISD::SHRD;
23955     std::swap(Op0, Op1);
23956     std::swap(ShAmt0, ShAmt1);
23957   }
23958
23959   unsigned Bits = VT.getSizeInBits();
23960   if (ShAmt1.getOpcode() == ISD::SUB) {
23961     SDValue Sum = ShAmt1.getOperand(0);
23962     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23963       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23964       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23965         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23966       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23967         return DAG.getNode(Opc, DL, VT,
23968                            Op0, Op1,
23969                            DAG.getNode(ISD::TRUNCATE, DL,
23970                                        MVT::i8, ShAmt0));
23971     }
23972   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23973     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23974     if (ShAmt0C &&
23975         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23976       return DAG.getNode(Opc, DL, VT,
23977                          N0.getOperand(0), N1.getOperand(0),
23978                          DAG.getNode(ISD::TRUNCATE, DL,
23979                                        MVT::i8, ShAmt0));
23980   }
23981
23982   return SDValue();
23983 }
23984
23985 // Generate NEG and CMOV for integer abs.
23986 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23987   EVT VT = N->getValueType(0);
23988
23989   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23990   // 8-bit integer abs to NEG and CMOV.
23991   if (VT.isInteger() && VT.getSizeInBits() == 8)
23992     return SDValue();
23993
23994   SDValue N0 = N->getOperand(0);
23995   SDValue N1 = N->getOperand(1);
23996   SDLoc DL(N);
23997
23998   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23999   // and change it to SUB and CMOV.
24000   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24001       N0.getOpcode() == ISD::ADD &&
24002       N0.getOperand(1) == N1 &&
24003       N1.getOpcode() == ISD::SRA &&
24004       N1.getOperand(0) == N0.getOperand(0))
24005     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24006       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24007         // Generate SUB & CMOV.
24008         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24009                                   DAG.getConstant(0, VT), N0.getOperand(0));
24010
24011         SDValue Ops[] = { N0.getOperand(0), Neg,
24012                           DAG.getConstant(X86::COND_GE, MVT::i8),
24013                           SDValue(Neg.getNode(), 1) };
24014         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24015       }
24016   return SDValue();
24017 }
24018
24019 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24020 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24021                                  TargetLowering::DAGCombinerInfo &DCI,
24022                                  const X86Subtarget *Subtarget) {
24023   if (DCI.isBeforeLegalizeOps())
24024     return SDValue();
24025
24026   if (Subtarget->hasCMov()) {
24027     SDValue RV = performIntegerAbsCombine(N, DAG);
24028     if (RV.getNode())
24029       return RV;
24030   }
24031
24032   return SDValue();
24033 }
24034
24035 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24036 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24037                                   TargetLowering::DAGCombinerInfo &DCI,
24038                                   const X86Subtarget *Subtarget) {
24039   LoadSDNode *Ld = cast<LoadSDNode>(N);
24040   EVT RegVT = Ld->getValueType(0);
24041   EVT MemVT = Ld->getMemoryVT();
24042   SDLoc dl(Ld);
24043   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24044
24045   // On Sandybridge unaligned 256bit loads are inefficient.
24046   ISD::LoadExtType Ext = Ld->getExtensionType();
24047   unsigned Alignment = Ld->getAlignment();
24048   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24049   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
24050       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24051     unsigned NumElems = RegVT.getVectorNumElements();
24052     if (NumElems < 2)
24053       return SDValue();
24054
24055     SDValue Ptr = Ld->getBasePtr();
24056     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
24057
24058     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24059                                   NumElems/2);
24060     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24061                                 Ld->getPointerInfo(), Ld->isVolatile(),
24062                                 Ld->isNonTemporal(), Ld->isInvariant(),
24063                                 Alignment);
24064     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24065     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24066                                 Ld->getPointerInfo(), Ld->isVolatile(),
24067                                 Ld->isNonTemporal(), Ld->isInvariant(),
24068                                 std::min(16U, Alignment));
24069     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24070                              Load1.getValue(1),
24071                              Load2.getValue(1));
24072
24073     SDValue NewVec = DAG.getUNDEF(RegVT);
24074     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24075     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24076     return DCI.CombineTo(N, NewVec, TF, true);
24077   }
24078
24079   return SDValue();
24080 }
24081
24082 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24083 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24084                                    const X86Subtarget *Subtarget) {
24085   StoreSDNode *St = cast<StoreSDNode>(N);
24086   EVT VT = St->getValue().getValueType();
24087   EVT StVT = St->getMemoryVT();
24088   SDLoc dl(St);
24089   SDValue StoredVal = St->getOperand(1);
24090   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24091
24092   // If we are saving a concatenation of two XMM registers, perform two stores.
24093   // On Sandy Bridge, 256-bit memory operations are executed by two
24094   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
24095   // memory  operation.
24096   unsigned Alignment = St->getAlignment();
24097   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24098   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
24099       StVT == VT && !IsAligned) {
24100     unsigned NumElems = VT.getVectorNumElements();
24101     if (NumElems < 2)
24102       return SDValue();
24103
24104     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24105     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24106
24107     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
24108     SDValue Ptr0 = St->getBasePtr();
24109     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24110
24111     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24112                                 St->getPointerInfo(), St->isVolatile(),
24113                                 St->isNonTemporal(), Alignment);
24114     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24115                                 St->getPointerInfo(), St->isVolatile(),
24116                                 St->isNonTemporal(),
24117                                 std::min(16U, Alignment));
24118     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24119   }
24120
24121   // Optimize trunc store (of multiple scalars) to shuffle and store.
24122   // First, pack all of the elements in one place. Next, store to memory
24123   // in fewer chunks.
24124   if (St->isTruncatingStore() && VT.isVector()) {
24125     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24126     unsigned NumElems = VT.getVectorNumElements();
24127     assert(StVT != VT && "Cannot truncate to the same type");
24128     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24129     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24130
24131     // From, To sizes and ElemCount must be pow of two
24132     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24133     // We are going to use the original vector elt for storing.
24134     // Accumulated smaller vector elements must be a multiple of the store size.
24135     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24136
24137     unsigned SizeRatio  = FromSz / ToSz;
24138
24139     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24140
24141     // Create a type on which we perform the shuffle
24142     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24143             StVT.getScalarType(), NumElems*SizeRatio);
24144
24145     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24146
24147     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
24148     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24149     for (unsigned i = 0; i != NumElems; ++i)
24150       ShuffleVec[i] = i * SizeRatio;
24151
24152     // Can't shuffle using an illegal type.
24153     if (!TLI.isTypeLegal(WideVecVT))
24154       return SDValue();
24155
24156     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24157                                          DAG.getUNDEF(WideVecVT),
24158                                          &ShuffleVec[0]);
24159     // At this point all of the data is stored at the bottom of the
24160     // register. We now need to save it to mem.
24161
24162     // Find the largest store unit
24163     MVT StoreType = MVT::i8;
24164     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
24165          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
24166       MVT Tp = (MVT::SimpleValueType)tp;
24167       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24168         StoreType = Tp;
24169     }
24170
24171     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24172     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24173         (64 <= NumElems * ToSz))
24174       StoreType = MVT::f64;
24175
24176     // Bitcast the original vector into a vector of store-size units
24177     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24178             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24179     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24180     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
24181     SmallVector<SDValue, 8> Chains;
24182     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
24183                                         TLI.getPointerTy());
24184     SDValue Ptr = St->getBasePtr();
24185
24186     // Perform one or more big stores into memory.
24187     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24188       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24189                                    StoreType, ShuffWide,
24190                                    DAG.getIntPtrConstant(i));
24191       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24192                                 St->getPointerInfo(), St->isVolatile(),
24193                                 St->isNonTemporal(), St->getAlignment());
24194       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24195       Chains.push_back(Ch);
24196     }
24197
24198     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24199   }
24200
24201   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24202   // the FP state in cases where an emms may be missing.
24203   // A preferable solution to the general problem is to figure out the right
24204   // places to insert EMMS.  This qualifies as a quick hack.
24205
24206   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24207   if (VT.getSizeInBits() != 64)
24208     return SDValue();
24209
24210   const Function *F = DAG.getMachineFunction().getFunction();
24211   bool NoImplicitFloatOps = F->getAttributes().
24212     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
24213   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
24214                      && Subtarget->hasSSE2();
24215   if ((VT.isVector() ||
24216        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24217       isa<LoadSDNode>(St->getValue()) &&
24218       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24219       St->getChain().hasOneUse() && !St->isVolatile()) {
24220     SDNode* LdVal = St->getValue().getNode();
24221     LoadSDNode *Ld = nullptr;
24222     int TokenFactorIndex = -1;
24223     SmallVector<SDValue, 8> Ops;
24224     SDNode* ChainVal = St->getChain().getNode();
24225     // Must be a store of a load.  We currently handle two cases:  the load
24226     // is a direct child, and it's under an intervening TokenFactor.  It is
24227     // possible to dig deeper under nested TokenFactors.
24228     if (ChainVal == LdVal)
24229       Ld = cast<LoadSDNode>(St->getChain());
24230     else if (St->getValue().hasOneUse() &&
24231              ChainVal->getOpcode() == ISD::TokenFactor) {
24232       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24233         if (ChainVal->getOperand(i).getNode() == LdVal) {
24234           TokenFactorIndex = i;
24235           Ld = cast<LoadSDNode>(St->getValue());
24236         } else
24237           Ops.push_back(ChainVal->getOperand(i));
24238       }
24239     }
24240
24241     if (!Ld || !ISD::isNormalLoad(Ld))
24242       return SDValue();
24243
24244     // If this is not the MMX case, i.e. we are just turning i64 load/store
24245     // into f64 load/store, avoid the transformation if there are multiple
24246     // uses of the loaded value.
24247     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24248       return SDValue();
24249
24250     SDLoc LdDL(Ld);
24251     SDLoc StDL(N);
24252     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24253     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24254     // pair instead.
24255     if (Subtarget->is64Bit() || F64IsLegal) {
24256       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24257       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24258                                   Ld->getPointerInfo(), Ld->isVolatile(),
24259                                   Ld->isNonTemporal(), Ld->isInvariant(),
24260                                   Ld->getAlignment());
24261       SDValue NewChain = NewLd.getValue(1);
24262       if (TokenFactorIndex != -1) {
24263         Ops.push_back(NewChain);
24264         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24265       }
24266       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24267                           St->getPointerInfo(),
24268                           St->isVolatile(), St->isNonTemporal(),
24269                           St->getAlignment());
24270     }
24271
24272     // Otherwise, lower to two pairs of 32-bit loads / stores.
24273     SDValue LoAddr = Ld->getBasePtr();
24274     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24275                                  DAG.getConstant(4, MVT::i32));
24276
24277     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24278                                Ld->getPointerInfo(),
24279                                Ld->isVolatile(), Ld->isNonTemporal(),
24280                                Ld->isInvariant(), Ld->getAlignment());
24281     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24282                                Ld->getPointerInfo().getWithOffset(4),
24283                                Ld->isVolatile(), Ld->isNonTemporal(),
24284                                Ld->isInvariant(),
24285                                MinAlign(Ld->getAlignment(), 4));
24286
24287     SDValue NewChain = LoLd.getValue(1);
24288     if (TokenFactorIndex != -1) {
24289       Ops.push_back(LoLd);
24290       Ops.push_back(HiLd);
24291       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24292     }
24293
24294     LoAddr = St->getBasePtr();
24295     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24296                          DAG.getConstant(4, MVT::i32));
24297
24298     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24299                                 St->getPointerInfo(),
24300                                 St->isVolatile(), St->isNonTemporal(),
24301                                 St->getAlignment());
24302     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24303                                 St->getPointerInfo().getWithOffset(4),
24304                                 St->isVolatile(),
24305                                 St->isNonTemporal(),
24306                                 MinAlign(St->getAlignment(), 4));
24307     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24308   }
24309   return SDValue();
24310 }
24311
24312 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
24313 /// and return the operands for the horizontal operation in LHS and RHS.  A
24314 /// horizontal operation performs the binary operation on successive elements
24315 /// of its first operand, then on successive elements of its second operand,
24316 /// returning the resulting values in a vector.  For example, if
24317 ///   A = < float a0, float a1, float a2, float a3 >
24318 /// and
24319 ///   B = < float b0, float b1, float b2, float b3 >
24320 /// then the result of doing a horizontal operation on A and B is
24321 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24322 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24323 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24324 /// set to A, RHS to B, and the routine returns 'true'.
24325 /// Note that the binary operation should have the property that if one of the
24326 /// operands is UNDEF then the result is UNDEF.
24327 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24328   // Look for the following pattern: if
24329   //   A = < float a0, float a1, float a2, float a3 >
24330   //   B = < float b0, float b1, float b2, float b3 >
24331   // and
24332   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24333   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24334   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24335   // which is A horizontal-op B.
24336
24337   // At least one of the operands should be a vector shuffle.
24338   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24339       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24340     return false;
24341
24342   MVT VT = LHS.getSimpleValueType();
24343
24344   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24345          "Unsupported vector type for horizontal add/sub");
24346
24347   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24348   // operate independently on 128-bit lanes.
24349   unsigned NumElts = VT.getVectorNumElements();
24350   unsigned NumLanes = VT.getSizeInBits()/128;
24351   unsigned NumLaneElts = NumElts / NumLanes;
24352   assert((NumLaneElts % 2 == 0) &&
24353          "Vector type should have an even number of elements in each lane");
24354   unsigned HalfLaneElts = NumLaneElts/2;
24355
24356   // View LHS in the form
24357   //   LHS = VECTOR_SHUFFLE A, B, LMask
24358   // If LHS is not a shuffle then pretend it is the shuffle
24359   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24360   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24361   // type VT.
24362   SDValue A, B;
24363   SmallVector<int, 16> LMask(NumElts);
24364   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24365     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24366       A = LHS.getOperand(0);
24367     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24368       B = LHS.getOperand(1);
24369     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24370     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24371   } else {
24372     if (LHS.getOpcode() != ISD::UNDEF)
24373       A = LHS;
24374     for (unsigned i = 0; i != NumElts; ++i)
24375       LMask[i] = i;
24376   }
24377
24378   // Likewise, view RHS in the form
24379   //   RHS = VECTOR_SHUFFLE C, D, RMask
24380   SDValue C, D;
24381   SmallVector<int, 16> RMask(NumElts);
24382   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24383     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24384       C = RHS.getOperand(0);
24385     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24386       D = RHS.getOperand(1);
24387     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24388     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24389   } else {
24390     if (RHS.getOpcode() != ISD::UNDEF)
24391       C = RHS;
24392     for (unsigned i = 0; i != NumElts; ++i)
24393       RMask[i] = i;
24394   }
24395
24396   // Check that the shuffles are both shuffling the same vectors.
24397   if (!(A == C && B == D) && !(A == D && B == C))
24398     return false;
24399
24400   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24401   if (!A.getNode() && !B.getNode())
24402     return false;
24403
24404   // If A and B occur in reverse order in RHS, then "swap" them (which means
24405   // rewriting the mask).
24406   if (A != C)
24407     CommuteVectorShuffleMask(RMask, NumElts);
24408
24409   // At this point LHS and RHS are equivalent to
24410   //   LHS = VECTOR_SHUFFLE A, B, LMask
24411   //   RHS = VECTOR_SHUFFLE A, B, RMask
24412   // Check that the masks correspond to performing a horizontal operation.
24413   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24414     for (unsigned i = 0; i != NumLaneElts; ++i) {
24415       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24416
24417       // Ignore any UNDEF components.
24418       if (LIdx < 0 || RIdx < 0 ||
24419           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24420           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24421         continue;
24422
24423       // Check that successive elements are being operated on.  If not, this is
24424       // not a horizontal operation.
24425       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24426       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24427       if (!(LIdx == Index && RIdx == Index + 1) &&
24428           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24429         return false;
24430     }
24431   }
24432
24433   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24434   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24435   return true;
24436 }
24437
24438 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
24439 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24440                                   const X86Subtarget *Subtarget) {
24441   EVT VT = N->getValueType(0);
24442   SDValue LHS = N->getOperand(0);
24443   SDValue RHS = N->getOperand(1);
24444
24445   // Try to synthesize horizontal adds from adds of shuffles.
24446   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24447        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24448       isHorizontalBinOp(LHS, RHS, true))
24449     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24450   return SDValue();
24451 }
24452
24453 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
24454 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24455                                   const X86Subtarget *Subtarget) {
24456   EVT VT = N->getValueType(0);
24457   SDValue LHS = N->getOperand(0);
24458   SDValue RHS = N->getOperand(1);
24459
24460   // Try to synthesize horizontal subs from subs of shuffles.
24461   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24462        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24463       isHorizontalBinOp(LHS, RHS, false))
24464     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24465   return SDValue();
24466 }
24467
24468 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
24469 /// X86ISD::FXOR nodes.
24470 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24471   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24472   // F[X]OR(0.0, x) -> x
24473   // F[X]OR(x, 0.0) -> x
24474   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24475     if (C->getValueAPF().isPosZero())
24476       return N->getOperand(1);
24477   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24478     if (C->getValueAPF().isPosZero())
24479       return N->getOperand(0);
24480   return SDValue();
24481 }
24482
24483 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
24484 /// X86ISD::FMAX nodes.
24485 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24486   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24487
24488   // Only perform optimizations if UnsafeMath is used.
24489   if (!DAG.getTarget().Options.UnsafeFPMath)
24490     return SDValue();
24491
24492   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24493   // into FMINC and FMAXC, which are Commutative operations.
24494   unsigned NewOp = 0;
24495   switch (N->getOpcode()) {
24496     default: llvm_unreachable("unknown opcode");
24497     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24498     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24499   }
24500
24501   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24502                      N->getOperand(0), N->getOperand(1));
24503 }
24504
24505 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
24506 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24507   // FAND(0.0, x) -> 0.0
24508   // FAND(x, 0.0) -> 0.0
24509   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24510     if (C->getValueAPF().isPosZero())
24511       return N->getOperand(0);
24512   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24513     if (C->getValueAPF().isPosZero())
24514       return N->getOperand(1);
24515   return SDValue();
24516 }
24517
24518 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
24519 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24520   // FANDN(x, 0.0) -> 0.0
24521   // FANDN(0.0, x) -> x
24522   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24523     if (C->getValueAPF().isPosZero())
24524       return N->getOperand(1);
24525   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24526     if (C->getValueAPF().isPosZero())
24527       return N->getOperand(1);
24528   return SDValue();
24529 }
24530
24531 static SDValue PerformBTCombine(SDNode *N,
24532                                 SelectionDAG &DAG,
24533                                 TargetLowering::DAGCombinerInfo &DCI) {
24534   // BT ignores high bits in the bit index operand.
24535   SDValue Op1 = N->getOperand(1);
24536   if (Op1.hasOneUse()) {
24537     unsigned BitWidth = Op1.getValueSizeInBits();
24538     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24539     APInt KnownZero, KnownOne;
24540     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24541                                           !DCI.isBeforeLegalizeOps());
24542     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24543     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24544         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24545       DCI.CommitTargetLoweringOpt(TLO);
24546   }
24547   return SDValue();
24548 }
24549
24550 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24551   SDValue Op = N->getOperand(0);
24552   if (Op.getOpcode() == ISD::BITCAST)
24553     Op = Op.getOperand(0);
24554   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24555   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24556       VT.getVectorElementType().getSizeInBits() ==
24557       OpVT.getVectorElementType().getSizeInBits()) {
24558     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24559   }
24560   return SDValue();
24561 }
24562
24563 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24564                                                const X86Subtarget *Subtarget) {
24565   EVT VT = N->getValueType(0);
24566   if (!VT.isVector())
24567     return SDValue();
24568
24569   SDValue N0 = N->getOperand(0);
24570   SDValue N1 = N->getOperand(1);
24571   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24572   SDLoc dl(N);
24573
24574   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24575   // both SSE and AVX2 since there is no sign-extended shift right
24576   // operation on a vector with 64-bit elements.
24577   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24578   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24579   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24580       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24581     SDValue N00 = N0.getOperand(0);
24582
24583     // EXTLOAD has a better solution on AVX2,
24584     // it may be replaced with X86ISD::VSEXT node.
24585     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24586       if (!ISD::isNormalLoad(N00.getNode()))
24587         return SDValue();
24588
24589     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24590         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24591                                   N00, N1);
24592       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24593     }
24594   }
24595   return SDValue();
24596 }
24597
24598 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24599                                   TargetLowering::DAGCombinerInfo &DCI,
24600                                   const X86Subtarget *Subtarget) {
24601   SDValue N0 = N->getOperand(0);
24602   EVT VT = N->getValueType(0);
24603
24604   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24605   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24606   // This exposes the sext to the sdivrem lowering, so that it directly extends
24607   // from AH (which we otherwise need to do contortions to access).
24608   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24609       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
24610     SDLoc dl(N);
24611     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24612     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
24613                             N0.getOperand(0), N0.getOperand(1));
24614     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24615     return R.getValue(1);
24616   }
24617
24618   if (!DCI.isBeforeLegalizeOps())
24619     return SDValue();
24620
24621   if (!Subtarget->hasFp256())
24622     return SDValue();
24623
24624   if (VT.isVector() && VT.getSizeInBits() == 256) {
24625     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
24626     if (R.getNode())
24627       return R;
24628   }
24629
24630   return SDValue();
24631 }
24632
24633 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24634                                  const X86Subtarget* Subtarget) {
24635   SDLoc dl(N);
24636   EVT VT = N->getValueType(0);
24637
24638   // Let legalize expand this if it isn't a legal type yet.
24639   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24640     return SDValue();
24641
24642   EVT ScalarVT = VT.getScalarType();
24643   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24644       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
24645     return SDValue();
24646
24647   SDValue A = N->getOperand(0);
24648   SDValue B = N->getOperand(1);
24649   SDValue C = N->getOperand(2);
24650
24651   bool NegA = (A.getOpcode() == ISD::FNEG);
24652   bool NegB = (B.getOpcode() == ISD::FNEG);
24653   bool NegC = (C.getOpcode() == ISD::FNEG);
24654
24655   // Negative multiplication when NegA xor NegB
24656   bool NegMul = (NegA != NegB);
24657   if (NegA)
24658     A = A.getOperand(0);
24659   if (NegB)
24660     B = B.getOperand(0);
24661   if (NegC)
24662     C = C.getOperand(0);
24663
24664   unsigned Opcode;
24665   if (!NegMul)
24666     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24667   else
24668     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24669
24670   return DAG.getNode(Opcode, dl, VT, A, B, C);
24671 }
24672
24673 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24674                                   TargetLowering::DAGCombinerInfo &DCI,
24675                                   const X86Subtarget *Subtarget) {
24676   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24677   //           (and (i32 x86isd::setcc_carry), 1)
24678   // This eliminates the zext. This transformation is necessary because
24679   // ISD::SETCC is always legalized to i8.
24680   SDLoc dl(N);
24681   SDValue N0 = N->getOperand(0);
24682   EVT VT = N->getValueType(0);
24683
24684   if (N0.getOpcode() == ISD::AND &&
24685       N0.hasOneUse() &&
24686       N0.getOperand(0).hasOneUse()) {
24687     SDValue N00 = N0.getOperand(0);
24688     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24689       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24690       if (!C || C->getZExtValue() != 1)
24691         return SDValue();
24692       return DAG.getNode(ISD::AND, dl, VT,
24693                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24694                                      N00.getOperand(0), N00.getOperand(1)),
24695                          DAG.getConstant(1, VT));
24696     }
24697   }
24698
24699   if (N0.getOpcode() == ISD::TRUNCATE &&
24700       N0.hasOneUse() &&
24701       N0.getOperand(0).hasOneUse()) {
24702     SDValue N00 = N0.getOperand(0);
24703     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24704       return DAG.getNode(ISD::AND, dl, VT,
24705                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24706                                      N00.getOperand(0), N00.getOperand(1)),
24707                          DAG.getConstant(1, VT));
24708     }
24709   }
24710   if (VT.is256BitVector()) {
24711     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
24712     if (R.getNode())
24713       return R;
24714   }
24715
24716   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24717   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24718   // This exposes the zext to the udivrem lowering, so that it directly extends
24719   // from AH (which we otherwise need to do contortions to access).
24720   if (N0.getOpcode() == ISD::UDIVREM &&
24721       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24722       (VT == MVT::i32 || VT == MVT::i64)) {
24723     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24724     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24725                             N0.getOperand(0), N0.getOperand(1));
24726     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24727     return R.getValue(1);
24728   }
24729
24730   return SDValue();
24731 }
24732
24733 // Optimize x == -y --> x+y == 0
24734 //          x != -y --> x+y != 0
24735 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24736                                       const X86Subtarget* Subtarget) {
24737   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24738   SDValue LHS = N->getOperand(0);
24739   SDValue RHS = N->getOperand(1);
24740   EVT VT = N->getValueType(0);
24741   SDLoc DL(N);
24742
24743   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24744     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24745       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24746         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
24747                                    LHS.getValueType(), RHS, LHS.getOperand(1));
24748         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
24749                             addV, DAG.getConstant(0, addV.getValueType()), CC);
24750       }
24751   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24752     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24753       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24754         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
24755                                    RHS.getValueType(), LHS, RHS.getOperand(1));
24756         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
24757                             addV, DAG.getConstant(0, addV.getValueType()), CC);
24758       }
24759
24760   if (VT.getScalarType() == MVT::i1) {
24761     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24762       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
24763     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
24764     if (!IsSEXT0 && !IsVZero0)
24765       return SDValue();
24766     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
24767       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
24768     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24769
24770     if (!IsSEXT1 && !IsVZero1)
24771       return SDValue();
24772
24773     if (IsSEXT0 && IsVZero1) {
24774       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
24775       if (CC == ISD::SETEQ)
24776         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24777       return LHS.getOperand(0);
24778     }
24779     if (IsSEXT1 && IsVZero0) {
24780       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
24781       if (CC == ISD::SETEQ)
24782         return DAG.getNOT(DL, RHS.getOperand(0), VT);
24783       return RHS.getOperand(0);
24784     }
24785   }
24786
24787   return SDValue();
24788 }
24789
24790 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24791                                       const X86Subtarget *Subtarget) {
24792   SDLoc dl(N);
24793   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24794   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24795          "X86insertps is only defined for v4x32");
24796
24797   SDValue Ld = N->getOperand(1);
24798   if (MayFoldLoad(Ld)) {
24799     // Extract the countS bits from the immediate so we can get the proper
24800     // address when narrowing the vector load to a specific element.
24801     // When the second source op is a memory address, interps doesn't use
24802     // countS and just gets an f32 from that address.
24803     unsigned DestIndex =
24804         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24805     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24806   } else
24807     return SDValue();
24808
24809   // Create this as a scalar to vector to match the instruction pattern.
24810   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24811   // countS bits are ignored when loading from memory on insertps, which
24812   // means we don't need to explicitly set them to 0.
24813   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24814                      LoadScalarToVector, N->getOperand(2));
24815 }
24816
24817 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24818 // as "sbb reg,reg", since it can be extended without zext and produces
24819 // an all-ones bit which is more useful than 0/1 in some cases.
24820 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24821                                MVT VT) {
24822   if (VT == MVT::i8)
24823     return DAG.getNode(ISD::AND, DL, VT,
24824                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24825                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
24826                        DAG.getConstant(1, VT));
24827   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24828   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24829                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24830                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
24831 }
24832
24833 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24834 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24835                                    TargetLowering::DAGCombinerInfo &DCI,
24836                                    const X86Subtarget *Subtarget) {
24837   SDLoc DL(N);
24838   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24839   SDValue EFLAGS = N->getOperand(1);
24840
24841   if (CC == X86::COND_A) {
24842     // Try to convert COND_A into COND_B in an attempt to facilitate
24843     // materializing "setb reg".
24844     //
24845     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24846     // cannot take an immediate as its first operand.
24847     //
24848     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24849         EFLAGS.getValueType().isInteger() &&
24850         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24851       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24852                                    EFLAGS.getNode()->getVTList(),
24853                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24854       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24855       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24856     }
24857   }
24858
24859   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24860   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24861   // cases.
24862   if (CC == X86::COND_B)
24863     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24864
24865   SDValue Flags;
24866
24867   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24868   if (Flags.getNode()) {
24869     SDValue Cond = DAG.getConstant(CC, MVT::i8);
24870     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24871   }
24872
24873   return SDValue();
24874 }
24875
24876 // Optimize branch condition evaluation.
24877 //
24878 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24879                                     TargetLowering::DAGCombinerInfo &DCI,
24880                                     const X86Subtarget *Subtarget) {
24881   SDLoc DL(N);
24882   SDValue Chain = N->getOperand(0);
24883   SDValue Dest = N->getOperand(1);
24884   SDValue EFLAGS = N->getOperand(3);
24885   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24886
24887   SDValue Flags;
24888
24889   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24890   if (Flags.getNode()) {
24891     SDValue Cond = DAG.getConstant(CC, MVT::i8);
24892     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24893                        Flags);
24894   }
24895
24896   return SDValue();
24897 }
24898
24899 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24900                                                          SelectionDAG &DAG) {
24901   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24902   // optimize away operation when it's from a constant.
24903   //
24904   // The general transformation is:
24905   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24906   //       AND(VECTOR_CMP(x,y), constant2)
24907   //    constant2 = UNARYOP(constant)
24908
24909   // Early exit if this isn't a vector operation, the operand of the
24910   // unary operation isn't a bitwise AND, or if the sizes of the operations
24911   // aren't the same.
24912   EVT VT = N->getValueType(0);
24913   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24914       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24915       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24916     return SDValue();
24917
24918   // Now check that the other operand of the AND is a constant. We could
24919   // make the transformation for non-constant splats as well, but it's unclear
24920   // that would be a benefit as it would not eliminate any operations, just
24921   // perform one more step in scalar code before moving to the vector unit.
24922   if (BuildVectorSDNode *BV =
24923           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24924     // Bail out if the vector isn't a constant.
24925     if (!BV->isConstant())
24926       return SDValue();
24927
24928     // Everything checks out. Build up the new and improved node.
24929     SDLoc DL(N);
24930     EVT IntVT = BV->getValueType(0);
24931     // Create a new constant of the appropriate type for the transformed
24932     // DAG.
24933     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24934     // The AND node needs bitcasts to/from an integer vector type around it.
24935     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24936     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24937                                  N->getOperand(0)->getOperand(0), MaskConst);
24938     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24939     return Res;
24940   }
24941
24942   return SDValue();
24943 }
24944
24945 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24946                                         const X86TargetLowering *XTLI) {
24947   // First try to optimize away the conversion entirely when it's
24948   // conditionally from a constant. Vectors only.
24949   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24950   if (Res != SDValue())
24951     return Res;
24952
24953   // Now move on to more general possibilities.
24954   SDValue Op0 = N->getOperand(0);
24955   EVT InVT = Op0->getValueType(0);
24956
24957   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24958   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24959     SDLoc dl(N);
24960     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24961     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24962     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24963   }
24964
24965   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24966   // a 32-bit target where SSE doesn't support i64->FP operations.
24967   if (Op0.getOpcode() == ISD::LOAD) {
24968     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24969     EVT VT = Ld->getValueType(0);
24970     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24971         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24972         !XTLI->getSubtarget()->is64Bit() &&
24973         VT == MVT::i64) {
24974       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
24975                                           Ld->getChain(), Op0, DAG);
24976       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24977       return FILDChain;
24978     }
24979   }
24980   return SDValue();
24981 }
24982
24983 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24984 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24985                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24986   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24987   // the result is either zero or one (depending on the input carry bit).
24988   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24989   if (X86::isZeroNode(N->getOperand(0)) &&
24990       X86::isZeroNode(N->getOperand(1)) &&
24991       // We don't have a good way to replace an EFLAGS use, so only do this when
24992       // dead right now.
24993       SDValue(N, 1).use_empty()) {
24994     SDLoc DL(N);
24995     EVT VT = N->getValueType(0);
24996     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
24997     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24998                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24999                                            DAG.getConstant(X86::COND_B,MVT::i8),
25000                                            N->getOperand(2)),
25001                                DAG.getConstant(1, VT));
25002     return DCI.CombineTo(N, Res1, CarryOut);
25003   }
25004
25005   return SDValue();
25006 }
25007
25008 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25009 //      (add Y, (setne X, 0)) -> sbb -1, Y
25010 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25011 //      (sub (setne X, 0), Y) -> adc -1, Y
25012 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25013   SDLoc DL(N);
25014
25015   // Look through ZExts.
25016   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25017   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25018     return SDValue();
25019
25020   SDValue SetCC = Ext.getOperand(0);
25021   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25022     return SDValue();
25023
25024   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25025   if (CC != X86::COND_E && CC != X86::COND_NE)
25026     return SDValue();
25027
25028   SDValue Cmp = SetCC.getOperand(1);
25029   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25030       !X86::isZeroNode(Cmp.getOperand(1)) ||
25031       !Cmp.getOperand(0).getValueType().isInteger())
25032     return SDValue();
25033
25034   SDValue CmpOp0 = Cmp.getOperand(0);
25035   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25036                                DAG.getConstant(1, CmpOp0.getValueType()));
25037
25038   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25039   if (CC == X86::COND_NE)
25040     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25041                        DL, OtherVal.getValueType(), OtherVal,
25042                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
25043   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25044                      DL, OtherVal.getValueType(), OtherVal,
25045                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
25046 }
25047
25048 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25049 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25050                                  const X86Subtarget *Subtarget) {
25051   EVT VT = N->getValueType(0);
25052   SDValue Op0 = N->getOperand(0);
25053   SDValue Op1 = N->getOperand(1);
25054
25055   // Try to synthesize horizontal adds from adds of shuffles.
25056   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25057        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25058       isHorizontalBinOp(Op0, Op1, true))
25059     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25060
25061   return OptimizeConditionalInDecrement(N, DAG);
25062 }
25063
25064 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25065                                  const X86Subtarget *Subtarget) {
25066   SDValue Op0 = N->getOperand(0);
25067   SDValue Op1 = N->getOperand(1);
25068
25069   // X86 can't encode an immediate LHS of a sub. See if we can push the
25070   // negation into a preceding instruction.
25071   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25072     // If the RHS of the sub is a XOR with one use and a constant, invert the
25073     // immediate. Then add one to the LHS of the sub so we can turn
25074     // X-Y -> X+~Y+1, saving one register.
25075     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25076         isa<ConstantSDNode>(Op1.getOperand(1))) {
25077       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25078       EVT VT = Op0.getValueType();
25079       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25080                                    Op1.getOperand(0),
25081                                    DAG.getConstant(~XorC, VT));
25082       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25083                          DAG.getConstant(C->getAPIntValue()+1, VT));
25084     }
25085   }
25086
25087   // Try to synthesize horizontal adds from adds of shuffles.
25088   EVT VT = N->getValueType(0);
25089   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25090        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25091       isHorizontalBinOp(Op0, Op1, true))
25092     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25093
25094   return OptimizeConditionalInDecrement(N, DAG);
25095 }
25096
25097 /// performVZEXTCombine - Performs build vector combines
25098 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25099                                    TargetLowering::DAGCombinerInfo &DCI,
25100                                    const X86Subtarget *Subtarget) {
25101   SDLoc DL(N);
25102   MVT VT = N->getSimpleValueType(0);
25103   SDValue Op = N->getOperand(0);
25104   MVT OpVT = Op.getSimpleValueType();
25105   MVT OpEltVT = OpVT.getVectorElementType();
25106   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25107
25108   // (vzext (bitcast (vzext (x)) -> (vzext x)
25109   SDValue V = Op;
25110   while (V.getOpcode() == ISD::BITCAST)
25111     V = V.getOperand(0);
25112
25113   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25114     MVT InnerVT = V.getSimpleValueType();
25115     MVT InnerEltVT = InnerVT.getVectorElementType();
25116
25117     // If the element sizes match exactly, we can just do one larger vzext. This
25118     // is always an exact type match as vzext operates on integer types.
25119     if (OpEltVT == InnerEltVT) {
25120       assert(OpVT == InnerVT && "Types must match for vzext!");
25121       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25122     }
25123
25124     // The only other way we can combine them is if only a single element of the
25125     // inner vzext is used in the input to the outer vzext.
25126     if (InnerEltVT.getSizeInBits() < InputBits)
25127       return SDValue();
25128
25129     // In this case, the inner vzext is completely dead because we're going to
25130     // only look at bits inside of the low element. Just do the outer vzext on
25131     // a bitcast of the input to the inner.
25132     return DAG.getNode(X86ISD::VZEXT, DL, VT,
25133                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
25134   }
25135
25136   // Check if we can bypass extracting and re-inserting an element of an input
25137   // vector. Essentialy:
25138   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25139   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25140       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25141       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25142     SDValue ExtractedV = V.getOperand(0);
25143     SDValue OrigV = ExtractedV.getOperand(0);
25144     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25145       if (ExtractIdx->getZExtValue() == 0) {
25146         MVT OrigVT = OrigV.getSimpleValueType();
25147         // Extract a subvector if necessary...
25148         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25149           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25150           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25151                                     OrigVT.getVectorNumElements() / Ratio);
25152           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25153                               DAG.getIntPtrConstant(0));
25154         }
25155         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
25156         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25157       }
25158   }
25159
25160   return SDValue();
25161 }
25162
25163 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25164                                              DAGCombinerInfo &DCI) const {
25165   SelectionDAG &DAG = DCI.DAG;
25166   switch (N->getOpcode()) {
25167   default: break;
25168   case ISD::EXTRACT_VECTOR_ELT:
25169     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25170   case ISD::VSELECT:
25171   case ISD::SELECT:
25172   case X86ISD::SHRUNKBLEND:
25173     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25174   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25175   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25176   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25177   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25178   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25179   case ISD::SHL:
25180   case ISD::SRA:
25181   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25182   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25183   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25184   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25185   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25186   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25187   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
25188   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25189   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25190   case X86ISD::FXOR:
25191   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25192   case X86ISD::FMIN:
25193   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25194   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25195   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25196   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25197   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25198   case ISD::ANY_EXTEND:
25199   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25200   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25201   case ISD::SIGN_EXTEND_INREG:
25202     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25203   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
25204   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25205   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25206   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25207   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25208   case X86ISD::SHUFP:       // Handle all target specific shuffles
25209   case X86ISD::PALIGNR:
25210   case X86ISD::UNPCKH:
25211   case X86ISD::UNPCKL:
25212   case X86ISD::MOVHLPS:
25213   case X86ISD::MOVLHPS:
25214   case X86ISD::PSHUFB:
25215   case X86ISD::PSHUFD:
25216   case X86ISD::PSHUFHW:
25217   case X86ISD::PSHUFLW:
25218   case X86ISD::MOVSS:
25219   case X86ISD::MOVSD:
25220   case X86ISD::VPERMILPI:
25221   case X86ISD::VPERM2X128:
25222   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25223   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25224   case ISD::INTRINSIC_WO_CHAIN:
25225     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25226   case X86ISD::INSERTPS:
25227     return PerformINSERTPSCombine(N, DAG, Subtarget);
25228   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
25229   }
25230
25231   return SDValue();
25232 }
25233
25234 /// isTypeDesirableForOp - Return true if the target has native support for
25235 /// the specified value type and it is 'desirable' to use the type for the
25236 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25237 /// instruction encodings are longer and some i16 instructions are slow.
25238 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25239   if (!isTypeLegal(VT))
25240     return false;
25241   if (VT != MVT::i16)
25242     return true;
25243
25244   switch (Opc) {
25245   default:
25246     return true;
25247   case ISD::LOAD:
25248   case ISD::SIGN_EXTEND:
25249   case ISD::ZERO_EXTEND:
25250   case ISD::ANY_EXTEND:
25251   case ISD::SHL:
25252   case ISD::SRL:
25253   case ISD::SUB:
25254   case ISD::ADD:
25255   case ISD::MUL:
25256   case ISD::AND:
25257   case ISD::OR:
25258   case ISD::XOR:
25259     return false;
25260   }
25261 }
25262
25263 /// IsDesirableToPromoteOp - This method query the target whether it is
25264 /// beneficial for dag combiner to promote the specified node. If true, it
25265 /// should return the desired promotion type by reference.
25266 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25267   EVT VT = Op.getValueType();
25268   if (VT != MVT::i16)
25269     return false;
25270
25271   bool Promote = false;
25272   bool Commute = false;
25273   switch (Op.getOpcode()) {
25274   default: break;
25275   case ISD::LOAD: {
25276     LoadSDNode *LD = cast<LoadSDNode>(Op);
25277     // If the non-extending load has a single use and it's not live out, then it
25278     // might be folded.
25279     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25280                                                      Op.hasOneUse()*/) {
25281       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25282              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25283         // The only case where we'd want to promote LOAD (rather then it being
25284         // promoted as an operand is when it's only use is liveout.
25285         if (UI->getOpcode() != ISD::CopyToReg)
25286           return false;
25287       }
25288     }
25289     Promote = true;
25290     break;
25291   }
25292   case ISD::SIGN_EXTEND:
25293   case ISD::ZERO_EXTEND:
25294   case ISD::ANY_EXTEND:
25295     Promote = true;
25296     break;
25297   case ISD::SHL:
25298   case ISD::SRL: {
25299     SDValue N0 = Op.getOperand(0);
25300     // Look out for (store (shl (load), x)).
25301     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25302       return false;
25303     Promote = true;
25304     break;
25305   }
25306   case ISD::ADD:
25307   case ISD::MUL:
25308   case ISD::AND:
25309   case ISD::OR:
25310   case ISD::XOR:
25311     Commute = true;
25312     // fallthrough
25313   case ISD::SUB: {
25314     SDValue N0 = Op.getOperand(0);
25315     SDValue N1 = Op.getOperand(1);
25316     if (!Commute && MayFoldLoad(N1))
25317       return false;
25318     // Avoid disabling potential load folding opportunities.
25319     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25320       return false;
25321     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25322       return false;
25323     Promote = true;
25324   }
25325   }
25326
25327   PVT = MVT::i32;
25328   return Promote;
25329 }
25330
25331 //===----------------------------------------------------------------------===//
25332 //                           X86 Inline Assembly Support
25333 //===----------------------------------------------------------------------===//
25334
25335 namespace {
25336   // Helper to match a string separated by whitespace.
25337   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
25338     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
25339
25340     for (unsigned i = 0, e = args.size(); i != e; ++i) {
25341       StringRef piece(*args[i]);
25342       if (!s.startswith(piece)) // Check if the piece matches.
25343         return false;
25344
25345       s = s.substr(piece.size());
25346       StringRef::size_type pos = s.find_first_not_of(" \t");
25347       if (pos == 0) // We matched a prefix.
25348         return false;
25349
25350       s = s.substr(pos);
25351     }
25352
25353     return s.empty();
25354   }
25355   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
25356 }
25357
25358 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25359
25360   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25361     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25362         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25363         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25364
25365       if (AsmPieces.size() == 3)
25366         return true;
25367       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25368         return true;
25369     }
25370   }
25371   return false;
25372 }
25373
25374 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25375   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25376
25377   std::string AsmStr = IA->getAsmString();
25378
25379   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25380   if (!Ty || Ty->getBitWidth() % 16 != 0)
25381     return false;
25382
25383   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25384   SmallVector<StringRef, 4> AsmPieces;
25385   SplitString(AsmStr, AsmPieces, ";\n");
25386
25387   switch (AsmPieces.size()) {
25388   default: return false;
25389   case 1:
25390     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25391     // we will turn this bswap into something that will be lowered to logical
25392     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25393     // lower so don't worry about this.
25394     // bswap $0
25395     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
25396         matchAsm(AsmPieces[0], "bswapl", "$0") ||
25397         matchAsm(AsmPieces[0], "bswapq", "$0") ||
25398         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
25399         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
25400         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
25401       // No need to check constraints, nothing other than the equivalent of
25402       // "=r,0" would be valid here.
25403       return IntrinsicLowering::LowerToByteSwap(CI);
25404     }
25405
25406     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25407     if (CI->getType()->isIntegerTy(16) &&
25408         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25409         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
25410          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
25411       AsmPieces.clear();
25412       const std::string &ConstraintsStr = IA->getConstraintString();
25413       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25414       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25415       if (clobbersFlagRegisters(AsmPieces))
25416         return IntrinsicLowering::LowerToByteSwap(CI);
25417     }
25418     break;
25419   case 3:
25420     if (CI->getType()->isIntegerTy(32) &&
25421         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25422         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
25423         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
25424         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
25425       AsmPieces.clear();
25426       const std::string &ConstraintsStr = IA->getConstraintString();
25427       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25428       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25429       if (clobbersFlagRegisters(AsmPieces))
25430         return IntrinsicLowering::LowerToByteSwap(CI);
25431     }
25432
25433     if (CI->getType()->isIntegerTy(64)) {
25434       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25435       if (Constraints.size() >= 2 &&
25436           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25437           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25438         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25439         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
25440             matchAsm(AsmPieces[1], "bswap", "%edx") &&
25441             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
25442           return IntrinsicLowering::LowerToByteSwap(CI);
25443       }
25444     }
25445     break;
25446   }
25447   return false;
25448 }
25449
25450 /// getConstraintType - Given a constraint letter, return the type of
25451 /// constraint it is for this target.
25452 X86TargetLowering::ConstraintType
25453 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
25454   if (Constraint.size() == 1) {
25455     switch (Constraint[0]) {
25456     case 'R':
25457     case 'q':
25458     case 'Q':
25459     case 'f':
25460     case 't':
25461     case 'u':
25462     case 'y':
25463     case 'x':
25464     case 'Y':
25465     case 'l':
25466       return C_RegisterClass;
25467     case 'a':
25468     case 'b':
25469     case 'c':
25470     case 'd':
25471     case 'S':
25472     case 'D':
25473     case 'A':
25474       return C_Register;
25475     case 'I':
25476     case 'J':
25477     case 'K':
25478     case 'L':
25479     case 'M':
25480     case 'N':
25481     case 'G':
25482     case 'C':
25483     case 'e':
25484     case 'Z':
25485       return C_Other;
25486     default:
25487       break;
25488     }
25489   }
25490   return TargetLowering::getConstraintType(Constraint);
25491 }
25492
25493 /// Examine constraint type and operand type and determine a weight value.
25494 /// This object must already have been set up with the operand type
25495 /// and the current alternative constraint selected.
25496 TargetLowering::ConstraintWeight
25497   X86TargetLowering::getSingleConstraintMatchWeight(
25498     AsmOperandInfo &info, const char *constraint) const {
25499   ConstraintWeight weight = CW_Invalid;
25500   Value *CallOperandVal = info.CallOperandVal;
25501     // If we don't have a value, we can't do a match,
25502     // but allow it at the lowest weight.
25503   if (!CallOperandVal)
25504     return CW_Default;
25505   Type *type = CallOperandVal->getType();
25506   // Look at the constraint type.
25507   switch (*constraint) {
25508   default:
25509     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25510   case 'R':
25511   case 'q':
25512   case 'Q':
25513   case 'a':
25514   case 'b':
25515   case 'c':
25516   case 'd':
25517   case 'S':
25518   case 'D':
25519   case 'A':
25520     if (CallOperandVal->getType()->isIntegerTy())
25521       weight = CW_SpecificReg;
25522     break;
25523   case 'f':
25524   case 't':
25525   case 'u':
25526     if (type->isFloatingPointTy())
25527       weight = CW_SpecificReg;
25528     break;
25529   case 'y':
25530     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25531       weight = CW_SpecificReg;
25532     break;
25533   case 'x':
25534   case 'Y':
25535     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25536         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25537       weight = CW_Register;
25538     break;
25539   case 'I':
25540     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25541       if (C->getZExtValue() <= 31)
25542         weight = CW_Constant;
25543     }
25544     break;
25545   case 'J':
25546     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25547       if (C->getZExtValue() <= 63)
25548         weight = CW_Constant;
25549     }
25550     break;
25551   case 'K':
25552     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25553       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25554         weight = CW_Constant;
25555     }
25556     break;
25557   case 'L':
25558     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25559       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25560         weight = CW_Constant;
25561     }
25562     break;
25563   case 'M':
25564     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25565       if (C->getZExtValue() <= 3)
25566         weight = CW_Constant;
25567     }
25568     break;
25569   case 'N':
25570     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25571       if (C->getZExtValue() <= 0xff)
25572         weight = CW_Constant;
25573     }
25574     break;
25575   case 'G':
25576   case 'C':
25577     if (dyn_cast<ConstantFP>(CallOperandVal)) {
25578       weight = CW_Constant;
25579     }
25580     break;
25581   case 'e':
25582     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25583       if ((C->getSExtValue() >= -0x80000000LL) &&
25584           (C->getSExtValue() <= 0x7fffffffLL))
25585         weight = CW_Constant;
25586     }
25587     break;
25588   case 'Z':
25589     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25590       if (C->getZExtValue() <= 0xffffffff)
25591         weight = CW_Constant;
25592     }
25593     break;
25594   }
25595   return weight;
25596 }
25597
25598 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25599 /// with another that has more specific requirements based on the type of the
25600 /// corresponding operand.
25601 const char *X86TargetLowering::
25602 LowerXConstraint(EVT ConstraintVT) const {
25603   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25604   // 'f' like normal targets.
25605   if (ConstraintVT.isFloatingPoint()) {
25606     if (Subtarget->hasSSE2())
25607       return "Y";
25608     if (Subtarget->hasSSE1())
25609       return "x";
25610   }
25611
25612   return TargetLowering::LowerXConstraint(ConstraintVT);
25613 }
25614
25615 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25616 /// vector.  If it is invalid, don't add anything to Ops.
25617 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25618                                                      std::string &Constraint,
25619                                                      std::vector<SDValue>&Ops,
25620                                                      SelectionDAG &DAG) const {
25621   SDValue Result;
25622
25623   // Only support length 1 constraints for now.
25624   if (Constraint.length() > 1) return;
25625
25626   char ConstraintLetter = Constraint[0];
25627   switch (ConstraintLetter) {
25628   default: break;
25629   case 'I':
25630     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25631       if (C->getZExtValue() <= 31) {
25632         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25633         break;
25634       }
25635     }
25636     return;
25637   case 'J':
25638     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25639       if (C->getZExtValue() <= 63) {
25640         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25641         break;
25642       }
25643     }
25644     return;
25645   case 'K':
25646     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25647       if (isInt<8>(C->getSExtValue())) {
25648         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25649         break;
25650       }
25651     }
25652     return;
25653   case 'N':
25654     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25655       if (C->getZExtValue() <= 255) {
25656         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25657         break;
25658       }
25659     }
25660     return;
25661   case 'e': {
25662     // 32-bit signed value
25663     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25664       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25665                                            C->getSExtValue())) {
25666         // Widen to 64 bits here to get it sign extended.
25667         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
25668         break;
25669       }
25670     // FIXME gcc accepts some relocatable values here too, but only in certain
25671     // memory models; it's complicated.
25672     }
25673     return;
25674   }
25675   case 'Z': {
25676     // 32-bit unsigned value
25677     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25678       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25679                                            C->getZExtValue())) {
25680         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25681         break;
25682       }
25683     }
25684     // FIXME gcc accepts some relocatable values here too, but only in certain
25685     // memory models; it's complicated.
25686     return;
25687   }
25688   case 'i': {
25689     // Literal immediates are always ok.
25690     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25691       // Widen to 64 bits here to get it sign extended.
25692       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
25693       break;
25694     }
25695
25696     // In any sort of PIC mode addresses need to be computed at runtime by
25697     // adding in a register or some sort of table lookup.  These can't
25698     // be used as immediates.
25699     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25700       return;
25701
25702     // If we are in non-pic codegen mode, we allow the address of a global (with
25703     // an optional displacement) to be used with 'i'.
25704     GlobalAddressSDNode *GA = nullptr;
25705     int64_t Offset = 0;
25706
25707     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25708     while (1) {
25709       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25710         Offset += GA->getOffset();
25711         break;
25712       } else if (Op.getOpcode() == ISD::ADD) {
25713         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25714           Offset += C->getZExtValue();
25715           Op = Op.getOperand(0);
25716           continue;
25717         }
25718       } else if (Op.getOpcode() == ISD::SUB) {
25719         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25720           Offset += -C->getZExtValue();
25721           Op = Op.getOperand(0);
25722           continue;
25723         }
25724       }
25725
25726       // Otherwise, this isn't something we can handle, reject it.
25727       return;
25728     }
25729
25730     const GlobalValue *GV = GA->getGlobal();
25731     // If we require an extra load to get this address, as in PIC mode, we
25732     // can't accept it.
25733     if (isGlobalStubReference(
25734             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25735       return;
25736
25737     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25738                                         GA->getValueType(0), Offset);
25739     break;
25740   }
25741   }
25742
25743   if (Result.getNode()) {
25744     Ops.push_back(Result);
25745     return;
25746   }
25747   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25748 }
25749
25750 std::pair<unsigned, const TargetRegisterClass*>
25751 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
25752                                                 MVT VT) const {
25753   // First, see if this is a constraint that directly corresponds to an LLVM
25754   // register class.
25755   if (Constraint.size() == 1) {
25756     // GCC Constraint Letters
25757     switch (Constraint[0]) {
25758     default: break;
25759       // TODO: Slight differences here in allocation order and leaving
25760       // RIP in the class. Do they matter any more here than they do
25761       // in the normal allocation?
25762     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25763       if (Subtarget->is64Bit()) {
25764         if (VT == MVT::i32 || VT == MVT::f32)
25765           return std::make_pair(0U, &X86::GR32RegClass);
25766         if (VT == MVT::i16)
25767           return std::make_pair(0U, &X86::GR16RegClass);
25768         if (VT == MVT::i8 || VT == MVT::i1)
25769           return std::make_pair(0U, &X86::GR8RegClass);
25770         if (VT == MVT::i64 || VT == MVT::f64)
25771           return std::make_pair(0U, &X86::GR64RegClass);
25772         break;
25773       }
25774       // 32-bit fallthrough
25775     case 'Q':   // Q_REGS
25776       if (VT == MVT::i32 || VT == MVT::f32)
25777         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25778       if (VT == MVT::i16)
25779         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25780       if (VT == MVT::i8 || VT == MVT::i1)
25781         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25782       if (VT == MVT::i64)
25783         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25784       break;
25785     case 'r':   // GENERAL_REGS
25786     case 'l':   // INDEX_REGS
25787       if (VT == MVT::i8 || VT == MVT::i1)
25788         return std::make_pair(0U, &X86::GR8RegClass);
25789       if (VT == MVT::i16)
25790         return std::make_pair(0U, &X86::GR16RegClass);
25791       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25792         return std::make_pair(0U, &X86::GR32RegClass);
25793       return std::make_pair(0U, &X86::GR64RegClass);
25794     case 'R':   // LEGACY_REGS
25795       if (VT == MVT::i8 || VT == MVT::i1)
25796         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25797       if (VT == MVT::i16)
25798         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25799       if (VT == MVT::i32 || !Subtarget->is64Bit())
25800         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25801       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25802     case 'f':  // FP Stack registers.
25803       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25804       // value to the correct fpstack register class.
25805       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25806         return std::make_pair(0U, &X86::RFP32RegClass);
25807       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25808         return std::make_pair(0U, &X86::RFP64RegClass);
25809       return std::make_pair(0U, &X86::RFP80RegClass);
25810     case 'y':   // MMX_REGS if MMX allowed.
25811       if (!Subtarget->hasMMX()) break;
25812       return std::make_pair(0U, &X86::VR64RegClass);
25813     case 'Y':   // SSE_REGS if SSE2 allowed
25814       if (!Subtarget->hasSSE2()) break;
25815       // FALL THROUGH.
25816     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25817       if (!Subtarget->hasSSE1()) break;
25818
25819       switch (VT.SimpleTy) {
25820       default: break;
25821       // Scalar SSE types.
25822       case MVT::f32:
25823       case MVT::i32:
25824         return std::make_pair(0U, &X86::FR32RegClass);
25825       case MVT::f64:
25826       case MVT::i64:
25827         return std::make_pair(0U, &X86::FR64RegClass);
25828       // Vector types.
25829       case MVT::v16i8:
25830       case MVT::v8i16:
25831       case MVT::v4i32:
25832       case MVT::v2i64:
25833       case MVT::v4f32:
25834       case MVT::v2f64:
25835         return std::make_pair(0U, &X86::VR128RegClass);
25836       // AVX types.
25837       case MVT::v32i8:
25838       case MVT::v16i16:
25839       case MVT::v8i32:
25840       case MVT::v4i64:
25841       case MVT::v8f32:
25842       case MVT::v4f64:
25843         return std::make_pair(0U, &X86::VR256RegClass);
25844       case MVT::v8f64:
25845       case MVT::v16f32:
25846       case MVT::v16i32:
25847       case MVT::v8i64:
25848         return std::make_pair(0U, &X86::VR512RegClass);
25849       }
25850       break;
25851     }
25852   }
25853
25854   // Use the default implementation in TargetLowering to convert the register
25855   // constraint into a member of a register class.
25856   std::pair<unsigned, const TargetRegisterClass*> Res;
25857   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
25858
25859   // Not found as a standard register?
25860   if (!Res.second) {
25861     // Map st(0) -> st(7) -> ST0
25862     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25863         tolower(Constraint[1]) == 's' &&
25864         tolower(Constraint[2]) == 't' &&
25865         Constraint[3] == '(' &&
25866         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25867         Constraint[5] == ')' &&
25868         Constraint[6] == '}') {
25869
25870       Res.first = X86::FP0+Constraint[4]-'0';
25871       Res.second = &X86::RFP80RegClass;
25872       return Res;
25873     }
25874
25875     // GCC allows "st(0)" to be called just plain "st".
25876     if (StringRef("{st}").equals_lower(Constraint)) {
25877       Res.first = X86::FP0;
25878       Res.second = &X86::RFP80RegClass;
25879       return Res;
25880     }
25881
25882     // flags -> EFLAGS
25883     if (StringRef("{flags}").equals_lower(Constraint)) {
25884       Res.first = X86::EFLAGS;
25885       Res.second = &X86::CCRRegClass;
25886       return Res;
25887     }
25888
25889     // 'A' means EAX + EDX.
25890     if (Constraint == "A") {
25891       Res.first = X86::EAX;
25892       Res.second = &X86::GR32_ADRegClass;
25893       return Res;
25894     }
25895     return Res;
25896   }
25897
25898   // Otherwise, check to see if this is a register class of the wrong value
25899   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25900   // turn into {ax},{dx}.
25901   if (Res.second->hasType(VT))
25902     return Res;   // Correct type already, nothing to do.
25903
25904   // All of the single-register GCC register classes map their values onto
25905   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25906   // really want an 8-bit or 32-bit register, map to the appropriate register
25907   // class and return the appropriate register.
25908   if (Res.second == &X86::GR16RegClass) {
25909     if (VT == MVT::i8 || VT == MVT::i1) {
25910       unsigned DestReg = 0;
25911       switch (Res.first) {
25912       default: break;
25913       case X86::AX: DestReg = X86::AL; break;
25914       case X86::DX: DestReg = X86::DL; break;
25915       case X86::CX: DestReg = X86::CL; break;
25916       case X86::BX: DestReg = X86::BL; break;
25917       }
25918       if (DestReg) {
25919         Res.first = DestReg;
25920         Res.second = &X86::GR8RegClass;
25921       }
25922     } else if (VT == MVT::i32 || VT == MVT::f32) {
25923       unsigned DestReg = 0;
25924       switch (Res.first) {
25925       default: break;
25926       case X86::AX: DestReg = X86::EAX; break;
25927       case X86::DX: DestReg = X86::EDX; break;
25928       case X86::CX: DestReg = X86::ECX; break;
25929       case X86::BX: DestReg = X86::EBX; break;
25930       case X86::SI: DestReg = X86::ESI; break;
25931       case X86::DI: DestReg = X86::EDI; break;
25932       case X86::BP: DestReg = X86::EBP; break;
25933       case X86::SP: DestReg = X86::ESP; break;
25934       }
25935       if (DestReg) {
25936         Res.first = DestReg;
25937         Res.second = &X86::GR32RegClass;
25938       }
25939     } else if (VT == MVT::i64 || VT == MVT::f64) {
25940       unsigned DestReg = 0;
25941       switch (Res.first) {
25942       default: break;
25943       case X86::AX: DestReg = X86::RAX; break;
25944       case X86::DX: DestReg = X86::RDX; break;
25945       case X86::CX: DestReg = X86::RCX; break;
25946       case X86::BX: DestReg = X86::RBX; break;
25947       case X86::SI: DestReg = X86::RSI; break;
25948       case X86::DI: DestReg = X86::RDI; break;
25949       case X86::BP: DestReg = X86::RBP; break;
25950       case X86::SP: DestReg = X86::RSP; break;
25951       }
25952       if (DestReg) {
25953         Res.first = DestReg;
25954         Res.second = &X86::GR64RegClass;
25955       }
25956     }
25957   } else if (Res.second == &X86::FR32RegClass ||
25958              Res.second == &X86::FR64RegClass ||
25959              Res.second == &X86::VR128RegClass ||
25960              Res.second == &X86::VR256RegClass ||
25961              Res.second == &X86::FR32XRegClass ||
25962              Res.second == &X86::FR64XRegClass ||
25963              Res.second == &X86::VR128XRegClass ||
25964              Res.second == &X86::VR256XRegClass ||
25965              Res.second == &X86::VR512RegClass) {
25966     // Handle references to XMM physical registers that got mapped into the
25967     // wrong class.  This can happen with constraints like {xmm0} where the
25968     // target independent register mapper will just pick the first match it can
25969     // find, ignoring the required type.
25970
25971     if (VT == MVT::f32 || VT == MVT::i32)
25972       Res.second = &X86::FR32RegClass;
25973     else if (VT == MVT::f64 || VT == MVT::i64)
25974       Res.second = &X86::FR64RegClass;
25975     else if (X86::VR128RegClass.hasType(VT))
25976       Res.second = &X86::VR128RegClass;
25977     else if (X86::VR256RegClass.hasType(VT))
25978       Res.second = &X86::VR256RegClass;
25979     else if (X86::VR512RegClass.hasType(VT))
25980       Res.second = &X86::VR512RegClass;
25981   }
25982
25983   return Res;
25984 }
25985
25986 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25987                                             Type *Ty) const {
25988   // Scaling factors are not free at all.
25989   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25990   // will take 2 allocations in the out of order engine instead of 1
25991   // for plain addressing mode, i.e. inst (reg1).
25992   // E.g.,
25993   // vaddps (%rsi,%drx), %ymm0, %ymm1
25994   // Requires two allocations (one for the load, one for the computation)
25995   // whereas:
25996   // vaddps (%rsi), %ymm0, %ymm1
25997   // Requires just 1 allocation, i.e., freeing allocations for other operations
25998   // and having less micro operations to execute.
25999   //
26000   // For some X86 architectures, this is even worse because for instance for
26001   // stores, the complex addressing mode forces the instruction to use the
26002   // "load" ports instead of the dedicated "store" port.
26003   // E.g., on Haswell:
26004   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26005   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
26006   if (isLegalAddressingMode(AM, Ty))
26007     // Scale represents reg2 * scale, thus account for 1
26008     // as soon as we use a second register.
26009     return AM.Scale != 0;
26010   return -1;
26011 }
26012
26013 bool X86TargetLowering::isTargetFTOL() const {
26014   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26015 }