[AVX512] Enable FP arithmetic lowering for AVX512VL subsets.
[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   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
115 }
116
117 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
118 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
119 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
120 /// instructions or a simple subregister reference. Idx is an index in the
121 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
122 /// lowering EXTRACT_VECTOR_ELT operations easier.
123 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
124                                    SelectionDAG &DAG, SDLoc dl) {
125   assert((Vec.getValueType().is256BitVector() ||
126           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
127   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
128 }
129
130 /// Generate a DAG to grab 256-bits from a 512-bit vector.
131 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
132                                    SelectionDAG &DAG, SDLoc dl) {
133   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
134   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
135 }
136
137 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
138                                unsigned IdxVal, SelectionDAG &DAG,
139                                SDLoc dl, unsigned vectorWidth) {
140   assert((vectorWidth == 128 || vectorWidth == 256) &&
141          "Unsupported vector width");
142   // Inserting UNDEF is Result
143   if (Vec.getOpcode() == ISD::UNDEF)
144     return Result;
145   EVT VT = Vec.getValueType();
146   EVT ElVT = VT.getVectorElementType();
147   EVT ResultVT = Result.getValueType();
148
149   // Insert the relevant vectorWidth bits.
150   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
151
152   // This is the index of the first element of the vectorWidth-bit chunk
153   // we want.
154   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
155                                * ElemsPerChunk);
156
157   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
158   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
159 }
160
161 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
162 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
163 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
164 /// simple superregister reference.  Idx is an index in the 128 bits
165 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
166 /// lowering INSERT_VECTOR_ELT operations easier.
167 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
168                                   SelectionDAG &DAG,SDLoc dl) {
169   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
170   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
171 }
172
173 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
174                                   SelectionDAG &DAG, SDLoc dl) {
175   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
176   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
177 }
178
179 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
180 /// instructions. This is used because creating CONCAT_VECTOR nodes of
181 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
182 /// large BUILD_VECTORS.
183 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
184                                    unsigned NumElems, SelectionDAG &DAG,
185                                    SDLoc dl) {
186   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
187   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
188 }
189
190 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
191                                    unsigned NumElems, SelectionDAG &DAG,
192                                    SDLoc dl) {
193   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
194   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
195 }
196
197 // FIXME: This should stop caching the target machine as soon as
198 // we can remove resetOperationActions et al.
199 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM)
200     : TargetLowering(TM) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasSSE2();
203   X86ScalarSSEf32 = Subtarget->hasSSE1();
204   TD = getDataLayout();
205
206   resetOperationActions();
207 }
208
209 void X86TargetLowering::resetOperationActions() {
210   const TargetMachine &TM = getTargetMachine();
211   static bool FirstTimeThrough = true;
212
213   // If none of the target options have changed, then we don't need to reset the
214   // operation actions.
215   if (!FirstTimeThrough && TO == TM.Options) return;
216
217   if (!FirstTimeThrough) {
218     // Reinitialize the actions.
219     initActions();
220     FirstTimeThrough = false;
221   }
222
223   TO = TM.Options;
224
225   // Set up the TargetLowering object.
226   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227
228   // X86 is weird. It always uses i8 for shift amounts and setcc results.
229   setBooleanContents(ZeroOrOneBooleanContent);
230   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232
233   // For 64-bit, since we have so many registers, use the ILP scheduler.
234   // For 32-bit, use the register pressure specific scheduling.
235   // For Atom, always use ILP scheduling.
236   if (Subtarget->isAtom())
237     setSchedulingPreference(Sched::ILP);
238   else if (Subtarget->is64Bit())
239     setSchedulingPreference(Sched::ILP);
240   else
241     setSchedulingPreference(Sched::RegPressure);
242   const X86RegisterInfo *RegInfo =
243       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
244   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245
246   // Bypass expensive divides on Atom when compiling with O2.
247   if (TM.getOptLevel() >= CodeGenOpt::Default) {
248     if (Subtarget->hasSlowDivide32())
249       addBypassSlowDiv(32, 8);
250     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
251       addBypassSlowDiv(64, 16);
252   }
253
254   if (Subtarget->isTargetKnownWindowsMSVC()) {
255     // Setup Windows compiler runtime calls.
256     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258     setLibcallName(RTLIB::SREM_I64, "_allrem");
259     setLibcallName(RTLIB::UREM_I64, "_aullrem");
260     setLibcallName(RTLIB::MUL_I64, "_allmul");
261     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266
267     // The _ftol2 runtime function has an unusual calling conv, which
268     // is modeled by a special pseudo-instruction.
269     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
270     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
273   }
274
275   if (Subtarget->isTargetDarwin()) {
276     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277     setUseUnderscoreSetJmp(false);
278     setUseUnderscoreLongJmp(false);
279   } else if (Subtarget->isTargetWindowsGNU()) {
280     // MS runtime is weird: it exports _setjmp, but longjmp!
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(false);
283   } else {
284     setUseUnderscoreSetJmp(true);
285     setUseUnderscoreLongJmp(true);
286   }
287
288   // Set up the register classes.
289   addRegisterClass(MVT::i8, &X86::GR8RegClass);
290   addRegisterClass(MVT::i16, &X86::GR16RegClass);
291   addRegisterClass(MVT::i32, &X86::GR32RegClass);
292   if (Subtarget->is64Bit())
293     addRegisterClass(MVT::i64, &X86::GR64RegClass);
294
295   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296
297   // We don't accept any truncstore of integer registers.
298   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
304
305   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
306
307   // SETOEQ and SETUNE require checking two conditions.
308   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314
315   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316   // operation.
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
318   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
319   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
320
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
323     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
324   } else if (!TM.Options.UseSoftFloat) {
325     // We have an algorithm for SSE2->double, and we turn this into a
326     // 64-bit FILD followed by conditional FADD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
328     // We have an algorithm for SSE2, and we turn this into a 64-bit
329     // FILD for other targets.
330     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
331   }
332
333   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334   // this operation.
335   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
336   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
337
338   if (!TM.Options.UseSoftFloat) {
339     // SSE has no i16 to fp conversion, only i32
340     if (X86ScalarSSEf32) {
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
342       // f32 and f64 cases are Legal, f80 case is not
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     } else {
345       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
346       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
347     }
348   } else {
349     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
350     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
351   }
352
353   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
354   // are Legal, f80 is custom lowered.
355   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
356   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
357
358   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359   // this operation.
360   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
361   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
362
363   if (X86ScalarSSEf32) {
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
365     // f32 and f64 cases are Legal, f80 case is not
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   } else {
368     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
369     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
370   }
371
372   // Handle FP_TO_UINT by promoting the destination to a larger signed
373   // conversion.
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
375   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
376   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
377
378   if (Subtarget->is64Bit()) {
379     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
380     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
381   } else if (!TM.Options.UseSoftFloat) {
382     // Since AVX is a superset of SSE3, only check for SSE here.
383     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384       // Expand FP_TO_UINT into a select.
385       // FIXME: We would like to use a Custom expander here eventually to do
386       // the optimal thing for SSE vs. the default expansion in the legalizer.
387       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
388     else
389       // With SSE3 we can use fisttpll to convert to a signed i64; without
390       // SSE, we're stuck with a fistpll.
391       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
392   }
393
394   if (isTargetFTOL()) {
395     // Use the _ftol2 runtime function, which has a pseudo-instruction
396     // to handle its weird calling convention.
397     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
398   }
399
400   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401   if (!X86ScalarSSEf64) {
402     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
403     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
404     if (Subtarget->is64Bit()) {
405       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
406       // Without SSE, i64->f64 goes through memory.
407       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
408     }
409   }
410
411   // Scalar integer divide and remainder are lowered to use operations that
412   // produce two results, to match the available instructions. This exposes
413   // the two-result form to trivial CSE, which is able to combine x/y and x%y
414   // into a single instruction.
415   //
416   // Scalar integer multiply-high is also lowered to use two-result
417   // operations, to match the available instructions. However, plain multiply
418   // (low) operations are left as Legal, as there are single-result
419   // instructions for this in x86. Using the two-result multiply instructions
420   // when both high and low results are needed must be arranged by dagcombine.
421   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422     MVT VT = IntVTs[i];
423     setOperationAction(ISD::MULHS, VT, Expand);
424     setOperationAction(ISD::MULHU, VT, Expand);
425     setOperationAction(ISD::SDIV, VT, Expand);
426     setOperationAction(ISD::UDIV, VT, Expand);
427     setOperationAction(ISD::SREM, VT, Expand);
428     setOperationAction(ISD::UREM, VT, Expand);
429
430     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431     setOperationAction(ISD::ADDC, VT, Custom);
432     setOperationAction(ISD::ADDE, VT, Custom);
433     setOperationAction(ISD::SUBC, VT, Custom);
434     setOperationAction(ISD::SUBE, VT, Custom);
435   }
436
437   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
438   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
439   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
444   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
445   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
446   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
447   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
448   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
449   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
450   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
451   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
452   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
453   if (Subtarget->is64Bit())
454     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
455   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
456   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
457   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
458   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
459   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
460   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
461   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
462   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
463
464   // Promote the i8 variants and force them on up to i32 which has a shorter
465   // encoding.
466   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
467   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
468   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
469   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
470   if (Subtarget->hasBMI()) {
471     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
472     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
473     if (Subtarget->is64Bit())
474       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
475   } else {
476     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
477     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
478     if (Subtarget->is64Bit())
479       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
480   }
481
482   if (Subtarget->hasLZCNT()) {
483     // When promoting the i8 variants, force them to i32 for a shorter
484     // encoding.
485     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
486     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
488     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
491     if (Subtarget->is64Bit())
492       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
493   } else {
494     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
495     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
496     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
497     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
498     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
500     if (Subtarget->is64Bit()) {
501       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
502       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
503     }
504   }
505
506   // Special handling for half-precision floating point conversions.
507   // If we don't have F16C support, then lower half float conversions
508   // into library calls.
509   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
510     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
511     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
512   }
513
514   // There's never any support for operations beyond MVT::f32.
515   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
516   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
517   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
518   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
519
520   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
521   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
522   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
523   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
524
525   if (Subtarget->hasPOPCNT()) {
526     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
527   } else {
528     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
529     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
530     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
531     if (Subtarget->is64Bit())
532       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
533   }
534
535   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
536
537   if (!Subtarget->hasMOVBE())
538     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
539
540   // These should be promoted to a larger select which is supported.
541   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
542   // X86 wants to expand cmov itself.
543   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
544   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
545   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
546   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
547   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
548   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
549   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
550   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
551   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
552   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
553   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
554   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
555   if (Subtarget->is64Bit()) {
556     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
557     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
558   }
559   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
560   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
561   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
562   // support continuation, user-level threading, and etc.. As a result, no
563   // other SjLj exception interfaces are implemented and please don't build
564   // your own exception handling based on them.
565   // LLVM/Clang supports zero-cost DWARF exception handling.
566   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
567   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
568
569   // Darwin ABI issue.
570   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
571   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
572   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
573   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
574   if (Subtarget->is64Bit())
575     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
576   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
577   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
578   if (Subtarget->is64Bit()) {
579     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
580     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
581     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
582     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
583     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
584   }
585   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
586   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
587   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
588   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
589   if (Subtarget->is64Bit()) {
590     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
591     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
592     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
593   }
594
595   if (Subtarget->hasSSE1())
596     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
597
598   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
599
600   // Expand certain atomics
601   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
602     MVT VT = IntVTs[i];
603     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
604     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
605     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
606   }
607
608   if (Subtarget->hasCmpxchg16b()) {
609     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
610   }
611
612   // FIXME - use subtarget debug flags
613   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
614       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
615     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
616   }
617
618   if (Subtarget->is64Bit()) {
619     setExceptionPointerRegister(X86::RAX);
620     setExceptionSelectorRegister(X86::RDX);
621   } else {
622     setExceptionPointerRegister(X86::EAX);
623     setExceptionSelectorRegister(X86::EDX);
624   }
625   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
626   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
627
628   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
629   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
630
631   setOperationAction(ISD::TRAP, MVT::Other, Legal);
632   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
633
634   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
635   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
636   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
637   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
638     // TargetInfo::X86_64ABIBuiltinVaList
639     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
640     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
641   } else {
642     // TargetInfo::CharPtrBuiltinVaList
643     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
644     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
645   }
646
647   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
648   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
649
650   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
651
652   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
653     // f32 and f64 use SSE.
654     // Set up the FP register classes.
655     addRegisterClass(MVT::f32, &X86::FR32RegClass);
656     addRegisterClass(MVT::f64, &X86::FR64RegClass);
657
658     // Use ANDPD to simulate FABS.
659     setOperationAction(ISD::FABS , MVT::f64, Custom);
660     setOperationAction(ISD::FABS , MVT::f32, Custom);
661
662     // Use XORP to simulate FNEG.
663     setOperationAction(ISD::FNEG , MVT::f64, Custom);
664     setOperationAction(ISD::FNEG , MVT::f32, Custom);
665
666     // Use ANDPD and ORPD to simulate FCOPYSIGN.
667     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
668     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
669
670     // Lower this to FGETSIGNx86 plus an AND.
671     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
672     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
673
674     // We don't support sin/cos/fmod
675     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
676     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
677     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
678     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
679     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
680     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
681
682     // Expand FP immediates into loads from the stack, except for the special
683     // cases we handle.
684     addLegalFPImmediate(APFloat(+0.0)); // xorpd
685     addLegalFPImmediate(APFloat(+0.0f)); // xorps
686   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
687     // Use SSE for f32, x87 for f64.
688     // Set up the FP register classes.
689     addRegisterClass(MVT::f32, &X86::FR32RegClass);
690     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
691
692     // Use ANDPS to simulate FABS.
693     setOperationAction(ISD::FABS , MVT::f32, Custom);
694
695     // Use XORP to simulate FNEG.
696     setOperationAction(ISD::FNEG , MVT::f32, Custom);
697
698     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
699
700     // Use ANDPS and ORPS to simulate FCOPYSIGN.
701     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
702     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
703
704     // We don't support sin/cos/fmod
705     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
706     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
707     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
708
709     // Special cases we handle for FP constants.
710     addLegalFPImmediate(APFloat(+0.0f)); // xorps
711     addLegalFPImmediate(APFloat(+0.0)); // FLD0
712     addLegalFPImmediate(APFloat(+1.0)); // FLD1
713     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
714     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
715
716     if (!TM.Options.UnsafeFPMath) {
717       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
718       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
719       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
720     }
721   } else if (!TM.Options.UseSoftFloat) {
722     // f32 and f64 in x87.
723     // Set up the FP register classes.
724     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
725     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
726
727     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
728     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
729     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
730     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
731
732     if (!TM.Options.UnsafeFPMath) {
733       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
734       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
735       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
736       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
737       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
738       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
739     }
740     addLegalFPImmediate(APFloat(+0.0)); // FLD0
741     addLegalFPImmediate(APFloat(+1.0)); // FLD1
742     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
743     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
744     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
745     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
746     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
747     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
748   }
749
750   // We don't support FMA.
751   setOperationAction(ISD::FMA, MVT::f64, Expand);
752   setOperationAction(ISD::FMA, MVT::f32, Expand);
753
754   // Long double always uses X87.
755   if (!TM.Options.UseSoftFloat) {
756     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
757     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
758     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
759     {
760       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
761       addLegalFPImmediate(TmpFlt);  // FLD0
762       TmpFlt.changeSign();
763       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
764
765       bool ignored;
766       APFloat TmpFlt2(+1.0);
767       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
768                       &ignored);
769       addLegalFPImmediate(TmpFlt2);  // FLD1
770       TmpFlt2.changeSign();
771       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
772     }
773
774     if (!TM.Options.UnsafeFPMath) {
775       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
776       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
777       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
778     }
779
780     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
781     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
782     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
783     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
784     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
785     setOperationAction(ISD::FMA, MVT::f80, Expand);
786   }
787
788   // Always use a library call for pow.
789   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
790   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
791   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
792
793   setOperationAction(ISD::FLOG, MVT::f80, Expand);
794   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
795   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
796   setOperationAction(ISD::FEXP, MVT::f80, Expand);
797   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
798   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
799   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
800
801   // First set operation action for all vector types to either promote
802   // (for widening) or expand (for scalarization). Then we will selectively
803   // turn on ones that can be effectively codegen'd.
804   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
805            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
806     MVT VT = (MVT::SimpleValueType)i;
807     setOperationAction(ISD::ADD , VT, Expand);
808     setOperationAction(ISD::SUB , VT, Expand);
809     setOperationAction(ISD::FADD, VT, Expand);
810     setOperationAction(ISD::FNEG, VT, Expand);
811     setOperationAction(ISD::FSUB, VT, Expand);
812     setOperationAction(ISD::MUL , VT, Expand);
813     setOperationAction(ISD::FMUL, VT, Expand);
814     setOperationAction(ISD::SDIV, VT, Expand);
815     setOperationAction(ISD::UDIV, VT, Expand);
816     setOperationAction(ISD::FDIV, VT, Expand);
817     setOperationAction(ISD::SREM, VT, Expand);
818     setOperationAction(ISD::UREM, VT, Expand);
819     setOperationAction(ISD::LOAD, VT, Expand);
820     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
821     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
822     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
823     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
824     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
825     setOperationAction(ISD::FABS, VT, Expand);
826     setOperationAction(ISD::FSIN, VT, Expand);
827     setOperationAction(ISD::FSINCOS, VT, Expand);
828     setOperationAction(ISD::FCOS, VT, Expand);
829     setOperationAction(ISD::FSINCOS, VT, Expand);
830     setOperationAction(ISD::FREM, VT, Expand);
831     setOperationAction(ISD::FMA,  VT, Expand);
832     setOperationAction(ISD::FPOWI, VT, Expand);
833     setOperationAction(ISD::FSQRT, VT, Expand);
834     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
835     setOperationAction(ISD::FFLOOR, VT, Expand);
836     setOperationAction(ISD::FCEIL, VT, Expand);
837     setOperationAction(ISD::FTRUNC, VT, Expand);
838     setOperationAction(ISD::FRINT, VT, Expand);
839     setOperationAction(ISD::FNEARBYINT, VT, Expand);
840     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
841     setOperationAction(ISD::MULHS, VT, Expand);
842     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
843     setOperationAction(ISD::MULHU, VT, Expand);
844     setOperationAction(ISD::SDIVREM, VT, Expand);
845     setOperationAction(ISD::UDIVREM, VT, Expand);
846     setOperationAction(ISD::FPOW, VT, Expand);
847     setOperationAction(ISD::CTPOP, VT, Expand);
848     setOperationAction(ISD::CTTZ, VT, Expand);
849     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
850     setOperationAction(ISD::CTLZ, VT, Expand);
851     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
852     setOperationAction(ISD::SHL, VT, Expand);
853     setOperationAction(ISD::SRA, VT, Expand);
854     setOperationAction(ISD::SRL, VT, Expand);
855     setOperationAction(ISD::ROTL, VT, Expand);
856     setOperationAction(ISD::ROTR, VT, Expand);
857     setOperationAction(ISD::BSWAP, VT, Expand);
858     setOperationAction(ISD::SETCC, VT, Expand);
859     setOperationAction(ISD::FLOG, VT, Expand);
860     setOperationAction(ISD::FLOG2, VT, Expand);
861     setOperationAction(ISD::FLOG10, VT, Expand);
862     setOperationAction(ISD::FEXP, VT, Expand);
863     setOperationAction(ISD::FEXP2, VT, Expand);
864     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
865     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
866     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
867     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
868     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
869     setOperationAction(ISD::TRUNCATE, VT, Expand);
870     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
871     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
872     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
873     setOperationAction(ISD::VSELECT, VT, Expand);
874     setOperationAction(ISD::SELECT_CC, VT, Expand);
875     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
876              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
877       setTruncStoreAction(VT,
878                           (MVT::SimpleValueType)InnerVT, Expand);
879     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
880     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
881
882     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
883     // we have to deal with them whether we ask for Expansion or not. Setting
884     // Expand causes its own optimisation problems though, so leave them legal.
885     if (VT.getVectorElementType() == MVT::i1)
886       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
887   }
888
889   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
890   // with -msoft-float, disable use of MMX as well.
891   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
892     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
893     // No operations on x86mmx supported, everything uses intrinsics.
894   }
895
896   // MMX-sized vectors (other than x86mmx) are expected to be expanded
897   // into smaller operations.
898   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
899   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
900   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
901   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
902   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
903   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
904   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
905   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
906   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
907   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
908   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
909   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
910   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
911   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
912   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
913   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
914   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
915   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
916   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
917   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
918   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
919   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
920   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
921   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
922   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
923   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
924   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
925   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
926   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
927
928   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
929     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
930
931     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
932     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
933     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
934     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
935     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
936     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
937     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
938     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
939     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
940     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
942     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
943     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
944   }
945
946   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
947     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
948
949     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
950     // registers cannot be used even for integer operations.
951     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
952     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
953     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
954     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
955
956     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
957     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
958     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
959     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
960     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
961     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
962     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
963     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
964     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
965     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
966     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
967     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
968     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
969     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
971     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
972     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
973     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
974     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
975     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
976     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
977     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
978
979     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
980     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
981     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
982     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
983
984     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
985     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
989
990     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
991     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
992       MVT VT = (MVT::SimpleValueType)i;
993       // Do not attempt to custom lower non-power-of-2 vectors
994       if (!isPowerOf2_32(VT.getVectorNumElements()))
995         continue;
996       // Do not attempt to custom lower non-128-bit vectors
997       if (!VT.is128BitVector())
998         continue;
999       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1000       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1001       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1002     }
1003
1004     // We support custom legalizing of sext and anyext loads for specific
1005     // memory vector types which we can load as a scalar (or sequence of
1006     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1007     // loads these must work with a single scalar load.
1008     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1009     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1010     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1011     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1012     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1013     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1014     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1015     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1016     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1017
1018     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1019     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1020     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1021     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1022     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1023     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1024
1025     if (Subtarget->is64Bit()) {
1026       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1027       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1028     }
1029
1030     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1031     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1032       MVT VT = (MVT::SimpleValueType)i;
1033
1034       // Do not attempt to promote non-128-bit vectors
1035       if (!VT.is128BitVector())
1036         continue;
1037
1038       setOperationAction(ISD::AND,    VT, Promote);
1039       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1040       setOperationAction(ISD::OR,     VT, Promote);
1041       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1042       setOperationAction(ISD::XOR,    VT, Promote);
1043       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1044       setOperationAction(ISD::LOAD,   VT, Promote);
1045       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1046       setOperationAction(ISD::SELECT, VT, Promote);
1047       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1048     }
1049
1050     // Custom lower v2i64 and v2f64 selects.
1051     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1052     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1053     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1054     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1055
1056     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1057     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1058
1059     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1060     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1061     // As there is no 64-bit GPR available, we need build a special custom
1062     // sequence to convert from v2i32 to v2f32.
1063     if (!Subtarget->is64Bit())
1064       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1065
1066     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1067     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1068
1069     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1070
1071     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1072     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1073     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1074   }
1075
1076   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1077     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1078     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1079     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1080     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1081     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1082     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1083     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1084     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1085     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1086     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1087
1088     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1089     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1090     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1091     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1092     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1093     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1094     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1095     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1096     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1097     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1098
1099     // FIXME: Do we need to handle scalar-to-vector here?
1100     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1101
1102     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1103     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1104     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1105     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1106     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1107     // There is no BLENDI for byte vectors. We don't need to custom lower
1108     // some vselects for now.
1109     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1110
1111     // SSE41 brings specific instructions for doing vector sign extend even in
1112     // cases where we don't have SRA.
1113     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1114     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1115     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1116
1117     // i8 and i16 vectors are custom because the source register and source
1118     // source memory operand types are not the same width.  f32 vectors are
1119     // custom since the immediate controlling the insert encodes additional
1120     // information.
1121     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1122     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1123     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1124     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1125
1126     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1127     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1128     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1129     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1130
1131     // FIXME: these should be Legal, but that's only for the case where
1132     // the index is constant.  For now custom expand to deal with that.
1133     if (Subtarget->is64Bit()) {
1134       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1135       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1136     }
1137   }
1138
1139   if (Subtarget->hasSSE2()) {
1140     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1141     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1142
1143     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1144     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1145
1146     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1147     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1148
1149     // In the customized shift lowering, the legal cases in AVX2 will be
1150     // recognized.
1151     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1152     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1153
1154     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1155     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1156
1157     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1158   }
1159
1160   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1161     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1162     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1163     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1164     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1165     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1166     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1167
1168     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1169     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1170     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1171
1172     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1173     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1174     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1175     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1176     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1177     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1178     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1179     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1180     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1181     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1182     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1183     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1184
1185     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1186     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1187     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1188     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1189     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1190     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1191     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1192     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1193     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1194     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1195     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1196     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1197
1198     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1199     // even though v8i16 is a legal type.
1200     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1201     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1202     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1203
1204     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1205     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1206     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1207
1208     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1209     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1210
1211     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1212
1213     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1214     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1215
1216     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1217     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1218
1219     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1220     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1221
1222     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1223     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1224     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1225     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1226
1227     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1228     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1229     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1230
1231     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1232     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1233     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1234     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1235
1236     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1237     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1238     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1239     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1240     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1241     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1242     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1243     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1244     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1245     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1246     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1247     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1248
1249     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1250       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1251       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1252       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1253       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1254       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1255       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1256     }
1257
1258     if (Subtarget->hasInt256()) {
1259       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1260       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1261       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1262       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1263
1264       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1265       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1266       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1267       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1268
1269       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1270       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1271       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1272       // Don't lower v32i8 because there is no 128-bit byte mul
1273
1274       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1275       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1276       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1277       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1278
1279       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1280       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1281
1282       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1283       // when we have a 256bit-wide blend with immediate.
1284       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1285     } else {
1286       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1287       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1288       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1289       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1290
1291       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1292       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1293       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1294       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1295
1296       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1297       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1298       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1299       // Don't lower v32i8 because there is no 128-bit byte mul
1300     }
1301
1302     // In the customized shift lowering, the legal cases in AVX2 will be
1303     // recognized.
1304     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1305     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1306
1307     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1308     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1309
1310     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1311
1312     // Custom lower several nodes for 256-bit types.
1313     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1314              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1315       MVT VT = (MVT::SimpleValueType)i;
1316
1317       // Extract subvector is special because the value type
1318       // (result) is 128-bit but the source is 256-bit wide.
1319       if (VT.is128BitVector()) {
1320         if (VT.getScalarSizeInBits() >= 32) {
1321           setOperationAction(ISD::MLOAD,  VT, Custom);
1322           setOperationAction(ISD::MSTORE, VT, Custom);
1323         }
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       if (VT.getScalarSizeInBits() >= 32) {
1331         setOperationAction(ISD::MLOAD,  VT, Legal);
1332         setOperationAction(ISD::MSTORE, VT, Legal);
1333       }
1334       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1335       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1336       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1337       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1338       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1339       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1340       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1341     }
1342
1343     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1344     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1345       MVT VT = (MVT::SimpleValueType)i;
1346
1347       // Do not attempt to promote non-256-bit vectors
1348       if (!VT.is256BitVector())
1349         continue;
1350
1351       setOperationAction(ISD::AND,    VT, Promote);
1352       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1353       setOperationAction(ISD::OR,     VT, Promote);
1354       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1355       setOperationAction(ISD::XOR,    VT, Promote);
1356       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1357       setOperationAction(ISD::LOAD,   VT, Promote);
1358       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1359       setOperationAction(ISD::SELECT, VT, Promote);
1360       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1361     }
1362   }
1363
1364   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1365     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1366     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1369
1370     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1371     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1372     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1373
1374     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1375     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1376     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1377     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1378     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1379     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1380     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1385
1386     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1387     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1391     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1392
1393     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1394     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1398     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1399     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1400     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1401
1402     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1403     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1405     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1406     if (Subtarget->is64Bit()) {
1407       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1408       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1410       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1411     }
1412     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1413     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1416     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1417     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1419     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1420     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1421     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1422     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1423     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1424     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1425     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1426
1427     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1431     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1432     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1433     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1434     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1438     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1439     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1440
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1445     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1446     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1447
1448     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1449     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1450
1451     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1452
1453     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1454     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1455     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1456     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1457     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1458     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1460     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1461     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1462
1463     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1464     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1465
1466     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1467     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1468
1469     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1470
1471     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1472     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1473
1474     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1475     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1476
1477     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1478     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1479
1480     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1482     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1483     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1484     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1485     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1486
1487     if (Subtarget->hasCDI()) {
1488       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1489       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1490     }
1491
1492     // Custom lower several nodes.
1493     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1494              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1495       MVT VT = (MVT::SimpleValueType)i;
1496
1497       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1498       // Extract subvector is special because the value type
1499       // (result) is 256/128-bit but the source is 512-bit wide.
1500       if (VT.is128BitVector() || VT.is256BitVector()) {
1501         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1502         if ( EltSize >= 32) {
1503           setOperationAction(ISD::MLOAD,   VT, Legal);
1504           setOperationAction(ISD::MSTORE,  VT, Legal);
1505         }
1506       }
1507       if (VT.getVectorElementType() == MVT::i1)
1508         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1509
1510       // Do not attempt to custom lower other non-512-bit vectors
1511       if (!VT.is512BitVector())
1512         continue;
1513
1514       if ( EltSize >= 32) {
1515         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1516         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1517         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1518         setOperationAction(ISD::VSELECT,             VT, Legal);
1519         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1520         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1521         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1522         setOperationAction(ISD::MLOAD,               VT, Legal);
1523         setOperationAction(ISD::MSTORE,              VT, Legal);
1524       }
1525     }
1526     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1527       MVT VT = (MVT::SimpleValueType)i;
1528
1529       // Do not attempt to promote non-256-bit vectors.
1530       if (!VT.is512BitVector())
1531         continue;
1532
1533       setOperationAction(ISD::SELECT, VT, Promote);
1534       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1535     }
1536   }// has  AVX-512
1537
1538   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1539     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1540     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1541
1542     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1543     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1544
1545     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1546     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1547     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1548     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1549     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1550     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1551     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1552     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1553     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1554
1555     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1556       const MVT VT = (MVT::SimpleValueType)i;
1557
1558       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1559
1560       // Do not attempt to promote non-256-bit vectors.
1561       if (!VT.is512BitVector())
1562         continue;
1563
1564       if (EltSize < 32) {
1565         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1566         setOperationAction(ISD::VSELECT,             VT, Legal);
1567       }
1568     }
1569   }
1570
1571   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1572     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1573     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1574
1575     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1576     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1577     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Legal);
1578
1579     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1580     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1581     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1582     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1583     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1584     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1585   }
1586
1587   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1588   // of this type with custom code.
1589   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1590            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1591     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1592                        Custom);
1593   }
1594
1595   // We want to custom lower some of our intrinsics.
1596   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1597   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1598   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1599   if (!Subtarget->is64Bit())
1600     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1601
1602   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1603   // handle type legalization for these operations here.
1604   //
1605   // FIXME: We really should do custom legalization for addition and
1606   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1607   // than generic legalization for 64-bit multiplication-with-overflow, though.
1608   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1609     // Add/Sub/Mul with overflow operations are custom lowered.
1610     MVT VT = IntVTs[i];
1611     setOperationAction(ISD::SADDO, VT, Custom);
1612     setOperationAction(ISD::UADDO, VT, Custom);
1613     setOperationAction(ISD::SSUBO, VT, Custom);
1614     setOperationAction(ISD::USUBO, VT, Custom);
1615     setOperationAction(ISD::SMULO, VT, Custom);
1616     setOperationAction(ISD::UMULO, VT, Custom);
1617   }
1618
1619
1620   if (!Subtarget->is64Bit()) {
1621     // These libcalls are not available in 32-bit.
1622     setLibcallName(RTLIB::SHL_I128, nullptr);
1623     setLibcallName(RTLIB::SRL_I128, nullptr);
1624     setLibcallName(RTLIB::SRA_I128, nullptr);
1625   }
1626
1627   // Combine sin / cos into one node or libcall if possible.
1628   if (Subtarget->hasSinCos()) {
1629     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1630     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1631     if (Subtarget->isTargetDarwin()) {
1632       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1633       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1634       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1635       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1636     }
1637   }
1638
1639   if (Subtarget->isTargetWin64()) {
1640     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1641     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1642     setOperationAction(ISD::SREM, MVT::i128, Custom);
1643     setOperationAction(ISD::UREM, MVT::i128, Custom);
1644     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1645     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1646   }
1647
1648   // We have target-specific dag combine patterns for the following nodes:
1649   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1650   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1651   setTargetDAGCombine(ISD::VSELECT);
1652   setTargetDAGCombine(ISD::SELECT);
1653   setTargetDAGCombine(ISD::SHL);
1654   setTargetDAGCombine(ISD::SRA);
1655   setTargetDAGCombine(ISD::SRL);
1656   setTargetDAGCombine(ISD::OR);
1657   setTargetDAGCombine(ISD::AND);
1658   setTargetDAGCombine(ISD::ADD);
1659   setTargetDAGCombine(ISD::FADD);
1660   setTargetDAGCombine(ISD::FSUB);
1661   setTargetDAGCombine(ISD::FMA);
1662   setTargetDAGCombine(ISD::SUB);
1663   setTargetDAGCombine(ISD::LOAD);
1664   setTargetDAGCombine(ISD::STORE);
1665   setTargetDAGCombine(ISD::ZERO_EXTEND);
1666   setTargetDAGCombine(ISD::ANY_EXTEND);
1667   setTargetDAGCombine(ISD::SIGN_EXTEND);
1668   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1669   setTargetDAGCombine(ISD::TRUNCATE);
1670   setTargetDAGCombine(ISD::SINT_TO_FP);
1671   setTargetDAGCombine(ISD::SETCC);
1672   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1673   setTargetDAGCombine(ISD::BUILD_VECTOR);
1674   if (Subtarget->is64Bit())
1675     setTargetDAGCombine(ISD::MUL);
1676   setTargetDAGCombine(ISD::XOR);
1677
1678   computeRegisterProperties();
1679
1680   // On Darwin, -Os means optimize for size without hurting performance,
1681   // do not reduce the limit.
1682   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1683   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1684   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1685   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1686   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1687   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1688   setPrefLoopAlignment(4); // 2^4 bytes.
1689
1690   // Predictable cmov don't hurt on atom because it's in-order.
1691   PredictableSelectIsExpensive = !Subtarget->isAtom();
1692   EnableExtLdPromotion = true;
1693   setPrefFunctionAlignment(4); // 2^4 bytes.
1694
1695   verifyIntrinsicTables();
1696 }
1697
1698 // This has so far only been implemented for 64-bit MachO.
1699 bool X86TargetLowering::useLoadStackGuardNode() const {
1700   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1701 }
1702
1703 TargetLoweringBase::LegalizeTypeAction
1704 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1705   if (ExperimentalVectorWideningLegalization &&
1706       VT.getVectorNumElements() != 1 &&
1707       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1708     return TypeWidenVector;
1709
1710   return TargetLoweringBase::getPreferredVectorAction(VT);
1711 }
1712
1713 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1714   if (!VT.isVector())
1715     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1716
1717   const unsigned NumElts = VT.getVectorNumElements();
1718   const EVT EltVT = VT.getVectorElementType();
1719   if (VT.is512BitVector()) {
1720     if (Subtarget->hasAVX512())
1721       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1722           EltVT == MVT::f32 || EltVT == MVT::f64)
1723         switch(NumElts) {
1724         case  8: return MVT::v8i1;
1725         case 16: return MVT::v16i1;
1726       }
1727     if (Subtarget->hasBWI())
1728       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1729         switch(NumElts) {
1730         case 32: return MVT::v32i1;
1731         case 64: return MVT::v64i1;
1732       }
1733   }
1734
1735   if (VT.is256BitVector() || VT.is128BitVector()) {
1736     if (Subtarget->hasVLX())
1737       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1738           EltVT == MVT::f32 || EltVT == MVT::f64)
1739         switch(NumElts) {
1740         case 2: return MVT::v2i1;
1741         case 4: return MVT::v4i1;
1742         case 8: return MVT::v8i1;
1743       }
1744     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1745       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1746         switch(NumElts) {
1747         case  8: return MVT::v8i1;
1748         case 16: return MVT::v16i1;
1749         case 32: return MVT::v32i1;
1750       }
1751   }
1752
1753   return VT.changeVectorElementTypeToInteger();
1754 }
1755
1756 /// Helper for getByValTypeAlignment to determine
1757 /// the desired ByVal argument alignment.
1758 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1759   if (MaxAlign == 16)
1760     return;
1761   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1762     if (VTy->getBitWidth() == 128)
1763       MaxAlign = 16;
1764   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1765     unsigned EltAlign = 0;
1766     getMaxByValAlign(ATy->getElementType(), EltAlign);
1767     if (EltAlign > MaxAlign)
1768       MaxAlign = EltAlign;
1769   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1770     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1771       unsigned EltAlign = 0;
1772       getMaxByValAlign(STy->getElementType(i), EltAlign);
1773       if (EltAlign > MaxAlign)
1774         MaxAlign = EltAlign;
1775       if (MaxAlign == 16)
1776         break;
1777     }
1778   }
1779 }
1780
1781 /// Return the desired alignment for ByVal aggregate
1782 /// function arguments in the caller parameter area. For X86, aggregates
1783 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1784 /// are at 4-byte boundaries.
1785 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1786   if (Subtarget->is64Bit()) {
1787     // Max of 8 and alignment of type.
1788     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1789     if (TyAlign > 8)
1790       return TyAlign;
1791     return 8;
1792   }
1793
1794   unsigned Align = 4;
1795   if (Subtarget->hasSSE1())
1796     getMaxByValAlign(Ty, Align);
1797   return Align;
1798 }
1799
1800 /// Returns the target specific optimal type for load
1801 /// and store operations as a result of memset, memcpy, and memmove
1802 /// lowering. If DstAlign is zero that means it's safe to destination
1803 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1804 /// means there isn't a need to check it against alignment requirement,
1805 /// probably because the source does not need to be loaded. If 'IsMemset' is
1806 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1807 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1808 /// source is constant so it does not need to be loaded.
1809 /// It returns EVT::Other if the type should be determined using generic
1810 /// target-independent logic.
1811 EVT
1812 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1813                                        unsigned DstAlign, unsigned SrcAlign,
1814                                        bool IsMemset, bool ZeroMemset,
1815                                        bool MemcpyStrSrc,
1816                                        MachineFunction &MF) const {
1817   const Function *F = MF.getFunction();
1818   if ((!IsMemset || ZeroMemset) &&
1819       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1820                                        Attribute::NoImplicitFloat)) {
1821     if (Size >= 16 &&
1822         (Subtarget->isUnalignedMemAccessFast() ||
1823          ((DstAlign == 0 || DstAlign >= 16) &&
1824           (SrcAlign == 0 || SrcAlign >= 16)))) {
1825       if (Size >= 32) {
1826         if (Subtarget->hasInt256())
1827           return MVT::v8i32;
1828         if (Subtarget->hasFp256())
1829           return MVT::v8f32;
1830       }
1831       if (Subtarget->hasSSE2())
1832         return MVT::v4i32;
1833       if (Subtarget->hasSSE1())
1834         return MVT::v4f32;
1835     } else if (!MemcpyStrSrc && Size >= 8 &&
1836                !Subtarget->is64Bit() &&
1837                Subtarget->hasSSE2()) {
1838       // Do not use f64 to lower memcpy if source is string constant. It's
1839       // better to use i32 to avoid the loads.
1840       return MVT::f64;
1841     }
1842   }
1843   if (Subtarget->is64Bit() && Size >= 8)
1844     return MVT::i64;
1845   return MVT::i32;
1846 }
1847
1848 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1849   if (VT == MVT::f32)
1850     return X86ScalarSSEf32;
1851   else if (VT == MVT::f64)
1852     return X86ScalarSSEf64;
1853   return true;
1854 }
1855
1856 bool
1857 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1858                                                   unsigned,
1859                                                   unsigned,
1860                                                   bool *Fast) const {
1861   if (Fast)
1862     *Fast = Subtarget->isUnalignedMemAccessFast();
1863   return true;
1864 }
1865
1866 /// Return the entry encoding for a jump table in the
1867 /// current function.  The returned value is a member of the
1868 /// MachineJumpTableInfo::JTEntryKind enum.
1869 unsigned X86TargetLowering::getJumpTableEncoding() const {
1870   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1871   // symbol.
1872   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1873       Subtarget->isPICStyleGOT())
1874     return MachineJumpTableInfo::EK_Custom32;
1875
1876   // Otherwise, use the normal jump table encoding heuristics.
1877   return TargetLowering::getJumpTableEncoding();
1878 }
1879
1880 const MCExpr *
1881 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1882                                              const MachineBasicBlock *MBB,
1883                                              unsigned uid,MCContext &Ctx) const{
1884   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1885          Subtarget->isPICStyleGOT());
1886   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1887   // entries.
1888   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1889                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1890 }
1891
1892 /// Returns relocation base for the given PIC jumptable.
1893 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1894                                                     SelectionDAG &DAG) const {
1895   if (!Subtarget->is64Bit())
1896     // This doesn't have SDLoc associated with it, but is not really the
1897     // same as a Register.
1898     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1899   return Table;
1900 }
1901
1902 /// This returns the relocation base for the given PIC jumptable,
1903 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1904 const MCExpr *X86TargetLowering::
1905 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1906                              MCContext &Ctx) const {
1907   // X86-64 uses RIP relative addressing based on the jump table label.
1908   if (Subtarget->isPICStyleRIPRel())
1909     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1910
1911   // Otherwise, the reference is relative to the PIC base.
1912   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1913 }
1914
1915 // FIXME: Why this routine is here? Move to RegInfo!
1916 std::pair<const TargetRegisterClass*, uint8_t>
1917 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1918   const TargetRegisterClass *RRC = nullptr;
1919   uint8_t Cost = 1;
1920   switch (VT.SimpleTy) {
1921   default:
1922     return TargetLowering::findRepresentativeClass(VT);
1923   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1924     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1925     break;
1926   case MVT::x86mmx:
1927     RRC = &X86::VR64RegClass;
1928     break;
1929   case MVT::f32: case MVT::f64:
1930   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1931   case MVT::v4f32: case MVT::v2f64:
1932   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1933   case MVT::v4f64:
1934     RRC = &X86::VR128RegClass;
1935     break;
1936   }
1937   return std::make_pair(RRC, Cost);
1938 }
1939
1940 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1941                                                unsigned &Offset) const {
1942   if (!Subtarget->isTargetLinux())
1943     return false;
1944
1945   if (Subtarget->is64Bit()) {
1946     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1947     Offset = 0x28;
1948     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1949       AddressSpace = 256;
1950     else
1951       AddressSpace = 257;
1952   } else {
1953     // %gs:0x14 on i386
1954     Offset = 0x14;
1955     AddressSpace = 256;
1956   }
1957   return true;
1958 }
1959
1960 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1961                                             unsigned DestAS) const {
1962   assert(SrcAS != DestAS && "Expected different address spaces!");
1963
1964   return SrcAS < 256 && DestAS < 256;
1965 }
1966
1967 //===----------------------------------------------------------------------===//
1968 //               Return Value Calling Convention Implementation
1969 //===----------------------------------------------------------------------===//
1970
1971 #include "X86GenCallingConv.inc"
1972
1973 bool
1974 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1975                                   MachineFunction &MF, bool isVarArg,
1976                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1977                         LLVMContext &Context) const {
1978   SmallVector<CCValAssign, 16> RVLocs;
1979   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1980   return CCInfo.CheckReturn(Outs, RetCC_X86);
1981 }
1982
1983 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1984   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1985   return ScratchRegs;
1986 }
1987
1988 SDValue
1989 X86TargetLowering::LowerReturn(SDValue Chain,
1990                                CallingConv::ID CallConv, bool isVarArg,
1991                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1992                                const SmallVectorImpl<SDValue> &OutVals,
1993                                SDLoc dl, SelectionDAG &DAG) const {
1994   MachineFunction &MF = DAG.getMachineFunction();
1995   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1996
1997   SmallVector<CCValAssign, 16> RVLocs;
1998   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1999   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2000
2001   SDValue Flag;
2002   SmallVector<SDValue, 6> RetOps;
2003   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2004   // Operand #1 = Bytes To Pop
2005   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2006                    MVT::i16));
2007
2008   // Copy the result values into the output registers.
2009   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2010     CCValAssign &VA = RVLocs[i];
2011     assert(VA.isRegLoc() && "Can only return in registers!");
2012     SDValue ValToCopy = OutVals[i];
2013     EVT ValVT = ValToCopy.getValueType();
2014
2015     // Promote values to the appropriate types.
2016     if (VA.getLocInfo() == CCValAssign::SExt)
2017       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2018     else if (VA.getLocInfo() == CCValAssign::ZExt)
2019       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2020     else if (VA.getLocInfo() == CCValAssign::AExt)
2021       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2022     else if (VA.getLocInfo() == CCValAssign::BCvt)
2023       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2024
2025     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2026            "Unexpected FP-extend for return value.");
2027
2028     // If this is x86-64, and we disabled SSE, we can't return FP values,
2029     // or SSE or MMX vectors.
2030     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2031          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2032           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2033       report_fatal_error("SSE register return with SSE disabled");
2034     }
2035     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2036     // llvm-gcc has never done it right and no one has noticed, so this
2037     // should be OK for now.
2038     if (ValVT == MVT::f64 &&
2039         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2040       report_fatal_error("SSE2 register return with SSE2 disabled");
2041
2042     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2043     // the RET instruction and handled by the FP Stackifier.
2044     if (VA.getLocReg() == X86::FP0 ||
2045         VA.getLocReg() == X86::FP1) {
2046       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2047       // change the value to the FP stack register class.
2048       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2049         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2050       RetOps.push_back(ValToCopy);
2051       // Don't emit a copytoreg.
2052       continue;
2053     }
2054
2055     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2056     // which is returned in RAX / RDX.
2057     if (Subtarget->is64Bit()) {
2058       if (ValVT == MVT::x86mmx) {
2059         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2060           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2061           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2062                                   ValToCopy);
2063           // If we don't have SSE2 available, convert to v4f32 so the generated
2064           // register is legal.
2065           if (!Subtarget->hasSSE2())
2066             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2067         }
2068       }
2069     }
2070
2071     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2072     Flag = Chain.getValue(1);
2073     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2074   }
2075
2076   // The x86-64 ABIs require that for returning structs by value we copy
2077   // the sret argument into %rax/%eax (depending on ABI) for the return.
2078   // Win32 requires us to put the sret argument to %eax as well.
2079   // We saved the argument into a virtual register in the entry block,
2080   // so now we copy the value out and into %rax/%eax.
2081   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2082       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2083     MachineFunction &MF = DAG.getMachineFunction();
2084     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2085     unsigned Reg = FuncInfo->getSRetReturnReg();
2086     assert(Reg &&
2087            "SRetReturnReg should have been set in LowerFormalArguments().");
2088     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2089
2090     unsigned RetValReg
2091         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2092           X86::RAX : X86::EAX;
2093     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2094     Flag = Chain.getValue(1);
2095
2096     // RAX/EAX now acts like a return value.
2097     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2098   }
2099
2100   RetOps[0] = Chain;  // Update chain.
2101
2102   // Add the flag if we have it.
2103   if (Flag.getNode())
2104     RetOps.push_back(Flag);
2105
2106   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2107 }
2108
2109 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2110   if (N->getNumValues() != 1)
2111     return false;
2112   if (!N->hasNUsesOfValue(1, 0))
2113     return false;
2114
2115   SDValue TCChain = Chain;
2116   SDNode *Copy = *N->use_begin();
2117   if (Copy->getOpcode() == ISD::CopyToReg) {
2118     // If the copy has a glue operand, we conservatively assume it isn't safe to
2119     // perform a tail call.
2120     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2121       return false;
2122     TCChain = Copy->getOperand(0);
2123   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2124     return false;
2125
2126   bool HasRet = false;
2127   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2128        UI != UE; ++UI) {
2129     if (UI->getOpcode() != X86ISD::RET_FLAG)
2130       return false;
2131     // If we are returning more than one value, we can definitely
2132     // not make a tail call see PR19530
2133     if (UI->getNumOperands() > 4)
2134       return false;
2135     if (UI->getNumOperands() == 4 &&
2136         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2137       return false;
2138     HasRet = true;
2139   }
2140
2141   if (!HasRet)
2142     return false;
2143
2144   Chain = TCChain;
2145   return true;
2146 }
2147
2148 EVT
2149 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2150                                             ISD::NodeType ExtendKind) const {
2151   MVT ReturnMVT;
2152   // TODO: Is this also valid on 32-bit?
2153   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2154     ReturnMVT = MVT::i8;
2155   else
2156     ReturnMVT = MVT::i32;
2157
2158   EVT MinVT = getRegisterType(Context, ReturnMVT);
2159   return VT.bitsLT(MinVT) ? MinVT : VT;
2160 }
2161
2162 /// Lower the result values of a call into the
2163 /// appropriate copies out of appropriate physical registers.
2164 ///
2165 SDValue
2166 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2167                                    CallingConv::ID CallConv, bool isVarArg,
2168                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2169                                    SDLoc dl, SelectionDAG &DAG,
2170                                    SmallVectorImpl<SDValue> &InVals) const {
2171
2172   // Assign locations to each value returned by this call.
2173   SmallVector<CCValAssign, 16> RVLocs;
2174   bool Is64Bit = Subtarget->is64Bit();
2175   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2176                  *DAG.getContext());
2177   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2178
2179   // Copy all of the result registers out of their specified physreg.
2180   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2181     CCValAssign &VA = RVLocs[i];
2182     EVT CopyVT = VA.getValVT();
2183
2184     // If this is x86-64, and we disabled SSE, we can't return FP values
2185     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2186         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2187       report_fatal_error("SSE register return with SSE disabled");
2188     }
2189
2190     // If we prefer to use the value in xmm registers, copy it out as f80 and
2191     // use a truncate to move it from fp stack reg to xmm reg.
2192     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2193         isScalarFPTypeInSSEReg(VA.getValVT()))
2194       CopyVT = MVT::f80;
2195
2196     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2197                                CopyVT, InFlag).getValue(1);
2198     SDValue Val = Chain.getValue(0);
2199
2200     if (CopyVT != VA.getValVT())
2201       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2202                         // This truncation won't change the value.
2203                         DAG.getIntPtrConstant(1));
2204
2205     InFlag = Chain.getValue(2);
2206     InVals.push_back(Val);
2207   }
2208
2209   return Chain;
2210 }
2211
2212 //===----------------------------------------------------------------------===//
2213 //                C & StdCall & Fast Calling Convention implementation
2214 //===----------------------------------------------------------------------===//
2215 //  StdCall calling convention seems to be standard for many Windows' API
2216 //  routines and around. It differs from C calling convention just a little:
2217 //  callee should clean up the stack, not caller. Symbols should be also
2218 //  decorated in some fancy way :) It doesn't support any vector arguments.
2219 //  For info on fast calling convention see Fast Calling Convention (tail call)
2220 //  implementation LowerX86_32FastCCCallTo.
2221
2222 /// CallIsStructReturn - Determines whether a call uses struct return
2223 /// semantics.
2224 enum StructReturnType {
2225   NotStructReturn,
2226   RegStructReturn,
2227   StackStructReturn
2228 };
2229 static StructReturnType
2230 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2231   if (Outs.empty())
2232     return NotStructReturn;
2233
2234   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2235   if (!Flags.isSRet())
2236     return NotStructReturn;
2237   if (Flags.isInReg())
2238     return RegStructReturn;
2239   return StackStructReturn;
2240 }
2241
2242 /// Determines whether a function uses struct return semantics.
2243 static StructReturnType
2244 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2245   if (Ins.empty())
2246     return NotStructReturn;
2247
2248   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2249   if (!Flags.isSRet())
2250     return NotStructReturn;
2251   if (Flags.isInReg())
2252     return RegStructReturn;
2253   return StackStructReturn;
2254 }
2255
2256 /// Make a copy of an aggregate at address specified by "Src" to address
2257 /// "Dst" with size and alignment information specified by the specific
2258 /// parameter attribute. The copy will be passed as a byval function parameter.
2259 static SDValue
2260 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2261                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2262                           SDLoc dl) {
2263   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2264
2265   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2266                        /*isVolatile*/false, /*AlwaysInline=*/true,
2267                        MachinePointerInfo(), MachinePointerInfo());
2268 }
2269
2270 /// Return true if the calling convention is one that
2271 /// supports tail call optimization.
2272 static bool IsTailCallConvention(CallingConv::ID CC) {
2273   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2274           CC == CallingConv::HiPE);
2275 }
2276
2277 /// \brief Return true if the calling convention is a C calling convention.
2278 static bool IsCCallConvention(CallingConv::ID CC) {
2279   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2280           CC == CallingConv::X86_64_SysV);
2281 }
2282
2283 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2284   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2285     return false;
2286
2287   CallSite CS(CI);
2288   CallingConv::ID CalleeCC = CS.getCallingConv();
2289   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2290     return false;
2291
2292   return true;
2293 }
2294
2295 /// Return true if the function is being made into
2296 /// a tailcall target by changing its ABI.
2297 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2298                                    bool GuaranteedTailCallOpt) {
2299   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2300 }
2301
2302 SDValue
2303 X86TargetLowering::LowerMemArgument(SDValue Chain,
2304                                     CallingConv::ID CallConv,
2305                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2306                                     SDLoc dl, SelectionDAG &DAG,
2307                                     const CCValAssign &VA,
2308                                     MachineFrameInfo *MFI,
2309                                     unsigned i) const {
2310   // Create the nodes corresponding to a load from this parameter slot.
2311   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2312   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2313       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2314   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2315   EVT ValVT;
2316
2317   // If value is passed by pointer we have address passed instead of the value
2318   // itself.
2319   if (VA.getLocInfo() == CCValAssign::Indirect)
2320     ValVT = VA.getLocVT();
2321   else
2322     ValVT = VA.getValVT();
2323
2324   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2325   // changed with more analysis.
2326   // In case of tail call optimization mark all arguments mutable. Since they
2327   // could be overwritten by lowering of arguments in case of a tail call.
2328   if (Flags.isByVal()) {
2329     unsigned Bytes = Flags.getByValSize();
2330     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2331     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2332     return DAG.getFrameIndex(FI, getPointerTy());
2333   } else {
2334     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2335                                     VA.getLocMemOffset(), isImmutable);
2336     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2337     return DAG.getLoad(ValVT, dl, Chain, FIN,
2338                        MachinePointerInfo::getFixedStack(FI),
2339                        false, false, false, 0);
2340   }
2341 }
2342
2343 // FIXME: Get this from tablegen.
2344 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2345                                                 const X86Subtarget *Subtarget) {
2346   assert(Subtarget->is64Bit());
2347
2348   if (Subtarget->isCallingConvWin64(CallConv)) {
2349     static const MCPhysReg GPR64ArgRegsWin64[] = {
2350       X86::RCX, X86::RDX, X86::R8,  X86::R9
2351     };
2352     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2353   }
2354
2355   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2356     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2357   };
2358   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2359 }
2360
2361 // FIXME: Get this from tablegen.
2362 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2363                                                 CallingConv::ID CallConv,
2364                                                 const X86Subtarget *Subtarget) {
2365   assert(Subtarget->is64Bit());
2366   if (Subtarget->isCallingConvWin64(CallConv)) {
2367     // The XMM registers which might contain var arg parameters are shadowed
2368     // in their paired GPR.  So we only need to save the GPR to their home
2369     // slots.
2370     // TODO: __vectorcall will change this.
2371     return None;
2372   }
2373
2374   const Function *Fn = MF.getFunction();
2375   bool NoImplicitFloatOps = Fn->getAttributes().
2376       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2377   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2378          "SSE register cannot be used when SSE is disabled!");
2379   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2380       !Subtarget->hasSSE1())
2381     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2382     // registers.
2383     return None;
2384
2385   static const MCPhysReg XMMArgRegs64Bit[] = {
2386     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2387     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2388   };
2389   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2390 }
2391
2392 SDValue
2393 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2394                                         CallingConv::ID CallConv,
2395                                         bool isVarArg,
2396                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2397                                         SDLoc dl,
2398                                         SelectionDAG &DAG,
2399                                         SmallVectorImpl<SDValue> &InVals)
2400                                           const {
2401   MachineFunction &MF = DAG.getMachineFunction();
2402   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2403
2404   const Function* Fn = MF.getFunction();
2405   if (Fn->hasExternalLinkage() &&
2406       Subtarget->isTargetCygMing() &&
2407       Fn->getName() == "main")
2408     FuncInfo->setForceFramePointer(true);
2409
2410   MachineFrameInfo *MFI = MF.getFrameInfo();
2411   bool Is64Bit = Subtarget->is64Bit();
2412   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2413
2414   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2415          "Var args not supported with calling convention fastcc, ghc or hipe");
2416
2417   // Assign locations to all of the incoming arguments.
2418   SmallVector<CCValAssign, 16> ArgLocs;
2419   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2420
2421   // Allocate shadow area for Win64
2422   if (IsWin64)
2423     CCInfo.AllocateStack(32, 8);
2424
2425   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2426
2427   unsigned LastVal = ~0U;
2428   SDValue ArgValue;
2429   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2430     CCValAssign &VA = ArgLocs[i];
2431     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2432     // places.
2433     assert(VA.getValNo() != LastVal &&
2434            "Don't support value assigned to multiple locs yet");
2435     (void)LastVal;
2436     LastVal = VA.getValNo();
2437
2438     if (VA.isRegLoc()) {
2439       EVT RegVT = VA.getLocVT();
2440       const TargetRegisterClass *RC;
2441       if (RegVT == MVT::i32)
2442         RC = &X86::GR32RegClass;
2443       else if (Is64Bit && RegVT == MVT::i64)
2444         RC = &X86::GR64RegClass;
2445       else if (RegVT == MVT::f32)
2446         RC = &X86::FR32RegClass;
2447       else if (RegVT == MVT::f64)
2448         RC = &X86::FR64RegClass;
2449       else if (RegVT.is512BitVector())
2450         RC = &X86::VR512RegClass;
2451       else if (RegVT.is256BitVector())
2452         RC = &X86::VR256RegClass;
2453       else if (RegVT.is128BitVector())
2454         RC = &X86::VR128RegClass;
2455       else if (RegVT == MVT::x86mmx)
2456         RC = &X86::VR64RegClass;
2457       else if (RegVT == MVT::i1)
2458         RC = &X86::VK1RegClass;
2459       else if (RegVT == MVT::v8i1)
2460         RC = &X86::VK8RegClass;
2461       else if (RegVT == MVT::v16i1)
2462         RC = &X86::VK16RegClass;
2463       else if (RegVT == MVT::v32i1)
2464         RC = &X86::VK32RegClass;
2465       else if (RegVT == MVT::v64i1)
2466         RC = &X86::VK64RegClass;
2467       else
2468         llvm_unreachable("Unknown argument type!");
2469
2470       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2471       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2472
2473       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2474       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2475       // right size.
2476       if (VA.getLocInfo() == CCValAssign::SExt)
2477         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2478                                DAG.getValueType(VA.getValVT()));
2479       else if (VA.getLocInfo() == CCValAssign::ZExt)
2480         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2481                                DAG.getValueType(VA.getValVT()));
2482       else if (VA.getLocInfo() == CCValAssign::BCvt)
2483         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2484
2485       if (VA.isExtInLoc()) {
2486         // Handle MMX values passed in XMM regs.
2487         if (RegVT.isVector())
2488           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2489         else
2490           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2491       }
2492     } else {
2493       assert(VA.isMemLoc());
2494       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2495     }
2496
2497     // If value is passed via pointer - do a load.
2498     if (VA.getLocInfo() == CCValAssign::Indirect)
2499       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2500                              MachinePointerInfo(), false, false, false, 0);
2501
2502     InVals.push_back(ArgValue);
2503   }
2504
2505   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2506     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2507       // The x86-64 ABIs require that for returning structs by value we copy
2508       // the sret argument into %rax/%eax (depending on ABI) for the return.
2509       // Win32 requires us to put the sret argument to %eax as well.
2510       // Save the argument into a virtual register so that we can access it
2511       // from the return points.
2512       if (Ins[i].Flags.isSRet()) {
2513         unsigned Reg = FuncInfo->getSRetReturnReg();
2514         if (!Reg) {
2515           MVT PtrTy = getPointerTy();
2516           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2517           FuncInfo->setSRetReturnReg(Reg);
2518         }
2519         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2520         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2521         break;
2522       }
2523     }
2524   }
2525
2526   unsigned StackSize = CCInfo.getNextStackOffset();
2527   // Align stack specially for tail calls.
2528   if (FuncIsMadeTailCallSafe(CallConv,
2529                              MF.getTarget().Options.GuaranteedTailCallOpt))
2530     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2531
2532   // If the function takes variable number of arguments, make a frame index for
2533   // the start of the first vararg value... for expansion of llvm.va_start. We
2534   // can skip this if there are no va_start calls.
2535   if (MFI->hasVAStart() &&
2536       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2537                    CallConv != CallingConv::X86_ThisCall))) {
2538     FuncInfo->setVarArgsFrameIndex(
2539         MFI->CreateFixedObject(1, StackSize, true));
2540   }
2541
2542   // 64-bit calling conventions support varargs and register parameters, so we
2543   // have to do extra work to spill them in the prologue or forward them to
2544   // musttail calls.
2545   if (Is64Bit && isVarArg &&
2546       (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2547     // Find the first unallocated argument registers.
2548     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2549     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2550     unsigned NumIntRegs =
2551         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2552     unsigned NumXMMRegs =
2553         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2554     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2555            "SSE register cannot be used when SSE is disabled!");
2556
2557     // Gather all the live in physical registers.
2558     SmallVector<SDValue, 6> LiveGPRs;
2559     SmallVector<SDValue, 8> LiveXMMRegs;
2560     SDValue ALVal;
2561     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2562       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2563       LiveGPRs.push_back(
2564           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2565     }
2566     if (!ArgXMMs.empty()) {
2567       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2568       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2569       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2570         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2571         LiveXMMRegs.push_back(
2572             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2573       }
2574     }
2575
2576     // Store them to the va_list returned by va_start.
2577     if (MFI->hasVAStart()) {
2578       if (IsWin64) {
2579         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2580         // Get to the caller-allocated home save location.  Add 8 to account
2581         // for the return address.
2582         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2583         FuncInfo->setRegSaveFrameIndex(
2584           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2585         // Fixup to set vararg frame on shadow area (4 x i64).
2586         if (NumIntRegs < 4)
2587           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2588       } else {
2589         // For X86-64, if there are vararg parameters that are passed via
2590         // registers, then we must store them to their spots on the stack so
2591         // they may be loaded by deferencing the result of va_next.
2592         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2593         FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2594         FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2595             ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2596       }
2597
2598       // Store the integer parameter registers.
2599       SmallVector<SDValue, 8> MemOps;
2600       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2601                                         getPointerTy());
2602       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2603       for (SDValue Val : LiveGPRs) {
2604         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2605                                   DAG.getIntPtrConstant(Offset));
2606         SDValue Store =
2607           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2608                        MachinePointerInfo::getFixedStack(
2609                          FuncInfo->getRegSaveFrameIndex(), Offset),
2610                        false, false, 0);
2611         MemOps.push_back(Store);
2612         Offset += 8;
2613       }
2614
2615       if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2616         // Now store the XMM (fp + vector) parameter registers.
2617         SmallVector<SDValue, 12> SaveXMMOps;
2618         SaveXMMOps.push_back(Chain);
2619         SaveXMMOps.push_back(ALVal);
2620         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2621                                FuncInfo->getRegSaveFrameIndex()));
2622         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2623                                FuncInfo->getVarArgsFPOffset()));
2624         SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2625                           LiveXMMRegs.end());
2626         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2627                                      MVT::Other, SaveXMMOps));
2628       }
2629
2630       if (!MemOps.empty())
2631         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2632     } else {
2633       // Add all GPRs, al, and XMMs to the list of forwards.  We will add then
2634       // to the liveout set on a musttail call.
2635       assert(MFI->hasMustTailInVarArgFunc());
2636       auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2637       typedef X86MachineFunctionInfo::Forward Forward;
2638
2639       for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2640         unsigned VReg =
2641             MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2642         Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2643         Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2644       }
2645
2646       if (!ArgXMMs.empty()) {
2647         unsigned ALVReg =
2648             MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2649         Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2650         Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2651
2652         for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2653           unsigned VReg =
2654               MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2655           Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2656           Forwards.push_back(
2657               Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2658         }
2659       }
2660     }
2661   }
2662
2663   // Some CCs need callee pop.
2664   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2665                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2666     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2667   } else {
2668     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2669     // If this is an sret function, the return should pop the hidden pointer.
2670     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2671         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2672         argsAreStructReturn(Ins) == StackStructReturn)
2673       FuncInfo->setBytesToPopOnReturn(4);
2674   }
2675
2676   if (!Is64Bit) {
2677     // RegSaveFrameIndex is X86-64 only.
2678     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2679     if (CallConv == CallingConv::X86_FastCall ||
2680         CallConv == CallingConv::X86_ThisCall)
2681       // fastcc functions can't have varargs.
2682       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2683   }
2684
2685   FuncInfo->setArgumentStackSize(StackSize);
2686
2687   return Chain;
2688 }
2689
2690 SDValue
2691 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2692                                     SDValue StackPtr, SDValue Arg,
2693                                     SDLoc dl, SelectionDAG &DAG,
2694                                     const CCValAssign &VA,
2695                                     ISD::ArgFlagsTy Flags) const {
2696   unsigned LocMemOffset = VA.getLocMemOffset();
2697   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2698   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2699   if (Flags.isByVal())
2700     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2701
2702   return DAG.getStore(Chain, dl, Arg, PtrOff,
2703                       MachinePointerInfo::getStack(LocMemOffset),
2704                       false, false, 0);
2705 }
2706
2707 /// Emit a load of return address if tail call
2708 /// optimization is performed and it is required.
2709 SDValue
2710 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2711                                            SDValue &OutRetAddr, SDValue Chain,
2712                                            bool IsTailCall, bool Is64Bit,
2713                                            int FPDiff, SDLoc dl) const {
2714   // Adjust the Return address stack slot.
2715   EVT VT = getPointerTy();
2716   OutRetAddr = getReturnAddressFrameIndex(DAG);
2717
2718   // Load the "old" Return address.
2719   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2720                            false, false, false, 0);
2721   return SDValue(OutRetAddr.getNode(), 1);
2722 }
2723
2724 /// Emit a store of the return address if tail call
2725 /// optimization is performed and it is required (FPDiff!=0).
2726 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2727                                         SDValue Chain, SDValue RetAddrFrIdx,
2728                                         EVT PtrVT, unsigned SlotSize,
2729                                         int FPDiff, SDLoc dl) {
2730   // Store the return address to the appropriate stack slot.
2731   if (!FPDiff) return Chain;
2732   // Calculate the new stack slot for the return address.
2733   int NewReturnAddrFI =
2734     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2735                                          false);
2736   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2737   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2738                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2739                        false, false, 0);
2740   return Chain;
2741 }
2742
2743 SDValue
2744 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2745                              SmallVectorImpl<SDValue> &InVals) const {
2746   SelectionDAG &DAG                     = CLI.DAG;
2747   SDLoc &dl                             = CLI.DL;
2748   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2749   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2750   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2751   SDValue Chain                         = CLI.Chain;
2752   SDValue Callee                        = CLI.Callee;
2753   CallingConv::ID CallConv              = CLI.CallConv;
2754   bool &isTailCall                      = CLI.IsTailCall;
2755   bool isVarArg                         = CLI.IsVarArg;
2756
2757   MachineFunction &MF = DAG.getMachineFunction();
2758   bool Is64Bit        = Subtarget->is64Bit();
2759   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2760   StructReturnType SR = callIsStructReturn(Outs);
2761   bool IsSibcall      = false;
2762   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2763
2764   if (MF.getTarget().Options.DisableTailCalls)
2765     isTailCall = false;
2766
2767   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2768   if (IsMustTail) {
2769     // Force this to be a tail call.  The verifier rules are enough to ensure
2770     // that we can lower this successfully without moving the return address
2771     // around.
2772     isTailCall = true;
2773   } else if (isTailCall) {
2774     // Check if it's really possible to do a tail call.
2775     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2776                     isVarArg, SR != NotStructReturn,
2777                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2778                     Outs, OutVals, Ins, DAG);
2779
2780     // Sibcalls are automatically detected tailcalls which do not require
2781     // ABI changes.
2782     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2783       IsSibcall = true;
2784
2785     if (isTailCall)
2786       ++NumTailCalls;
2787   }
2788
2789   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2790          "Var args not supported with calling convention fastcc, ghc or hipe");
2791
2792   // Analyze operands of the call, assigning locations to each operand.
2793   SmallVector<CCValAssign, 16> ArgLocs;
2794   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2795
2796   // Allocate shadow area for Win64
2797   if (IsWin64)
2798     CCInfo.AllocateStack(32, 8);
2799
2800   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2801
2802   // Get a count of how many bytes are to be pushed on the stack.
2803   unsigned NumBytes = CCInfo.getNextStackOffset();
2804   if (IsSibcall)
2805     // This is a sibcall. The memory operands are available in caller's
2806     // own caller's stack.
2807     NumBytes = 0;
2808   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2809            IsTailCallConvention(CallConv))
2810     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2811
2812   int FPDiff = 0;
2813   if (isTailCall && !IsSibcall && !IsMustTail) {
2814     // Lower arguments at fp - stackoffset + fpdiff.
2815     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2816
2817     FPDiff = NumBytesCallerPushed - NumBytes;
2818
2819     // Set the delta of movement of the returnaddr stackslot.
2820     // But only set if delta is greater than previous delta.
2821     if (FPDiff < X86Info->getTCReturnAddrDelta())
2822       X86Info->setTCReturnAddrDelta(FPDiff);
2823   }
2824
2825   unsigned NumBytesToPush = NumBytes;
2826   unsigned NumBytesToPop = NumBytes;
2827
2828   // If we have an inalloca argument, all stack space has already been allocated
2829   // for us and be right at the top of the stack.  We don't support multiple
2830   // arguments passed in memory when using inalloca.
2831   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2832     NumBytesToPush = 0;
2833     if (!ArgLocs.back().isMemLoc())
2834       report_fatal_error("cannot use inalloca attribute on a register "
2835                          "parameter");
2836     if (ArgLocs.back().getLocMemOffset() != 0)
2837       report_fatal_error("any parameter with the inalloca attribute must be "
2838                          "the only memory argument");
2839   }
2840
2841   if (!IsSibcall)
2842     Chain = DAG.getCALLSEQ_START(
2843         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2844
2845   SDValue RetAddrFrIdx;
2846   // Load return address for tail calls.
2847   if (isTailCall && FPDiff)
2848     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2849                                     Is64Bit, FPDiff, dl);
2850
2851   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2852   SmallVector<SDValue, 8> MemOpChains;
2853   SDValue StackPtr;
2854
2855   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2856   // of tail call optimization arguments are handle later.
2857   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2858       DAG.getSubtarget().getRegisterInfo());
2859   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2860     // Skip inalloca arguments, they have already been written.
2861     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2862     if (Flags.isInAlloca())
2863       continue;
2864
2865     CCValAssign &VA = ArgLocs[i];
2866     EVT RegVT = VA.getLocVT();
2867     SDValue Arg = OutVals[i];
2868     bool isByVal = Flags.isByVal();
2869
2870     // Promote the value if needed.
2871     switch (VA.getLocInfo()) {
2872     default: llvm_unreachable("Unknown loc info!");
2873     case CCValAssign::Full: break;
2874     case CCValAssign::SExt:
2875       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2876       break;
2877     case CCValAssign::ZExt:
2878       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2879       break;
2880     case CCValAssign::AExt:
2881       if (RegVT.is128BitVector()) {
2882         // Special case: passing MMX values in XMM registers.
2883         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2884         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2885         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2886       } else
2887         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2888       break;
2889     case CCValAssign::BCvt:
2890       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2891       break;
2892     case CCValAssign::Indirect: {
2893       // Store the argument.
2894       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2895       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2896       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2897                            MachinePointerInfo::getFixedStack(FI),
2898                            false, false, 0);
2899       Arg = SpillSlot;
2900       break;
2901     }
2902     }
2903
2904     if (VA.isRegLoc()) {
2905       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2906       if (isVarArg && IsWin64) {
2907         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2908         // shadow reg if callee is a varargs function.
2909         unsigned ShadowReg = 0;
2910         switch (VA.getLocReg()) {
2911         case X86::XMM0: ShadowReg = X86::RCX; break;
2912         case X86::XMM1: ShadowReg = X86::RDX; break;
2913         case X86::XMM2: ShadowReg = X86::R8; break;
2914         case X86::XMM3: ShadowReg = X86::R9; break;
2915         }
2916         if (ShadowReg)
2917           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2918       }
2919     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2920       assert(VA.isMemLoc());
2921       if (!StackPtr.getNode())
2922         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2923                                       getPointerTy());
2924       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2925                                              dl, DAG, VA, Flags));
2926     }
2927   }
2928
2929   if (!MemOpChains.empty())
2930     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2931
2932   if (Subtarget->isPICStyleGOT()) {
2933     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2934     // GOT pointer.
2935     if (!isTailCall) {
2936       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2937                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2938     } else {
2939       // If we are tail calling and generating PIC/GOT style code load the
2940       // address of the callee into ECX. The value in ecx is used as target of
2941       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2942       // for tail calls on PIC/GOT architectures. Normally we would just put the
2943       // address of GOT into ebx and then call target@PLT. But for tail calls
2944       // ebx would be restored (since ebx is callee saved) before jumping to the
2945       // target@PLT.
2946
2947       // Note: The actual moving to ECX is done further down.
2948       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2949       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2950           !G->getGlobal()->hasProtectedVisibility())
2951         Callee = LowerGlobalAddress(Callee, DAG);
2952       else if (isa<ExternalSymbolSDNode>(Callee))
2953         Callee = LowerExternalSymbol(Callee, DAG);
2954     }
2955   }
2956
2957   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2958     // From AMD64 ABI document:
2959     // For calls that may call functions that use varargs or stdargs
2960     // (prototype-less calls or calls to functions containing ellipsis (...) in
2961     // the declaration) %al is used as hidden argument to specify the number
2962     // of SSE registers used. The contents of %al do not need to match exactly
2963     // the number of registers, but must be an ubound on the number of SSE
2964     // registers used and is in the range 0 - 8 inclusive.
2965
2966     // Count the number of XMM registers allocated.
2967     static const MCPhysReg XMMArgRegs[] = {
2968       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2969       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2970     };
2971     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2972     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2973            && "SSE registers cannot be used when SSE is disabled");
2974
2975     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2976                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2977   }
2978
2979   if (Is64Bit && isVarArg && IsMustTail) {
2980     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2981     for (const auto &F : Forwards) {
2982       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2983       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2984     }
2985   }
2986
2987   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2988   // don't need this because the eligibility check rejects calls that require
2989   // shuffling arguments passed in memory.
2990   if (!IsSibcall && isTailCall) {
2991     // Force all the incoming stack arguments to be loaded from the stack
2992     // before any new outgoing arguments are stored to the stack, because the
2993     // outgoing stack slots may alias the incoming argument stack slots, and
2994     // the alias isn't otherwise explicit. This is slightly more conservative
2995     // than necessary, because it means that each store effectively depends
2996     // on every argument instead of just those arguments it would clobber.
2997     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2998
2999     SmallVector<SDValue, 8> MemOpChains2;
3000     SDValue FIN;
3001     int FI = 0;
3002     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3003       CCValAssign &VA = ArgLocs[i];
3004       if (VA.isRegLoc())
3005         continue;
3006       assert(VA.isMemLoc());
3007       SDValue Arg = OutVals[i];
3008       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3009       // Skip inalloca arguments.  They don't require any work.
3010       if (Flags.isInAlloca())
3011         continue;
3012       // Create frame index.
3013       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3014       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3015       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3016       FIN = DAG.getFrameIndex(FI, getPointerTy());
3017
3018       if (Flags.isByVal()) {
3019         // Copy relative to framepointer.
3020         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3021         if (!StackPtr.getNode())
3022           StackPtr = DAG.getCopyFromReg(Chain, dl,
3023                                         RegInfo->getStackRegister(),
3024                                         getPointerTy());
3025         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3026
3027         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3028                                                          ArgChain,
3029                                                          Flags, DAG, dl));
3030       } else {
3031         // Store relative to framepointer.
3032         MemOpChains2.push_back(
3033           DAG.getStore(ArgChain, dl, Arg, FIN,
3034                        MachinePointerInfo::getFixedStack(FI),
3035                        false, false, 0));
3036       }
3037     }
3038
3039     if (!MemOpChains2.empty())
3040       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3041
3042     // Store the return address to the appropriate stack slot.
3043     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3044                                      getPointerTy(), RegInfo->getSlotSize(),
3045                                      FPDiff, dl);
3046   }
3047
3048   // Build a sequence of copy-to-reg nodes chained together with token chain
3049   // and flag operands which copy the outgoing args into registers.
3050   SDValue InFlag;
3051   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3052     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3053                              RegsToPass[i].second, InFlag);
3054     InFlag = Chain.getValue(1);
3055   }
3056
3057   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3058     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3059     // In the 64-bit large code model, we have to make all calls
3060     // through a register, since the call instruction's 32-bit
3061     // pc-relative offset may not be large enough to hold the whole
3062     // address.
3063   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3064     // If the callee is a GlobalAddress node (quite common, every direct call
3065     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3066     // it.
3067
3068     // We should use extra load for direct calls to dllimported functions in
3069     // non-JIT mode.
3070     const GlobalValue *GV = G->getGlobal();
3071     if (!GV->hasDLLImportStorageClass()) {
3072       unsigned char OpFlags = 0;
3073       bool ExtraLoad = false;
3074       unsigned WrapperKind = ISD::DELETED_NODE;
3075
3076       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3077       // external symbols most go through the PLT in PIC mode.  If the symbol
3078       // has hidden or protected visibility, or if it is static or local, then
3079       // we don't need to use the PLT - we can directly call it.
3080       if (Subtarget->isTargetELF() &&
3081           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3082           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3083         OpFlags = X86II::MO_PLT;
3084       } else if (Subtarget->isPICStyleStubAny() &&
3085                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3086                  (!Subtarget->getTargetTriple().isMacOSX() ||
3087                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3088         // PC-relative references to external symbols should go through $stub,
3089         // unless we're building with the leopard linker or later, which
3090         // automatically synthesizes these stubs.
3091         OpFlags = X86II::MO_DARWIN_STUB;
3092       } else if (Subtarget->isPICStyleRIPRel() &&
3093                  isa<Function>(GV) &&
3094                  cast<Function>(GV)->getAttributes().
3095                    hasAttribute(AttributeSet::FunctionIndex,
3096                                 Attribute::NonLazyBind)) {
3097         // If the function is marked as non-lazy, generate an indirect call
3098         // which loads from the GOT directly. This avoids runtime overhead
3099         // at the cost of eager binding (and one extra byte of encoding).
3100         OpFlags = X86II::MO_GOTPCREL;
3101         WrapperKind = X86ISD::WrapperRIP;
3102         ExtraLoad = true;
3103       }
3104
3105       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3106                                           G->getOffset(), OpFlags);
3107
3108       // Add a wrapper if needed.
3109       if (WrapperKind != ISD::DELETED_NODE)
3110         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3111       // Add extra indirection if needed.
3112       if (ExtraLoad)
3113         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3114                              MachinePointerInfo::getGOT(),
3115                              false, false, false, 0);
3116     }
3117   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3118     unsigned char OpFlags = 0;
3119
3120     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3121     // external symbols should go through the PLT.
3122     if (Subtarget->isTargetELF() &&
3123         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3124       OpFlags = X86II::MO_PLT;
3125     } else if (Subtarget->isPICStyleStubAny() &&
3126                (!Subtarget->getTargetTriple().isMacOSX() ||
3127                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3128       // PC-relative references to external symbols should go through $stub,
3129       // unless we're building with the leopard linker or later, which
3130       // automatically synthesizes these stubs.
3131       OpFlags = X86II::MO_DARWIN_STUB;
3132     }
3133
3134     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3135                                          OpFlags);
3136   } else if (Subtarget->isTarget64BitILP32() && Callee->getValueType(0) == MVT::i32) {
3137     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3138     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3139   }
3140
3141   // Returns a chain & a flag for retval copy to use.
3142   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3143   SmallVector<SDValue, 8> Ops;
3144
3145   if (!IsSibcall && isTailCall) {
3146     Chain = DAG.getCALLSEQ_END(Chain,
3147                                DAG.getIntPtrConstant(NumBytesToPop, true),
3148                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3149     InFlag = Chain.getValue(1);
3150   }
3151
3152   Ops.push_back(Chain);
3153   Ops.push_back(Callee);
3154
3155   if (isTailCall)
3156     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3157
3158   // Add argument registers to the end of the list so that they are known live
3159   // into the call.
3160   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3161     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3162                                   RegsToPass[i].second.getValueType()));
3163
3164   // Add a register mask operand representing the call-preserved registers.
3165   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3166   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3167   assert(Mask && "Missing call preserved mask for calling convention");
3168   Ops.push_back(DAG.getRegisterMask(Mask));
3169
3170   if (InFlag.getNode())
3171     Ops.push_back(InFlag);
3172
3173   if (isTailCall) {
3174     // We used to do:
3175     //// If this is the first return lowered for this function, add the regs
3176     //// to the liveout set for the function.
3177     // This isn't right, although it's probably harmless on x86; liveouts
3178     // should be computed from returns not tail calls.  Consider a void
3179     // function making a tail call to a function returning int.
3180     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3181   }
3182
3183   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3184   InFlag = Chain.getValue(1);
3185
3186   // Create the CALLSEQ_END node.
3187   unsigned NumBytesForCalleeToPop;
3188   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3189                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3190     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3191   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3192            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3193            SR == StackStructReturn)
3194     // If this is a call to a struct-return function, the callee
3195     // pops the hidden struct pointer, so we have to push it back.
3196     // This is common for Darwin/X86, Linux & Mingw32 targets.
3197     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3198     NumBytesForCalleeToPop = 4;
3199   else
3200     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3201
3202   // Returns a flag for retval copy to use.
3203   if (!IsSibcall) {
3204     Chain = DAG.getCALLSEQ_END(Chain,
3205                                DAG.getIntPtrConstant(NumBytesToPop, true),
3206                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3207                                                      true),
3208                                InFlag, dl);
3209     InFlag = Chain.getValue(1);
3210   }
3211
3212   // Handle result values, copying them out of physregs into vregs that we
3213   // return.
3214   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3215                          Ins, dl, DAG, InVals);
3216 }
3217
3218 //===----------------------------------------------------------------------===//
3219 //                Fast Calling Convention (tail call) implementation
3220 //===----------------------------------------------------------------------===//
3221
3222 //  Like std call, callee cleans arguments, convention except that ECX is
3223 //  reserved for storing the tail called function address. Only 2 registers are
3224 //  free for argument passing (inreg). Tail call optimization is performed
3225 //  provided:
3226 //                * tailcallopt is enabled
3227 //                * caller/callee are fastcc
3228 //  On X86_64 architecture with GOT-style position independent code only local
3229 //  (within module) calls are supported at the moment.
3230 //  To keep the stack aligned according to platform abi the function
3231 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3232 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3233 //  If a tail called function callee has more arguments than the caller the
3234 //  caller needs to make sure that there is room to move the RETADDR to. This is
3235 //  achieved by reserving an area the size of the argument delta right after the
3236 //  original RETADDR, but before the saved framepointer or the spilled registers
3237 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3238 //  stack layout:
3239 //    arg1
3240 //    arg2
3241 //    RETADDR
3242 //    [ new RETADDR
3243 //      move area ]
3244 //    (possible EBP)
3245 //    ESI
3246 //    EDI
3247 //    local1 ..
3248
3249 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3250 /// for a 16 byte align requirement.
3251 unsigned
3252 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3253                                                SelectionDAG& DAG) const {
3254   MachineFunction &MF = DAG.getMachineFunction();
3255   const TargetMachine &TM = MF.getTarget();
3256   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3257       TM.getSubtargetImpl()->getRegisterInfo());
3258   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3259   unsigned StackAlignment = TFI.getStackAlignment();
3260   uint64_t AlignMask = StackAlignment - 1;
3261   int64_t Offset = StackSize;
3262   unsigned SlotSize = RegInfo->getSlotSize();
3263   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3264     // Number smaller than 12 so just add the difference.
3265     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3266   } else {
3267     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3268     Offset = ((~AlignMask) & Offset) + StackAlignment +
3269       (StackAlignment-SlotSize);
3270   }
3271   return Offset;
3272 }
3273
3274 /// MatchingStackOffset - Return true if the given stack call argument is
3275 /// already available in the same position (relatively) of the caller's
3276 /// incoming argument stack.
3277 static
3278 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3279                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3280                          const X86InstrInfo *TII) {
3281   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3282   int FI = INT_MAX;
3283   if (Arg.getOpcode() == ISD::CopyFromReg) {
3284     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3285     if (!TargetRegisterInfo::isVirtualRegister(VR))
3286       return false;
3287     MachineInstr *Def = MRI->getVRegDef(VR);
3288     if (!Def)
3289       return false;
3290     if (!Flags.isByVal()) {
3291       if (!TII->isLoadFromStackSlot(Def, FI))
3292         return false;
3293     } else {
3294       unsigned Opcode = Def->getOpcode();
3295       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3296           Def->getOperand(1).isFI()) {
3297         FI = Def->getOperand(1).getIndex();
3298         Bytes = Flags.getByValSize();
3299       } else
3300         return false;
3301     }
3302   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3303     if (Flags.isByVal())
3304       // ByVal argument is passed in as a pointer but it's now being
3305       // dereferenced. e.g.
3306       // define @foo(%struct.X* %A) {
3307       //   tail call @bar(%struct.X* byval %A)
3308       // }
3309       return false;
3310     SDValue Ptr = Ld->getBasePtr();
3311     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3312     if (!FINode)
3313       return false;
3314     FI = FINode->getIndex();
3315   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3316     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3317     FI = FINode->getIndex();
3318     Bytes = Flags.getByValSize();
3319   } else
3320     return false;
3321
3322   assert(FI != INT_MAX);
3323   if (!MFI->isFixedObjectIndex(FI))
3324     return false;
3325   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3326 }
3327
3328 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3329 /// for tail call optimization. Targets which want to do tail call
3330 /// optimization should implement this function.
3331 bool
3332 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3333                                                      CallingConv::ID CalleeCC,
3334                                                      bool isVarArg,
3335                                                      bool isCalleeStructRet,
3336                                                      bool isCallerStructRet,
3337                                                      Type *RetTy,
3338                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3339                                     const SmallVectorImpl<SDValue> &OutVals,
3340                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3341                                                      SelectionDAG &DAG) const {
3342   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3343     return false;
3344
3345   // If -tailcallopt is specified, make fastcc functions tail-callable.
3346   const MachineFunction &MF = DAG.getMachineFunction();
3347   const Function *CallerF = MF.getFunction();
3348
3349   // If the function return type is x86_fp80 and the callee return type is not,
3350   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3351   // perform a tailcall optimization here.
3352   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3353     return false;
3354
3355   CallingConv::ID CallerCC = CallerF->getCallingConv();
3356   bool CCMatch = CallerCC == CalleeCC;
3357   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3358   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3359
3360   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3361     if (IsTailCallConvention(CalleeCC) && CCMatch)
3362       return true;
3363     return false;
3364   }
3365
3366   // Look for obvious safe cases to perform tail call optimization that do not
3367   // require ABI changes. This is what gcc calls sibcall.
3368
3369   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3370   // emit a special epilogue.
3371   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3372       DAG.getSubtarget().getRegisterInfo());
3373   if (RegInfo->needsStackRealignment(MF))
3374     return false;
3375
3376   // Also avoid sibcall optimization if either caller or callee uses struct
3377   // return semantics.
3378   if (isCalleeStructRet || isCallerStructRet)
3379     return false;
3380
3381   // An stdcall/thiscall caller is expected to clean up its arguments; the
3382   // callee isn't going to do that.
3383   // FIXME: this is more restrictive than needed. We could produce a tailcall
3384   // when the stack adjustment matches. For example, with a thiscall that takes
3385   // only one argument.
3386   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3387                    CallerCC == CallingConv::X86_ThisCall))
3388     return false;
3389
3390   // Do not sibcall optimize vararg calls unless all arguments are passed via
3391   // registers.
3392   if (isVarArg && !Outs.empty()) {
3393
3394     // Optimizing for varargs on Win64 is unlikely to be safe without
3395     // additional testing.
3396     if (IsCalleeWin64 || IsCallerWin64)
3397       return false;
3398
3399     SmallVector<CCValAssign, 16> ArgLocs;
3400     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3401                    *DAG.getContext());
3402
3403     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3404     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3405       if (!ArgLocs[i].isRegLoc())
3406         return false;
3407   }
3408
3409   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3410   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3411   // this into a sibcall.
3412   bool Unused = false;
3413   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3414     if (!Ins[i].Used) {
3415       Unused = true;
3416       break;
3417     }
3418   }
3419   if (Unused) {
3420     SmallVector<CCValAssign, 16> RVLocs;
3421     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3422                    *DAG.getContext());
3423     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3424     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3425       CCValAssign &VA = RVLocs[i];
3426       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3427         return false;
3428     }
3429   }
3430
3431   // If the calling conventions do not match, then we'd better make sure the
3432   // results are returned in the same way as what the caller expects.
3433   if (!CCMatch) {
3434     SmallVector<CCValAssign, 16> RVLocs1;
3435     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3436                     *DAG.getContext());
3437     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3438
3439     SmallVector<CCValAssign, 16> RVLocs2;
3440     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3441                     *DAG.getContext());
3442     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3443
3444     if (RVLocs1.size() != RVLocs2.size())
3445       return false;
3446     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3447       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3448         return false;
3449       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3450         return false;
3451       if (RVLocs1[i].isRegLoc()) {
3452         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3453           return false;
3454       } else {
3455         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3456           return false;
3457       }
3458     }
3459   }
3460
3461   // If the callee takes no arguments then go on to check the results of the
3462   // call.
3463   if (!Outs.empty()) {
3464     // Check if stack adjustment is needed. For now, do not do this if any
3465     // argument is passed on the stack.
3466     SmallVector<CCValAssign, 16> ArgLocs;
3467     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3468                    *DAG.getContext());
3469
3470     // Allocate shadow area for Win64
3471     if (IsCalleeWin64)
3472       CCInfo.AllocateStack(32, 8);
3473
3474     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3475     if (CCInfo.getNextStackOffset()) {
3476       MachineFunction &MF = DAG.getMachineFunction();
3477       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3478         return false;
3479
3480       // Check if the arguments are already laid out in the right way as
3481       // the caller's fixed stack objects.
3482       MachineFrameInfo *MFI = MF.getFrameInfo();
3483       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3484       const X86InstrInfo *TII =
3485           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3486       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3487         CCValAssign &VA = ArgLocs[i];
3488         SDValue Arg = OutVals[i];
3489         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3490         if (VA.getLocInfo() == CCValAssign::Indirect)
3491           return false;
3492         if (!VA.isRegLoc()) {
3493           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3494                                    MFI, MRI, TII))
3495             return false;
3496         }
3497       }
3498     }
3499
3500     // If the tailcall address may be in a register, then make sure it's
3501     // possible to register allocate for it. In 32-bit, the call address can
3502     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3503     // callee-saved registers are restored. These happen to be the same
3504     // registers used to pass 'inreg' arguments so watch out for those.
3505     if (!Subtarget->is64Bit() &&
3506         ((!isa<GlobalAddressSDNode>(Callee) &&
3507           !isa<ExternalSymbolSDNode>(Callee)) ||
3508          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3509       unsigned NumInRegs = 0;
3510       // In PIC we need an extra register to formulate the address computation
3511       // for the callee.
3512       unsigned MaxInRegs =
3513         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3514
3515       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3516         CCValAssign &VA = ArgLocs[i];
3517         if (!VA.isRegLoc())
3518           continue;
3519         unsigned Reg = VA.getLocReg();
3520         switch (Reg) {
3521         default: break;
3522         case X86::EAX: case X86::EDX: case X86::ECX:
3523           if (++NumInRegs == MaxInRegs)
3524             return false;
3525           break;
3526         }
3527       }
3528     }
3529   }
3530
3531   return true;
3532 }
3533
3534 FastISel *
3535 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3536                                   const TargetLibraryInfo *libInfo) const {
3537   return X86::createFastISel(funcInfo, libInfo);
3538 }
3539
3540 //===----------------------------------------------------------------------===//
3541 //                           Other Lowering Hooks
3542 //===----------------------------------------------------------------------===//
3543
3544 static bool MayFoldLoad(SDValue Op) {
3545   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3546 }
3547
3548 static bool MayFoldIntoStore(SDValue Op) {
3549   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3550 }
3551
3552 static bool isTargetShuffle(unsigned Opcode) {
3553   switch(Opcode) {
3554   default: return false;
3555   case X86ISD::BLENDI:
3556   case X86ISD::PSHUFB:
3557   case X86ISD::PSHUFD:
3558   case X86ISD::PSHUFHW:
3559   case X86ISD::PSHUFLW:
3560   case X86ISD::SHUFP:
3561   case X86ISD::PALIGNR:
3562   case X86ISD::MOVLHPS:
3563   case X86ISD::MOVLHPD:
3564   case X86ISD::MOVHLPS:
3565   case X86ISD::MOVLPS:
3566   case X86ISD::MOVLPD:
3567   case X86ISD::MOVSHDUP:
3568   case X86ISD::MOVSLDUP:
3569   case X86ISD::MOVDDUP:
3570   case X86ISD::MOVSS:
3571   case X86ISD::MOVSD:
3572   case X86ISD::UNPCKL:
3573   case X86ISD::UNPCKH:
3574   case X86ISD::VPERMILPI:
3575   case X86ISD::VPERM2X128:
3576   case X86ISD::VPERMI:
3577     return true;
3578   }
3579 }
3580
3581 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3582                                     SDValue V1, SelectionDAG &DAG) {
3583   switch(Opc) {
3584   default: llvm_unreachable("Unknown x86 shuffle node");
3585   case X86ISD::MOVSHDUP:
3586   case X86ISD::MOVSLDUP:
3587   case X86ISD::MOVDDUP:
3588     return DAG.getNode(Opc, dl, VT, V1);
3589   }
3590 }
3591
3592 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3593                                     SDValue V1, unsigned TargetMask,
3594                                     SelectionDAG &DAG) {
3595   switch(Opc) {
3596   default: llvm_unreachable("Unknown x86 shuffle node");
3597   case X86ISD::PSHUFD:
3598   case X86ISD::PSHUFHW:
3599   case X86ISD::PSHUFLW:
3600   case X86ISD::VPERMILPI:
3601   case X86ISD::VPERMI:
3602     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3603   }
3604 }
3605
3606 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3607                                     SDValue V1, SDValue V2, unsigned TargetMask,
3608                                     SelectionDAG &DAG) {
3609   switch(Opc) {
3610   default: llvm_unreachable("Unknown x86 shuffle node");
3611   case X86ISD::PALIGNR:
3612   case X86ISD::VALIGN:
3613   case X86ISD::SHUFP:
3614   case X86ISD::VPERM2X128:
3615     return DAG.getNode(Opc, dl, VT, V1, V2,
3616                        DAG.getConstant(TargetMask, MVT::i8));
3617   }
3618 }
3619
3620 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3621                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3622   switch(Opc) {
3623   default: llvm_unreachable("Unknown x86 shuffle node");
3624   case X86ISD::MOVLHPS:
3625   case X86ISD::MOVLHPD:
3626   case X86ISD::MOVHLPS:
3627   case X86ISD::MOVLPS:
3628   case X86ISD::MOVLPD:
3629   case X86ISD::MOVSS:
3630   case X86ISD::MOVSD:
3631   case X86ISD::UNPCKL:
3632   case X86ISD::UNPCKH:
3633     return DAG.getNode(Opc, dl, VT, V1, V2);
3634   }
3635 }
3636
3637 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3638   MachineFunction &MF = DAG.getMachineFunction();
3639   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3640       DAG.getSubtarget().getRegisterInfo());
3641   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3642   int ReturnAddrIndex = FuncInfo->getRAIndex();
3643
3644   if (ReturnAddrIndex == 0) {
3645     // Set up a frame object for the return address.
3646     unsigned SlotSize = RegInfo->getSlotSize();
3647     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3648                                                            -(int64_t)SlotSize,
3649                                                            false);
3650     FuncInfo->setRAIndex(ReturnAddrIndex);
3651   }
3652
3653   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3654 }
3655
3656 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3657                                        bool hasSymbolicDisplacement) {
3658   // Offset should fit into 32 bit immediate field.
3659   if (!isInt<32>(Offset))
3660     return false;
3661
3662   // If we don't have a symbolic displacement - we don't have any extra
3663   // restrictions.
3664   if (!hasSymbolicDisplacement)
3665     return true;
3666
3667   // FIXME: Some tweaks might be needed for medium code model.
3668   if (M != CodeModel::Small && M != CodeModel::Kernel)
3669     return false;
3670
3671   // For small code model we assume that latest object is 16MB before end of 31
3672   // bits boundary. We may also accept pretty large negative constants knowing
3673   // that all objects are in the positive half of address space.
3674   if (M == CodeModel::Small && Offset < 16*1024*1024)
3675     return true;
3676
3677   // For kernel code model we know that all object resist in the negative half
3678   // of 32bits address space. We may not accept negative offsets, since they may
3679   // be just off and we may accept pretty large positive ones.
3680   if (M == CodeModel::Kernel && Offset >= 0)
3681     return true;
3682
3683   return false;
3684 }
3685
3686 /// isCalleePop - Determines whether the callee is required to pop its
3687 /// own arguments. Callee pop is necessary to support tail calls.
3688 bool X86::isCalleePop(CallingConv::ID CallingConv,
3689                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3690   switch (CallingConv) {
3691   default:
3692     return false;
3693   case CallingConv::X86_StdCall:
3694   case CallingConv::X86_FastCall:
3695   case CallingConv::X86_ThisCall:
3696     return !is64Bit;
3697   case CallingConv::Fast:
3698   case CallingConv::GHC:
3699   case CallingConv::HiPE:
3700     if (IsVarArg)
3701       return false;
3702     return TailCallOpt;
3703   }
3704 }
3705
3706 /// \brief Return true if the condition is an unsigned comparison operation.
3707 static bool isX86CCUnsigned(unsigned X86CC) {
3708   switch (X86CC) {
3709   default: llvm_unreachable("Invalid integer condition!");
3710   case X86::COND_E:     return true;
3711   case X86::COND_G:     return false;
3712   case X86::COND_GE:    return false;
3713   case X86::COND_L:     return false;
3714   case X86::COND_LE:    return false;
3715   case X86::COND_NE:    return true;
3716   case X86::COND_B:     return true;
3717   case X86::COND_A:     return true;
3718   case X86::COND_BE:    return true;
3719   case X86::COND_AE:    return true;
3720   }
3721   llvm_unreachable("covered switch fell through?!");
3722 }
3723
3724 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3725 /// specific condition code, returning the condition code and the LHS/RHS of the
3726 /// comparison to make.
3727 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3728                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3729   if (!isFP) {
3730     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3731       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3732         // X > -1   -> X == 0, jump !sign.
3733         RHS = DAG.getConstant(0, RHS.getValueType());
3734         return X86::COND_NS;
3735       }
3736       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3737         // X < 0   -> X == 0, jump on sign.
3738         return X86::COND_S;
3739       }
3740       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3741         // X < 1   -> X <= 0
3742         RHS = DAG.getConstant(0, RHS.getValueType());
3743         return X86::COND_LE;
3744       }
3745     }
3746
3747     switch (SetCCOpcode) {
3748     default: llvm_unreachable("Invalid integer condition!");
3749     case ISD::SETEQ:  return X86::COND_E;
3750     case ISD::SETGT:  return X86::COND_G;
3751     case ISD::SETGE:  return X86::COND_GE;
3752     case ISD::SETLT:  return X86::COND_L;
3753     case ISD::SETLE:  return X86::COND_LE;
3754     case ISD::SETNE:  return X86::COND_NE;
3755     case ISD::SETULT: return X86::COND_B;
3756     case ISD::SETUGT: return X86::COND_A;
3757     case ISD::SETULE: return X86::COND_BE;
3758     case ISD::SETUGE: return X86::COND_AE;
3759     }
3760   }
3761
3762   // First determine if it is required or is profitable to flip the operands.
3763
3764   // If LHS is a foldable load, but RHS is not, flip the condition.
3765   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3766       !ISD::isNON_EXTLoad(RHS.getNode())) {
3767     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3768     std::swap(LHS, RHS);
3769   }
3770
3771   switch (SetCCOpcode) {
3772   default: break;
3773   case ISD::SETOLT:
3774   case ISD::SETOLE:
3775   case ISD::SETUGT:
3776   case ISD::SETUGE:
3777     std::swap(LHS, RHS);
3778     break;
3779   }
3780
3781   // On a floating point condition, the flags are set as follows:
3782   // ZF  PF  CF   op
3783   //  0 | 0 | 0 | X > Y
3784   //  0 | 0 | 1 | X < Y
3785   //  1 | 0 | 0 | X == Y
3786   //  1 | 1 | 1 | unordered
3787   switch (SetCCOpcode) {
3788   default: llvm_unreachable("Condcode should be pre-legalized away");
3789   case ISD::SETUEQ:
3790   case ISD::SETEQ:   return X86::COND_E;
3791   case ISD::SETOLT:              // flipped
3792   case ISD::SETOGT:
3793   case ISD::SETGT:   return X86::COND_A;
3794   case ISD::SETOLE:              // flipped
3795   case ISD::SETOGE:
3796   case ISD::SETGE:   return X86::COND_AE;
3797   case ISD::SETUGT:              // flipped
3798   case ISD::SETULT:
3799   case ISD::SETLT:   return X86::COND_B;
3800   case ISD::SETUGE:              // flipped
3801   case ISD::SETULE:
3802   case ISD::SETLE:   return X86::COND_BE;
3803   case ISD::SETONE:
3804   case ISD::SETNE:   return X86::COND_NE;
3805   case ISD::SETUO:   return X86::COND_P;
3806   case ISD::SETO:    return X86::COND_NP;
3807   case ISD::SETOEQ:
3808   case ISD::SETUNE:  return X86::COND_INVALID;
3809   }
3810 }
3811
3812 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3813 /// code. Current x86 isa includes the following FP cmov instructions:
3814 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3815 static bool hasFPCMov(unsigned X86CC) {
3816   switch (X86CC) {
3817   default:
3818     return false;
3819   case X86::COND_B:
3820   case X86::COND_BE:
3821   case X86::COND_E:
3822   case X86::COND_P:
3823   case X86::COND_A:
3824   case X86::COND_AE:
3825   case X86::COND_NE:
3826   case X86::COND_NP:
3827     return true;
3828   }
3829 }
3830
3831 /// isFPImmLegal - Returns true if the target can instruction select the
3832 /// specified FP immediate natively. If false, the legalizer will
3833 /// materialize the FP immediate as a load from a constant pool.
3834 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3835   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3836     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3837       return true;
3838   }
3839   return false;
3840 }
3841
3842 /// \brief Returns true if it is beneficial to convert a load of a constant
3843 /// to just the constant itself.
3844 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3845                                                           Type *Ty) const {
3846   assert(Ty->isIntegerTy());
3847
3848   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3849   if (BitSize == 0 || BitSize > 64)
3850     return false;
3851   return true;
3852 }
3853
3854 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, 
3855                                                 unsigned Index) const {
3856   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3857     return false;
3858
3859   return (Index == 0 || Index == ResVT.getVectorNumElements());
3860 }
3861
3862 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3863 /// the specified range (L, H].
3864 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3865   return (Val < 0) || (Val >= Low && Val < Hi);
3866 }
3867
3868 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3869 /// specified value.
3870 static bool isUndefOrEqual(int Val, int CmpVal) {
3871   return (Val < 0 || Val == CmpVal);
3872 }
3873
3874 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3875 /// from position Pos and ending in Pos+Size, falls within the specified
3876 /// sequential range (L, L+Pos]. or is undef.
3877 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3878                                        unsigned Pos, unsigned Size, int Low) {
3879   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3880     if (!isUndefOrEqual(Mask[i], Low))
3881       return false;
3882   return true;
3883 }
3884
3885 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3886 /// is suitable for input to PSHUFD. That is, it doesn't reference the other
3887 /// operand - by default will match for first operand.
3888 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT,
3889                          bool TestSecondOperand = false) {
3890   if (VT != MVT::v4f32 && VT != MVT::v4i32 &&
3891       VT != MVT::v2f64 && VT != MVT::v2i64)
3892     return false;
3893
3894   unsigned NumElems = VT.getVectorNumElements();
3895   unsigned Lo = TestSecondOperand ? NumElems : 0;
3896   unsigned Hi = Lo + NumElems;
3897
3898   for (unsigned i = 0; i < NumElems; ++i)
3899     if (!isUndefOrInRange(Mask[i], (int)Lo, (int)Hi))
3900       return false;
3901
3902   return true;
3903 }
3904
3905 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3906 /// is suitable for input to PSHUFHW.
3907 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3908   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3909     return false;
3910
3911   // Lower quadword copied in order or undef.
3912   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3913     return false;
3914
3915   // Upper quadword shuffled.
3916   for (unsigned i = 4; i != 8; ++i)
3917     if (!isUndefOrInRange(Mask[i], 4, 8))
3918       return false;
3919
3920   if (VT == MVT::v16i16) {
3921     // Lower quadword copied in order or undef.
3922     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3923       return false;
3924
3925     // Upper quadword shuffled.
3926     for (unsigned i = 12; i != 16; ++i)
3927       if (!isUndefOrInRange(Mask[i], 12, 16))
3928         return false;
3929   }
3930
3931   return true;
3932 }
3933
3934 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3935 /// is suitable for input to PSHUFLW.
3936 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3937   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3938     return false;
3939
3940   // Upper quadword copied in order.
3941   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3942     return false;
3943
3944   // Lower quadword shuffled.
3945   for (unsigned i = 0; i != 4; ++i)
3946     if (!isUndefOrInRange(Mask[i], 0, 4))
3947       return false;
3948
3949   if (VT == MVT::v16i16) {
3950     // Upper quadword copied in order.
3951     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3952       return false;
3953
3954     // Lower quadword shuffled.
3955     for (unsigned i = 8; i != 12; ++i)
3956       if (!isUndefOrInRange(Mask[i], 8, 12))
3957         return false;
3958   }
3959
3960   return true;
3961 }
3962
3963 /// \brief Return true if the mask specifies a shuffle of elements that is
3964 /// suitable for input to intralane (palignr) or interlane (valign) vector
3965 /// right-shift.
3966 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3967   unsigned NumElts = VT.getVectorNumElements();
3968   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3969   unsigned NumLaneElts = NumElts/NumLanes;
3970
3971   // Do not handle 64-bit element shuffles with palignr.
3972   if (NumLaneElts == 2)
3973     return false;
3974
3975   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3976     unsigned i;
3977     for (i = 0; i != NumLaneElts; ++i) {
3978       if (Mask[i+l] >= 0)
3979         break;
3980     }
3981
3982     // Lane is all undef, go to next lane
3983     if (i == NumLaneElts)
3984       continue;
3985
3986     int Start = Mask[i+l];
3987
3988     // Make sure its in this lane in one of the sources
3989     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3990         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3991       return false;
3992
3993     // If not lane 0, then we must match lane 0
3994     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3995       return false;
3996
3997     // Correct second source to be contiguous with first source
3998     if (Start >= (int)NumElts)
3999       Start -= NumElts - NumLaneElts;
4000
4001     // Make sure we're shifting in the right direction.
4002     if (Start <= (int)(i+l))
4003       return false;
4004
4005     Start -= i;
4006
4007     // Check the rest of the elements to see if they are consecutive.
4008     for (++i; i != NumLaneElts; ++i) {
4009       int Idx = Mask[i+l];
4010
4011       // Make sure its in this lane
4012       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
4013           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
4014         return false;
4015
4016       // If not lane 0, then we must match lane 0
4017       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
4018         return false;
4019
4020       if (Idx >= (int)NumElts)
4021         Idx -= NumElts - NumLaneElts;
4022
4023       if (!isUndefOrEqual(Idx, Start+i))
4024         return false;
4025
4026     }
4027   }
4028
4029   return true;
4030 }
4031
4032 /// \brief Return true if the node specifies a shuffle of elements that is
4033 /// suitable for input to PALIGNR.
4034 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4035                           const X86Subtarget *Subtarget) {
4036   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4037       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4038       VT.is512BitVector())
4039     // FIXME: Add AVX512BW.
4040     return false;
4041
4042   return isAlignrMask(Mask, VT, false);
4043 }
4044
4045 /// \brief Return true if the node specifies a shuffle of elements that is
4046 /// suitable for input to VALIGN.
4047 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4048                           const X86Subtarget *Subtarget) {
4049   // FIXME: Add AVX512VL.
4050   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4051     return false;
4052   return isAlignrMask(Mask, VT, true);
4053 }
4054
4055 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4056 /// the two vector operands have swapped position.
4057 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4058                                      unsigned NumElems) {
4059   for (unsigned i = 0; i != NumElems; ++i) {
4060     int idx = Mask[i];
4061     if (idx < 0)
4062       continue;
4063     else if (idx < (int)NumElems)
4064       Mask[i] = idx + NumElems;
4065     else
4066       Mask[i] = idx - NumElems;
4067   }
4068 }
4069
4070 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4071 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4072 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4073 /// reverse of what x86 shuffles want.
4074 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4075
4076   unsigned NumElems = VT.getVectorNumElements();
4077   unsigned NumLanes = VT.getSizeInBits()/128;
4078   unsigned NumLaneElems = NumElems/NumLanes;
4079
4080   if (NumLaneElems != 2 && NumLaneElems != 4)
4081     return false;
4082
4083   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4084   bool symetricMaskRequired =
4085     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4086
4087   // VSHUFPSY divides the resulting vector into 4 chunks.
4088   // The sources are also splitted into 4 chunks, and each destination
4089   // chunk must come from a different source chunk.
4090   //
4091   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4092   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4093   //
4094   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4095   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4096   //
4097   // VSHUFPDY divides the resulting vector into 4 chunks.
4098   // The sources are also splitted into 4 chunks, and each destination
4099   // chunk must come from a different source chunk.
4100   //
4101   //  SRC1 =>      X3       X2       X1       X0
4102   //  SRC2 =>      Y3       Y2       Y1       Y0
4103   //
4104   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4105   //
4106   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4107   unsigned HalfLaneElems = NumLaneElems/2;
4108   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4109     for (unsigned i = 0; i != NumLaneElems; ++i) {
4110       int Idx = Mask[i+l];
4111       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4112       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4113         return false;
4114       // For VSHUFPSY, the mask of the second half must be the same as the
4115       // first but with the appropriate offsets. This works in the same way as
4116       // VPERMILPS works with masks.
4117       if (!symetricMaskRequired || Idx < 0)
4118         continue;
4119       if (MaskVal[i] < 0) {
4120         MaskVal[i] = Idx - l;
4121         continue;
4122       }
4123       if ((signed)(Idx - l) != MaskVal[i])
4124         return false;
4125     }
4126   }
4127
4128   return true;
4129 }
4130
4131 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4132 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4133 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4134   if (!VT.is128BitVector())
4135     return false;
4136
4137   unsigned NumElems = VT.getVectorNumElements();
4138
4139   if (NumElems != 4)
4140     return false;
4141
4142   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4143   return isUndefOrEqual(Mask[0], 6) &&
4144          isUndefOrEqual(Mask[1], 7) &&
4145          isUndefOrEqual(Mask[2], 2) &&
4146          isUndefOrEqual(Mask[3], 3);
4147 }
4148
4149 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4150 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4151 /// <2, 3, 2, 3>
4152 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4153   if (!VT.is128BitVector())
4154     return false;
4155
4156   unsigned NumElems = VT.getVectorNumElements();
4157
4158   if (NumElems != 4)
4159     return false;
4160
4161   return isUndefOrEqual(Mask[0], 2) &&
4162          isUndefOrEqual(Mask[1], 3) &&
4163          isUndefOrEqual(Mask[2], 2) &&
4164          isUndefOrEqual(Mask[3], 3);
4165 }
4166
4167 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4168 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4169 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4170   if (!VT.is128BitVector())
4171     return false;
4172
4173   unsigned NumElems = VT.getVectorNumElements();
4174
4175   if (NumElems != 2 && NumElems != 4)
4176     return false;
4177
4178   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4179     if (!isUndefOrEqual(Mask[i], i + NumElems))
4180       return false;
4181
4182   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4183     if (!isUndefOrEqual(Mask[i], i))
4184       return false;
4185
4186   return true;
4187 }
4188
4189 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4190 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4191 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4192   if (!VT.is128BitVector())
4193     return false;
4194
4195   unsigned NumElems = VT.getVectorNumElements();
4196
4197   if (NumElems != 2 && NumElems != 4)
4198     return false;
4199
4200   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4201     if (!isUndefOrEqual(Mask[i], i))
4202       return false;
4203
4204   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4205     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4206       return false;
4207
4208   return true;
4209 }
4210
4211 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4212 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4213 /// i. e: If all but one element come from the same vector.
4214 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4215   // TODO: Deal with AVX's VINSERTPS
4216   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4217     return false;
4218
4219   unsigned CorrectPosV1 = 0;
4220   unsigned CorrectPosV2 = 0;
4221   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4222     if (Mask[i] == -1) {
4223       ++CorrectPosV1;
4224       ++CorrectPosV2;
4225       continue;
4226     }
4227
4228     if (Mask[i] == i)
4229       ++CorrectPosV1;
4230     else if (Mask[i] == i + 4)
4231       ++CorrectPosV2;
4232   }
4233
4234   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4235     // We have 3 elements (undefs count as elements from any vector) from one
4236     // vector, and one from another.
4237     return true;
4238
4239   return false;
4240 }
4241
4242 //
4243 // Some special combinations that can be optimized.
4244 //
4245 static
4246 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4247                                SelectionDAG &DAG) {
4248   MVT VT = SVOp->getSimpleValueType(0);
4249   SDLoc dl(SVOp);
4250
4251   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4252     return SDValue();
4253
4254   ArrayRef<int> Mask = SVOp->getMask();
4255
4256   // These are the special masks that may be optimized.
4257   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4258   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4259   bool MatchEvenMask = true;
4260   bool MatchOddMask  = true;
4261   for (int i=0; i<8; ++i) {
4262     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4263       MatchEvenMask = false;
4264     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4265       MatchOddMask = false;
4266   }
4267
4268   if (!MatchEvenMask && !MatchOddMask)
4269     return SDValue();
4270
4271   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4272
4273   SDValue Op0 = SVOp->getOperand(0);
4274   SDValue Op1 = SVOp->getOperand(1);
4275
4276   if (MatchEvenMask) {
4277     // Shift the second operand right to 32 bits.
4278     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4279     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4280   } else {
4281     // Shift the first operand left to 32 bits.
4282     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4283     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4284   }
4285   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4286   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4287 }
4288
4289 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4290 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4291 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4292                          bool HasInt256, bool V2IsSplat = false) {
4293
4294   assert(VT.getSizeInBits() >= 128 &&
4295          "Unsupported vector type for unpckl");
4296
4297   unsigned NumElts = VT.getVectorNumElements();
4298   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4299       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4300     return false;
4301
4302   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4303          "Unsupported vector type for unpckh");
4304
4305   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4306   unsigned NumLanes = VT.getSizeInBits()/128;
4307   unsigned NumLaneElts = NumElts/NumLanes;
4308
4309   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4310     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4311       int BitI  = Mask[l+i];
4312       int BitI1 = Mask[l+i+1];
4313       if (!isUndefOrEqual(BitI, j))
4314         return false;
4315       if (V2IsSplat) {
4316         if (!isUndefOrEqual(BitI1, NumElts))
4317           return false;
4318       } else {
4319         if (!isUndefOrEqual(BitI1, j + NumElts))
4320           return false;
4321       }
4322     }
4323   }
4324
4325   return true;
4326 }
4327
4328 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4329 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4330 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4331                          bool HasInt256, bool V2IsSplat = false) {
4332   assert(VT.getSizeInBits() >= 128 &&
4333          "Unsupported vector type for unpckh");
4334
4335   unsigned NumElts = VT.getVectorNumElements();
4336   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4337       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4338     return false;
4339
4340   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4341          "Unsupported vector type for unpckh");
4342
4343   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4344   unsigned NumLanes = VT.getSizeInBits()/128;
4345   unsigned NumLaneElts = NumElts/NumLanes;
4346
4347   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4348     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4349       int BitI  = Mask[l+i];
4350       int BitI1 = Mask[l+i+1];
4351       if (!isUndefOrEqual(BitI, j))
4352         return false;
4353       if (V2IsSplat) {
4354         if (isUndefOrEqual(BitI1, NumElts))
4355           return false;
4356       } else {
4357         if (!isUndefOrEqual(BitI1, j+NumElts))
4358           return false;
4359       }
4360     }
4361   }
4362   return true;
4363 }
4364
4365 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4366 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4367 /// <0, 0, 1, 1>
4368 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4369   unsigned NumElts = VT.getVectorNumElements();
4370   bool Is256BitVec = VT.is256BitVector();
4371
4372   if (VT.is512BitVector())
4373     return false;
4374   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4375          "Unsupported vector type for unpckh");
4376
4377   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4378       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4379     return false;
4380
4381   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4382   // FIXME: Need a better way to get rid of this, there's no latency difference
4383   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4384   // the former later. We should also remove the "_undef" special mask.
4385   if (NumElts == 4 && Is256BitVec)
4386     return false;
4387
4388   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4389   // independently on 128-bit lanes.
4390   unsigned NumLanes = VT.getSizeInBits()/128;
4391   unsigned NumLaneElts = NumElts/NumLanes;
4392
4393   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4394     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4395       int BitI  = Mask[l+i];
4396       int BitI1 = Mask[l+i+1];
4397
4398       if (!isUndefOrEqual(BitI, j))
4399         return false;
4400       if (!isUndefOrEqual(BitI1, j))
4401         return false;
4402     }
4403   }
4404
4405   return true;
4406 }
4407
4408 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4409 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4410 /// <2, 2, 3, 3>
4411 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4412   unsigned NumElts = VT.getVectorNumElements();
4413
4414   if (VT.is512BitVector())
4415     return false;
4416
4417   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4418          "Unsupported vector type for unpckh");
4419
4420   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4421       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4422     return false;
4423
4424   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4425   // independently on 128-bit lanes.
4426   unsigned NumLanes = VT.getSizeInBits()/128;
4427   unsigned NumLaneElts = NumElts/NumLanes;
4428
4429   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4430     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4431       int BitI  = Mask[l+i];
4432       int BitI1 = Mask[l+i+1];
4433       if (!isUndefOrEqual(BitI, j))
4434         return false;
4435       if (!isUndefOrEqual(BitI1, j))
4436         return false;
4437     }
4438   }
4439   return true;
4440 }
4441
4442 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4443 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4444 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4445   if (!VT.is512BitVector())
4446     return false;
4447
4448   unsigned NumElts = VT.getVectorNumElements();
4449   unsigned HalfSize = NumElts/2;
4450   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4451     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4452       *Imm = 1;
4453       return true;
4454     }
4455   }
4456   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4457     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4458       *Imm = 0;
4459       return true;
4460     }
4461   }
4462   return false;
4463 }
4464
4465 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4466 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4467 /// MOVSD, and MOVD, i.e. setting the lowest element.
4468 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4469   if (VT.getVectorElementType().getSizeInBits() < 32)
4470     return false;
4471   if (!VT.is128BitVector())
4472     return false;
4473
4474   unsigned NumElts = VT.getVectorNumElements();
4475
4476   if (!isUndefOrEqual(Mask[0], NumElts))
4477     return false;
4478
4479   for (unsigned i = 1; i != NumElts; ++i)
4480     if (!isUndefOrEqual(Mask[i], i))
4481       return false;
4482
4483   return true;
4484 }
4485
4486 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4487 /// as permutations between 128-bit chunks or halves. As an example: this
4488 /// shuffle bellow:
4489 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4490 /// The first half comes from the second half of V1 and the second half from the
4491 /// the second half of V2.
4492 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4493   if (!HasFp256 || !VT.is256BitVector())
4494     return false;
4495
4496   // The shuffle result is divided into half A and half B. In total the two
4497   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4498   // B must come from C, D, E or F.
4499   unsigned HalfSize = VT.getVectorNumElements()/2;
4500   bool MatchA = false, MatchB = false;
4501
4502   // Check if A comes from one of C, D, E, F.
4503   for (unsigned Half = 0; Half != 4; ++Half) {
4504     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4505       MatchA = true;
4506       break;
4507     }
4508   }
4509
4510   // Check if B comes from one of C, D, E, F.
4511   for (unsigned Half = 0; Half != 4; ++Half) {
4512     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4513       MatchB = true;
4514       break;
4515     }
4516   }
4517
4518   return MatchA && MatchB;
4519 }
4520
4521 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4522 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4523 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4524   MVT VT = SVOp->getSimpleValueType(0);
4525
4526   unsigned HalfSize = VT.getVectorNumElements()/2;
4527
4528   unsigned FstHalf = 0, SndHalf = 0;
4529   for (unsigned i = 0; i < HalfSize; ++i) {
4530     if (SVOp->getMaskElt(i) > 0) {
4531       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4532       break;
4533     }
4534   }
4535   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4536     if (SVOp->getMaskElt(i) > 0) {
4537       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4538       break;
4539     }
4540   }
4541
4542   return (FstHalf | (SndHalf << 4));
4543 }
4544
4545 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4546 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4547   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4548   if (EltSize < 32)
4549     return false;
4550
4551   unsigned NumElts = VT.getVectorNumElements();
4552   Imm8 = 0;
4553   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4554     for (unsigned i = 0; i != NumElts; ++i) {
4555       if (Mask[i] < 0)
4556         continue;
4557       Imm8 |= Mask[i] << (i*2);
4558     }
4559     return true;
4560   }
4561
4562   unsigned LaneSize = 4;
4563   SmallVector<int, 4> MaskVal(LaneSize, -1);
4564
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 (Mask[i+l] < 0)
4570         continue;
4571       if (MaskVal[i] < 0) {
4572         MaskVal[i] = Mask[i+l] - l;
4573         Imm8 |= MaskVal[i] << (i*2);
4574         continue;
4575       }
4576       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4577         return false;
4578     }
4579   }
4580   return true;
4581 }
4582
4583 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4584 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4585 /// Note that VPERMIL mask matching is different depending whether theunderlying
4586 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4587 /// to the same elements of the low, but to the higher half of the source.
4588 /// In VPERMILPD the two lanes could be shuffled independently of each other
4589 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4590 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4591   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4592   if (VT.getSizeInBits() < 256 || EltSize < 32)
4593     return false;
4594   bool symetricMaskRequired = (EltSize == 32);
4595   unsigned NumElts = VT.getVectorNumElements();
4596
4597   unsigned NumLanes = VT.getSizeInBits()/128;
4598   unsigned LaneSize = NumElts/NumLanes;
4599   // 2 or 4 elements in one lane
4600
4601   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4602   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4603     for (unsigned i = 0; i != LaneSize; ++i) {
4604       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4605         return false;
4606       if (symetricMaskRequired) {
4607         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4608           ExpectedMaskVal[i] = Mask[i+l] - l;
4609           continue;
4610         }
4611         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4612           return false;
4613       }
4614     }
4615   }
4616   return true;
4617 }
4618
4619 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4620 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4621 /// element of vector 2 and the other elements to come from vector 1 in order.
4622 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4623                                bool V2IsSplat = false, bool V2IsUndef = false) {
4624   if (!VT.is128BitVector())
4625     return false;
4626
4627   unsigned NumOps = VT.getVectorNumElements();
4628   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4629     return false;
4630
4631   if (!isUndefOrEqual(Mask[0], 0))
4632     return false;
4633
4634   for (unsigned i = 1; i != NumOps; ++i)
4635     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4636           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4637           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4638       return false;
4639
4640   return true;
4641 }
4642
4643 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4644 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4645 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4646 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4647                            const X86Subtarget *Subtarget) {
4648   if (!Subtarget->hasSSE3())
4649     return false;
4650
4651   unsigned NumElems = VT.getVectorNumElements();
4652
4653   if ((VT.is128BitVector() && NumElems != 4) ||
4654       (VT.is256BitVector() && NumElems != 8) ||
4655       (VT.is512BitVector() && NumElems != 16))
4656     return false;
4657
4658   // "i+1" is the value the indexed mask element must have
4659   for (unsigned i = 0; i != NumElems; i += 2)
4660     if (!isUndefOrEqual(Mask[i], i+1) ||
4661         !isUndefOrEqual(Mask[i+1], i+1))
4662       return false;
4663
4664   return true;
4665 }
4666
4667 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4668 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4669 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4670 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4671                            const X86Subtarget *Subtarget) {
4672   if (!Subtarget->hasSSE3())
4673     return false;
4674
4675   unsigned NumElems = VT.getVectorNumElements();
4676
4677   if ((VT.is128BitVector() && NumElems != 4) ||
4678       (VT.is256BitVector() && NumElems != 8) ||
4679       (VT.is512BitVector() && NumElems != 16))
4680     return false;
4681
4682   // "i" is the value the indexed mask element must have
4683   for (unsigned i = 0; i != NumElems; i += 2)
4684     if (!isUndefOrEqual(Mask[i], i) ||
4685         !isUndefOrEqual(Mask[i+1], i))
4686       return false;
4687
4688   return true;
4689 }
4690
4691 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4692 /// specifies a shuffle of elements that is suitable for input to 256-bit
4693 /// version of MOVDDUP.
4694 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4695   if (!HasFp256 || !VT.is256BitVector())
4696     return false;
4697
4698   unsigned NumElts = VT.getVectorNumElements();
4699   if (NumElts != 4)
4700     return false;
4701
4702   for (unsigned i = 0; i != NumElts/2; ++i)
4703     if (!isUndefOrEqual(Mask[i], 0))
4704       return false;
4705   for (unsigned i = NumElts/2; i != NumElts; ++i)
4706     if (!isUndefOrEqual(Mask[i], NumElts/2))
4707       return false;
4708   return true;
4709 }
4710
4711 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4712 /// specifies a shuffle of elements that is suitable for input to 128-bit
4713 /// version of MOVDDUP.
4714 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4715   if (!VT.is128BitVector())
4716     return false;
4717
4718   unsigned e = VT.getVectorNumElements() / 2;
4719   for (unsigned i = 0; i != e; ++i)
4720     if (!isUndefOrEqual(Mask[i], i))
4721       return false;
4722   for (unsigned i = 0; i != e; ++i)
4723     if (!isUndefOrEqual(Mask[e+i], i))
4724       return false;
4725   return true;
4726 }
4727
4728 /// isVEXTRACTIndex - Return true if the specified
4729 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4730 /// suitable for instruction that extract 128 or 256 bit vectors
4731 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4732   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4733   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4734     return false;
4735
4736   // The index should be aligned on a vecWidth-bit boundary.
4737   uint64_t Index =
4738     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4739
4740   MVT VT = N->getSimpleValueType(0);
4741   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4742   bool Result = (Index * ElSize) % vecWidth == 0;
4743
4744   return Result;
4745 }
4746
4747 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4748 /// operand specifies a subvector insert that is suitable for input to
4749 /// insertion of 128 or 256-bit subvectors
4750 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4751   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4752   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4753     return false;
4754   // The index should be aligned on a vecWidth-bit boundary.
4755   uint64_t Index =
4756     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4757
4758   MVT VT = N->getSimpleValueType(0);
4759   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4760   bool Result = (Index * ElSize) % vecWidth == 0;
4761
4762   return Result;
4763 }
4764
4765 bool X86::isVINSERT128Index(SDNode *N) {
4766   return isVINSERTIndex(N, 128);
4767 }
4768
4769 bool X86::isVINSERT256Index(SDNode *N) {
4770   return isVINSERTIndex(N, 256);
4771 }
4772
4773 bool X86::isVEXTRACT128Index(SDNode *N) {
4774   return isVEXTRACTIndex(N, 128);
4775 }
4776
4777 bool X86::isVEXTRACT256Index(SDNode *N) {
4778   return isVEXTRACTIndex(N, 256);
4779 }
4780
4781 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4782 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4783 /// Handles 128-bit and 256-bit.
4784 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4785   MVT VT = N->getSimpleValueType(0);
4786
4787   assert((VT.getSizeInBits() >= 128) &&
4788          "Unsupported vector type for PSHUF/SHUFP");
4789
4790   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4791   // independently on 128-bit lanes.
4792   unsigned NumElts = VT.getVectorNumElements();
4793   unsigned NumLanes = VT.getSizeInBits()/128;
4794   unsigned NumLaneElts = NumElts/NumLanes;
4795
4796   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4797          "Only supports 2, 4 or 8 elements per lane");
4798
4799   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4800   unsigned Mask = 0;
4801   for (unsigned i = 0; i != NumElts; ++i) {
4802     int Elt = N->getMaskElt(i);
4803     if (Elt < 0) continue;
4804     Elt &= NumLaneElts - 1;
4805     unsigned ShAmt = (i << Shift) % 8;
4806     Mask |= Elt << ShAmt;
4807   }
4808
4809   return Mask;
4810 }
4811
4812 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4813 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4814 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4815   MVT VT = N->getSimpleValueType(0);
4816
4817   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4818          "Unsupported vector type for PSHUFHW");
4819
4820   unsigned NumElts = VT.getVectorNumElements();
4821
4822   unsigned Mask = 0;
4823   for (unsigned l = 0; l != NumElts; l += 8) {
4824     // 8 nodes per lane, but we only care about the last 4.
4825     for (unsigned i = 0; i < 4; ++i) {
4826       int Elt = N->getMaskElt(l+i+4);
4827       if (Elt < 0) continue;
4828       Elt &= 0x3; // only 2-bits.
4829       Mask |= Elt << (i * 2);
4830     }
4831   }
4832
4833   return Mask;
4834 }
4835
4836 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4837 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4838 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4839   MVT VT = N->getSimpleValueType(0);
4840
4841   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4842          "Unsupported vector type for PSHUFHW");
4843
4844   unsigned NumElts = VT.getVectorNumElements();
4845
4846   unsigned Mask = 0;
4847   for (unsigned l = 0; l != NumElts; l += 8) {
4848     // 8 nodes per lane, but we only care about the first 4.
4849     for (unsigned i = 0; i < 4; ++i) {
4850       int Elt = N->getMaskElt(l+i);
4851       if (Elt < 0) continue;
4852       Elt &= 0x3; // only 2-bits
4853       Mask |= Elt << (i * 2);
4854     }
4855   }
4856
4857   return Mask;
4858 }
4859
4860 /// \brief Return the appropriate immediate to shuffle the specified
4861 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4862 /// VALIGN (if Interlane is true) instructions.
4863 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4864                                            bool InterLane) {
4865   MVT VT = SVOp->getSimpleValueType(0);
4866   unsigned EltSize = InterLane ? 1 :
4867     VT.getVectorElementType().getSizeInBits() >> 3;
4868
4869   unsigned NumElts = VT.getVectorNumElements();
4870   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4871   unsigned NumLaneElts = NumElts/NumLanes;
4872
4873   int Val = 0;
4874   unsigned i;
4875   for (i = 0; i != NumElts; ++i) {
4876     Val = SVOp->getMaskElt(i);
4877     if (Val >= 0)
4878       break;
4879   }
4880   if (Val >= (int)NumElts)
4881     Val -= NumElts - NumLaneElts;
4882
4883   assert(Val - i > 0 && "PALIGNR imm should be positive");
4884   return (Val - i) * EltSize;
4885 }
4886
4887 /// \brief Return the appropriate immediate to shuffle the specified
4888 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4889 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4890   return getShuffleAlignrImmediate(SVOp, false);
4891 }
4892
4893 /// \brief Return the appropriate immediate to shuffle the specified
4894 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4895 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4896   return getShuffleAlignrImmediate(SVOp, true);
4897 }
4898
4899
4900 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4901   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4902   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4903     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4904
4905   uint64_t Index =
4906     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4907
4908   MVT VecVT = N->getOperand(0).getSimpleValueType();
4909   MVT ElVT = VecVT.getVectorElementType();
4910
4911   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4912   return Index / NumElemsPerChunk;
4913 }
4914
4915 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4916   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4917   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4918     llvm_unreachable("Illegal insert subvector for VINSERT");
4919
4920   uint64_t Index =
4921     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4922
4923   MVT VecVT = N->getSimpleValueType(0);
4924   MVT ElVT = VecVT.getVectorElementType();
4925
4926   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4927   return Index / NumElemsPerChunk;
4928 }
4929
4930 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4931 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4932 /// and VINSERTI128 instructions.
4933 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4934   return getExtractVEXTRACTImmediate(N, 128);
4935 }
4936
4937 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4938 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4939 /// and VINSERTI64x4 instructions.
4940 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4941   return getExtractVEXTRACTImmediate(N, 256);
4942 }
4943
4944 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4945 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4946 /// and VINSERTI128 instructions.
4947 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4948   return getInsertVINSERTImmediate(N, 128);
4949 }
4950
4951 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4952 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4953 /// and VINSERTI64x4 instructions.
4954 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4955   return getInsertVINSERTImmediate(N, 256);
4956 }
4957
4958 /// isZero - Returns true if Elt is a constant integer zero
4959 static bool isZero(SDValue V) {
4960   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4961   return C && C->isNullValue();
4962 }
4963
4964 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4965 /// constant +0.0.
4966 bool X86::isZeroNode(SDValue Elt) {
4967   if (isZero(Elt))
4968     return true;
4969   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4970     return CFP->getValueAPF().isPosZero();
4971   return false;
4972 }
4973
4974 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4975 /// match movhlps. The lower half elements should come from upper half of
4976 /// V1 (and in order), and the upper half elements should come from the upper
4977 /// half of V2 (and in order).
4978 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4979   if (!VT.is128BitVector())
4980     return false;
4981   if (VT.getVectorNumElements() != 4)
4982     return false;
4983   for (unsigned i = 0, e = 2; i != e; ++i)
4984     if (!isUndefOrEqual(Mask[i], i+2))
4985       return false;
4986   for (unsigned i = 2; i != 4; ++i)
4987     if (!isUndefOrEqual(Mask[i], i+4))
4988       return false;
4989   return true;
4990 }
4991
4992 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4993 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4994 /// required.
4995 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4996   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4997     return false;
4998   N = N->getOperand(0).getNode();
4999   if (!ISD::isNON_EXTLoad(N))
5000     return false;
5001   if (LD)
5002     *LD = cast<LoadSDNode>(N);
5003   return true;
5004 }
5005
5006 // Test whether the given value is a vector value which will be legalized
5007 // into a load.
5008 static bool WillBeConstantPoolLoad(SDNode *N) {
5009   if (N->getOpcode() != ISD::BUILD_VECTOR)
5010     return false;
5011
5012   // Check for any non-constant elements.
5013   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5014     switch (N->getOperand(i).getNode()->getOpcode()) {
5015     case ISD::UNDEF:
5016     case ISD::ConstantFP:
5017     case ISD::Constant:
5018       break;
5019     default:
5020       return false;
5021     }
5022
5023   // Vectors of all-zeros and all-ones are materialized with special
5024   // instructions rather than being loaded.
5025   return !ISD::isBuildVectorAllZeros(N) &&
5026          !ISD::isBuildVectorAllOnes(N);
5027 }
5028
5029 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5030 /// match movlp{s|d}. The lower half elements should come from lower half of
5031 /// V1 (and in order), and the upper half elements should come from the upper
5032 /// half of V2 (and in order). And since V1 will become the source of the
5033 /// MOVLP, it must be either a vector load or a scalar load to vector.
5034 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5035                                ArrayRef<int> Mask, MVT VT) {
5036   if (!VT.is128BitVector())
5037     return false;
5038
5039   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5040     return false;
5041   // Is V2 is a vector load, don't do this transformation. We will try to use
5042   // load folding shufps op.
5043   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5044     return false;
5045
5046   unsigned NumElems = VT.getVectorNumElements();
5047
5048   if (NumElems != 2 && NumElems != 4)
5049     return false;
5050   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5051     if (!isUndefOrEqual(Mask[i], i))
5052       return false;
5053   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5054     if (!isUndefOrEqual(Mask[i], i+NumElems))
5055       return false;
5056   return true;
5057 }
5058
5059 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5060 /// to an zero vector.
5061 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5062 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5063   SDValue V1 = N->getOperand(0);
5064   SDValue V2 = N->getOperand(1);
5065   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5066   for (unsigned i = 0; i != NumElems; ++i) {
5067     int Idx = N->getMaskElt(i);
5068     if (Idx >= (int)NumElems) {
5069       unsigned Opc = V2.getOpcode();
5070       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5071         continue;
5072       if (Opc != ISD::BUILD_VECTOR ||
5073           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5074         return false;
5075     } else if (Idx >= 0) {
5076       unsigned Opc = V1.getOpcode();
5077       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5078         continue;
5079       if (Opc != ISD::BUILD_VECTOR ||
5080           !X86::isZeroNode(V1.getOperand(Idx)))
5081         return false;
5082     }
5083   }
5084   return true;
5085 }
5086
5087 /// getZeroVector - Returns a vector of specified type with all zero elements.
5088 ///
5089 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5090                              SelectionDAG &DAG, SDLoc dl) {
5091   assert(VT.isVector() && "Expected a vector type");
5092
5093   // Always build SSE zero vectors as <4 x i32> bitcasted
5094   // to their dest type. This ensures they get CSE'd.
5095   SDValue Vec;
5096   if (VT.is128BitVector()) {  // SSE
5097     if (Subtarget->hasSSE2()) {  // SSE2
5098       SDValue Cst = DAG.getConstant(0, MVT::i32);
5099       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5100     } else { // SSE1
5101       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5102       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5103     }
5104   } else if (VT.is256BitVector()) { // AVX
5105     if (Subtarget->hasInt256()) { // AVX2
5106       SDValue Cst = DAG.getConstant(0, MVT::i32);
5107       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5108       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5109     } else {
5110       // 256-bit logic and arithmetic instructions in AVX are all
5111       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5112       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5113       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5114       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5115     }
5116   } else if (VT.is512BitVector()) { // AVX-512
5117       SDValue Cst = DAG.getConstant(0, MVT::i32);
5118       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5119                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5120       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5121   } else if (VT.getScalarType() == MVT::i1) {
5122     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5123     SDValue Cst = DAG.getConstant(0, MVT::i1);
5124     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5125     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5126   } else
5127     llvm_unreachable("Unexpected vector type");
5128
5129   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5130 }
5131
5132 /// getOnesVector - Returns a vector of specified type with all bits set.
5133 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5134 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5135 /// Then bitcast to their original type, ensuring they get CSE'd.
5136 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5137                              SDLoc dl) {
5138   assert(VT.isVector() && "Expected a vector type");
5139
5140   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
5141   SDValue Vec;
5142   if (VT.is256BitVector()) {
5143     if (HasInt256) { // AVX2
5144       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5145       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5146     } else { // AVX
5147       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5148       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5149     }
5150   } else if (VT.is128BitVector()) {
5151     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5152   } else
5153     llvm_unreachable("Unexpected vector type");
5154
5155   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5156 }
5157
5158 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5159 /// that point to V2 points to its first element.
5160 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5161   for (unsigned i = 0; i != NumElems; ++i) {
5162     if (Mask[i] > (int)NumElems) {
5163       Mask[i] = NumElems;
5164     }
5165   }
5166 }
5167
5168 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5169 /// operation of specified width.
5170 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5171                        SDValue V2) {
5172   unsigned NumElems = VT.getVectorNumElements();
5173   SmallVector<int, 8> Mask;
5174   Mask.push_back(NumElems);
5175   for (unsigned i = 1; i != NumElems; ++i)
5176     Mask.push_back(i);
5177   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5178 }
5179
5180 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5181 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5182                           SDValue V2) {
5183   unsigned NumElems = VT.getVectorNumElements();
5184   SmallVector<int, 8> Mask;
5185   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5186     Mask.push_back(i);
5187     Mask.push_back(i + NumElems);
5188   }
5189   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5190 }
5191
5192 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5193 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5194                           SDValue V2) {
5195   unsigned NumElems = VT.getVectorNumElements();
5196   SmallVector<int, 8> Mask;
5197   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5198     Mask.push_back(i + Half);
5199     Mask.push_back(i + NumElems + Half);
5200   }
5201   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5202 }
5203
5204 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5205 // a generic shuffle instruction because the target has no such instructions.
5206 // Generate shuffles which repeat i16 and i8 several times until they can be
5207 // represented by v4f32 and then be manipulated by target suported shuffles.
5208 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5209   MVT VT = V.getSimpleValueType();
5210   int NumElems = VT.getVectorNumElements();
5211   SDLoc dl(V);
5212
5213   while (NumElems > 4) {
5214     if (EltNo < NumElems/2) {
5215       V = getUnpackl(DAG, dl, VT, V, V);
5216     } else {
5217       V = getUnpackh(DAG, dl, VT, V, V);
5218       EltNo -= NumElems/2;
5219     }
5220     NumElems >>= 1;
5221   }
5222   return V;
5223 }
5224
5225 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5226 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5227   MVT VT = V.getSimpleValueType();
5228   SDLoc dl(V);
5229
5230   if (VT.is128BitVector()) {
5231     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5232     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5233     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5234                              &SplatMask[0]);
5235   } else if (VT.is256BitVector()) {
5236     // To use VPERMILPS to splat scalars, the second half of indicies must
5237     // refer to the higher part, which is a duplication of the lower one,
5238     // because VPERMILPS can only handle in-lane permutations.
5239     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5240                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5241
5242     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5243     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5244                              &SplatMask[0]);
5245   } else
5246     llvm_unreachable("Vector size not supported");
5247
5248   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5249 }
5250
5251 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5252 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5253   MVT SrcVT = SV->getSimpleValueType(0);
5254   SDValue V1 = SV->getOperand(0);
5255   SDLoc dl(SV);
5256
5257   int EltNo = SV->getSplatIndex();
5258   int NumElems = SrcVT.getVectorNumElements();
5259   bool Is256BitVec = SrcVT.is256BitVector();
5260
5261   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5262          "Unknown how to promote splat for type");
5263
5264   // Extract the 128-bit part containing the splat element and update
5265   // the splat element index when it refers to the higher register.
5266   if (Is256BitVec) {
5267     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5268     if (EltNo >= NumElems/2)
5269       EltNo -= NumElems/2;
5270   }
5271
5272   // All i16 and i8 vector types can't be used directly by a generic shuffle
5273   // instruction because the target has no such instruction. Generate shuffles
5274   // which repeat i16 and i8 several times until they fit in i32, and then can
5275   // be manipulated by target suported shuffles.
5276   MVT EltVT = SrcVT.getVectorElementType();
5277   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5278     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5279
5280   // Recreate the 256-bit vector and place the same 128-bit vector
5281   // into the low and high part. This is necessary because we want
5282   // to use VPERM* to shuffle the vectors
5283   if (Is256BitVec) {
5284     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5285   }
5286
5287   return getLegalSplat(DAG, V1, EltNo);
5288 }
5289
5290 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5291 /// vector of zero or undef vector.  This produces a shuffle where the low
5292 /// element of V2 is swizzled into the zero/undef vector, landing at element
5293 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5294 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5295                                            bool IsZero,
5296                                            const X86Subtarget *Subtarget,
5297                                            SelectionDAG &DAG) {
5298   MVT VT = V2.getSimpleValueType();
5299   SDValue V1 = IsZero
5300     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5301   unsigned NumElems = VT.getVectorNumElements();
5302   SmallVector<int, 16> MaskVec;
5303   for (unsigned i = 0; i != NumElems; ++i)
5304     // If this is the insertion idx, put the low elt of V2 here.
5305     MaskVec.push_back(i == Idx ? NumElems : i);
5306   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5307 }
5308
5309 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5310 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5311 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5312 /// shuffles which use a single input multiple times, and in those cases it will
5313 /// adjust the mask to only have indices within that single input.
5314 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5315                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5316   unsigned NumElems = VT.getVectorNumElements();
5317   SDValue ImmN;
5318
5319   IsUnary = false;
5320   bool IsFakeUnary = false;
5321   switch(N->getOpcode()) {
5322   case X86ISD::BLENDI:
5323     ImmN = N->getOperand(N->getNumOperands()-1);
5324     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5325     break;
5326   case X86ISD::SHUFP:
5327     ImmN = N->getOperand(N->getNumOperands()-1);
5328     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5329     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5330     break;
5331   case X86ISD::UNPCKH:
5332     DecodeUNPCKHMask(VT, Mask);
5333     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5334     break;
5335   case X86ISD::UNPCKL:
5336     DecodeUNPCKLMask(VT, Mask);
5337     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5338     break;
5339   case X86ISD::MOVHLPS:
5340     DecodeMOVHLPSMask(NumElems, Mask);
5341     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5342     break;
5343   case X86ISD::MOVLHPS:
5344     DecodeMOVLHPSMask(NumElems, Mask);
5345     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5346     break;
5347   case X86ISD::PALIGNR:
5348     ImmN = N->getOperand(N->getNumOperands()-1);
5349     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5350     break;
5351   case X86ISD::PSHUFD:
5352   case X86ISD::VPERMILPI:
5353     ImmN = N->getOperand(N->getNumOperands()-1);
5354     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5355     IsUnary = true;
5356     break;
5357   case X86ISD::PSHUFHW:
5358     ImmN = N->getOperand(N->getNumOperands()-1);
5359     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5360     IsUnary = true;
5361     break;
5362   case X86ISD::PSHUFLW:
5363     ImmN = N->getOperand(N->getNumOperands()-1);
5364     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5365     IsUnary = true;
5366     break;
5367   case X86ISD::PSHUFB: {
5368     IsUnary = true;
5369     SDValue MaskNode = N->getOperand(1);
5370     while (MaskNode->getOpcode() == ISD::BITCAST)
5371       MaskNode = MaskNode->getOperand(0);
5372
5373     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5374       // If we have a build-vector, then things are easy.
5375       EVT VT = MaskNode.getValueType();
5376       assert(VT.isVector() &&
5377              "Can't produce a non-vector with a build_vector!");
5378       if (!VT.isInteger())
5379         return false;
5380
5381       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5382
5383       SmallVector<uint64_t, 32> RawMask;
5384       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5385         SDValue Op = MaskNode->getOperand(i);
5386         if (Op->getOpcode() == ISD::UNDEF) {
5387           RawMask.push_back((uint64_t)SM_SentinelUndef);
5388           continue;
5389         }
5390         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5391         if (!CN)
5392           return false;
5393         APInt MaskElement = CN->getAPIntValue();
5394
5395         // We now have to decode the element which could be any integer size and
5396         // extract each byte of it.
5397         for (int j = 0; j < NumBytesPerElement; ++j) {
5398           // Note that this is x86 and so always little endian: the low byte is
5399           // the first byte of the mask.
5400           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5401           MaskElement = MaskElement.lshr(8);
5402         }
5403       }
5404       DecodePSHUFBMask(RawMask, Mask);
5405       break;
5406     }
5407
5408     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5409     if (!MaskLoad)
5410       return false;
5411
5412     SDValue Ptr = MaskLoad->getBasePtr();
5413     if (Ptr->getOpcode() == X86ISD::Wrapper)
5414       Ptr = Ptr->getOperand(0);
5415
5416     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5417     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5418       return false;
5419
5420     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5421       // FIXME: Support AVX-512 here.
5422       Type *Ty = C->getType();
5423       if (!Ty->isVectorTy() || (Ty->getVectorNumElements() != 16 &&
5424                                 Ty->getVectorNumElements() != 32))
5425         return false;
5426
5427       DecodePSHUFBMask(C, Mask);
5428       break;
5429     }
5430
5431     return false;
5432   }
5433   case X86ISD::VPERMI:
5434     ImmN = N->getOperand(N->getNumOperands()-1);
5435     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5436     IsUnary = true;
5437     break;
5438   case X86ISD::MOVSS:
5439   case X86ISD::MOVSD: {
5440     // The index 0 always comes from the first element of the second source,
5441     // this is why MOVSS and MOVSD are used in the first place. The other
5442     // elements come from the other positions of the first source vector
5443     Mask.push_back(NumElems);
5444     for (unsigned i = 1; i != NumElems; ++i) {
5445       Mask.push_back(i);
5446     }
5447     break;
5448   }
5449   case X86ISD::VPERM2X128:
5450     ImmN = N->getOperand(N->getNumOperands()-1);
5451     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5452     if (Mask.empty()) return false;
5453     break;
5454   case X86ISD::MOVSLDUP:
5455     DecodeMOVSLDUPMask(VT, Mask);
5456     break;
5457   case X86ISD::MOVSHDUP:
5458     DecodeMOVSHDUPMask(VT, Mask);
5459     break;
5460   case X86ISD::MOVDDUP:
5461   case X86ISD::MOVLHPD:
5462   case X86ISD::MOVLPD:
5463   case X86ISD::MOVLPS:
5464     // Not yet implemented
5465     return false;
5466   default: llvm_unreachable("unknown target shuffle node");
5467   }
5468
5469   // If we have a fake unary shuffle, the shuffle mask is spread across two
5470   // inputs that are actually the same node. Re-map the mask to always point
5471   // into the first input.
5472   if (IsFakeUnary)
5473     for (int &M : Mask)
5474       if (M >= (int)Mask.size())
5475         M -= Mask.size();
5476
5477   return true;
5478 }
5479
5480 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5481 /// element of the result of the vector shuffle.
5482 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5483                                    unsigned Depth) {
5484   if (Depth == 6)
5485     return SDValue();  // Limit search depth.
5486
5487   SDValue V = SDValue(N, 0);
5488   EVT VT = V.getValueType();
5489   unsigned Opcode = V.getOpcode();
5490
5491   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5492   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5493     int Elt = SV->getMaskElt(Index);
5494
5495     if (Elt < 0)
5496       return DAG.getUNDEF(VT.getVectorElementType());
5497
5498     unsigned NumElems = VT.getVectorNumElements();
5499     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5500                                          : SV->getOperand(1);
5501     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5502   }
5503
5504   // Recurse into target specific vector shuffles to find scalars.
5505   if (isTargetShuffle(Opcode)) {
5506     MVT ShufVT = V.getSimpleValueType();
5507     unsigned NumElems = ShufVT.getVectorNumElements();
5508     SmallVector<int, 16> ShuffleMask;
5509     bool IsUnary;
5510
5511     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5512       return SDValue();
5513
5514     int Elt = ShuffleMask[Index];
5515     if (Elt < 0)
5516       return DAG.getUNDEF(ShufVT.getVectorElementType());
5517
5518     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5519                                          : N->getOperand(1);
5520     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5521                                Depth+1);
5522   }
5523
5524   // Actual nodes that may contain scalar elements
5525   if (Opcode == ISD::BITCAST) {
5526     V = V.getOperand(0);
5527     EVT SrcVT = V.getValueType();
5528     unsigned NumElems = VT.getVectorNumElements();
5529
5530     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5531       return SDValue();
5532   }
5533
5534   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5535     return (Index == 0) ? V.getOperand(0)
5536                         : DAG.getUNDEF(VT.getVectorElementType());
5537
5538   if (V.getOpcode() == ISD::BUILD_VECTOR)
5539     return V.getOperand(Index);
5540
5541   return SDValue();
5542 }
5543
5544 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5545 /// shuffle operation which come from a consecutively from a zero. The
5546 /// search can start in two different directions, from left or right.
5547 /// We count undefs as zeros until PreferredNum is reached.
5548 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5549                                          unsigned NumElems, bool ZerosFromLeft,
5550                                          SelectionDAG &DAG,
5551                                          unsigned PreferredNum = -1U) {
5552   unsigned NumZeros = 0;
5553   for (unsigned i = 0; i != NumElems; ++i) {
5554     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5555     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5556     if (!Elt.getNode())
5557       break;
5558
5559     if (X86::isZeroNode(Elt))
5560       ++NumZeros;
5561     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5562       NumZeros = std::min(NumZeros + 1, PreferredNum);
5563     else
5564       break;
5565   }
5566
5567   return NumZeros;
5568 }
5569
5570 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5571 /// correspond consecutively to elements from one of the vector operands,
5572 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5573 static
5574 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5575                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5576                               unsigned NumElems, unsigned &OpNum) {
5577   bool SeenV1 = false;
5578   bool SeenV2 = false;
5579
5580   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5581     int Idx = SVOp->getMaskElt(i);
5582     // Ignore undef indicies
5583     if (Idx < 0)
5584       continue;
5585
5586     if (Idx < (int)NumElems)
5587       SeenV1 = true;
5588     else
5589       SeenV2 = true;
5590
5591     // Only accept consecutive elements from the same vector
5592     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5593       return false;
5594   }
5595
5596   OpNum = SeenV1 ? 0 : 1;
5597   return true;
5598 }
5599
5600 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5601 /// logical left shift of a vector.
5602 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5603                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5604   unsigned NumElems =
5605     SVOp->getSimpleValueType(0).getVectorNumElements();
5606   unsigned NumZeros = getNumOfConsecutiveZeros(
5607       SVOp, NumElems, false /* check zeros from right */, DAG,
5608       SVOp->getMaskElt(0));
5609   unsigned OpSrc;
5610
5611   if (!NumZeros)
5612     return false;
5613
5614   // Considering the elements in the mask that are not consecutive zeros,
5615   // check if they consecutively come from only one of the source vectors.
5616   //
5617   //               V1 = {X, A, B, C}     0
5618   //                         \  \  \    /
5619   //   vector_shuffle V1, V2 <1, 2, 3, X>
5620   //
5621   if (!isShuffleMaskConsecutive(SVOp,
5622             0,                   // Mask Start Index
5623             NumElems-NumZeros,   // Mask End Index(exclusive)
5624             NumZeros,            // Where to start looking in the src vector
5625             NumElems,            // Number of elements in vector
5626             OpSrc))              // Which source operand ?
5627     return false;
5628
5629   isLeft = false;
5630   ShAmt = NumZeros;
5631   ShVal = SVOp->getOperand(OpSrc);
5632   return true;
5633 }
5634
5635 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5636 /// logical left shift of a vector.
5637 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5638                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5639   unsigned NumElems =
5640     SVOp->getSimpleValueType(0).getVectorNumElements();
5641   unsigned NumZeros = getNumOfConsecutiveZeros(
5642       SVOp, NumElems, true /* check zeros from left */, DAG,
5643       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5644   unsigned OpSrc;
5645
5646   if (!NumZeros)
5647     return false;
5648
5649   // Considering the elements in the mask that are not consecutive zeros,
5650   // check if they consecutively come from only one of the source vectors.
5651   //
5652   //                           0    { A, B, X, X } = V2
5653   //                          / \    /  /
5654   //   vector_shuffle V1, V2 <X, X, 4, 5>
5655   //
5656   if (!isShuffleMaskConsecutive(SVOp,
5657             NumZeros,     // Mask Start Index
5658             NumElems,     // Mask End Index(exclusive)
5659             0,            // Where to start looking in the src vector
5660             NumElems,     // Number of elements in vector
5661             OpSrc))       // Which source operand ?
5662     return false;
5663
5664   isLeft = true;
5665   ShAmt = NumZeros;
5666   ShVal = SVOp->getOperand(OpSrc);
5667   return true;
5668 }
5669
5670 /// isVectorShift - Returns true if the shuffle can be implemented as a
5671 /// logical left or right shift of a vector.
5672 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5673                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5674   // Although the logic below support any bitwidth size, there are no
5675   // shift instructions which handle more than 128-bit vectors.
5676   if (!SVOp->getSimpleValueType(0).is128BitVector())
5677     return false;
5678
5679   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5680       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5681     return true;
5682
5683   return false;
5684 }
5685
5686 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5687 ///
5688 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5689                                        unsigned NumNonZero, unsigned NumZero,
5690                                        SelectionDAG &DAG,
5691                                        const X86Subtarget* Subtarget,
5692                                        const TargetLowering &TLI) {
5693   if (NumNonZero > 8)
5694     return SDValue();
5695
5696   SDLoc dl(Op);
5697   SDValue V;
5698   bool First = true;
5699   for (unsigned i = 0; i < 16; ++i) {
5700     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5701     if (ThisIsNonZero && First) {
5702       if (NumZero)
5703         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5704       else
5705         V = DAG.getUNDEF(MVT::v8i16);
5706       First = false;
5707     }
5708
5709     if ((i & 1) != 0) {
5710       SDValue ThisElt, LastElt;
5711       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5712       if (LastIsNonZero) {
5713         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5714                               MVT::i16, Op.getOperand(i-1));
5715       }
5716       if (ThisIsNonZero) {
5717         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5718         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5719                               ThisElt, DAG.getConstant(8, MVT::i8));
5720         if (LastIsNonZero)
5721           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5722       } else
5723         ThisElt = LastElt;
5724
5725       if (ThisElt.getNode())
5726         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5727                         DAG.getIntPtrConstant(i/2));
5728     }
5729   }
5730
5731   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5732 }
5733
5734 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5735 ///
5736 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5737                                      unsigned NumNonZero, unsigned NumZero,
5738                                      SelectionDAG &DAG,
5739                                      const X86Subtarget* Subtarget,
5740                                      const TargetLowering &TLI) {
5741   if (NumNonZero > 4)
5742     return SDValue();
5743
5744   SDLoc dl(Op);
5745   SDValue V;
5746   bool First = true;
5747   for (unsigned i = 0; i < 8; ++i) {
5748     bool isNonZero = (NonZeros & (1 << i)) != 0;
5749     if (isNonZero) {
5750       if (First) {
5751         if (NumZero)
5752           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5753         else
5754           V = DAG.getUNDEF(MVT::v8i16);
5755         First = false;
5756       }
5757       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5758                       MVT::v8i16, V, Op.getOperand(i),
5759                       DAG.getIntPtrConstant(i));
5760     }
5761   }
5762
5763   return V;
5764 }
5765
5766 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5767 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5768                                      const X86Subtarget *Subtarget,
5769                                      const TargetLowering &TLI) {
5770   // Find all zeroable elements.
5771   bool Zeroable[4];
5772   for (int i=0; i < 4; ++i) {
5773     SDValue Elt = Op->getOperand(i);
5774     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5775   }
5776   assert(std::count_if(&Zeroable[0], &Zeroable[4],
5777                        [](bool M) { return !M; }) > 1 &&
5778          "We expect at least two non-zero elements!");
5779
5780   // We only know how to deal with build_vector nodes where elements are either
5781   // zeroable or extract_vector_elt with constant index.
5782   SDValue FirstNonZero;
5783   unsigned FirstNonZeroIdx;
5784   for (unsigned i=0; i < 4; ++i) {
5785     if (Zeroable[i])
5786       continue;
5787     SDValue Elt = Op->getOperand(i);
5788     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5789         !isa<ConstantSDNode>(Elt.getOperand(1)))
5790       return SDValue();
5791     // Make sure that this node is extracting from a 128-bit vector.
5792     MVT VT = Elt.getOperand(0).getSimpleValueType();
5793     if (!VT.is128BitVector())
5794       return SDValue();
5795     if (!FirstNonZero.getNode()) {
5796       FirstNonZero = Elt;
5797       FirstNonZeroIdx = i;
5798     }
5799   }
5800
5801   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5802   SDValue V1 = FirstNonZero.getOperand(0);
5803   MVT VT = V1.getSimpleValueType();
5804
5805   // See if this build_vector can be lowered as a blend with zero.
5806   SDValue Elt;
5807   unsigned EltMaskIdx, EltIdx;
5808   int Mask[4];
5809   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5810     if (Zeroable[EltIdx]) {
5811       // The zero vector will be on the right hand side.
5812       Mask[EltIdx] = EltIdx+4;
5813       continue;
5814     }
5815
5816     Elt = Op->getOperand(EltIdx);
5817     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5818     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5819     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5820       break;
5821     Mask[EltIdx] = EltIdx;
5822   }
5823
5824   if (EltIdx == 4) {
5825     // Let the shuffle legalizer deal with blend operations.
5826     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5827     if (V1.getSimpleValueType() != VT)
5828       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5829     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5830   }
5831
5832   // See if we can lower this build_vector to a INSERTPS.
5833   if (!Subtarget->hasSSE41())
5834     return SDValue();
5835
5836   SDValue V2 = Elt.getOperand(0);
5837   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5838     V1 = SDValue();
5839
5840   bool CanFold = true;
5841   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5842     if (Zeroable[i])
5843       continue;
5844
5845     SDValue Current = Op->getOperand(i);
5846     SDValue SrcVector = Current->getOperand(0);
5847     if (!V1.getNode())
5848       V1 = SrcVector;
5849     CanFold = SrcVector == V1 &&
5850       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5851   }
5852
5853   if (!CanFold)
5854     return SDValue();
5855
5856   assert(V1.getNode() && "Expected at least two non-zero elements!");
5857   if (V1.getSimpleValueType() != MVT::v4f32)
5858     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5859   if (V2.getSimpleValueType() != MVT::v4f32)
5860     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5861
5862   // Ok, we can emit an INSERTPS instruction.
5863   unsigned ZMask = 0;
5864   for (int i = 0; i < 4; ++i)
5865     if (Zeroable[i])
5866       ZMask |= 1 << i;
5867
5868   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5869   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5870   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
5871                                DAG.getIntPtrConstant(InsertPSMask));
5872   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
5873 }
5874
5875 /// getVShift - Return a vector logical shift node.
5876 ///
5877 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5878                          unsigned NumBits, SelectionDAG &DAG,
5879                          const TargetLowering &TLI, SDLoc dl) {
5880   assert(VT.is128BitVector() && "Unknown type for VShift");
5881   EVT ShVT = MVT::v2i64;
5882   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5883   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5884   return DAG.getNode(ISD::BITCAST, dl, VT,
5885                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5886                              DAG.getConstant(NumBits,
5887                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5888 }
5889
5890 static SDValue
5891 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5892
5893   // Check if the scalar load can be widened into a vector load. And if
5894   // the address is "base + cst" see if the cst can be "absorbed" into
5895   // the shuffle mask.
5896   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5897     SDValue Ptr = LD->getBasePtr();
5898     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5899       return SDValue();
5900     EVT PVT = LD->getValueType(0);
5901     if (PVT != MVT::i32 && PVT != MVT::f32)
5902       return SDValue();
5903
5904     int FI = -1;
5905     int64_t Offset = 0;
5906     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5907       FI = FINode->getIndex();
5908       Offset = 0;
5909     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5910                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5911       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5912       Offset = Ptr.getConstantOperandVal(1);
5913       Ptr = Ptr.getOperand(0);
5914     } else {
5915       return SDValue();
5916     }
5917
5918     // FIXME: 256-bit vector instructions don't require a strict alignment,
5919     // improve this code to support it better.
5920     unsigned RequiredAlign = VT.getSizeInBits()/8;
5921     SDValue Chain = LD->getChain();
5922     // Make sure the stack object alignment is at least 16 or 32.
5923     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5924     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5925       if (MFI->isFixedObjectIndex(FI)) {
5926         // Can't change the alignment. FIXME: It's possible to compute
5927         // the exact stack offset and reference FI + adjust offset instead.
5928         // If someone *really* cares about this. That's the way to implement it.
5929         return SDValue();
5930       } else {
5931         MFI->setObjectAlignment(FI, RequiredAlign);
5932       }
5933     }
5934
5935     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5936     // Ptr + (Offset & ~15).
5937     if (Offset < 0)
5938       return SDValue();
5939     if ((Offset % RequiredAlign) & 3)
5940       return SDValue();
5941     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5942     if (StartOffset)
5943       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5944                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5945
5946     int EltNo = (Offset - StartOffset) >> 2;
5947     unsigned NumElems = VT.getVectorNumElements();
5948
5949     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5950     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5951                              LD->getPointerInfo().getWithOffset(StartOffset),
5952                              false, false, false, 0);
5953
5954     SmallVector<int, 8> Mask;
5955     for (unsigned i = 0; i != NumElems; ++i)
5956       Mask.push_back(EltNo);
5957
5958     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5959   }
5960
5961   return SDValue();
5962 }
5963
5964 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5965 /// vector of type 'VT', see if the elements can be replaced by a single large
5966 /// load which has the same value as a build_vector whose operands are 'elts'.
5967 ///
5968 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5969 ///
5970 /// FIXME: we'd also like to handle the case where the last elements are zero
5971 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5972 /// There's even a handy isZeroNode for that purpose.
5973 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5974                                         SDLoc &DL, SelectionDAG &DAG,
5975                                         bool isAfterLegalize) {
5976   EVT EltVT = VT.getVectorElementType();
5977   unsigned NumElems = Elts.size();
5978
5979   LoadSDNode *LDBase = nullptr;
5980   unsigned LastLoadedElt = -1U;
5981
5982   // For each element in the initializer, see if we've found a load or an undef.
5983   // If we don't find an initial load element, or later load elements are
5984   // non-consecutive, bail out.
5985   for (unsigned i = 0; i < NumElems; ++i) {
5986     SDValue Elt = Elts[i];
5987
5988     if (!Elt.getNode() ||
5989         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5990       return SDValue();
5991     if (!LDBase) {
5992       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5993         return SDValue();
5994       LDBase = cast<LoadSDNode>(Elt.getNode());
5995       LastLoadedElt = i;
5996       continue;
5997     }
5998     if (Elt.getOpcode() == ISD::UNDEF)
5999       continue;
6000
6001     LoadSDNode *LD = cast<LoadSDNode>(Elt);
6002     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
6003       return SDValue();
6004     LastLoadedElt = i;
6005   }
6006
6007   // If we have found an entire vector of loads and undefs, then return a large
6008   // load of the entire vector width starting at the base pointer.  If we found
6009   // consecutive loads for the low half, generate a vzext_load node.
6010   if (LastLoadedElt == NumElems - 1) {
6011
6012     if (isAfterLegalize &&
6013         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
6014       return SDValue();
6015
6016     SDValue NewLd = SDValue();
6017
6018     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
6019       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6020                           LDBase->getPointerInfo(),
6021                           LDBase->isVolatile(), LDBase->isNonTemporal(),
6022                           LDBase->isInvariant(), 0);
6023     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6024                         LDBase->getPointerInfo(),
6025                         LDBase->isVolatile(), LDBase->isNonTemporal(),
6026                         LDBase->isInvariant(), LDBase->getAlignment());
6027
6028     if (LDBase->hasAnyUseOfValue(1)) {
6029       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6030                                      SDValue(LDBase, 1),
6031                                      SDValue(NewLd.getNode(), 1));
6032       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6033       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6034                              SDValue(NewLd.getNode(), 1));
6035     }
6036
6037     return NewLd;
6038   }
6039   
6040   //TODO: The code below fires only for for loading the low v2i32 / v2f32
6041   //of a v4i32 / v4f32. It's probably worth generalizing.
6042   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
6043       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
6044     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
6045     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
6046     SDValue ResNode =
6047         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
6048                                 LDBase->getPointerInfo(),
6049                                 LDBase->getAlignment(),
6050                                 false/*isVolatile*/, true/*ReadMem*/,
6051                                 false/*WriteMem*/);
6052
6053     // Make sure the newly-created LOAD is in the same position as LDBase in
6054     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
6055     // update uses of LDBase's output chain to use the TokenFactor.
6056     if (LDBase->hasAnyUseOfValue(1)) {
6057       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6058                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
6059       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6060       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6061                              SDValue(ResNode.getNode(), 1));
6062     }
6063
6064     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
6065   }
6066   return SDValue();
6067 }
6068
6069 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6070 /// to generate a splat value for the following cases:
6071 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6072 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6073 /// a scalar load, or a constant.
6074 /// The VBROADCAST node is returned when a pattern is found,
6075 /// or SDValue() otherwise.
6076 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6077                                     SelectionDAG &DAG) {
6078   // VBROADCAST requires AVX.
6079   // TODO: Splats could be generated for non-AVX CPUs using SSE
6080   // instructions, but there's less potential gain for only 128-bit vectors.
6081   if (!Subtarget->hasAVX())
6082     return SDValue();
6083
6084   MVT VT = Op.getSimpleValueType();
6085   SDLoc dl(Op);
6086
6087   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6088          "Unsupported vector type for broadcast.");
6089
6090   SDValue Ld;
6091   bool ConstSplatVal;
6092
6093   switch (Op.getOpcode()) {
6094     default:
6095       // Unknown pattern found.
6096       return SDValue();
6097
6098     case ISD::BUILD_VECTOR: {
6099       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6100       BitVector UndefElements;
6101       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6102
6103       // We need a splat of a single value to use broadcast, and it doesn't
6104       // make any sense if the value is only in one element of the vector.
6105       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6106         return SDValue();
6107
6108       Ld = Splat;
6109       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6110                        Ld.getOpcode() == ISD::ConstantFP);
6111
6112       // Make sure that all of the users of a non-constant load are from the
6113       // BUILD_VECTOR node.
6114       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6115         return SDValue();
6116       break;
6117     }
6118
6119     case ISD::VECTOR_SHUFFLE: {
6120       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6121
6122       // Shuffles must have a splat mask where the first element is
6123       // broadcasted.
6124       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6125         return SDValue();
6126
6127       SDValue Sc = Op.getOperand(0);
6128       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6129           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6130
6131         if (!Subtarget->hasInt256())
6132           return SDValue();
6133
6134         // Use the register form of the broadcast instruction available on AVX2.
6135         if (VT.getSizeInBits() >= 256)
6136           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6137         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6138       }
6139
6140       Ld = Sc.getOperand(0);
6141       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6142                        Ld.getOpcode() == ISD::ConstantFP);
6143
6144       // The scalar_to_vector node and the suspected
6145       // load node must have exactly one user.
6146       // Constants may have multiple users.
6147
6148       // AVX-512 has register version of the broadcast
6149       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6150         Ld.getValueType().getSizeInBits() >= 32;
6151       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6152           !hasRegVer))
6153         return SDValue();
6154       break;
6155     }
6156   }
6157
6158   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6159   bool IsGE256 = (VT.getSizeInBits() >= 256);
6160
6161   // When optimizing for size, generate up to 5 extra bytes for a broadcast
6162   // instruction to save 8 or more bytes of constant pool data.
6163   // TODO: If multiple splats are generated to load the same constant,
6164   // it may be detrimental to overall size. There needs to be a way to detect
6165   // that condition to know if this is truly a size win.
6166   const Function *F = DAG.getMachineFunction().getFunction();
6167   bool OptForSize = F->getAttributes().
6168     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6169
6170   // Handle broadcasting a single constant scalar from the constant pool
6171   // into a vector.
6172   // On Sandybridge (no AVX2), it is still better to load a constant vector
6173   // from the constant pool and not to broadcast it from a scalar.
6174   // But override that restriction when optimizing for size.
6175   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
6176   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
6177     EVT CVT = Ld.getValueType();
6178     assert(!CVT.isVector() && "Must not broadcast a vector type");
6179
6180     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
6181     // For size optimization, also splat v2f64 and v2i64, and for size opt
6182     // with AVX2, also splat i8 and i16.
6183     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
6184     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6185         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
6186       const Constant *C = nullptr;
6187       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6188         C = CI->getConstantIntValue();
6189       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6190         C = CF->getConstantFPValue();
6191
6192       assert(C && "Invalid constant type");
6193
6194       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6195       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6196       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6197       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6198                        MachinePointerInfo::getConstantPool(),
6199                        false, false, false, Alignment);
6200
6201       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6202     }
6203   }
6204
6205   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6206
6207   // Handle AVX2 in-register broadcasts.
6208   if (!IsLoad && Subtarget->hasInt256() &&
6209       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6210     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6211
6212   // The scalar source must be a normal load.
6213   if (!IsLoad)
6214     return SDValue();
6215
6216   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6217       (Subtarget->hasVLX() && ScalarSize == 64))
6218     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6219
6220   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6221   // double since there is no vbroadcastsd xmm
6222   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6223     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6224       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6225   }
6226
6227   // Unsupported broadcast.
6228   return SDValue();
6229 }
6230
6231 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6232 /// underlying vector and index.
6233 ///
6234 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6235 /// index.
6236 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6237                                          SDValue ExtIdx) {
6238   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6239   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6240     return Idx;
6241
6242   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6243   // lowered this:
6244   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6245   // to:
6246   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6247   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6248   //                           undef)
6249   //                       Constant<0>)
6250   // In this case the vector is the extract_subvector expression and the index
6251   // is 2, as specified by the shuffle.
6252   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6253   SDValue ShuffleVec = SVOp->getOperand(0);
6254   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6255   assert(ShuffleVecVT.getVectorElementType() ==
6256          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6257
6258   int ShuffleIdx = SVOp->getMaskElt(Idx);
6259   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6260     ExtractedFromVec = ShuffleVec;
6261     return ShuffleIdx;
6262   }
6263   return Idx;
6264 }
6265
6266 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6267   MVT VT = Op.getSimpleValueType();
6268
6269   // Skip if insert_vec_elt is not supported.
6270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6271   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6272     return SDValue();
6273
6274   SDLoc DL(Op);
6275   unsigned NumElems = Op.getNumOperands();
6276
6277   SDValue VecIn1;
6278   SDValue VecIn2;
6279   SmallVector<unsigned, 4> InsertIndices;
6280   SmallVector<int, 8> Mask(NumElems, -1);
6281
6282   for (unsigned i = 0; i != NumElems; ++i) {
6283     unsigned Opc = Op.getOperand(i).getOpcode();
6284
6285     if (Opc == ISD::UNDEF)
6286       continue;
6287
6288     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6289       // Quit if more than 1 elements need inserting.
6290       if (InsertIndices.size() > 1)
6291         return SDValue();
6292
6293       InsertIndices.push_back(i);
6294       continue;
6295     }
6296
6297     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6298     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6299     // Quit if non-constant index.
6300     if (!isa<ConstantSDNode>(ExtIdx))
6301       return SDValue();
6302     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6303
6304     // Quit if extracted from vector of different type.
6305     if (ExtractedFromVec.getValueType() != VT)
6306       return SDValue();
6307
6308     if (!VecIn1.getNode())
6309       VecIn1 = ExtractedFromVec;
6310     else if (VecIn1 != ExtractedFromVec) {
6311       if (!VecIn2.getNode())
6312         VecIn2 = ExtractedFromVec;
6313       else if (VecIn2 != ExtractedFromVec)
6314         // Quit if more than 2 vectors to shuffle
6315         return SDValue();
6316     }
6317
6318     if (ExtractedFromVec == VecIn1)
6319       Mask[i] = Idx;
6320     else if (ExtractedFromVec == VecIn2)
6321       Mask[i] = Idx + NumElems;
6322   }
6323
6324   if (!VecIn1.getNode())
6325     return SDValue();
6326
6327   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6328   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6329   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6330     unsigned Idx = InsertIndices[i];
6331     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6332                      DAG.getIntPtrConstant(Idx));
6333   }
6334
6335   return NV;
6336 }
6337
6338 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6339 SDValue
6340 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6341
6342   MVT VT = Op.getSimpleValueType();
6343   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6344          "Unexpected type in LowerBUILD_VECTORvXi1!");
6345
6346   SDLoc dl(Op);
6347   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6348     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6349     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6350     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6351   }
6352
6353   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6354     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6355     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6356     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6357   }
6358
6359   bool AllContants = true;
6360   uint64_t Immediate = 0;
6361   int NonConstIdx = -1;
6362   bool IsSplat = true;
6363   unsigned NumNonConsts = 0;
6364   unsigned NumConsts = 0;
6365   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6366     SDValue In = Op.getOperand(idx);
6367     if (In.getOpcode() == ISD::UNDEF)
6368       continue;
6369     if (!isa<ConstantSDNode>(In)) {
6370       AllContants = false;
6371       NonConstIdx = idx;
6372       NumNonConsts++;
6373     } else {
6374       NumConsts++;
6375       if (cast<ConstantSDNode>(In)->getZExtValue())
6376       Immediate |= (1ULL << idx);
6377     }
6378     if (In != Op.getOperand(0))
6379       IsSplat = false;
6380   }
6381
6382   if (AllContants) {
6383     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6384       DAG.getConstant(Immediate, MVT::i16));
6385     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6386                        DAG.getIntPtrConstant(0));
6387   }
6388
6389   if (NumNonConsts == 1 && NonConstIdx != 0) {
6390     SDValue DstVec;
6391     if (NumConsts) {
6392       SDValue VecAsImm = DAG.getConstant(Immediate,
6393                                          MVT::getIntegerVT(VT.getSizeInBits()));
6394       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6395     }
6396     else
6397       DstVec = DAG.getUNDEF(VT);
6398     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6399                        Op.getOperand(NonConstIdx),
6400                        DAG.getIntPtrConstant(NonConstIdx));
6401   }
6402   if (!IsSplat && (NonConstIdx != 0))
6403     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6404   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6405   SDValue Select;
6406   if (IsSplat)
6407     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6408                           DAG.getConstant(-1, SelectVT),
6409                           DAG.getConstant(0, SelectVT));
6410   else
6411     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6412                          DAG.getConstant((Immediate | 1), SelectVT),
6413                          DAG.getConstant(Immediate, SelectVT));
6414   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6415 }
6416
6417 /// \brief Return true if \p N implements a horizontal binop and return the
6418 /// operands for the horizontal binop into V0 and V1.
6419 ///
6420 /// This is a helper function of PerformBUILD_VECTORCombine.
6421 /// This function checks that the build_vector \p N in input implements a
6422 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6423 /// operation to match.
6424 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6425 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6426 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6427 /// arithmetic sub.
6428 ///
6429 /// This function only analyzes elements of \p N whose indices are
6430 /// in range [BaseIdx, LastIdx).
6431 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6432                               SelectionDAG &DAG,
6433                               unsigned BaseIdx, unsigned LastIdx,
6434                               SDValue &V0, SDValue &V1) {
6435   EVT VT = N->getValueType(0);
6436
6437   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6438   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6439          "Invalid Vector in input!");
6440
6441   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6442   bool CanFold = true;
6443   unsigned ExpectedVExtractIdx = BaseIdx;
6444   unsigned NumElts = LastIdx - BaseIdx;
6445   V0 = DAG.getUNDEF(VT);
6446   V1 = DAG.getUNDEF(VT);
6447
6448   // Check if N implements a horizontal binop.
6449   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6450     SDValue Op = N->getOperand(i + BaseIdx);
6451
6452     // Skip UNDEFs.
6453     if (Op->getOpcode() == ISD::UNDEF) {
6454       // Update the expected vector extract index.
6455       if (i * 2 == NumElts)
6456         ExpectedVExtractIdx = BaseIdx;
6457       ExpectedVExtractIdx += 2;
6458       continue;
6459     }
6460
6461     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6462
6463     if (!CanFold)
6464       break;
6465
6466     SDValue Op0 = Op.getOperand(0);
6467     SDValue Op1 = Op.getOperand(1);
6468
6469     // Try to match the following pattern:
6470     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6471     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6472         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6473         Op0.getOperand(0) == Op1.getOperand(0) &&
6474         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6475         isa<ConstantSDNode>(Op1.getOperand(1)));
6476     if (!CanFold)
6477       break;
6478
6479     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6480     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6481
6482     if (i * 2 < NumElts) {
6483       if (V0.getOpcode() == ISD::UNDEF)
6484         V0 = Op0.getOperand(0);
6485     } else {
6486       if (V1.getOpcode() == ISD::UNDEF)
6487         V1 = Op0.getOperand(0);
6488       if (i * 2 == NumElts)
6489         ExpectedVExtractIdx = BaseIdx;
6490     }
6491
6492     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6493     if (I0 == ExpectedVExtractIdx)
6494       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6495     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6496       // Try to match the following dag sequence:
6497       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6498       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6499     } else
6500       CanFold = false;
6501
6502     ExpectedVExtractIdx += 2;
6503   }
6504
6505   return CanFold;
6506 }
6507
6508 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6509 /// a concat_vector.
6510 ///
6511 /// This is a helper function of PerformBUILD_VECTORCombine.
6512 /// This function expects two 256-bit vectors called V0 and V1.
6513 /// At first, each vector is split into two separate 128-bit vectors.
6514 /// Then, the resulting 128-bit vectors are used to implement two
6515 /// horizontal binary operations.
6516 ///
6517 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6518 ///
6519 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6520 /// the two new horizontal binop.
6521 /// When Mode is set, the first horizontal binop dag node would take as input
6522 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6523 /// horizontal binop dag node would take as input the lower 128-bit of V1
6524 /// and the upper 128-bit of V1.
6525 ///   Example:
6526 ///     HADD V0_LO, V0_HI
6527 ///     HADD V1_LO, V1_HI
6528 ///
6529 /// Otherwise, the first horizontal binop dag node takes as input the lower
6530 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6531 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6532 ///   Example:
6533 ///     HADD V0_LO, V1_LO
6534 ///     HADD V0_HI, V1_HI
6535 ///
6536 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6537 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6538 /// the upper 128-bits of the result.
6539 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6540                                      SDLoc DL, SelectionDAG &DAG,
6541                                      unsigned X86Opcode, bool Mode,
6542                                      bool isUndefLO, bool isUndefHI) {
6543   EVT VT = V0.getValueType();
6544   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6545          "Invalid nodes in input!");
6546
6547   unsigned NumElts = VT.getVectorNumElements();
6548   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6549   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6550   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6551   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6552   EVT NewVT = V0_LO.getValueType();
6553
6554   SDValue LO = DAG.getUNDEF(NewVT);
6555   SDValue HI = DAG.getUNDEF(NewVT);
6556
6557   if (Mode) {
6558     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6559     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6560       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6561     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6562       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6563   } else {
6564     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6565     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6566                        V1_LO->getOpcode() != ISD::UNDEF))
6567       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6568
6569     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6570                        V1_HI->getOpcode() != ISD::UNDEF))
6571       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6572   }
6573
6574   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6575 }
6576
6577 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6578 /// sequence of 'vadd + vsub + blendi'.
6579 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6580                            const X86Subtarget *Subtarget) {
6581   SDLoc DL(BV);
6582   EVT VT = BV->getValueType(0);
6583   unsigned NumElts = VT.getVectorNumElements();
6584   SDValue InVec0 = DAG.getUNDEF(VT);
6585   SDValue InVec1 = DAG.getUNDEF(VT);
6586
6587   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6588           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6589
6590   // Odd-numbered elements in the input build vector are obtained from
6591   // adding two integer/float elements.
6592   // Even-numbered elements in the input build vector are obtained from
6593   // subtracting two integer/float elements.
6594   unsigned ExpectedOpcode = ISD::FSUB;
6595   unsigned NextExpectedOpcode = ISD::FADD;
6596   bool AddFound = false;
6597   bool SubFound = false;
6598
6599   for (unsigned i = 0, e = NumElts; i != e; i++) {
6600     SDValue Op = BV->getOperand(i);
6601
6602     // Skip 'undef' values.
6603     unsigned Opcode = Op.getOpcode();
6604     if (Opcode == ISD::UNDEF) {
6605       std::swap(ExpectedOpcode, NextExpectedOpcode);
6606       continue;
6607     }
6608
6609     // Early exit if we found an unexpected opcode.
6610     if (Opcode != ExpectedOpcode)
6611       return SDValue();
6612
6613     SDValue Op0 = Op.getOperand(0);
6614     SDValue Op1 = Op.getOperand(1);
6615
6616     // Try to match the following pattern:
6617     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6618     // Early exit if we cannot match that sequence.
6619     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6620         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6621         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6622         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6623         Op0.getOperand(1) != Op1.getOperand(1))
6624       return SDValue();
6625
6626     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6627     if (I0 != i)
6628       return SDValue();
6629
6630     // We found a valid add/sub node. Update the information accordingly.
6631     if (i & 1)
6632       AddFound = true;
6633     else
6634       SubFound = true;
6635
6636     // Update InVec0 and InVec1.
6637     if (InVec0.getOpcode() == ISD::UNDEF)
6638       InVec0 = Op0.getOperand(0);
6639     if (InVec1.getOpcode() == ISD::UNDEF)
6640       InVec1 = Op1.getOperand(0);
6641
6642     // Make sure that operands in input to each add/sub node always
6643     // come from a same pair of vectors.
6644     if (InVec0 != Op0.getOperand(0)) {
6645       if (ExpectedOpcode == ISD::FSUB)
6646         return SDValue();
6647
6648       // FADD is commutable. Try to commute the operands
6649       // and then test again.
6650       std::swap(Op0, Op1);
6651       if (InVec0 != Op0.getOperand(0))
6652         return SDValue();
6653     }
6654
6655     if (InVec1 != Op1.getOperand(0))
6656       return SDValue();
6657
6658     // Update the pair of expected opcodes.
6659     std::swap(ExpectedOpcode, NextExpectedOpcode);
6660   }
6661
6662   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6663   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6664       InVec1.getOpcode() != ISD::UNDEF)
6665     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6666
6667   return SDValue();
6668 }
6669
6670 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6671                                           const X86Subtarget *Subtarget) {
6672   SDLoc DL(N);
6673   EVT VT = N->getValueType(0);
6674   unsigned NumElts = VT.getVectorNumElements();
6675   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6676   SDValue InVec0, InVec1;
6677
6678   // Try to match an ADDSUB.
6679   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6680       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6681     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6682     if (Value.getNode())
6683       return Value;
6684   }
6685
6686   // Try to match horizontal ADD/SUB.
6687   unsigned NumUndefsLO = 0;
6688   unsigned NumUndefsHI = 0;
6689   unsigned Half = NumElts/2;
6690
6691   // Count the number of UNDEF operands in the build_vector in input.
6692   for (unsigned i = 0, e = Half; i != e; ++i)
6693     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6694       NumUndefsLO++;
6695
6696   for (unsigned i = Half, e = NumElts; i != e; ++i)
6697     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6698       NumUndefsHI++;
6699
6700   // Early exit if this is either a build_vector of all UNDEFs or all the
6701   // operands but one are UNDEF.
6702   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6703     return SDValue();
6704
6705   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6706     // Try to match an SSE3 float HADD/HSUB.
6707     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6708       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6709
6710     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6711       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6712   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6713     // Try to match an SSSE3 integer HADD/HSUB.
6714     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6715       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6716
6717     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6718       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6719   }
6720
6721   if (!Subtarget->hasAVX())
6722     return SDValue();
6723
6724   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6725     // Try to match an AVX horizontal add/sub of packed single/double
6726     // precision floating point values from 256-bit vectors.
6727     SDValue InVec2, InVec3;
6728     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6729         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6730         ((InVec0.getOpcode() == ISD::UNDEF ||
6731           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6732         ((InVec1.getOpcode() == ISD::UNDEF ||
6733           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6734       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6735
6736     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6737         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6738         ((InVec0.getOpcode() == ISD::UNDEF ||
6739           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6740         ((InVec1.getOpcode() == ISD::UNDEF ||
6741           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6742       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6743   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6744     // Try to match an AVX2 horizontal add/sub of signed integers.
6745     SDValue InVec2, InVec3;
6746     unsigned X86Opcode;
6747     bool CanFold = true;
6748
6749     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6750         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6751         ((InVec0.getOpcode() == ISD::UNDEF ||
6752           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6753         ((InVec1.getOpcode() == ISD::UNDEF ||
6754           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6755       X86Opcode = X86ISD::HADD;
6756     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6757         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6758         ((InVec0.getOpcode() == ISD::UNDEF ||
6759           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6760         ((InVec1.getOpcode() == ISD::UNDEF ||
6761           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6762       X86Opcode = X86ISD::HSUB;
6763     else
6764       CanFold = false;
6765
6766     if (CanFold) {
6767       // Fold this build_vector into a single horizontal add/sub.
6768       // Do this only if the target has AVX2.
6769       if (Subtarget->hasAVX2())
6770         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6771
6772       // Do not try to expand this build_vector into a pair of horizontal
6773       // add/sub if we can emit a pair of scalar add/sub.
6774       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6775         return SDValue();
6776
6777       // Convert this build_vector into a pair of horizontal binop followed by
6778       // a concat vector.
6779       bool isUndefLO = NumUndefsLO == Half;
6780       bool isUndefHI = NumUndefsHI == Half;
6781       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6782                                    isUndefLO, isUndefHI);
6783     }
6784   }
6785
6786   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6787        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6788     unsigned X86Opcode;
6789     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6790       X86Opcode = X86ISD::HADD;
6791     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6792       X86Opcode = X86ISD::HSUB;
6793     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6794       X86Opcode = X86ISD::FHADD;
6795     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6796       X86Opcode = X86ISD::FHSUB;
6797     else
6798       return SDValue();
6799
6800     // Don't try to expand this build_vector into a pair of horizontal add/sub
6801     // if we can simply emit a pair of scalar add/sub.
6802     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6803       return SDValue();
6804
6805     // Convert this build_vector into two horizontal add/sub followed by
6806     // a concat vector.
6807     bool isUndefLO = NumUndefsLO == Half;
6808     bool isUndefHI = NumUndefsHI == Half;
6809     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6810                                  isUndefLO, isUndefHI);
6811   }
6812
6813   return SDValue();
6814 }
6815
6816 SDValue
6817 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6818   SDLoc dl(Op);
6819
6820   MVT VT = Op.getSimpleValueType();
6821   MVT ExtVT = VT.getVectorElementType();
6822   unsigned NumElems = Op.getNumOperands();
6823
6824   // Generate vectors for predicate vectors.
6825   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6826     return LowerBUILD_VECTORvXi1(Op, DAG);
6827
6828   // Vectors containing all zeros can be matched by pxor and xorps later
6829   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6830     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6831     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6832     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6833       return Op;
6834
6835     return getZeroVector(VT, Subtarget, DAG, dl);
6836   }
6837
6838   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6839   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6840   // vpcmpeqd on 256-bit vectors.
6841   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6842     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6843       return Op;
6844
6845     if (!VT.is512BitVector())
6846       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6847   }
6848
6849   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6850   if (Broadcast.getNode())
6851     return Broadcast;
6852
6853   unsigned EVTBits = ExtVT.getSizeInBits();
6854
6855   unsigned NumZero  = 0;
6856   unsigned NumNonZero = 0;
6857   unsigned NonZeros = 0;
6858   bool IsAllConstants = true;
6859   SmallSet<SDValue, 8> Values;
6860   for (unsigned i = 0; i < NumElems; ++i) {
6861     SDValue Elt = Op.getOperand(i);
6862     if (Elt.getOpcode() == ISD::UNDEF)
6863       continue;
6864     Values.insert(Elt);
6865     if (Elt.getOpcode() != ISD::Constant &&
6866         Elt.getOpcode() != ISD::ConstantFP)
6867       IsAllConstants = false;
6868     if (X86::isZeroNode(Elt))
6869       NumZero++;
6870     else {
6871       NonZeros |= (1 << i);
6872       NumNonZero++;
6873     }
6874   }
6875
6876   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6877   if (NumNonZero == 0)
6878     return DAG.getUNDEF(VT);
6879
6880   // Special case for single non-zero, non-undef, element.
6881   if (NumNonZero == 1) {
6882     unsigned Idx = countTrailingZeros(NonZeros);
6883     SDValue Item = Op.getOperand(Idx);
6884
6885     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6886     // the value are obviously zero, truncate the value to i32 and do the
6887     // insertion that way.  Only do this if the value is non-constant or if the
6888     // value is a constant being inserted into element 0.  It is cheaper to do
6889     // a constant pool load than it is to do a movd + shuffle.
6890     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6891         (!IsAllConstants || Idx == 0)) {
6892       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6893         // Handle SSE only.
6894         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6895         EVT VecVT = MVT::v4i32;
6896         unsigned VecElts = 4;
6897
6898         // Truncate the value (which may itself be a constant) to i32, and
6899         // convert it to a vector with movd (S2V+shuffle to zero extend).
6900         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6901         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6902
6903         // If using the new shuffle lowering, just directly insert this.
6904         if (ExperimentalVectorShuffleLowering)
6905           return DAG.getNode(
6906               ISD::BITCAST, dl, VT,
6907               getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6908
6909         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6910
6911         // Now we have our 32-bit value zero extended in the low element of
6912         // a vector.  If Idx != 0, swizzle it into place.
6913         if (Idx != 0) {
6914           SmallVector<int, 4> Mask;
6915           Mask.push_back(Idx);
6916           for (unsigned i = 1; i != VecElts; ++i)
6917             Mask.push_back(i);
6918           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6919                                       &Mask[0]);
6920         }
6921         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6922       }
6923     }
6924
6925     // If we have a constant or non-constant insertion into the low element of
6926     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6927     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6928     // depending on what the source datatype is.
6929     if (Idx == 0) {
6930       if (NumZero == 0)
6931         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6932
6933       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6934           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6935         if (VT.is256BitVector() || VT.is512BitVector()) {
6936           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6937           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6938                              Item, DAG.getIntPtrConstant(0));
6939         }
6940         assert(VT.is128BitVector() && "Expected an SSE value type!");
6941         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6942         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6943         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6944       }
6945
6946       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6947         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6948         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6949         if (VT.is256BitVector()) {
6950           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6951           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6952         } else {
6953           assert(VT.is128BitVector() && "Expected an SSE value type!");
6954           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6955         }
6956         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6957       }
6958     }
6959
6960     // Is it a vector logical left shift?
6961     if (NumElems == 2 && Idx == 1 &&
6962         X86::isZeroNode(Op.getOperand(0)) &&
6963         !X86::isZeroNode(Op.getOperand(1))) {
6964       unsigned NumBits = VT.getSizeInBits();
6965       return getVShift(true, VT,
6966                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6967                                    VT, Op.getOperand(1)),
6968                        NumBits/2, DAG, *this, dl);
6969     }
6970
6971     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6972       return SDValue();
6973
6974     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6975     // is a non-constant being inserted into an element other than the low one,
6976     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6977     // movd/movss) to move this into the low element, then shuffle it into
6978     // place.
6979     if (EVTBits == 32) {
6980       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6981
6982       // If using the new shuffle lowering, just directly insert this.
6983       if (ExperimentalVectorShuffleLowering)
6984         return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6985
6986       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6987       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6988       SmallVector<int, 8> MaskVec;
6989       for (unsigned i = 0; i != NumElems; ++i)
6990         MaskVec.push_back(i == Idx ? 0 : 1);
6991       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6992     }
6993   }
6994
6995   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6996   if (Values.size() == 1) {
6997     if (EVTBits == 32) {
6998       // Instead of a shuffle like this:
6999       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
7000       // Check if it's possible to issue this instead.
7001       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
7002       unsigned Idx = countTrailingZeros(NonZeros);
7003       SDValue Item = Op.getOperand(Idx);
7004       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
7005         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
7006     }
7007     return SDValue();
7008   }
7009
7010   // A vector full of immediates; various special cases are already
7011   // handled, so this is best done with a single constant-pool load.
7012   if (IsAllConstants)
7013     return SDValue();
7014
7015   // For AVX-length vectors, see if we can use a vector load to get all of the
7016   // elements, otherwise build the individual 128-bit pieces and use
7017   // shuffles to put them in place.
7018   if (VT.is256BitVector() || VT.is512BitVector()) {
7019     SmallVector<SDValue, 64> V;
7020     for (unsigned i = 0; i != NumElems; ++i)
7021       V.push_back(Op.getOperand(i));
7022
7023     // Check for a build vector of consecutive loads.
7024     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
7025       return LD;
7026     
7027     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
7028
7029     // Build both the lower and upper subvector.
7030     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7031                                 makeArrayRef(&V[0], NumElems/2));
7032     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7033                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
7034
7035     // Recreate the wider vector with the lower and upper part.
7036     if (VT.is256BitVector())
7037       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7038     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7039   }
7040
7041   // Let legalizer expand 2-wide build_vectors.
7042   if (EVTBits == 64) {
7043     if (NumNonZero == 1) {
7044       // One half is zero or undef.
7045       unsigned Idx = countTrailingZeros(NonZeros);
7046       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
7047                                  Op.getOperand(Idx));
7048       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
7049     }
7050     return SDValue();
7051   }
7052
7053   // If element VT is < 32 bits, convert it to inserts into a zero vector.
7054   if (EVTBits == 8 && NumElems == 16) {
7055     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
7056                                         Subtarget, *this);
7057     if (V.getNode()) return V;
7058   }
7059
7060   if (EVTBits == 16 && NumElems == 8) {
7061     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
7062                                       Subtarget, *this);
7063     if (V.getNode()) return V;
7064   }
7065
7066   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
7067   if (EVTBits == 32 && NumElems == 4) {
7068     SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
7069     if (V.getNode())
7070       return V;
7071   }
7072
7073   // If element VT is == 32 bits, turn it into a number of shuffles.
7074   SmallVector<SDValue, 8> V(NumElems);
7075   if (NumElems == 4 && NumZero > 0) {
7076     for (unsigned i = 0; i < 4; ++i) {
7077       bool isZero = !(NonZeros & (1 << i));
7078       if (isZero)
7079         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7080       else
7081         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7082     }
7083
7084     for (unsigned i = 0; i < 2; ++i) {
7085       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7086         default: break;
7087         case 0:
7088           V[i] = V[i*2];  // Must be a zero vector.
7089           break;
7090         case 1:
7091           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7092           break;
7093         case 2:
7094           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7095           break;
7096         case 3:
7097           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7098           break;
7099       }
7100     }
7101
7102     bool Reverse1 = (NonZeros & 0x3) == 2;
7103     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7104     int MaskVec[] = {
7105       Reverse1 ? 1 : 0,
7106       Reverse1 ? 0 : 1,
7107       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7108       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7109     };
7110     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7111   }
7112
7113   if (Values.size() > 1 && VT.is128BitVector()) {
7114     // Check for a build vector of consecutive loads.
7115     for (unsigned i = 0; i < NumElems; ++i)
7116       V[i] = Op.getOperand(i);
7117
7118     // Check for elements which are consecutive loads.
7119     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7120     if (LD.getNode())
7121       return LD;
7122
7123     // Check for a build vector from mostly shuffle plus few inserting.
7124     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7125     if (Sh.getNode())
7126       return Sh;
7127
7128     // For SSE 4.1, use insertps to put the high elements into the low element.
7129     if (getSubtarget()->hasSSE41()) {
7130       SDValue Result;
7131       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7132         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7133       else
7134         Result = DAG.getUNDEF(VT);
7135
7136       for (unsigned i = 1; i < NumElems; ++i) {
7137         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7138         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7139                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7140       }
7141       return Result;
7142     }
7143
7144     // Otherwise, expand into a number of unpckl*, start by extending each of
7145     // our (non-undef) elements to the full vector width with the element in the
7146     // bottom slot of the vector (which generates no code for SSE).
7147     for (unsigned i = 0; i < NumElems; ++i) {
7148       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7149         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7150       else
7151         V[i] = DAG.getUNDEF(VT);
7152     }
7153
7154     // Next, we iteratively mix elements, e.g. for v4f32:
7155     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7156     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7157     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7158     unsigned EltStride = NumElems >> 1;
7159     while (EltStride != 0) {
7160       for (unsigned i = 0; i < EltStride; ++i) {
7161         // If V[i+EltStride] is undef and this is the first round of mixing,
7162         // then it is safe to just drop this shuffle: V[i] is already in the
7163         // right place, the one element (since it's the first round) being
7164         // inserted as undef can be dropped.  This isn't safe for successive
7165         // rounds because they will permute elements within both vectors.
7166         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7167             EltStride == NumElems/2)
7168           continue;
7169
7170         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7171       }
7172       EltStride >>= 1;
7173     }
7174     return V[0];
7175   }
7176   return SDValue();
7177 }
7178
7179 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7180 // to create 256-bit vectors from two other 128-bit ones.
7181 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7182   SDLoc dl(Op);
7183   MVT ResVT = Op.getSimpleValueType();
7184
7185   assert((ResVT.is256BitVector() ||
7186           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7187
7188   SDValue V1 = Op.getOperand(0);
7189   SDValue V2 = Op.getOperand(1);
7190   unsigned NumElems = ResVT.getVectorNumElements();
7191   if(ResVT.is256BitVector())
7192     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7193
7194   if (Op.getNumOperands() == 4) {
7195     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7196                                 ResVT.getVectorNumElements()/2);
7197     SDValue V3 = Op.getOperand(2);
7198     SDValue V4 = Op.getOperand(3);
7199     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7200       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7201   }
7202   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7203 }
7204
7205 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7206   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7207   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7208          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7209           Op.getNumOperands() == 4)));
7210
7211   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7212   // from two other 128-bit ones.
7213
7214   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7215   return LowerAVXCONCAT_VECTORS(Op, DAG);
7216 }
7217
7218
7219 //===----------------------------------------------------------------------===//
7220 // Vector shuffle lowering
7221 //
7222 // This is an experimental code path for lowering vector shuffles on x86. It is
7223 // designed to handle arbitrary vector shuffles and blends, gracefully
7224 // degrading performance as necessary. It works hard to recognize idiomatic
7225 // shuffles and lower them to optimal instruction patterns without leaving
7226 // a framework that allows reasonably efficient handling of all vector shuffle
7227 // patterns.
7228 //===----------------------------------------------------------------------===//
7229
7230 /// \brief Tiny helper function to identify a no-op mask.
7231 ///
7232 /// This is a somewhat boring predicate function. It checks whether the mask
7233 /// array input, which is assumed to be a single-input shuffle mask of the kind
7234 /// used by the X86 shuffle instructions (not a fully general
7235 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7236 /// in-place shuffle are 'no-op's.
7237 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7238   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7239     if (Mask[i] != -1 && Mask[i] != i)
7240       return false;
7241   return true;
7242 }
7243
7244 /// \brief Helper function to classify a mask as a single-input mask.
7245 ///
7246 /// This isn't a generic single-input test because in the vector shuffle
7247 /// lowering we canonicalize single inputs to be the first input operand. This
7248 /// means we can more quickly test for a single input by only checking whether
7249 /// an input from the second operand exists. We also assume that the size of
7250 /// mask corresponds to the size of the input vectors which isn't true in the
7251 /// fully general case.
7252 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7253   for (int M : Mask)
7254     if (M >= (int)Mask.size())
7255       return false;
7256   return true;
7257 }
7258
7259 /// \brief Test whether there are elements crossing 128-bit lanes in this
7260 /// shuffle mask.
7261 ///
7262 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
7263 /// and we routinely test for these.
7264 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
7265   int LaneSize = 128 / VT.getScalarSizeInBits();
7266   int Size = Mask.size();
7267   for (int i = 0; i < Size; ++i)
7268     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
7269       return true;
7270   return false;
7271 }
7272
7273 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
7274 ///
7275 /// This checks a shuffle mask to see if it is performing the same
7276 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
7277 /// that it is also not lane-crossing. It may however involve a blend from the
7278 /// same lane of a second vector.
7279 ///
7280 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
7281 /// non-trivial to compute in the face of undef lanes. The representation is
7282 /// *not* suitable for use with existing 128-bit shuffles as it will contain
7283 /// entries from both V1 and V2 inputs to the wider mask.
7284 static bool
7285 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
7286                                 SmallVectorImpl<int> &RepeatedMask) {
7287   int LaneSize = 128 / VT.getScalarSizeInBits();
7288   RepeatedMask.resize(LaneSize, -1);
7289   int Size = Mask.size();
7290   for (int i = 0; i < Size; ++i) {
7291     if (Mask[i] < 0)
7292       continue;
7293     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
7294       // This entry crosses lanes, so there is no way to model this shuffle.
7295       return false;
7296
7297     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
7298     if (RepeatedMask[i % LaneSize] == -1)
7299       // This is the first non-undef entry in this slot of a 128-bit lane.
7300       RepeatedMask[i % LaneSize] =
7301           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
7302     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
7303       // Found a mismatch with the repeated mask.
7304       return false;
7305   }
7306   return true;
7307 }
7308
7309 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7310 // 2013 will allow us to use it as a non-type template parameter.
7311 namespace {
7312
7313 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7314 ///
7315 /// See its documentation for details.
7316 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7317   if (Mask.size() != Args.size())
7318     return false;
7319   for (int i = 0, e = Mask.size(); i < e; ++i) {
7320     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7321     if (Mask[i] != -1 && Mask[i] != *Args[i])
7322       return false;
7323   }
7324   return true;
7325 }
7326
7327 } // namespace
7328
7329 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7330 /// arguments.
7331 ///
7332 /// This is a fast way to test a shuffle mask against a fixed pattern:
7333 ///
7334 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7335 ///
7336 /// It returns true if the mask is exactly as wide as the argument list, and
7337 /// each element of the mask is either -1 (signifying undef) or the value given
7338 /// in the argument.
7339 static const VariadicFunction1<
7340     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7341
7342 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7343 ///
7344 /// This helper function produces an 8-bit shuffle immediate corresponding to
7345 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7346 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7347 /// example.
7348 ///
7349 /// NB: We rely heavily on "undef" masks preserving the input lane.
7350 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7351                                           SelectionDAG &DAG) {
7352   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7353   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7354   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7355   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7356   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7357
7358   unsigned Imm = 0;
7359   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7360   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7361   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7362   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7363   return DAG.getConstant(Imm, MVT::i8);
7364 }
7365
7366 /// \brief Try to emit a blend instruction for a shuffle.
7367 ///
7368 /// This doesn't do any checks for the availability of instructions for blending
7369 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7370 /// be matched in the backend with the type given. What it does check for is
7371 /// that the shuffle mask is in fact a blend.
7372 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7373                                          SDValue V2, ArrayRef<int> Mask,
7374                                          const X86Subtarget *Subtarget,
7375                                          SelectionDAG &DAG) {
7376
7377   unsigned BlendMask = 0;
7378   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7379     if (Mask[i] >= Size) {
7380       if (Mask[i] != i + Size)
7381         return SDValue(); // Shuffled V2 input!
7382       BlendMask |= 1u << i;
7383       continue;
7384     }
7385     if (Mask[i] >= 0 && Mask[i] != i)
7386       return SDValue(); // Shuffled V1 input!
7387   }
7388   switch (VT.SimpleTy) {
7389   case MVT::v2f64:
7390   case MVT::v4f32:
7391   case MVT::v4f64:
7392   case MVT::v8f32:
7393     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7394                        DAG.getConstant(BlendMask, MVT::i8));
7395
7396   case MVT::v4i64:
7397   case MVT::v8i32:
7398     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7399     // FALLTHROUGH
7400   case MVT::v2i64:
7401   case MVT::v4i32:
7402     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7403     // that instruction.
7404     if (Subtarget->hasAVX2()) {
7405       // Scale the blend by the number of 32-bit dwords per element.
7406       int Scale =  VT.getScalarSizeInBits() / 32;
7407       BlendMask = 0;
7408       for (int i = 0, Size = Mask.size(); i < Size; ++i)
7409         if (Mask[i] >= Size)
7410           for (int j = 0; j < Scale; ++j)
7411             BlendMask |= 1u << (i * Scale + j);
7412
7413       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7414       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
7415       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
7416       return DAG.getNode(ISD::BITCAST, DL, VT,
7417                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7418                                      DAG.getConstant(BlendMask, MVT::i8)));
7419     }
7420     // FALLTHROUGH
7421   case MVT::v8i16: {
7422     // For integer shuffles we need to expand the mask and cast the inputs to
7423     // v8i16s prior to blending.
7424     int Scale = 8 / VT.getVectorNumElements();
7425     BlendMask = 0;
7426     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7427       if (Mask[i] >= Size)
7428         for (int j = 0; j < Scale; ++j)
7429           BlendMask |= 1u << (i * Scale + j);
7430
7431     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
7432     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
7433     return DAG.getNode(ISD::BITCAST, DL, VT,
7434                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7435                                    DAG.getConstant(BlendMask, MVT::i8)));
7436   }
7437
7438   case MVT::v16i16: {
7439     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7440     SmallVector<int, 8> RepeatedMask;
7441     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7442       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7443       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7444       BlendMask = 0;
7445       for (int i = 0; i < 8; ++i)
7446         if (RepeatedMask[i] >= 16)
7447           BlendMask |= 1u << i;
7448       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7449                          DAG.getConstant(BlendMask, MVT::i8));
7450     }
7451   }
7452     // FALLTHROUGH
7453   case MVT::v32i8: {
7454     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7455     // Scale the blend by the number of bytes per element.
7456     int Scale =  VT.getScalarSizeInBits() / 8;
7457     assert(Mask.size() * Scale == 32 && "Not a 256-bit vector!");
7458
7459     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7460     // mix of LLVM's code generator and the x86 backend. We tell the code
7461     // generator that boolean values in the elements of an x86 vector register
7462     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7463     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7464     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7465     // of the element (the remaining are ignored) and 0 in that high bit would
7466     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7467     // the LLVM model for boolean values in vector elements gets the relevant
7468     // bit set, it is set backwards and over constrained relative to x86's
7469     // actual model.
7470     SDValue VSELECTMask[32];
7471     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7472       for (int j = 0; j < Scale; ++j)
7473         VSELECTMask[Scale * i + j] =
7474             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7475                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8);
7476
7477     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1);
7478     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V2);
7479     return DAG.getNode(
7480         ISD::BITCAST, DL, VT,
7481         DAG.getNode(ISD::VSELECT, DL, MVT::v32i8,
7482                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, VSELECTMask),
7483                     V1, V2));
7484   }
7485
7486   default:
7487     llvm_unreachable("Not a supported integer vector type!");
7488   }
7489 }
7490
7491 /// \brief Generic routine to lower a shuffle and blend as a decomposed set of
7492 /// unblended shuffles followed by an unshuffled blend.
7493 ///
7494 /// This matches the extremely common pattern for handling combined
7495 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7496 /// operations.
7497 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7498                                                           SDValue V1,
7499                                                           SDValue V2,
7500                                                           ArrayRef<int> Mask,
7501                                                           SelectionDAG &DAG) {
7502   // Shuffle the input elements into the desired positions in V1 and V2 and
7503   // blend them together.
7504   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7505   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7506   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7507   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7508     if (Mask[i] >= 0 && Mask[i] < Size) {
7509       V1Mask[i] = Mask[i];
7510       BlendMask[i] = i;
7511     } else if (Mask[i] >= Size) {
7512       V2Mask[i] = Mask[i] - Size;
7513       BlendMask[i] = i + Size;
7514     }
7515
7516   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7517   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7518   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7519 }
7520
7521 /// \brief Try to lower a vector shuffle as a byte rotation.
7522 ///
7523 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7524 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7525 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7526 /// try to generically lower a vector shuffle through such an pattern. It
7527 /// does not check for the profitability of lowering either as PALIGNR or
7528 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7529 /// This matches shuffle vectors that look like:
7530 ///
7531 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7532 ///
7533 /// Essentially it concatenates V1 and V2, shifts right by some number of
7534 /// elements, and takes the low elements as the result. Note that while this is
7535 /// specified as a *right shift* because x86 is little-endian, it is a *left
7536 /// rotate* of the vector lanes.
7537 ///
7538 /// Note that this only handles 128-bit vector widths currently.
7539 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7540                                               SDValue V2,
7541                                               ArrayRef<int> Mask,
7542                                               const X86Subtarget *Subtarget,
7543                                               SelectionDAG &DAG) {
7544   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7545
7546   // We need to detect various ways of spelling a rotation:
7547   //   [11, 12, 13, 14, 15,  0,  1,  2]
7548   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7549   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7550   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7551   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7552   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7553   int Rotation = 0;
7554   SDValue Lo, Hi;
7555   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7556     if (Mask[i] == -1)
7557       continue;
7558     assert(Mask[i] >= 0 && "Only -1 is a valid negative mask element!");
7559
7560     // Based on the mod-Size value of this mask element determine where
7561     // a rotated vector would have started.
7562     int StartIdx = i - (Mask[i] % Size);
7563     if (StartIdx == 0)
7564       // The identity rotation isn't interesting, stop.
7565       return SDValue();
7566
7567     // If we found the tail of a vector the rotation must be the missing
7568     // front. If we found the head of a vector, it must be how much of the head.
7569     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
7570
7571     if (Rotation == 0)
7572       Rotation = CandidateRotation;
7573     else if (Rotation != CandidateRotation)
7574       // The rotations don't match, so we can't match this mask.
7575       return SDValue();
7576
7577     // Compute which value this mask is pointing at.
7578     SDValue MaskV = Mask[i] < Size ? V1 : V2;
7579
7580     // Compute which of the two target values this index should be assigned to.
7581     // This reflects whether the high elements are remaining or the low elements
7582     // are remaining.
7583     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7584
7585     // Either set up this value if we've not encountered it before, or check
7586     // that it remains consistent.
7587     if (!TargetV)
7588       TargetV = MaskV;
7589     else if (TargetV != MaskV)
7590       // This may be a rotation, but it pulls from the inputs in some
7591       // unsupported interleaving.
7592       return SDValue();
7593   }
7594
7595   // Check that we successfully analyzed the mask, and normalize the results.
7596   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7597   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7598   if (!Lo)
7599     Lo = Hi;
7600   else if (!Hi)
7601     Hi = Lo;
7602
7603   assert(VT.getSizeInBits() == 128 &&
7604          "Rotate-based lowering only supports 128-bit lowering!");
7605   assert(Mask.size() <= 16 &&
7606          "Can shuffle at most 16 bytes in a 128-bit vector!");
7607
7608   // The actual rotate instruction rotates bytes, so we need to scale the
7609   // rotation based on how many bytes are in the vector.
7610   int Scale = 16 / Mask.size();
7611
7612   // SSSE3 targets can use the palignr instruction
7613   if (Subtarget->hasSSSE3()) {
7614     // Cast the inputs to v16i8 to match PALIGNR.
7615     Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Lo);
7616     Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Hi);
7617
7618     return DAG.getNode(ISD::BITCAST, DL, VT,
7619                        DAG.getNode(X86ISD::PALIGNR, DL, MVT::v16i8, Hi, Lo,
7620                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
7621   }
7622
7623   // Default SSE2 implementation
7624   int LoByteShift = 16 - Rotation * Scale;
7625   int HiByteShift = Rotation * Scale;
7626
7627   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7628   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
7629   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
7630
7631   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7632                                 DAG.getConstant(8 * LoByteShift, MVT::i8));
7633   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7634                                 DAG.getConstant(8 * HiByteShift, MVT::i8));
7635   return DAG.getNode(ISD::BITCAST, DL, VT,
7636                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7637 }
7638
7639 /// \brief Compute whether each element of a shuffle is zeroable.
7640 ///
7641 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7642 /// Either it is an undef element in the shuffle mask, the element of the input
7643 /// referenced is undef, or the element of the input referenced is known to be
7644 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7645 /// as many lanes with this technique as possible to simplify the remaining
7646 /// shuffle.
7647 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
7648                                                      SDValue V1, SDValue V2) {
7649   SmallBitVector Zeroable(Mask.size(), false);
7650
7651   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7652   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7653
7654   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7655     int M = Mask[i];
7656     // Handle the easy cases.
7657     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7658       Zeroable[i] = true;
7659       continue;
7660     }
7661
7662     // If this is an index into a build_vector node, dig out the input value and
7663     // use it.
7664     SDValue V = M < Size ? V1 : V2;
7665     if (V.getOpcode() != ISD::BUILD_VECTOR)
7666       continue;
7667
7668     SDValue Input = V.getOperand(M % Size);
7669     // The UNDEF opcode check really should be dead code here, but not quite
7670     // worth asserting on (it isn't invalid, just unexpected).
7671     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
7672       Zeroable[i] = true;
7673   }
7674
7675   return Zeroable;
7676 }
7677
7678 /// \brief Try to lower a vector shuffle as a byte shift (shifts in zeros).
7679 ///
7680 /// Attempts to match a shuffle mask against the PSRLDQ and PSLLDQ SSE2
7681 /// byte-shift instructions. The mask must consist of a shifted sequential
7682 /// shuffle from one of the input vectors and zeroable elements for the
7683 /// remaining 'shifted in' elements.
7684 ///
7685 /// Note that this only handles 128-bit vector widths currently.
7686 static SDValue lowerVectorShuffleAsByteShift(SDLoc DL, MVT VT, SDValue V1,
7687                                              SDValue V2, ArrayRef<int> Mask,
7688                                              SelectionDAG &DAG) {
7689   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7690
7691   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7692
7693   int Size = Mask.size();
7694   int Scale = 16 / Size;
7695
7696   auto isSequential = [](int Base, int StartIndex, int EndIndex, int MaskOffset,
7697                          ArrayRef<int> Mask) {
7698     for (int i = StartIndex; i < EndIndex; i++) {
7699       if (Mask[i] < 0)
7700         continue;
7701       if (i + Base != Mask[i] - MaskOffset)
7702         return false;
7703     }
7704     return true;
7705   };
7706
7707   for (int Shift = 1; Shift < Size; Shift++) {
7708     int ByteShift = Shift * Scale;
7709
7710     // PSRLDQ : (little-endian) right byte shift
7711     // [ 5,  6,  7, zz, zz, zz, zz, zz]
7712     // [ -1, 5,  6,  7, zz, zz, zz, zz]
7713     // [  1, 2, -1, -1, -1, -1, zz, zz]
7714     bool ZeroableRight = true;
7715     for (int i = Size - Shift; i < Size; i++) {
7716       ZeroableRight &= Zeroable[i];
7717     }
7718
7719     if (ZeroableRight) {
7720       bool ValidShiftRight1 = isSequential(Shift, 0, Size - Shift, 0, Mask);
7721       bool ValidShiftRight2 = isSequential(Shift, 0, Size - Shift, Size, Mask);
7722
7723       if (ValidShiftRight1 || ValidShiftRight2) {
7724         // Cast the inputs to v2i64 to match PSRLDQ.
7725         SDValue &TargetV = ValidShiftRight1 ? V1 : V2;
7726         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7727         SDValue Shifted = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, V,
7728                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7729         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7730       }
7731     }
7732
7733     // PSLLDQ : (little-endian) left byte shift
7734     // [ zz,  0,  1,  2,  3,  4,  5,  6]
7735     // [ zz, zz, -1, -1,  2,  3,  4, -1]
7736     // [ zz, zz, zz, zz, zz, zz, -1,  1]
7737     bool ZeroableLeft = true;
7738     for (int i = 0; i < Shift; i++) {
7739       ZeroableLeft &= Zeroable[i];
7740     }
7741
7742     if (ZeroableLeft) {
7743       bool ValidShiftLeft1 = isSequential(-Shift, Shift, Size, 0, Mask);
7744       bool ValidShiftLeft2 = isSequential(-Shift, Shift, Size, Size, Mask);
7745
7746       if (ValidShiftLeft1 || ValidShiftLeft2) {
7747         // Cast the inputs to v2i64 to match PSLLDQ.
7748         SDValue &TargetV = ValidShiftLeft1 ? V1 : V2;
7749         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7750         SDValue Shifted = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, V,
7751                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7752         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7753       }
7754     }
7755   }
7756
7757   return SDValue();
7758 }
7759
7760 /// \brief Lower a vector shuffle as a zero or any extension.
7761 ///
7762 /// Given a specific number of elements, element bit width, and extension
7763 /// stride, produce either a zero or any extension based on the available
7764 /// features of the subtarget.
7765 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7766     SDLoc DL, MVT VT, int NumElements, int Scale, bool AnyExt, SDValue InputV,
7767     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7768   assert(Scale > 1 && "Need a scale to extend.");
7769   int EltBits = VT.getSizeInBits() / NumElements;
7770   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7771          "Only 8, 16, and 32 bit elements can be extended.");
7772   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7773
7774   // Found a valid zext mask! Try various lowering strategies based on the
7775   // input type and available ISA extensions.
7776   if (Subtarget->hasSSE41()) {
7777     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7778     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7779                                  NumElements / Scale);
7780     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7781     return DAG.getNode(ISD::BITCAST, DL, VT,
7782                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7783   }
7784
7785   // For any extends we can cheat for larger element sizes and use shuffle
7786   // instructions that can fold with a load and/or copy.
7787   if (AnyExt && EltBits == 32) {
7788     int PSHUFDMask[4] = {0, -1, 1, -1};
7789     return DAG.getNode(
7790         ISD::BITCAST, DL, VT,
7791         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7792                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7793                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7794   }
7795   if (AnyExt && EltBits == 16 && Scale > 2) {
7796     int PSHUFDMask[4] = {0, -1, 0, -1};
7797     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7798                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7799                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
7800     int PSHUFHWMask[4] = {1, -1, -1, -1};
7801     return DAG.getNode(
7802         ISD::BITCAST, DL, VT,
7803         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7804                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
7805                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
7806   }
7807
7808   // If this would require more than 2 unpack instructions to expand, use
7809   // pshufb when available. We can only use more than 2 unpack instructions
7810   // when zero extending i8 elements which also makes it easier to use pshufb.
7811   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7812     assert(NumElements == 16 && "Unexpected byte vector width!");
7813     SDValue PSHUFBMask[16];
7814     for (int i = 0; i < 16; ++i)
7815       PSHUFBMask[i] =
7816           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
7817     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
7818     return DAG.getNode(ISD::BITCAST, DL, VT,
7819                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7820                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
7821                                                MVT::v16i8, PSHUFBMask)));
7822   }
7823
7824   // Otherwise emit a sequence of unpacks.
7825   do {
7826     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7827     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7828                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7829     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7830     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7831     Scale /= 2;
7832     EltBits *= 2;
7833     NumElements /= 2;
7834   } while (Scale > 1);
7835   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
7836 }
7837
7838 /// \brief Try to lower a vector shuffle as a zero extension on any micrarch.
7839 ///
7840 /// This routine will try to do everything in its power to cleverly lower
7841 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7842 /// check for the profitability of this lowering,  it tries to aggressively
7843 /// match this pattern. It will use all of the micro-architectural details it
7844 /// can to emit an efficient lowering. It handles both blends with all-zero
7845 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7846 /// masking out later).
7847 ///
7848 /// The reason we have dedicated lowering for zext-style shuffles is that they
7849 /// are both incredibly common and often quite performance sensitive.
7850 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7851     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7852     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7853   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7854
7855   int Bits = VT.getSizeInBits();
7856   int NumElements = Mask.size();
7857
7858   // Define a helper function to check a particular ext-scale and lower to it if
7859   // valid.
7860   auto Lower = [&](int Scale) -> SDValue {
7861     SDValue InputV;
7862     bool AnyExt = true;
7863     for (int i = 0; i < NumElements; ++i) {
7864       if (Mask[i] == -1)
7865         continue; // Valid anywhere but doesn't tell us anything.
7866       if (i % Scale != 0) {
7867         // Each of the extend elements needs to be zeroable.
7868         if (!Zeroable[i])
7869           return SDValue();
7870
7871         // We no lorger are in the anyext case.
7872         AnyExt = false;
7873         continue;
7874       }
7875
7876       // Each of the base elements needs to be consecutive indices into the
7877       // same input vector.
7878       SDValue V = Mask[i] < NumElements ? V1 : V2;
7879       if (!InputV)
7880         InputV = V;
7881       else if (InputV != V)
7882         return SDValue(); // Flip-flopping inputs.
7883
7884       if (Mask[i] % NumElements != i / Scale)
7885         return SDValue(); // Non-consecutive strided elemenst.
7886     }
7887
7888     // If we fail to find an input, we have a zero-shuffle which should always
7889     // have already been handled.
7890     // FIXME: Maybe handle this here in case during blending we end up with one?
7891     if (!InputV)
7892       return SDValue();
7893
7894     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7895         DL, VT, NumElements, Scale, AnyExt, InputV, Subtarget, DAG);
7896   };
7897
7898   // The widest scale possible for extending is to a 64-bit integer.
7899   assert(Bits % 64 == 0 &&
7900          "The number of bits in a vector must be divisible by 64 on x86!");
7901   int NumExtElements = Bits / 64;
7902
7903   // Each iteration, try extending the elements half as much, but into twice as
7904   // many elements.
7905   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7906     assert(NumElements % NumExtElements == 0 &&
7907            "The input vector size must be divisble by the extended size.");
7908     if (SDValue V = Lower(NumElements / NumExtElements))
7909       return V;
7910   }
7911
7912   // No viable ext lowering found.
7913   return SDValue();
7914 }
7915
7916 /// \brief Try to get a scalar value for a specific element of a vector.
7917 ///
7918 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7919 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7920                                               SelectionDAG &DAG) {
7921   MVT VT = V.getSimpleValueType();
7922   MVT EltVT = VT.getVectorElementType();
7923   while (V.getOpcode() == ISD::BITCAST)
7924     V = V.getOperand(0);
7925   // If the bitcasts shift the element size, we can't extract an equivalent
7926   // element from it.
7927   MVT NewVT = V.getSimpleValueType();
7928   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7929     return SDValue();
7930
7931   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7932       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
7933     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
7934
7935   return SDValue();
7936 }
7937
7938 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7939 ///
7940 /// This is particularly important because the set of instructions varies
7941 /// significantly based on whether the operand is a load or not.
7942 static bool isShuffleFoldableLoad(SDValue V) {
7943   while (V.getOpcode() == ISD::BITCAST)
7944     V = V.getOperand(0);
7945
7946   return ISD::isNON_EXTLoad(V.getNode());
7947 }
7948
7949 /// \brief Try to lower insertion of a single element into a zero vector.
7950 ///
7951 /// This is a common pattern that we have especially efficient patterns to lower
7952 /// across all subtarget feature sets.
7953 static SDValue lowerVectorShuffleAsElementInsertion(
7954     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7955     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7956   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7957   MVT ExtVT = VT;
7958   MVT EltVT = VT.getVectorElementType();
7959
7960   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7961                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7962                 Mask.begin();
7963   bool IsV1Zeroable = true;
7964   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7965     if (i != V2Index && !Zeroable[i]) {
7966       IsV1Zeroable = false;
7967       break;
7968     }
7969
7970   // Check for a single input from a SCALAR_TO_VECTOR node.
7971   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7972   // all the smarts here sunk into that routine. However, the current
7973   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7974   // vector shuffle lowering is dead.
7975   if (SDValue V2S = getScalarValueForVectorElement(
7976           V2, Mask[V2Index] - Mask.size(), DAG)) {
7977     // We need to zext the scalar if it is smaller than an i32.
7978     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7979     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7980       // Using zext to expand a narrow element won't work for non-zero
7981       // insertions.
7982       if (!IsV1Zeroable)
7983         return SDValue();
7984
7985       // Zero-extend directly to i32.
7986       ExtVT = MVT::v4i32;
7987       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7988     }
7989     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7990   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7991              EltVT == MVT::i16) {
7992     // Either not inserting from the low element of the input or the input
7993     // element size is too small to use VZEXT_MOVL to clear the high bits.
7994     return SDValue();
7995   }
7996
7997   if (!IsV1Zeroable) {
7998     // If V1 can't be treated as a zero vector we have fewer options to lower
7999     // this. We can't support integer vectors or non-zero targets cheaply, and
8000     // the V1 elements can't be permuted in any way.
8001     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8002     if (!VT.isFloatingPoint() || V2Index != 0)
8003       return SDValue();
8004     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8005     V1Mask[V2Index] = -1;
8006     if (!isNoopShuffleMask(V1Mask))
8007       return SDValue();
8008     // This is essentially a special case blend operation, but if we have
8009     // general purpose blend operations, they are always faster. Bail and let
8010     // the rest of the lowering handle these as blends.
8011     if (Subtarget->hasSSE41())
8012       return SDValue();
8013
8014     // Otherwise, use MOVSD or MOVSS.
8015     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8016            "Only two types of floating point element types to handle!");
8017     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8018                        ExtVT, V1, V2);
8019   }
8020
8021   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8022   if (ExtVT != VT)
8023     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8024
8025   if (V2Index != 0) {
8026     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8027     // the desired position. Otherwise it is more efficient to do a vector
8028     // shift left. We know that we can do a vector shift left because all
8029     // the inputs are zero.
8030     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8031       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8032       V2Shuffle[V2Index] = 0;
8033       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8034     } else {
8035       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
8036       V2 = DAG.getNode(
8037           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8038           DAG.getConstant(
8039               V2Index * EltVT.getSizeInBits(),
8040               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
8041       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8042     }
8043   }
8044   return V2;
8045 }
8046
8047 /// \brief Try to lower broadcast of a single element.
8048 ///
8049 /// For convenience, this code also bundles all of the subtarget feature set
8050 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8051 /// a convenient way to factor it out.
8052 static SDValue lowerVectorShuffleAsBroadcast(MVT VT, SDLoc DL, SDValue V,
8053                                              ArrayRef<int> Mask,
8054                                              const X86Subtarget *Subtarget,
8055                                              SelectionDAG &DAG) {
8056   if (!Subtarget->hasAVX())
8057     return SDValue();
8058   if (VT.isInteger() && !Subtarget->hasAVX2())
8059     return SDValue();
8060
8061   // Check that the mask is a broadcast.
8062   int BroadcastIdx = -1;
8063   for (int M : Mask)
8064     if (M >= 0 && BroadcastIdx == -1)
8065       BroadcastIdx = M;
8066     else if (M >= 0 && M != BroadcastIdx)
8067       return SDValue();
8068
8069   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8070                                             "a sorted mask where the broadcast "
8071                                             "comes from V1.");
8072
8073   // Go up the chain of (vector) values to try and find a scalar load that
8074   // we can combine with the broadcast.
8075   for (;;) {
8076     switch (V.getOpcode()) {
8077     case ISD::CONCAT_VECTORS: {
8078       int OperandSize = Mask.size() / V.getNumOperands();
8079       V = V.getOperand(BroadcastIdx / OperandSize);
8080       BroadcastIdx %= OperandSize;
8081       continue;
8082     }
8083
8084     case ISD::INSERT_SUBVECTOR: {
8085       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8086       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8087       if (!ConstantIdx)
8088         break;
8089
8090       int BeginIdx = (int)ConstantIdx->getZExtValue();
8091       int EndIdx =
8092           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
8093       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8094         BroadcastIdx -= BeginIdx;
8095         V = VInner;
8096       } else {
8097         V = VOuter;
8098       }
8099       continue;
8100     }
8101     }
8102     break;
8103   }
8104
8105   // Check if this is a broadcast of a scalar. We special case lowering
8106   // for scalars so that we can more effectively fold with loads.
8107   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8108       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8109     V = V.getOperand(BroadcastIdx);
8110
8111     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
8112     // AVX2.
8113     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8114       return SDValue();
8115   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8116     // We can't broadcast from a vector register w/o AVX2, and we can only
8117     // broadcast from the zero-element of a vector register.
8118     return SDValue();
8119   }
8120
8121   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8122 }
8123
8124 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8125 ///
8126 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8127 /// support for floating point shuffles but not integer shuffles. These
8128 /// instructions will incur a domain crossing penalty on some chips though so
8129 /// it is better to avoid lowering through this for integer vectors where
8130 /// possible.
8131 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8132                                        const X86Subtarget *Subtarget,
8133                                        SelectionDAG &DAG) {
8134   SDLoc DL(Op);
8135   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8136   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8137   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8138   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8139   ArrayRef<int> Mask = SVOp->getMask();
8140   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8141
8142   if (isSingleInputShuffleMask(Mask)) {
8143     // Straight shuffle of a single input vector. Simulate this by using the
8144     // single input as both of the "inputs" to this instruction..
8145     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8146
8147     if (Subtarget->hasAVX()) {
8148       // If we have AVX, we can use VPERMILPS which will allow folding a load
8149       // into the shuffle.
8150       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8151                          DAG.getConstant(SHUFPDMask, MVT::i8));
8152     }
8153
8154     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
8155                        DAG.getConstant(SHUFPDMask, MVT::i8));
8156   }
8157   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8158   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8159
8160   // Use dedicated unpack instructions for masks that match their pattern.
8161   if (isShuffleEquivalent(Mask, 0, 2))
8162     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8163   if (isShuffleEquivalent(Mask, 1, 3))
8164     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8165
8166   // If we have a single input, insert that into V1 if we can do so cheaply.
8167   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8168     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8169             MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
8170       return Insertion;
8171     // Try inverting the insertion since for v2 masks it is easy to do and we
8172     // can't reliably sort the mask one way or the other.
8173     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8174                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8175     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8176             MVT::v2f64, DL, V2, V1, InverseMask, Subtarget, DAG))
8177       return Insertion;
8178   }
8179
8180   // Try to use one of the special instruction patterns to handle two common
8181   // blend patterns if a zero-blend above didn't work.
8182   if (isShuffleEquivalent(Mask, 0, 3) || isShuffleEquivalent(Mask, 1, 3))
8183     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8184       // We can either use a special instruction to load over the low double or
8185       // to move just the low double.
8186       return DAG.getNode(
8187           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8188           DL, MVT::v2f64, V2,
8189           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8190
8191   if (Subtarget->hasSSE41())
8192     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8193                                                   Subtarget, DAG))
8194       return Blend;
8195
8196   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8197   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
8198                      DAG.getConstant(SHUFPDMask, MVT::i8));
8199 }
8200
8201 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8202 ///
8203 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8204 /// the integer unit to minimize domain crossing penalties. However, for blends
8205 /// it falls back to the floating point shuffle operation with appropriate bit
8206 /// casting.
8207 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8208                                        const X86Subtarget *Subtarget,
8209                                        SelectionDAG &DAG) {
8210   SDLoc DL(Op);
8211   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8212   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8213   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8214   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8215   ArrayRef<int> Mask = SVOp->getMask();
8216   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8217
8218   if (isSingleInputShuffleMask(Mask)) {
8219     // Check for being able to broadcast a single element.
8220     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v2i64, DL, V1,
8221                                                           Mask, Subtarget, DAG))
8222       return Broadcast;
8223
8224     // Straight shuffle of a single input vector. For everything from SSE2
8225     // onward this has a single fast instruction with no scary immediates.
8226     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8227     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
8228     int WidenedMask[4] = {
8229         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8230         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8231     return DAG.getNode(
8232         ISD::BITCAST, DL, MVT::v2i64,
8233         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
8234                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
8235   }
8236
8237   // Try to use byte shift instructions.
8238   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8239           DL, MVT::v2i64, V1, V2, Mask, DAG))
8240     return Shift;
8241
8242   // If we have a single input from V2 insert that into V1 if we can do so
8243   // cheaply.
8244   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8245     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8246             MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
8247       return Insertion;
8248     // Try inverting the insertion since for v2 masks it is easy to do and we
8249     // can't reliably sort the mask one way or the other.
8250     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8251                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8252     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8253             MVT::v2i64, DL, V2, V1, InverseMask, Subtarget, DAG))
8254       return Insertion;
8255   }
8256
8257   // Use dedicated unpack instructions for masks that match their pattern.
8258   if (isShuffleEquivalent(Mask, 0, 2))
8259     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8260   if (isShuffleEquivalent(Mask, 1, 3))
8261     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8262
8263   if (Subtarget->hasSSE41())
8264     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8265                                                   Subtarget, DAG))
8266       return Blend;
8267
8268   // Try to use byte rotation instructions.
8269   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8270   if (Subtarget->hasSSSE3())
8271     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8272             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8273       return Rotate;
8274
8275   // We implement this with SHUFPD which is pretty lame because it will likely
8276   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8277   // However, all the alternatives are still more cycles and newer chips don't
8278   // have this problem. It would be really nice if x86 had better shuffles here.
8279   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
8280   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
8281   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
8282                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8283 }
8284
8285 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8286 ///
8287 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8288 /// It makes no assumptions about whether this is the *best* lowering, it simply
8289 /// uses it.
8290 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8291                                             ArrayRef<int> Mask, SDValue V1,
8292                                             SDValue V2, SelectionDAG &DAG) {
8293   SDValue LowV = V1, HighV = V2;
8294   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8295
8296   int NumV2Elements =
8297       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8298
8299   if (NumV2Elements == 1) {
8300     int V2Index =
8301         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8302         Mask.begin();
8303
8304     // Compute the index adjacent to V2Index and in the same half by toggling
8305     // the low bit.
8306     int V2AdjIndex = V2Index ^ 1;
8307
8308     if (Mask[V2AdjIndex] == -1) {
8309       // Handles all the cases where we have a single V2 element and an undef.
8310       // This will only ever happen in the high lanes because we commute the
8311       // vector otherwise.
8312       if (V2Index < 2)
8313         std::swap(LowV, HighV);
8314       NewMask[V2Index] -= 4;
8315     } else {
8316       // Handle the case where the V2 element ends up adjacent to a V1 element.
8317       // To make this work, blend them together as the first step.
8318       int V1Index = V2AdjIndex;
8319       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8320       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8321                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8322
8323       // Now proceed to reconstruct the final blend as we have the necessary
8324       // high or low half formed.
8325       if (V2Index < 2) {
8326         LowV = V2;
8327         HighV = V1;
8328       } else {
8329         HighV = V2;
8330       }
8331       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8332       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8333     }
8334   } else if (NumV2Elements == 2) {
8335     if (Mask[0] < 4 && Mask[1] < 4) {
8336       // Handle the easy case where we have V1 in the low lanes and V2 in the
8337       // high lanes.
8338       NewMask[2] -= 4;
8339       NewMask[3] -= 4;
8340     } else if (Mask[2] < 4 && Mask[3] < 4) {
8341       // We also handle the reversed case because this utility may get called
8342       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8343       // arrange things in the right direction.
8344       NewMask[0] -= 4;
8345       NewMask[1] -= 4;
8346       HighV = V1;
8347       LowV = V2;
8348     } else {
8349       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8350       // trying to place elements directly, just blend them and set up the final
8351       // shuffle to place them.
8352
8353       // The first two blend mask elements are for V1, the second two are for
8354       // V2.
8355       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8356                           Mask[2] < 4 ? Mask[2] : Mask[3],
8357                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8358                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8359       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8360                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8361
8362       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8363       // a blend.
8364       LowV = HighV = V1;
8365       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8366       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8367       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8368       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8369     }
8370   }
8371   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8372                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
8373 }
8374
8375 /// \brief Lower 4-lane 32-bit floating point shuffles.
8376 ///
8377 /// Uses instructions exclusively from the floating point unit to minimize
8378 /// domain crossing penalties, as these are sufficient to implement all v4f32
8379 /// shuffles.
8380 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8381                                        const X86Subtarget *Subtarget,
8382                                        SelectionDAG &DAG) {
8383   SDLoc DL(Op);
8384   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8385   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8386   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8387   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8388   ArrayRef<int> Mask = SVOp->getMask();
8389   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8390
8391   int NumV2Elements =
8392       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8393
8394   if (NumV2Elements == 0) {
8395     // Check for being able to broadcast a single element.
8396     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f32, DL, V1,
8397                                                           Mask, Subtarget, DAG))
8398       return Broadcast;
8399
8400     if (Subtarget->hasAVX()) {
8401       // If we have AVX, we can use VPERMILPS which will allow folding a load
8402       // into the shuffle.
8403       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8404                          getV4X86ShuffleImm8ForMask(Mask, DAG));
8405     }
8406
8407     // Otherwise, use a straight shuffle of a single input vector. We pass the
8408     // input vector to both operands to simulate this with a SHUFPS.
8409     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8410                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8411   }
8412
8413   // Use dedicated unpack instructions for masks that match their pattern.
8414   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8415     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8416   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8417     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8418
8419   // There are special ways we can lower some single-element blends. However, we
8420   // have custom ways we can lower more complex single-element blends below that
8421   // we defer to if both this and BLENDPS fail to match, so restrict this to
8422   // when the V2 input is targeting element 0 of the mask -- that is the fast
8423   // case here.
8424   if (NumV2Elements == 1 && Mask[0] >= 4)
8425     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
8426                                                          Mask, Subtarget, DAG))
8427       return V;
8428
8429   if (Subtarget->hasSSE41())
8430     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8431                                                   Subtarget, DAG))
8432       return Blend;
8433
8434   // Check for whether we can use INSERTPS to perform the blend. We only use
8435   // INSERTPS when the V1 elements are already in the correct locations
8436   // because otherwise we can just always use two SHUFPS instructions which
8437   // are much smaller to encode than a SHUFPS and an INSERTPS.
8438   if (NumV2Elements == 1 && Subtarget->hasSSE41()) {
8439     int V2Index =
8440         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8441         Mask.begin();
8442
8443     // When using INSERTPS we can zero any lane of the destination. Collect
8444     // the zero inputs into a mask and drop them from the lanes of V1 which
8445     // actually need to be present as inputs to the INSERTPS.
8446     SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8447
8448     // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
8449     bool InsertNeedsShuffle = false;
8450     unsigned ZMask = 0;
8451     for (int i = 0; i < 4; ++i)
8452       if (i != V2Index) {
8453         if (Zeroable[i]) {
8454           ZMask |= 1 << i;
8455         } else if (Mask[i] != i) {
8456           InsertNeedsShuffle = true;
8457           break;
8458         }
8459       }
8460
8461     // We don't want to use INSERTPS or other insertion techniques if it will
8462     // require shuffling anyways.
8463     if (!InsertNeedsShuffle) {
8464       // If all of V1 is zeroable, replace it with undef.
8465       if ((ZMask | 1 << V2Index) == 0xF)
8466         V1 = DAG.getUNDEF(MVT::v4f32);
8467
8468       unsigned InsertPSMask = (Mask[V2Index] - 4) << 6 | V2Index << 4 | ZMask;
8469       assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8470
8471       // Insert the V2 element into the desired position.
8472       return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8473                          DAG.getConstant(InsertPSMask, MVT::i8));
8474     }
8475   }
8476
8477   // Otherwise fall back to a SHUFPS lowering strategy.
8478   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8479 }
8480
8481 /// \brief Lower 4-lane i32 vector shuffles.
8482 ///
8483 /// We try to handle these with integer-domain shuffles where we can, but for
8484 /// blends we use the floating point domain blend instructions.
8485 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8486                                        const X86Subtarget *Subtarget,
8487                                        SelectionDAG &DAG) {
8488   SDLoc DL(Op);
8489   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8490   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8491   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8492   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8493   ArrayRef<int> Mask = SVOp->getMask();
8494   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8495
8496   // Whenever we can lower this as a zext, that instruction is strictly faster
8497   // than any alternative. It also allows us to fold memory operands into the
8498   // shuffle in many cases.
8499   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8500                                                          Mask, Subtarget, DAG))
8501     return ZExt;
8502
8503   int NumV2Elements =
8504       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8505
8506   if (NumV2Elements == 0) {
8507     // Check for being able to broadcast a single element.
8508     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i32, DL, V1,
8509                                                           Mask, Subtarget, DAG))
8510       return Broadcast;
8511
8512     // Straight shuffle of a single input vector. For everything from SSE2
8513     // onward this has a single fast instruction with no scary immediates.
8514     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8515     // but we aren't actually going to use the UNPCK instruction because doing
8516     // so prevents folding a load into this instruction or making a copy.
8517     const int UnpackLoMask[] = {0, 0, 1, 1};
8518     const int UnpackHiMask[] = {2, 2, 3, 3};
8519     if (isShuffleEquivalent(Mask, 0, 0, 1, 1))
8520       Mask = UnpackLoMask;
8521     else if (isShuffleEquivalent(Mask, 2, 2, 3, 3))
8522       Mask = UnpackHiMask;
8523
8524     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8525                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8526   }
8527
8528   // Try to use byte shift instructions.
8529   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8530           DL, MVT::v4i32, V1, V2, Mask, DAG))
8531     return Shift;
8532
8533   // There are special ways we can lower some single-element blends.
8534   if (NumV2Elements == 1)
8535     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
8536                                                          Mask, Subtarget, DAG))
8537       return V;
8538
8539   // Use dedicated unpack instructions for masks that match their pattern.
8540   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8541     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8542   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8543     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8544
8545   if (Subtarget->hasSSE41())
8546     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8547                                                   Subtarget, DAG))
8548       return Blend;
8549
8550   // Try to use byte rotation instructions.
8551   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8552   if (Subtarget->hasSSSE3())
8553     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8554             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8555       return Rotate;
8556
8557   // We implement this with SHUFPS because it can blend from two vectors.
8558   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8559   // up the inputs, bypassing domain shift penalties that we would encur if we
8560   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8561   // relevant.
8562   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
8563                      DAG.getVectorShuffle(
8564                          MVT::v4f32, DL,
8565                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
8566                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
8567 }
8568
8569 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8570 /// shuffle lowering, and the most complex part.
8571 ///
8572 /// The lowering strategy is to try to form pairs of input lanes which are
8573 /// targeted at the same half of the final vector, and then use a dword shuffle
8574 /// to place them onto the right half, and finally unpack the paired lanes into
8575 /// their final position.
8576 ///
8577 /// The exact breakdown of how to form these dword pairs and align them on the
8578 /// correct sides is really tricky. See the comments within the function for
8579 /// more of the details.
8580 static SDValue lowerV8I16SingleInputVectorShuffle(
8581     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
8582     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8583   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8584   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8585   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8586
8587   SmallVector<int, 4> LoInputs;
8588   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8589                [](int M) { return M >= 0; });
8590   std::sort(LoInputs.begin(), LoInputs.end());
8591   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8592   SmallVector<int, 4> HiInputs;
8593   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8594                [](int M) { return M >= 0; });
8595   std::sort(HiInputs.begin(), HiInputs.end());
8596   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8597   int NumLToL =
8598       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8599   int NumHToL = LoInputs.size() - NumLToL;
8600   int NumLToH =
8601       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8602   int NumHToH = HiInputs.size() - NumLToH;
8603   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8604   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8605   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8606   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8607
8608   // Check for being able to broadcast a single element.
8609   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i16, DL, V,
8610                                                         Mask, Subtarget, DAG))
8611     return Broadcast;
8612
8613   // Try to use byte shift instructions.
8614   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8615           DL, MVT::v8i16, V, V, Mask, DAG))
8616     return Shift;
8617
8618   // Use dedicated unpack instructions for masks that match their pattern.
8619   if (isShuffleEquivalent(Mask, 0, 0, 1, 1, 2, 2, 3, 3))
8620     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
8621   if (isShuffleEquivalent(Mask, 4, 4, 5, 5, 6, 6, 7, 7))
8622     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
8623
8624   // Try to use byte rotation instructions.
8625   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8626           DL, MVT::v8i16, V, V, Mask, Subtarget, DAG))
8627     return Rotate;
8628
8629   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8630   // such inputs we can swap two of the dwords across the half mark and end up
8631   // with <=2 inputs to each half in each half. Once there, we can fall through
8632   // to the generic code below. For example:
8633   //
8634   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8635   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8636   //
8637   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8638   // and an existing 2-into-2 on the other half. In this case we may have to
8639   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8640   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8641   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8642   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8643   // half than the one we target for fixing) will be fixed when we re-enter this
8644   // path. We will also combine away any sequence of PSHUFD instructions that
8645   // result into a single instruction. Here is an example of the tricky case:
8646   //
8647   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8648   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8649   //
8650   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8651   //
8652   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8653   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8654   //
8655   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8656   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8657   //
8658   // The result is fine to be handled by the generic logic.
8659   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8660                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8661                           int AOffset, int BOffset) {
8662     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8663            "Must call this with A having 3 or 1 inputs from the A half.");
8664     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8665            "Must call this with B having 1 or 3 inputs from the B half.");
8666     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8667            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8668
8669     // Compute the index of dword with only one word among the three inputs in
8670     // a half by taking the sum of the half with three inputs and subtracting
8671     // the sum of the actual three inputs. The difference is the remaining
8672     // slot.
8673     int ADWord, BDWord;
8674     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8675     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8676     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8677     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8678     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8679     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8680     int TripleNonInputIdx =
8681         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8682     TripleDWord = TripleNonInputIdx / 2;
8683
8684     // We use xor with one to compute the adjacent DWord to whichever one the
8685     // OneInput is in.
8686     OneInputDWord = (OneInput / 2) ^ 1;
8687
8688     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8689     // and BToA inputs. If there is also such a problem with the BToB and AToB
8690     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8691     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8692     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8693     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8694       // Compute how many inputs will be flipped by swapping these DWords. We
8695       // need
8696       // to balance this to ensure we don't form a 3-1 shuffle in the other
8697       // half.
8698       int NumFlippedAToBInputs =
8699           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8700           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8701       int NumFlippedBToBInputs =
8702           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8703           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8704       if ((NumFlippedAToBInputs == 1 &&
8705            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8706           (NumFlippedBToBInputs == 1 &&
8707            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8708         // We choose whether to fix the A half or B half based on whether that
8709         // half has zero flipped inputs. At zero, we may not be able to fix it
8710         // with that half. We also bias towards fixing the B half because that
8711         // will more commonly be the high half, and we have to bias one way.
8712         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8713                                                        ArrayRef<int> Inputs) {
8714           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8715           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8716                                          PinnedIdx ^ 1) != Inputs.end();
8717           // Determine whether the free index is in the flipped dword or the
8718           // unflipped dword based on where the pinned index is. We use this bit
8719           // in an xor to conditionally select the adjacent dword.
8720           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8721           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8722                                              FixFreeIdx) != Inputs.end();
8723           if (IsFixIdxInput == IsFixFreeIdxInput)
8724             FixFreeIdx += 1;
8725           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8726                                         FixFreeIdx) != Inputs.end();
8727           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8728                  "We need to be changing the number of flipped inputs!");
8729           int PSHUFHalfMask[] = {0, 1, 2, 3};
8730           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8731           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8732                           MVT::v8i16, V,
8733                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
8734
8735           for (int &M : Mask)
8736             if (M != -1 && M == FixIdx)
8737               M = FixFreeIdx;
8738             else if (M != -1 && M == FixFreeIdx)
8739               M = FixIdx;
8740         };
8741         if (NumFlippedBToBInputs != 0) {
8742           int BPinnedIdx =
8743               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8744           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8745         } else {
8746           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8747           int APinnedIdx =
8748               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8749           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8750         }
8751       }
8752     }
8753
8754     int PSHUFDMask[] = {0, 1, 2, 3};
8755     PSHUFDMask[ADWord] = BDWord;
8756     PSHUFDMask[BDWord] = ADWord;
8757     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8758                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8759                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8760                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8761
8762     // Adjust the mask to match the new locations of A and B.
8763     for (int &M : Mask)
8764       if (M != -1 && M/2 == ADWord)
8765         M = 2 * BDWord + M % 2;
8766       else if (M != -1 && M/2 == BDWord)
8767         M = 2 * ADWord + M % 2;
8768
8769     // Recurse back into this routine to re-compute state now that this isn't
8770     // a 3 and 1 problem.
8771     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8772                                 Mask);
8773   };
8774   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8775     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8776   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8777     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8778
8779   // At this point there are at most two inputs to the low and high halves from
8780   // each half. That means the inputs can always be grouped into dwords and
8781   // those dwords can then be moved to the correct half with a dword shuffle.
8782   // We use at most one low and one high word shuffle to collect these paired
8783   // inputs into dwords, and finally a dword shuffle to place them.
8784   int PSHUFLMask[4] = {-1, -1, -1, -1};
8785   int PSHUFHMask[4] = {-1, -1, -1, -1};
8786   int PSHUFDMask[4] = {-1, -1, -1, -1};
8787
8788   // First fix the masks for all the inputs that are staying in their
8789   // original halves. This will then dictate the targets of the cross-half
8790   // shuffles.
8791   auto fixInPlaceInputs =
8792       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8793                     MutableArrayRef<int> SourceHalfMask,
8794                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8795     if (InPlaceInputs.empty())
8796       return;
8797     if (InPlaceInputs.size() == 1) {
8798       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8799           InPlaceInputs[0] - HalfOffset;
8800       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8801       return;
8802     }
8803     if (IncomingInputs.empty()) {
8804       // Just fix all of the in place inputs.
8805       for (int Input : InPlaceInputs) {
8806         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8807         PSHUFDMask[Input / 2] = Input / 2;
8808       }
8809       return;
8810     }
8811
8812     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8813     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8814         InPlaceInputs[0] - HalfOffset;
8815     // Put the second input next to the first so that they are packed into
8816     // a dword. We find the adjacent index by toggling the low bit.
8817     int AdjIndex = InPlaceInputs[0] ^ 1;
8818     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8819     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8820     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8821   };
8822   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8823   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8824
8825   // Now gather the cross-half inputs and place them into a free dword of
8826   // their target half.
8827   // FIXME: This operation could almost certainly be simplified dramatically to
8828   // look more like the 3-1 fixing operation.
8829   auto moveInputsToRightHalf = [&PSHUFDMask](
8830       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8831       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8832       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8833       int DestOffset) {
8834     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8835       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8836     };
8837     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8838                                                int Word) {
8839       int LowWord = Word & ~1;
8840       int HighWord = Word | 1;
8841       return isWordClobbered(SourceHalfMask, LowWord) ||
8842              isWordClobbered(SourceHalfMask, HighWord);
8843     };
8844
8845     if (IncomingInputs.empty())
8846       return;
8847
8848     if (ExistingInputs.empty()) {
8849       // Map any dwords with inputs from them into the right half.
8850       for (int Input : IncomingInputs) {
8851         // If the source half mask maps over the inputs, turn those into
8852         // swaps and use the swapped lane.
8853         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8854           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8855             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8856                 Input - SourceOffset;
8857             // We have to swap the uses in our half mask in one sweep.
8858             for (int &M : HalfMask)
8859               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8860                 M = Input;
8861               else if (M == Input)
8862                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8863           } else {
8864             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8865                        Input - SourceOffset &&
8866                    "Previous placement doesn't match!");
8867           }
8868           // Note that this correctly re-maps both when we do a swap and when
8869           // we observe the other side of the swap above. We rely on that to
8870           // avoid swapping the members of the input list directly.
8871           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8872         }
8873
8874         // Map the input's dword into the correct half.
8875         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8876           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8877         else
8878           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8879                      Input / 2 &&
8880                  "Previous placement doesn't match!");
8881       }
8882
8883       // And just directly shift any other-half mask elements to be same-half
8884       // as we will have mirrored the dword containing the element into the
8885       // same position within that half.
8886       for (int &M : HalfMask)
8887         if (M >= SourceOffset && M < SourceOffset + 4) {
8888           M = M - SourceOffset + DestOffset;
8889           assert(M >= 0 && "This should never wrap below zero!");
8890         }
8891       return;
8892     }
8893
8894     // Ensure we have the input in a viable dword of its current half. This
8895     // is particularly tricky because the original position may be clobbered
8896     // by inputs being moved and *staying* in that half.
8897     if (IncomingInputs.size() == 1) {
8898       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8899         int InputFixed = std::find(std::begin(SourceHalfMask),
8900                                    std::end(SourceHalfMask), -1) -
8901                          std::begin(SourceHalfMask) + SourceOffset;
8902         SourceHalfMask[InputFixed - SourceOffset] =
8903             IncomingInputs[0] - SourceOffset;
8904         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8905                      InputFixed);
8906         IncomingInputs[0] = InputFixed;
8907       }
8908     } else if (IncomingInputs.size() == 2) {
8909       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8910           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8911         // We have two non-adjacent or clobbered inputs we need to extract from
8912         // the source half. To do this, we need to map them into some adjacent
8913         // dword slot in the source mask.
8914         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8915                               IncomingInputs[1] - SourceOffset};
8916
8917         // If there is a free slot in the source half mask adjacent to one of
8918         // the inputs, place the other input in it. We use (Index XOR 1) to
8919         // compute an adjacent index.
8920         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8921             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8922           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8923           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8924           InputsFixed[1] = InputsFixed[0] ^ 1;
8925         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8926                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8927           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8928           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8929           InputsFixed[0] = InputsFixed[1] ^ 1;
8930         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8931                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8932           // The two inputs are in the same DWord but it is clobbered and the
8933           // adjacent DWord isn't used at all. Move both inputs to the free
8934           // slot.
8935           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8936           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8937           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8938           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8939         } else {
8940           // The only way we hit this point is if there is no clobbering
8941           // (because there are no off-half inputs to this half) and there is no
8942           // free slot adjacent to one of the inputs. In this case, we have to
8943           // swap an input with a non-input.
8944           for (int i = 0; i < 4; ++i)
8945             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8946                    "We can't handle any clobbers here!");
8947           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8948                  "Cannot have adjacent inputs here!");
8949
8950           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8951           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8952
8953           // We also have to update the final source mask in this case because
8954           // it may need to undo the above swap.
8955           for (int &M : FinalSourceHalfMask)
8956             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8957               M = InputsFixed[1] + SourceOffset;
8958             else if (M == InputsFixed[1] + SourceOffset)
8959               M = (InputsFixed[0] ^ 1) + SourceOffset;
8960
8961           InputsFixed[1] = InputsFixed[0] ^ 1;
8962         }
8963
8964         // Point everything at the fixed inputs.
8965         for (int &M : HalfMask)
8966           if (M == IncomingInputs[0])
8967             M = InputsFixed[0] + SourceOffset;
8968           else if (M == IncomingInputs[1])
8969             M = InputsFixed[1] + SourceOffset;
8970
8971         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8972         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8973       }
8974     } else {
8975       llvm_unreachable("Unhandled input size!");
8976     }
8977
8978     // Now hoist the DWord down to the right half.
8979     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8980     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8981     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8982     for (int &M : HalfMask)
8983       for (int Input : IncomingInputs)
8984         if (M == Input)
8985           M = FreeDWord * 2 + Input % 2;
8986   };
8987   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8988                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8989   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8990                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8991
8992   // Now enact all the shuffles we've computed to move the inputs into their
8993   // target half.
8994   if (!isNoopShuffleMask(PSHUFLMask))
8995     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8996                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8997   if (!isNoopShuffleMask(PSHUFHMask))
8998     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8999                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
9000   if (!isNoopShuffleMask(PSHUFDMask))
9001     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9002                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
9003                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
9004                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9005
9006   // At this point, each half should contain all its inputs, and we can then
9007   // just shuffle them into their final position.
9008   assert(std::count_if(LoMask.begin(), LoMask.end(),
9009                        [](int M) { return M >= 4; }) == 0 &&
9010          "Failed to lift all the high half inputs to the low mask!");
9011   assert(std::count_if(HiMask.begin(), HiMask.end(),
9012                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9013          "Failed to lift all the low half inputs to the high mask!");
9014
9015   // Do a half shuffle for the low mask.
9016   if (!isNoopShuffleMask(LoMask))
9017     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
9018                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
9019
9020   // Do a half shuffle with the high mask after shifting its values down.
9021   for (int &M : HiMask)
9022     if (M >= 0)
9023       M -= 4;
9024   if (!isNoopShuffleMask(HiMask))
9025     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
9026                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
9027
9028   return V;
9029 }
9030
9031 /// \brief Detect whether the mask pattern should be lowered through
9032 /// interleaving.
9033 ///
9034 /// This essentially tests whether viewing the mask as an interleaving of two
9035 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
9036 /// lowering it through interleaving is a significantly better strategy.
9037 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
9038   int NumEvenInputs[2] = {0, 0};
9039   int NumOddInputs[2] = {0, 0};
9040   int NumLoInputs[2] = {0, 0};
9041   int NumHiInputs[2] = {0, 0};
9042   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9043     if (Mask[i] < 0)
9044       continue;
9045
9046     int InputIdx = Mask[i] >= Size;
9047
9048     if (i < Size / 2)
9049       ++NumLoInputs[InputIdx];
9050     else
9051       ++NumHiInputs[InputIdx];
9052
9053     if ((i % 2) == 0)
9054       ++NumEvenInputs[InputIdx];
9055     else
9056       ++NumOddInputs[InputIdx];
9057   }
9058
9059   // The minimum number of cross-input results for both the interleaved and
9060   // split cases. If interleaving results in fewer cross-input results, return
9061   // true.
9062   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
9063                                     NumEvenInputs[0] + NumOddInputs[1]);
9064   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
9065                               NumLoInputs[0] + NumHiInputs[1]);
9066   return InterleavedCrosses < SplitCrosses;
9067 }
9068
9069 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
9070 ///
9071 /// This strategy only works when the inputs from each vector fit into a single
9072 /// half of that vector, and generally there are not so many inputs as to leave
9073 /// the in-place shuffles required highly constrained (and thus expensive). It
9074 /// shifts all the inputs into a single side of both input vectors and then
9075 /// uses an unpack to interleave these inputs in a single vector. At that
9076 /// point, we will fall back on the generic single input shuffle lowering.
9077 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
9078                                                  SDValue V2,
9079                                                  MutableArrayRef<int> Mask,
9080                                                  const X86Subtarget *Subtarget,
9081                                                  SelectionDAG &DAG) {
9082   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9083   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9084   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
9085   for (int i = 0; i < 8; ++i)
9086     if (Mask[i] >= 0 && Mask[i] < 4)
9087       LoV1Inputs.push_back(i);
9088     else if (Mask[i] >= 4 && Mask[i] < 8)
9089       HiV1Inputs.push_back(i);
9090     else if (Mask[i] >= 8 && Mask[i] < 12)
9091       LoV2Inputs.push_back(i);
9092     else if (Mask[i] >= 12)
9093       HiV2Inputs.push_back(i);
9094
9095   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
9096   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
9097   (void)NumV1Inputs;
9098   (void)NumV2Inputs;
9099   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
9100   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
9101   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
9102
9103   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
9104                      HiV1Inputs.size() + HiV2Inputs.size();
9105
9106   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
9107                               ArrayRef<int> HiInputs, bool MoveToLo,
9108                               int MaskOffset) {
9109     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
9110     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
9111     if (BadInputs.empty())
9112       return V;
9113
9114     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9115     int MoveOffset = MoveToLo ? 0 : 4;
9116
9117     if (GoodInputs.empty()) {
9118       for (int BadInput : BadInputs) {
9119         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
9120         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
9121       }
9122     } else {
9123       if (GoodInputs.size() == 2) {
9124         // If the low inputs are spread across two dwords, pack them into
9125         // a single dword.
9126         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
9127         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
9128         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
9129         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
9130       } else {
9131         // Otherwise pin the good inputs.
9132         for (int GoodInput : GoodInputs)
9133           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
9134       }
9135
9136       if (BadInputs.size() == 2) {
9137         // If we have two bad inputs then there may be either one or two good
9138         // inputs fixed in place. Find a fixed input, and then find the *other*
9139         // two adjacent indices by using modular arithmetic.
9140         int GoodMaskIdx =
9141             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
9142                          [](int M) { return M >= 0; }) -
9143             std::begin(MoveMask);
9144         int MoveMaskIdx =
9145             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
9146         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
9147         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
9148         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9149         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
9150         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9151         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
9152       } else {
9153         assert(BadInputs.size() == 1 && "All sizes handled");
9154         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
9155                                     std::end(MoveMask), -1) -
9156                           std::begin(MoveMask);
9157         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9158         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9159       }
9160     }
9161
9162     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
9163                                 MoveMask);
9164   };
9165   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
9166                         /*MaskOffset*/ 0);
9167   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
9168                         /*MaskOffset*/ 8);
9169
9170   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
9171   // cross-half traffic in the final shuffle.
9172
9173   // Munge the mask to be a single-input mask after the unpack merges the
9174   // results.
9175   for (int &M : Mask)
9176     if (M != -1)
9177       M = 2 * (M % 4) + (M / 8);
9178
9179   return DAG.getVectorShuffle(
9180       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
9181                                   DL, MVT::v8i16, V1, V2),
9182       DAG.getUNDEF(MVT::v8i16), Mask);
9183 }
9184
9185 /// \brief Generic lowering of 8-lane i16 shuffles.
9186 ///
9187 /// This handles both single-input shuffles and combined shuffle/blends with
9188 /// two inputs. The single input shuffles are immediately delegated to
9189 /// a dedicated lowering routine.
9190 ///
9191 /// The blends are lowered in one of three fundamental ways. If there are few
9192 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9193 /// of the input is significantly cheaper when lowered as an interleaving of
9194 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9195 /// halves of the inputs separately (making them have relatively few inputs)
9196 /// and then concatenate them.
9197 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9198                                        const X86Subtarget *Subtarget,
9199                                        SelectionDAG &DAG) {
9200   SDLoc DL(Op);
9201   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9202   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9203   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9204   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9205   ArrayRef<int> OrigMask = SVOp->getMask();
9206   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9207                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9208   MutableArrayRef<int> Mask(MaskStorage);
9209
9210   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9211
9212   // Whenever we can lower this as a zext, that instruction is strictly faster
9213   // than any alternative.
9214   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9215           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9216     return ZExt;
9217
9218   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9219   auto isV2 = [](int M) { return M >= 8; };
9220
9221   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
9222   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9223
9224   if (NumV2Inputs == 0)
9225     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
9226
9227   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
9228                             "to be V1-input shuffles.");
9229
9230   // Try to use byte shift instructions.
9231   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9232           DL, MVT::v8i16, V1, V2, Mask, DAG))
9233     return Shift;
9234
9235   // There are special ways we can lower some single-element blends.
9236   if (NumV2Inputs == 1)
9237     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
9238                                                          Mask, Subtarget, DAG))
9239       return V;
9240
9241   // Use dedicated unpack instructions for masks that match their pattern.
9242   if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 2, 10, 3, 11))
9243     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9244   if (isShuffleEquivalent(Mask, 4, 12, 5, 13, 6, 14, 7, 15))
9245     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9246
9247   if (Subtarget->hasSSE41())
9248     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9249                                                   Subtarget, DAG))
9250       return Blend;
9251
9252   // Try to use byte rotation instructions.
9253   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9254           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9255     return Rotate;
9256
9257   if (NumV1Inputs + NumV2Inputs <= 4)
9258     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
9259
9260   // Check whether an interleaving lowering is likely to be more efficient.
9261   // This isn't perfect but it is a strong heuristic that tends to work well on
9262   // the kinds of shuffles that show up in practice.
9263   //
9264   // FIXME: Handle 1x, 2x, and 4x interleaving.
9265   if (shouldLowerAsInterleaving(Mask)) {
9266     // FIXME: Figure out whether we should pack these into the low or high
9267     // halves.
9268
9269     int EMask[8], OMask[8];
9270     for (int i = 0; i < 4; ++i) {
9271       EMask[i] = Mask[2*i];
9272       OMask[i] = Mask[2*i + 1];
9273       EMask[i + 4] = -1;
9274       OMask[i + 4] = -1;
9275     }
9276
9277     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
9278     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
9279
9280     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
9281   }
9282
9283   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9284   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9285
9286   for (int i = 0; i < 4; ++i) {
9287     LoBlendMask[i] = Mask[i];
9288     HiBlendMask[i] = Mask[i + 4];
9289   }
9290
9291   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9292   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9293   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
9294   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
9295
9296   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9297                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
9298 }
9299
9300 /// \brief Check whether a compaction lowering can be done by dropping even
9301 /// elements and compute how many times even elements must be dropped.
9302 ///
9303 /// This handles shuffles which take every Nth element where N is a power of
9304 /// two. Example shuffle masks:
9305 ///
9306 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9307 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9308 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9309 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9310 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9311 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9312 ///
9313 /// Any of these lanes can of course be undef.
9314 ///
9315 /// This routine only supports N <= 3.
9316 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9317 /// for larger N.
9318 ///
9319 /// \returns N above, or the number of times even elements must be dropped if
9320 /// there is such a number. Otherwise returns zero.
9321 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9322   // Figure out whether we're looping over two inputs or just one.
9323   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9324
9325   // The modulus for the shuffle vector entries is based on whether this is
9326   // a single input or not.
9327   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9328   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9329          "We should only be called with masks with a power-of-2 size!");
9330
9331   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9332
9333   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9334   // and 2^3 simultaneously. This is because we may have ambiguity with
9335   // partially undef inputs.
9336   bool ViableForN[3] = {true, true, true};
9337
9338   for (int i = 0, e = Mask.size(); i < e; ++i) {
9339     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9340     // want.
9341     if (Mask[i] == -1)
9342       continue;
9343
9344     bool IsAnyViable = false;
9345     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9346       if (ViableForN[j]) {
9347         uint64_t N = j + 1;
9348
9349         // The shuffle mask must be equal to (i * 2^N) % M.
9350         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9351           IsAnyViable = true;
9352         else
9353           ViableForN[j] = false;
9354       }
9355     // Early exit if we exhaust the possible powers of two.
9356     if (!IsAnyViable)
9357       break;
9358   }
9359
9360   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9361     if (ViableForN[j])
9362       return j + 1;
9363
9364   // Return 0 as there is no viable power of two.
9365   return 0;
9366 }
9367
9368 /// \brief Generic lowering of v16i8 shuffles.
9369 ///
9370 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9371 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9372 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9373 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9374 /// back together.
9375 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9376                                        const X86Subtarget *Subtarget,
9377                                        SelectionDAG &DAG) {
9378   SDLoc DL(Op);
9379   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9380   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9381   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9382   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9383   ArrayRef<int> OrigMask = SVOp->getMask();
9384   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9385
9386   // Try to use byte shift instructions.
9387   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9388           DL, MVT::v16i8, V1, V2, OrigMask, DAG))
9389     return Shift;
9390
9391   // Try to use byte rotation instructions.
9392   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9393           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9394     return Rotate;
9395
9396   // Try to use a zext lowering.
9397   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9398           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9399     return ZExt;
9400
9401   int MaskStorage[16] = {
9402       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
9403       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
9404       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
9405       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
9406   MutableArrayRef<int> Mask(MaskStorage);
9407   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
9408   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
9409
9410   int NumV2Elements =
9411       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9412
9413   // For single-input shuffles, there are some nicer lowering tricks we can use.
9414   if (NumV2Elements == 0) {
9415     // Check for being able to broadcast a single element.
9416     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i8, DL, V1,
9417                                                           Mask, Subtarget, DAG))
9418       return Broadcast;
9419
9420     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9421     // Notably, this handles splat and partial-splat shuffles more efficiently.
9422     // However, it only makes sense if the pre-duplication shuffle simplifies
9423     // things significantly. Currently, this means we need to be able to
9424     // express the pre-duplication shuffle as an i16 shuffle.
9425     //
9426     // FIXME: We should check for other patterns which can be widened into an
9427     // i16 shuffle as well.
9428     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9429       for (int i = 0; i < 16; i += 2)
9430         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9431           return false;
9432
9433       return true;
9434     };
9435     auto tryToWidenViaDuplication = [&]() -> SDValue {
9436       if (!canWidenViaDuplication(Mask))
9437         return SDValue();
9438       SmallVector<int, 4> LoInputs;
9439       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9440                    [](int M) { return M >= 0 && M < 8; });
9441       std::sort(LoInputs.begin(), LoInputs.end());
9442       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9443                      LoInputs.end());
9444       SmallVector<int, 4> HiInputs;
9445       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9446                    [](int M) { return M >= 8; });
9447       std::sort(HiInputs.begin(), HiInputs.end());
9448       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9449                      HiInputs.end());
9450
9451       bool TargetLo = LoInputs.size() >= HiInputs.size();
9452       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9453       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9454
9455       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9456       SmallDenseMap<int, int, 8> LaneMap;
9457       for (int I : InPlaceInputs) {
9458         PreDupI16Shuffle[I/2] = I/2;
9459         LaneMap[I] = I;
9460       }
9461       int j = TargetLo ? 0 : 4, je = j + 4;
9462       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9463         // Check if j is already a shuffle of this input. This happens when
9464         // there are two adjacent bytes after we move the low one.
9465         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9466           // If we haven't yet mapped the input, search for a slot into which
9467           // we can map it.
9468           while (j < je && PreDupI16Shuffle[j] != -1)
9469             ++j;
9470
9471           if (j == je)
9472             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9473             return SDValue();
9474
9475           // Map this input with the i16 shuffle.
9476           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9477         }
9478
9479         // Update the lane map based on the mapping we ended up with.
9480         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9481       }
9482       V1 = DAG.getNode(
9483           ISD::BITCAST, DL, MVT::v16i8,
9484           DAG.getVectorShuffle(MVT::v8i16, DL,
9485                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9486                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9487
9488       // Unpack the bytes to form the i16s that will be shuffled into place.
9489       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9490                        MVT::v16i8, V1, V1);
9491
9492       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9493       for (int i = 0; i < 16; ++i)
9494         if (Mask[i] != -1) {
9495           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9496           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9497           if (PostDupI16Shuffle[i / 2] == -1)
9498             PostDupI16Shuffle[i / 2] = MappedMask;
9499           else
9500             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9501                    "Conflicting entrties in the original shuffle!");
9502         }
9503       return DAG.getNode(
9504           ISD::BITCAST, DL, MVT::v16i8,
9505           DAG.getVectorShuffle(MVT::v8i16, DL,
9506                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9507                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9508     };
9509     if (SDValue V = tryToWidenViaDuplication())
9510       return V;
9511   }
9512
9513   // Check whether an interleaving lowering is likely to be more efficient.
9514   // This isn't perfect but it is a strong heuristic that tends to work well on
9515   // the kinds of shuffles that show up in practice.
9516   //
9517   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
9518   if (shouldLowerAsInterleaving(Mask)) {
9519     int NumLoHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9520       return (M >= 0 && M < 8) || (M >= 16 && M < 24);
9521     });
9522     int NumHiHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9523       return (M >= 8 && M < 16) || M >= 24;
9524     });
9525     int EMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9526                      -1, -1, -1, -1, -1, -1, -1, -1};
9527     int OMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9528                      -1, -1, -1, -1, -1, -1, -1, -1};
9529     bool UnpackLo = NumLoHalf >= NumHiHalf;
9530     MutableArrayRef<int> TargetEMask(UnpackLo ? EMask : EMask + 8, 8);
9531     MutableArrayRef<int> TargetOMask(UnpackLo ? OMask : OMask + 8, 8);
9532     for (int i = 0; i < 8; ++i) {
9533       TargetEMask[i] = Mask[2 * i];
9534       TargetOMask[i] = Mask[2 * i + 1];
9535     }
9536
9537     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
9538     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
9539
9540     return DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9541                        MVT::v16i8, Evens, Odds);
9542   }
9543
9544   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9545   // with PSHUFB. It is important to do this before we attempt to generate any
9546   // blends but after all of the single-input lowerings. If the single input
9547   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9548   // want to preserve that and we can DAG combine any longer sequences into
9549   // a PSHUFB in the end. But once we start blending from multiple inputs,
9550   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9551   // and there are *very* few patterns that would actually be faster than the
9552   // PSHUFB approach because of its ability to zero lanes.
9553   //
9554   // FIXME: The only exceptions to the above are blends which are exact
9555   // interleavings with direct instructions supporting them. We currently don't
9556   // handle those well here.
9557   if (Subtarget->hasSSSE3()) {
9558     SDValue V1Mask[16];
9559     SDValue V2Mask[16];
9560     for (int i = 0; i < 16; ++i)
9561       if (Mask[i] == -1) {
9562         V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9563       } else {
9564         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
9565         V2Mask[i] =
9566             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
9567       }
9568     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
9569                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9570     if (isSingleInputShuffleMask(Mask))
9571       return V1; // Single inputs are easy.
9572
9573     // Otherwise, blend the two.
9574     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
9575                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9576     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9577   }
9578
9579   // There are special ways we can lower some single-element blends.
9580   if (NumV2Elements == 1)
9581     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
9582                                                          Mask, Subtarget, DAG))
9583       return V;
9584
9585   // Check whether a compaction lowering can be done. This handles shuffles
9586   // which take every Nth element for some even N. See the helper function for
9587   // details.
9588   //
9589   // We special case these as they can be particularly efficiently handled with
9590   // the PACKUSB instruction on x86 and they show up in common patterns of
9591   // rearranging bytes to truncate wide elements.
9592   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9593     // NumEvenDrops is the power of two stride of the elements. Another way of
9594     // thinking about it is that we need to drop the even elements this many
9595     // times to get the original input.
9596     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9597
9598     // First we need to zero all the dropped bytes.
9599     assert(NumEvenDrops <= 3 &&
9600            "No support for dropping even elements more than 3 times.");
9601     // We use the mask type to pick which bytes are preserved based on how many
9602     // elements are dropped.
9603     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9604     SDValue ByteClearMask =
9605         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
9606                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
9607     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9608     if (!IsSingleInput)
9609       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9610
9611     // Now pack things back together.
9612     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
9613     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
9614     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9615     for (int i = 1; i < NumEvenDrops; ++i) {
9616       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
9617       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9618     }
9619
9620     return Result;
9621   }
9622
9623   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9624   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9625   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9626   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9627
9628   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
9629                             MutableArrayRef<int> V1HalfBlendMask,
9630                             MutableArrayRef<int> V2HalfBlendMask) {
9631     for (int i = 0; i < 8; ++i)
9632       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
9633         V1HalfBlendMask[i] = HalfMask[i];
9634         HalfMask[i] = i;
9635       } else if (HalfMask[i] >= 16) {
9636         V2HalfBlendMask[i] = HalfMask[i] - 16;
9637         HalfMask[i] = i + 8;
9638       }
9639   };
9640   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
9641   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
9642
9643   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9644
9645   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
9646                              MutableArrayRef<int> HiBlendMask) {
9647     SDValue V1, V2;
9648     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9649     // them out and avoid using UNPCK{L,H} to extract the elements of V as
9650     // i16s.
9651     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
9652                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
9653         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
9654                      [](int M) { return M >= 0 && M % 2 == 1; })) {
9655       // Use a mask to drop the high bytes.
9656       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
9657       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
9658                        DAG.getConstant(0x00FF, MVT::v8i16));
9659
9660       // This will be a single vector shuffle instead of a blend so nuke V2.
9661       V2 = DAG.getUNDEF(MVT::v8i16);
9662
9663       // Squash the masks to point directly into V1.
9664       for (int &M : LoBlendMask)
9665         if (M >= 0)
9666           M /= 2;
9667       for (int &M : HiBlendMask)
9668         if (M >= 0)
9669           M /= 2;
9670     } else {
9671       // Otherwise just unpack the low half of V into V1 and the high half into
9672       // V2 so that we can blend them as i16s.
9673       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9674                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9675       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9676                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9677     }
9678
9679     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9680     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9681     return std::make_pair(BlendedLo, BlendedHi);
9682   };
9683   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
9684   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
9685   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
9686
9687   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
9688   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
9689
9690   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9691 }
9692
9693 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9694 ///
9695 /// This routine breaks down the specific type of 128-bit shuffle and
9696 /// dispatches to the lowering routines accordingly.
9697 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9698                                         MVT VT, const X86Subtarget *Subtarget,
9699                                         SelectionDAG &DAG) {
9700   switch (VT.SimpleTy) {
9701   case MVT::v2i64:
9702     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9703   case MVT::v2f64:
9704     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9705   case MVT::v4i32:
9706     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9707   case MVT::v4f32:
9708     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9709   case MVT::v8i16:
9710     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9711   case MVT::v16i8:
9712     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9713
9714   default:
9715     llvm_unreachable("Unimplemented!");
9716   }
9717 }
9718
9719 /// \brief Helper function to test whether a shuffle mask could be
9720 /// simplified by widening the elements being shuffled.
9721 ///
9722 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9723 /// leaves it in an unspecified state.
9724 ///
9725 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9726 /// shuffle masks. The latter have the special property of a '-2' representing
9727 /// a zero-ed lane of a vector.
9728 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9729                                     SmallVectorImpl<int> &WidenedMask) {
9730   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9731     // If both elements are undef, its trivial.
9732     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9733       WidenedMask.push_back(SM_SentinelUndef);
9734       continue;
9735     }
9736
9737     // Check for an undef mask and a mask value properly aligned to fit with
9738     // a pair of values. If we find such a case, use the non-undef mask's value.
9739     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9740       WidenedMask.push_back(Mask[i + 1] / 2);
9741       continue;
9742     }
9743     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9744       WidenedMask.push_back(Mask[i] / 2);
9745       continue;
9746     }
9747
9748     // When zeroing, we need to spread the zeroing across both lanes to widen.
9749     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9750       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9751           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9752         WidenedMask.push_back(SM_SentinelZero);
9753         continue;
9754       }
9755       return false;
9756     }
9757
9758     // Finally check if the two mask values are adjacent and aligned with
9759     // a pair.
9760     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9761       WidenedMask.push_back(Mask[i] / 2);
9762       continue;
9763     }
9764
9765     // Otherwise we can't safely widen the elements used in this shuffle.
9766     return false;
9767   }
9768   assert(WidenedMask.size() == Mask.size() / 2 &&
9769          "Incorrect size of mask after widening the elements!");
9770
9771   return true;
9772 }
9773
9774 /// \brief Generic routine to split ector shuffle into half-sized shuffles.
9775 ///
9776 /// This routine just extracts two subvectors, shuffles them independently, and
9777 /// then concatenates them back together. This should work effectively with all
9778 /// AVX vector shuffle types.
9779 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9780                                           SDValue V2, ArrayRef<int> Mask,
9781                                           SelectionDAG &DAG) {
9782   assert(VT.getSizeInBits() >= 256 &&
9783          "Only for 256-bit or wider vector shuffles!");
9784   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9785   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9786
9787   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9788   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9789
9790   int NumElements = VT.getVectorNumElements();
9791   int SplitNumElements = NumElements / 2;
9792   MVT ScalarVT = VT.getScalarType();
9793   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9794
9795   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9796                              DAG.getIntPtrConstant(0));
9797   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9798                              DAG.getIntPtrConstant(SplitNumElements));
9799   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9800                              DAG.getIntPtrConstant(0));
9801   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9802                              DAG.getIntPtrConstant(SplitNumElements));
9803
9804   // Now create two 4-way blends of these half-width vectors.
9805   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9806     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9807     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9808     for (int i = 0; i < SplitNumElements; ++i) {
9809       int M = HalfMask[i];
9810       if (M >= NumElements) {
9811         if (M >= NumElements + SplitNumElements)
9812           UseHiV2 = true;
9813         else
9814           UseLoV2 = true;
9815         V2BlendMask.push_back(M - NumElements);
9816         V1BlendMask.push_back(-1);
9817         BlendMask.push_back(SplitNumElements + i);
9818       } else if (M >= 0) {
9819         if (M >= SplitNumElements)
9820           UseHiV1 = true;
9821         else
9822           UseLoV1 = true;
9823         V2BlendMask.push_back(-1);
9824         V1BlendMask.push_back(M);
9825         BlendMask.push_back(i);
9826       } else {
9827         V2BlendMask.push_back(-1);
9828         V1BlendMask.push_back(-1);
9829         BlendMask.push_back(-1);
9830       }
9831     }
9832
9833     // Because the lowering happens after all combining takes place, we need to
9834     // manually combine these blend masks as much as possible so that we create
9835     // a minimal number of high-level vector shuffle nodes.
9836
9837     // First try just blending the halves of V1 or V2.
9838     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9839       return DAG.getUNDEF(SplitVT);
9840     if (!UseLoV2 && !UseHiV2)
9841       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9842     if (!UseLoV1 && !UseHiV1)
9843       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9844
9845     SDValue V1Blend, V2Blend;
9846     if (UseLoV1 && UseHiV1) {
9847       V1Blend =
9848         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9849     } else {
9850       // We only use half of V1 so map the usage down into the final blend mask.
9851       V1Blend = UseLoV1 ? LoV1 : HiV1;
9852       for (int i = 0; i < SplitNumElements; ++i)
9853         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9854           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9855     }
9856     if (UseLoV2 && UseHiV2) {
9857       V2Blend =
9858         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9859     } else {
9860       // We only use half of V2 so map the usage down into the final blend mask.
9861       V2Blend = UseLoV2 ? LoV2 : HiV2;
9862       for (int i = 0; i < SplitNumElements; ++i)
9863         if (BlendMask[i] >= SplitNumElements)
9864           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9865     }
9866     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9867   };
9868   SDValue Lo = HalfBlend(LoMask);
9869   SDValue Hi = HalfBlend(HiMask);
9870   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9871 }
9872
9873 /// \brief Either split a vector in halves or decompose the shuffles and the
9874 /// blend.
9875 ///
9876 /// This is provided as a good fallback for many lowerings of non-single-input
9877 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9878 /// between splitting the shuffle into 128-bit components and stitching those
9879 /// back together vs. extracting the single-input shuffles and blending those
9880 /// results.
9881 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9882                                                 SDValue V2, ArrayRef<int> Mask,
9883                                                 SelectionDAG &DAG) {
9884   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9885                                             "lower single-input shuffles as it "
9886                                             "could then recurse on itself.");
9887   int Size = Mask.size();
9888
9889   // If this can be modeled as a broadcast of two elements followed by a blend,
9890   // prefer that lowering. This is especially important because broadcasts can
9891   // often fold with memory operands.
9892   auto DoBothBroadcast = [&] {
9893     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9894     for (int M : Mask)
9895       if (M >= Size) {
9896         if (V2BroadcastIdx == -1)
9897           V2BroadcastIdx = M - Size;
9898         else if (M - Size != V2BroadcastIdx)
9899           return false;
9900       } else if (M >= 0) {
9901         if (V1BroadcastIdx == -1)
9902           V1BroadcastIdx = M;
9903         else if (M != V1BroadcastIdx)
9904           return false;
9905       }
9906     return true;
9907   };
9908   if (DoBothBroadcast())
9909     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9910                                                       DAG);
9911
9912   // If the inputs all stem from a single 128-bit lane of each input, then we
9913   // split them rather than blending because the split will decompose to
9914   // unusually few instructions.
9915   int LaneCount = VT.getSizeInBits() / 128;
9916   int LaneSize = Size / LaneCount;
9917   SmallBitVector LaneInputs[2];
9918   LaneInputs[0].resize(LaneCount, false);
9919   LaneInputs[1].resize(LaneCount, false);
9920   for (int i = 0; i < Size; ++i)
9921     if (Mask[i] >= 0)
9922       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9923   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9924     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9925
9926   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9927   // that the decomposed single-input shuffles don't end up here.
9928   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9929 }
9930
9931 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9932 /// a permutation and blend of those lanes.
9933 ///
9934 /// This essentially blends the out-of-lane inputs to each lane into the lane
9935 /// from a permuted copy of the vector. This lowering strategy results in four
9936 /// instructions in the worst case for a single-input cross lane shuffle which
9937 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9938 /// of. Special cases for each particular shuffle pattern should be handled
9939 /// prior to trying this lowering.
9940 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9941                                                        SDValue V1, SDValue V2,
9942                                                        ArrayRef<int> Mask,
9943                                                        SelectionDAG &DAG) {
9944   // FIXME: This should probably be generalized for 512-bit vectors as well.
9945   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9946   int LaneSize = Mask.size() / 2;
9947
9948   // If there are only inputs from one 128-bit lane, splitting will in fact be
9949   // less expensive. The flags track wether the given lane contains an element
9950   // that crosses to another lane.
9951   bool LaneCrossing[2] = {false, false};
9952   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9953     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9954       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9955   if (!LaneCrossing[0] || !LaneCrossing[1])
9956     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9957
9958   if (isSingleInputShuffleMask(Mask)) {
9959     SmallVector<int, 32> FlippedBlendMask;
9960     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9961       FlippedBlendMask.push_back(
9962           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9963                                   ? Mask[i]
9964                                   : Mask[i] % LaneSize +
9965                                         (i / LaneSize) * LaneSize + Size));
9966
9967     // Flip the vector, and blend the results which should now be in-lane. The
9968     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9969     // 5 for the high source. The value 3 selects the high half of source 2 and
9970     // the value 2 selects the low half of source 2. We only use source 2 to
9971     // allow folding it into a memory operand.
9972     unsigned PERMMask = 3 | 2 << 4;
9973     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9974                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9975     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9976   }
9977
9978   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9979   // will be handled by the above logic and a blend of the results, much like
9980   // other patterns in AVX.
9981   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9982 }
9983
9984 /// \brief Handle lowering 2-lane 128-bit shuffles.
9985 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9986                                         SDValue V2, ArrayRef<int> Mask,
9987                                         const X86Subtarget *Subtarget,
9988                                         SelectionDAG &DAG) {
9989   // Blends are faster and handle all the non-lane-crossing cases.
9990   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9991                                                 Subtarget, DAG))
9992     return Blend;
9993
9994   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9995                                VT.getVectorNumElements() / 2);
9996   // Check for patterns which can be matched with a single insert of a 128-bit
9997   // subvector.
9998   if (isShuffleEquivalent(Mask, 0, 1, 0, 1) ||
9999       isShuffleEquivalent(Mask, 0, 1, 4, 5)) {
10000     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10001                               DAG.getIntPtrConstant(0));
10002     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10003                               Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
10004     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10005   }
10006   if (isShuffleEquivalent(Mask, 0, 1, 6, 7)) {
10007     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10008                               DAG.getIntPtrConstant(0));
10009     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
10010                               DAG.getIntPtrConstant(2));
10011     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10012   }
10013
10014   // Otherwise form a 128-bit permutation.
10015   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
10016   unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
10017   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10018                      DAG.getConstant(PermMask, MVT::i8));
10019 }
10020
10021 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10022 /// shuffling each lane.
10023 ///
10024 /// This will only succeed when the result of fixing the 128-bit lanes results
10025 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10026 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10027 /// the lane crosses early and then use simpler shuffles within each lane.
10028 ///
10029 /// FIXME: It might be worthwhile at some point to support this without
10030 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10031 /// in x86 only floating point has interesting non-repeating shuffles, and even
10032 /// those are still *marginally* more expensive.
10033 static SDValue lowerVectorShuffleByMerging128BitLanes(
10034     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10035     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10036   assert(!isSingleInputShuffleMask(Mask) &&
10037          "This is only useful with multiple inputs.");
10038
10039   int Size = Mask.size();
10040   int LaneSize = 128 / VT.getScalarSizeInBits();
10041   int NumLanes = Size / LaneSize;
10042   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10043
10044   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10045   // check whether the in-128-bit lane shuffles share a repeating pattern.
10046   SmallVector<int, 4> Lanes;
10047   Lanes.resize(NumLanes, -1);
10048   SmallVector<int, 4> InLaneMask;
10049   InLaneMask.resize(LaneSize, -1);
10050   for (int i = 0; i < Size; ++i) {
10051     if (Mask[i] < 0)
10052       continue;
10053
10054     int j = i / LaneSize;
10055
10056     if (Lanes[j] < 0) {
10057       // First entry we've seen for this lane.
10058       Lanes[j] = Mask[i] / LaneSize;
10059     } else if (Lanes[j] != Mask[i] / LaneSize) {
10060       // This doesn't match the lane selected previously!
10061       return SDValue();
10062     }
10063
10064     // Check that within each lane we have a consistent shuffle mask.
10065     int k = i % LaneSize;
10066     if (InLaneMask[k] < 0) {
10067       InLaneMask[k] = Mask[i] % LaneSize;
10068     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10069       // This doesn't fit a repeating in-lane mask.
10070       return SDValue();
10071     }
10072   }
10073
10074   // First shuffle the lanes into place.
10075   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10076                                 VT.getSizeInBits() / 64);
10077   SmallVector<int, 8> LaneMask;
10078   LaneMask.resize(NumLanes * 2, -1);
10079   for (int i = 0; i < NumLanes; ++i)
10080     if (Lanes[i] >= 0) {
10081       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10082       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10083     }
10084
10085   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
10086   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
10087   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10088
10089   // Cast it back to the type we actually want.
10090   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
10091
10092   // Now do a simple shuffle that isn't lane crossing.
10093   SmallVector<int, 8> NewMask;
10094   NewMask.resize(Size, -1);
10095   for (int i = 0; i < Size; ++i)
10096     if (Mask[i] >= 0)
10097       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10098   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10099          "Must not introduce lane crosses at this point!");
10100
10101   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10102 }
10103
10104 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10105 /// given mask.
10106 ///
10107 /// This returns true if the elements from a particular input are already in the
10108 /// slot required by the given mask and require no permutation.
10109 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10110   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10111   int Size = Mask.size();
10112   for (int i = 0; i < Size; ++i)
10113     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10114       return false;
10115
10116   return true;
10117 }
10118
10119 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10120 ///
10121 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10122 /// isn't available.
10123 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10124                                        const X86Subtarget *Subtarget,
10125                                        SelectionDAG &DAG) {
10126   SDLoc DL(Op);
10127   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10128   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10129   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10130   ArrayRef<int> Mask = SVOp->getMask();
10131   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10132
10133   SmallVector<int, 4> WidenedMask;
10134   if (canWidenShuffleElements(Mask, WidenedMask))
10135     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10136                                     DAG);
10137
10138   if (isSingleInputShuffleMask(Mask)) {
10139     // Check for being able to broadcast a single element.
10140     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f64, DL, V1,
10141                                                           Mask, Subtarget, DAG))
10142       return Broadcast;
10143
10144     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10145       // Non-half-crossing single input shuffles can be lowerid with an
10146       // interleaved permutation.
10147       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10148                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10149       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10150                          DAG.getConstant(VPERMILPMask, MVT::i8));
10151     }
10152
10153     // With AVX2 we have direct support for this permutation.
10154     if (Subtarget->hasAVX2())
10155       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10156                          getV4X86ShuffleImm8ForMask(Mask, DAG));
10157
10158     // Otherwise, fall back.
10159     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10160                                                    DAG);
10161   }
10162
10163   // X86 has dedicated unpack instructions that can handle specific blend
10164   // operations: UNPCKH and UNPCKL.
10165   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10166     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10167   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10168     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10169
10170   // If we have a single input to the zero element, insert that into V1 if we
10171   // can do so cheaply.
10172   int NumV2Elements =
10173       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
10174   if (NumV2Elements == 1 && Mask[0] >= 4)
10175     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10176             MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
10177       return Insertion;
10178
10179   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10180                                                 Subtarget, DAG))
10181     return Blend;
10182
10183   // Check if the blend happens to exactly fit that of SHUFPD.
10184   if ((Mask[0] == -1 || Mask[0] < 2) &&
10185       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
10186       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
10187       (Mask[3] == -1 || Mask[3] >= 6)) {
10188     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
10189                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
10190     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
10191                        DAG.getConstant(SHUFPDMask, MVT::i8));
10192   }
10193   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
10194       (Mask[1] == -1 || Mask[1] < 2) &&
10195       (Mask[2] == -1 || Mask[2] >= 6) &&
10196       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
10197     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
10198                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
10199     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
10200                        DAG.getConstant(SHUFPDMask, MVT::i8));
10201   }
10202
10203   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10204   // shuffle. However, if we have AVX2 and either inputs are already in place,
10205   // we will be able to shuffle even across lanes the other input in a single
10206   // instruction so skip this pattern.
10207   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10208                                  isShuffleMaskInputInPlace(1, Mask))))
10209     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10210             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10211       return Result;
10212
10213   // If we have AVX2 then we always want to lower with a blend because an v4 we
10214   // can fully permute the elements.
10215   if (Subtarget->hasAVX2())
10216     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10217                                                       Mask, DAG);
10218
10219   // Otherwise fall back on generic lowering.
10220   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10221 }
10222
10223 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10224 ///
10225 /// This routine is only called when we have AVX2 and thus a reasonable
10226 /// instruction set for v4i64 shuffling..
10227 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10228                                        const X86Subtarget *Subtarget,
10229                                        SelectionDAG &DAG) {
10230   SDLoc DL(Op);
10231   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10232   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10233   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10234   ArrayRef<int> Mask = SVOp->getMask();
10235   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10236   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10237
10238   SmallVector<int, 4> WidenedMask;
10239   if (canWidenShuffleElements(Mask, WidenedMask))
10240     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10241                                     DAG);
10242
10243   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10244                                                 Subtarget, DAG))
10245     return Blend;
10246
10247   // Check for being able to broadcast a single element.
10248   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i64, DL, V1,
10249                                                         Mask, Subtarget, DAG))
10250     return Broadcast;
10251
10252   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10253   // use lower latency instructions that will operate on both 128-bit lanes.
10254   SmallVector<int, 2> RepeatedMask;
10255   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10256     if (isSingleInputShuffleMask(Mask)) {
10257       int PSHUFDMask[] = {-1, -1, -1, -1};
10258       for (int i = 0; i < 2; ++i)
10259         if (RepeatedMask[i] >= 0) {
10260           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10261           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10262         }
10263       return DAG.getNode(
10264           ISD::BITCAST, DL, MVT::v4i64,
10265           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10266                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
10267                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
10268     }
10269
10270     // Use dedicated unpack instructions for masks that match their pattern.
10271     if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10272       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10273     if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10274       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10275   }
10276
10277   // AVX2 provides a direct instruction for permuting a single input across
10278   // lanes.
10279   if (isSingleInputShuffleMask(Mask))
10280     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10281                        getV4X86ShuffleImm8ForMask(Mask, DAG));
10282
10283   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10284   // shuffle. However, if we have AVX2 and either inputs are already in place,
10285   // we will be able to shuffle even across lanes the other input in a single
10286   // instruction so skip this pattern.
10287   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10288                                  isShuffleMaskInputInPlace(1, Mask))))
10289     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10290             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10291       return Result;
10292
10293   // Otherwise fall back on generic blend lowering.
10294   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10295                                                     Mask, DAG);
10296 }
10297
10298 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10299 ///
10300 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10301 /// isn't available.
10302 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10303                                        const X86Subtarget *Subtarget,
10304                                        SelectionDAG &DAG) {
10305   SDLoc DL(Op);
10306   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10307   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10308   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10309   ArrayRef<int> Mask = SVOp->getMask();
10310   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10311
10312   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10313                                                 Subtarget, DAG))
10314     return Blend;
10315
10316   // Check for being able to broadcast a single element.
10317   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8f32, DL, V1,
10318                                                         Mask, Subtarget, DAG))
10319     return Broadcast;
10320
10321   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10322   // options to efficiently lower the shuffle.
10323   SmallVector<int, 4> RepeatedMask;
10324   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10325     assert(RepeatedMask.size() == 4 &&
10326            "Repeated masks must be half the mask width!");
10327     if (isSingleInputShuffleMask(Mask))
10328       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10329                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10330
10331     // Use dedicated unpack instructions for masks that match their pattern.
10332     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10333       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10334     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10335       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10336
10337     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10338     // have already handled any direct blends. We also need to squash the
10339     // repeated mask into a simulated v4f32 mask.
10340     for (int i = 0; i < 4; ++i)
10341       if (RepeatedMask[i] >= 8)
10342         RepeatedMask[i] -= 4;
10343     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10344   }
10345
10346   // If we have a single input shuffle with different shuffle patterns in the
10347   // two 128-bit lanes use the variable mask to VPERMILPS.
10348   if (isSingleInputShuffleMask(Mask)) {
10349     SDValue VPermMask[8];
10350     for (int i = 0; i < 8; ++i)
10351       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10352                                  : DAG.getConstant(Mask[i], MVT::i32);
10353     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10354       return DAG.getNode(
10355           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10356           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10357
10358     if (Subtarget->hasAVX2())
10359       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
10360                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
10361                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
10362                                                  MVT::v8i32, VPermMask)),
10363                          V1);
10364
10365     // Otherwise, fall back.
10366     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10367                                                    DAG);
10368   }
10369
10370   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10371   // shuffle.
10372   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10373           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10374     return Result;
10375
10376   // If we have AVX2 then we always want to lower with a blend because at v8 we
10377   // can fully permute the elements.
10378   if (Subtarget->hasAVX2())
10379     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10380                                                       Mask, DAG);
10381
10382   // Otherwise fall back on generic lowering.
10383   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10384 }
10385
10386 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10387 ///
10388 /// This routine is only called when we have AVX2 and thus a reasonable
10389 /// instruction set for v8i32 shuffling..
10390 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10391                                        const X86Subtarget *Subtarget,
10392                                        SelectionDAG &DAG) {
10393   SDLoc DL(Op);
10394   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10395   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10396   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10397   ArrayRef<int> Mask = SVOp->getMask();
10398   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10399   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10400
10401   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10402                                                 Subtarget, DAG))
10403     return Blend;
10404
10405   // Check for being able to broadcast a single element.
10406   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i32, DL, V1,
10407                                                         Mask, Subtarget, DAG))
10408     return Broadcast;
10409
10410   // If the shuffle mask is repeated in each 128-bit lane we can use more
10411   // efficient instructions that mirror the shuffles across the two 128-bit
10412   // lanes.
10413   SmallVector<int, 4> RepeatedMask;
10414   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10415     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10416     if (isSingleInputShuffleMask(Mask))
10417       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10418                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10419
10420     // Use dedicated unpack instructions for masks that match their pattern.
10421     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10422       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10423     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10424       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10425   }
10426
10427   // If the shuffle patterns aren't repeated but it is a single input, directly
10428   // generate a cross-lane VPERMD instruction.
10429   if (isSingleInputShuffleMask(Mask)) {
10430     SDValue VPermMask[8];
10431     for (int i = 0; i < 8; ++i)
10432       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10433                                  : DAG.getConstant(Mask[i], MVT::i32);
10434     return DAG.getNode(
10435         X86ISD::VPERMV, DL, MVT::v8i32,
10436         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10437   }
10438
10439   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10440   // shuffle.
10441   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10442           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10443     return Result;
10444
10445   // Otherwise fall back on generic blend lowering.
10446   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10447                                                     Mask, DAG);
10448 }
10449
10450 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10451 ///
10452 /// This routine is only called when we have AVX2 and thus a reasonable
10453 /// instruction set for v16i16 shuffling..
10454 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10455                                         const X86Subtarget *Subtarget,
10456                                         SelectionDAG &DAG) {
10457   SDLoc DL(Op);
10458   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10459   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10460   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10461   ArrayRef<int> Mask = SVOp->getMask();
10462   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10463   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10464
10465   // Check for being able to broadcast a single element.
10466   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i16, DL, V1,
10467                                                         Mask, Subtarget, DAG))
10468     return Broadcast;
10469
10470   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10471                                                 Subtarget, DAG))
10472     return Blend;
10473
10474   // Use dedicated unpack instructions for masks that match their pattern.
10475   if (isShuffleEquivalent(Mask,
10476                           // First 128-bit lane:
10477                           0, 16, 1, 17, 2, 18, 3, 19,
10478                           // Second 128-bit lane:
10479                           8, 24, 9, 25, 10, 26, 11, 27))
10480     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10481   if (isShuffleEquivalent(Mask,
10482                           // First 128-bit lane:
10483                           4, 20, 5, 21, 6, 22, 7, 23,
10484                           // Second 128-bit lane:
10485                           12, 28, 13, 29, 14, 30, 15, 31))
10486     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10487
10488   if (isSingleInputShuffleMask(Mask)) {
10489     // There are no generalized cross-lane shuffle operations available on i16
10490     // element types.
10491     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10492       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10493                                                      Mask, DAG);
10494
10495     SDValue PSHUFBMask[32];
10496     for (int i = 0; i < 16; ++i) {
10497       if (Mask[i] == -1) {
10498         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10499         continue;
10500       }
10501
10502       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10503       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10504       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
10505       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
10506     }
10507     return DAG.getNode(
10508         ISD::BITCAST, DL, MVT::v16i16,
10509         DAG.getNode(
10510             X86ISD::PSHUFB, DL, MVT::v32i8,
10511             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
10512             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
10513   }
10514
10515   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10516   // shuffle.
10517   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10518           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10519     return Result;
10520
10521   // Otherwise fall back on generic lowering.
10522   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10523 }
10524
10525 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10526 ///
10527 /// This routine is only called when we have AVX2 and thus a reasonable
10528 /// instruction set for v32i8 shuffling..
10529 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10530                                        const X86Subtarget *Subtarget,
10531                                        SelectionDAG &DAG) {
10532   SDLoc DL(Op);
10533   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10534   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10535   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10536   ArrayRef<int> Mask = SVOp->getMask();
10537   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10538   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10539
10540   // Check for being able to broadcast a single element.
10541   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v32i8, DL, V1,
10542                                                         Mask, Subtarget, DAG))
10543     return Broadcast;
10544
10545   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10546                                                 Subtarget, DAG))
10547     return Blend;
10548
10549   // Use dedicated unpack instructions for masks that match their pattern.
10550   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10551   // 256-bit lanes.
10552   if (isShuffleEquivalent(
10553           Mask,
10554           // First 128-bit lane:
10555           0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10556           // Second 128-bit lane:
10557           16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55))
10558     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10559   if (isShuffleEquivalent(
10560           Mask,
10561           // First 128-bit lane:
10562           8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10563           // Second 128-bit lane:
10564           24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63))
10565     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10566
10567   if (isSingleInputShuffleMask(Mask)) {
10568     // There are no generalized cross-lane shuffle operations available on i8
10569     // element types.
10570     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10571       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10572                                                      Mask, DAG);
10573
10574     SDValue PSHUFBMask[32];
10575     for (int i = 0; i < 32; ++i)
10576       PSHUFBMask[i] =
10577           Mask[i] < 0
10578               ? DAG.getUNDEF(MVT::i8)
10579               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
10580
10581     return DAG.getNode(
10582         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10583         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10584   }
10585
10586   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10587   // shuffle.
10588   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10589           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10590     return Result;
10591
10592   // Otherwise fall back on generic lowering.
10593   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10594 }
10595
10596 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10597 ///
10598 /// This routine either breaks down the specific type of a 256-bit x86 vector
10599 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10600 /// together based on the available instructions.
10601 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10602                                         MVT VT, const X86Subtarget *Subtarget,
10603                                         SelectionDAG &DAG) {
10604   SDLoc DL(Op);
10605   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10606   ArrayRef<int> Mask = SVOp->getMask();
10607
10608   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10609   // check for those subtargets here and avoid much of the subtarget querying in
10610   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10611   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10612   // floating point types there eventually, just immediately cast everything to
10613   // a float and operate entirely in that domain.
10614   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10615     int ElementBits = VT.getScalarSizeInBits();
10616     if (ElementBits < 32)
10617       // No floating point type available, decompose into 128-bit vectors.
10618       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10619
10620     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10621                                 VT.getVectorNumElements());
10622     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10623     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10624     return DAG.getNode(ISD::BITCAST, DL, VT,
10625                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10626   }
10627
10628   switch (VT.SimpleTy) {
10629   case MVT::v4f64:
10630     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10631   case MVT::v4i64:
10632     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10633   case MVT::v8f32:
10634     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10635   case MVT::v8i32:
10636     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10637   case MVT::v16i16:
10638     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10639   case MVT::v32i8:
10640     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10641
10642   default:
10643     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10644   }
10645 }
10646
10647 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10648 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10649                                        const X86Subtarget *Subtarget,
10650                                        SelectionDAG &DAG) {
10651   SDLoc DL(Op);
10652   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10653   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10654   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10655   ArrayRef<int> Mask = SVOp->getMask();
10656   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10657
10658   // FIXME: Implement direct support for this type!
10659   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10660 }
10661
10662 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10663 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10664                                        const X86Subtarget *Subtarget,
10665                                        SelectionDAG &DAG) {
10666   SDLoc DL(Op);
10667   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10668   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10669   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10670   ArrayRef<int> Mask = SVOp->getMask();
10671   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10672
10673   // FIXME: Implement direct support for this type!
10674   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10675 }
10676
10677 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10678 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10679                                        const X86Subtarget *Subtarget,
10680                                        SelectionDAG &DAG) {
10681   SDLoc DL(Op);
10682   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10683   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10684   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10685   ArrayRef<int> Mask = SVOp->getMask();
10686   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10687
10688   // FIXME: Implement direct support for this type!
10689   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10690 }
10691
10692 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10693 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10694                                        const X86Subtarget *Subtarget,
10695                                        SelectionDAG &DAG) {
10696   SDLoc DL(Op);
10697   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10698   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10699   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10700   ArrayRef<int> Mask = SVOp->getMask();
10701   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10702
10703   // FIXME: Implement direct support for this type!
10704   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10705 }
10706
10707 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10708 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10709                                         const X86Subtarget *Subtarget,
10710                                         SelectionDAG &DAG) {
10711   SDLoc DL(Op);
10712   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10713   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10714   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10715   ArrayRef<int> Mask = SVOp->getMask();
10716   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10717   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10718
10719   // FIXME: Implement direct support for this type!
10720   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10721 }
10722
10723 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10724 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10725                                        const X86Subtarget *Subtarget,
10726                                        SelectionDAG &DAG) {
10727   SDLoc DL(Op);
10728   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10729   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10730   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10731   ArrayRef<int> Mask = SVOp->getMask();
10732   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10733   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10734
10735   // FIXME: Implement direct support for this type!
10736   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10737 }
10738
10739 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10740 ///
10741 /// This routine either breaks down the specific type of a 512-bit x86 vector
10742 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10743 /// together based on the available instructions.
10744 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10745                                         MVT VT, const X86Subtarget *Subtarget,
10746                                         SelectionDAG &DAG) {
10747   SDLoc DL(Op);
10748   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10749   ArrayRef<int> Mask = SVOp->getMask();
10750   assert(Subtarget->hasAVX512() &&
10751          "Cannot lower 512-bit vectors w/ basic ISA!");
10752
10753   // Check for being able to broadcast a single element.
10754   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(VT.SimpleTy, DL, V1,
10755                                                         Mask, Subtarget, DAG))
10756     return Broadcast;
10757
10758   // Dispatch to each element type for lowering. If we don't have supprot for
10759   // specific element type shuffles at 512 bits, immediately split them and
10760   // lower them. Each lowering routine of a given type is allowed to assume that
10761   // the requisite ISA extensions for that element type are available.
10762   switch (VT.SimpleTy) {
10763   case MVT::v8f64:
10764     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10765   case MVT::v16f32:
10766     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10767   case MVT::v8i64:
10768     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10769   case MVT::v16i32:
10770     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10771   case MVT::v32i16:
10772     if (Subtarget->hasBWI())
10773       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10774     break;
10775   case MVT::v64i8:
10776     if (Subtarget->hasBWI())
10777       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10778     break;
10779
10780   default:
10781     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10782   }
10783
10784   // Otherwise fall back on splitting.
10785   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10786 }
10787
10788 /// \brief Top-level lowering for x86 vector shuffles.
10789 ///
10790 /// This handles decomposition, canonicalization, and lowering of all x86
10791 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10792 /// above in helper routines. The canonicalization attempts to widen shuffles
10793 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10794 /// s.t. only one of the two inputs needs to be tested, etc.
10795 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10796                                   SelectionDAG &DAG) {
10797   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10798   ArrayRef<int> Mask = SVOp->getMask();
10799   SDValue V1 = Op.getOperand(0);
10800   SDValue V2 = Op.getOperand(1);
10801   MVT VT = Op.getSimpleValueType();
10802   int NumElements = VT.getVectorNumElements();
10803   SDLoc dl(Op);
10804
10805   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10806
10807   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10808   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10809   if (V1IsUndef && V2IsUndef)
10810     return DAG.getUNDEF(VT);
10811
10812   // When we create a shuffle node we put the UNDEF node to second operand,
10813   // but in some cases the first operand may be transformed to UNDEF.
10814   // In this case we should just commute the node.
10815   if (V1IsUndef)
10816     return DAG.getCommutedVectorShuffle(*SVOp);
10817
10818   // Check for non-undef masks pointing at an undef vector and make the masks
10819   // undef as well. This makes it easier to match the shuffle based solely on
10820   // the mask.
10821   if (V2IsUndef)
10822     for (int M : Mask)
10823       if (M >= NumElements) {
10824         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10825         for (int &M : NewMask)
10826           if (M >= NumElements)
10827             M = -1;
10828         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10829       }
10830
10831   // Try to collapse shuffles into using a vector type with fewer elements but
10832   // wider element types. We cap this to not form integers or floating point
10833   // elements wider than 64 bits, but it might be interesting to form i128
10834   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10835   SmallVector<int, 16> WidenedMask;
10836   if (VT.getScalarSizeInBits() < 64 &&
10837       canWidenShuffleElements(Mask, WidenedMask)) {
10838     MVT NewEltVT = VT.isFloatingPoint()
10839                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10840                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10841     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10842     // Make sure that the new vector type is legal. For example, v2f64 isn't
10843     // legal on SSE1.
10844     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10845       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10846       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10847       return DAG.getNode(ISD::BITCAST, dl, VT,
10848                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10849     }
10850   }
10851
10852   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10853   for (int M : SVOp->getMask())
10854     if (M < 0)
10855       ++NumUndefElements;
10856     else if (M < NumElements)
10857       ++NumV1Elements;
10858     else
10859       ++NumV2Elements;
10860
10861   // Commute the shuffle as needed such that more elements come from V1 than
10862   // V2. This allows us to match the shuffle pattern strictly on how many
10863   // elements come from V1 without handling the symmetric cases.
10864   if (NumV2Elements > NumV1Elements)
10865     return DAG.getCommutedVectorShuffle(*SVOp);
10866
10867   // When the number of V1 and V2 elements are the same, try to minimize the
10868   // number of uses of V2 in the low half of the vector. When that is tied,
10869   // ensure that the sum of indices for V1 is equal to or lower than the sum
10870   // indices for V2. When those are equal, try to ensure that the number of odd
10871   // indices for V1 is lower than the number of odd indices for V2.
10872   if (NumV1Elements == NumV2Elements) {
10873     int LowV1Elements = 0, LowV2Elements = 0;
10874     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10875       if (M >= NumElements)
10876         ++LowV2Elements;
10877       else if (M >= 0)
10878         ++LowV1Elements;
10879     if (LowV2Elements > LowV1Elements) {
10880       return DAG.getCommutedVectorShuffle(*SVOp);
10881     } else if (LowV2Elements == LowV1Elements) {
10882       int SumV1Indices = 0, SumV2Indices = 0;
10883       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10884         if (SVOp->getMask()[i] >= NumElements)
10885           SumV2Indices += i;
10886         else if (SVOp->getMask()[i] >= 0)
10887           SumV1Indices += i;
10888       if (SumV2Indices < SumV1Indices) {
10889         return DAG.getCommutedVectorShuffle(*SVOp);
10890       } else if (SumV2Indices == SumV1Indices) {
10891         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10892         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10893           if (SVOp->getMask()[i] >= NumElements)
10894             NumV2OddIndices += i % 2;
10895           else if (SVOp->getMask()[i] >= 0)
10896             NumV1OddIndices += i % 2;
10897         if (NumV2OddIndices < NumV1OddIndices)
10898           return DAG.getCommutedVectorShuffle(*SVOp);
10899       }
10900     }
10901   }
10902
10903   // For each vector width, delegate to a specialized lowering routine.
10904   if (VT.getSizeInBits() == 128)
10905     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10906
10907   if (VT.getSizeInBits() == 256)
10908     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10909
10910   // Force AVX-512 vectors to be scalarized for now.
10911   // FIXME: Implement AVX-512 support!
10912   if (VT.getSizeInBits() == 512)
10913     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10914
10915   llvm_unreachable("Unimplemented!");
10916 }
10917
10918
10919 //===----------------------------------------------------------------------===//
10920 // Legacy vector shuffle lowering
10921 //
10922 // This code is the legacy code handling vector shuffles until the above
10923 // replaces its functionality and performance.
10924 //===----------------------------------------------------------------------===//
10925
10926 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
10927                         bool hasInt256, unsigned *MaskOut = nullptr) {
10928   MVT EltVT = VT.getVectorElementType();
10929
10930   // There is no blend with immediate in AVX-512.
10931   if (VT.is512BitVector())
10932     return false;
10933
10934   if (!hasSSE41 || EltVT == MVT::i8)
10935     return false;
10936   if (!hasInt256 && VT == MVT::v16i16)
10937     return false;
10938
10939   unsigned MaskValue = 0;
10940   unsigned NumElems = VT.getVectorNumElements();
10941   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10942   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10943   unsigned NumElemsInLane = NumElems / NumLanes;
10944
10945   // Blend for v16i16 should be symetric for the both lanes.
10946   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10947
10948     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
10949     int EltIdx = MaskVals[i];
10950
10951     if ((EltIdx < 0 || EltIdx == (int)i) &&
10952         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
10953       continue;
10954
10955     if (((unsigned)EltIdx == (i + NumElems)) &&
10956         (SndLaneEltIdx < 0 ||
10957          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
10958       MaskValue |= (1 << i);
10959     else
10960       return false;
10961   }
10962
10963   if (MaskOut)
10964     *MaskOut = MaskValue;
10965   return true;
10966 }
10967
10968 // Try to lower a shuffle node into a simple blend instruction.
10969 // This function assumes isBlendMask returns true for this
10970 // SuffleVectorSDNode
10971 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
10972                                           unsigned MaskValue,
10973                                           const X86Subtarget *Subtarget,
10974                                           SelectionDAG &DAG) {
10975   MVT VT = SVOp->getSimpleValueType(0);
10976   MVT EltVT = VT.getVectorElementType();
10977   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
10978                      Subtarget->hasInt256() && "Trying to lower a "
10979                                                "VECTOR_SHUFFLE to a Blend but "
10980                                                "with the wrong mask"));
10981   SDValue V1 = SVOp->getOperand(0);
10982   SDValue V2 = SVOp->getOperand(1);
10983   SDLoc dl(SVOp);
10984   unsigned NumElems = VT.getVectorNumElements();
10985
10986   // Convert i32 vectors to floating point if it is not AVX2.
10987   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10988   MVT BlendVT = VT;
10989   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10990     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10991                                NumElems);
10992     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
10993     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
10994   }
10995
10996   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
10997                             DAG.getConstant(MaskValue, MVT::i32));
10998   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10999 }
11000
11001 /// In vector type \p VT, return true if the element at index \p InputIdx
11002 /// falls on a different 128-bit lane than \p OutputIdx.
11003 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
11004                                      unsigned OutputIdx) {
11005   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
11006   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
11007 }
11008
11009 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
11010 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
11011 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
11012 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
11013 /// zero.
11014 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
11015                          SelectionDAG &DAG) {
11016   MVT VT = V1.getSimpleValueType();
11017   assert(VT.is128BitVector() || VT.is256BitVector());
11018
11019   MVT EltVT = VT.getVectorElementType();
11020   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
11021   unsigned NumElts = VT.getVectorNumElements();
11022
11023   SmallVector<SDValue, 32> PshufbMask;
11024   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
11025     int InputIdx = MaskVals[OutputIdx];
11026     unsigned InputByteIdx;
11027
11028     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
11029       InputByteIdx = 0x80;
11030     else {
11031       // Cross lane is not allowed.
11032       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
11033         return SDValue();
11034       InputByteIdx = InputIdx * EltSizeInBytes;
11035       // Index is an byte offset within the 128-bit lane.
11036       InputByteIdx &= 0xf;
11037     }
11038
11039     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
11040       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
11041       if (InputByteIdx != 0x80)
11042         ++InputByteIdx;
11043     }
11044   }
11045
11046   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
11047   if (ShufVT != VT)
11048     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
11049   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
11050                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
11051 }
11052
11053 // v8i16 shuffles - Prefer shuffles in the following order:
11054 // 1. [all]   pshuflw, pshufhw, optional move
11055 // 2. [ssse3] 1 x pshufb
11056 // 3. [ssse3] 2 x pshufb + 1 x por
11057 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
11058 static SDValue
11059 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
11060                          SelectionDAG &DAG) {
11061   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11062   SDValue V1 = SVOp->getOperand(0);
11063   SDValue V2 = SVOp->getOperand(1);
11064   SDLoc dl(SVOp);
11065   SmallVector<int, 8> MaskVals;
11066
11067   // Determine if more than 1 of the words in each of the low and high quadwords
11068   // of the result come from the same quadword of one of the two inputs.  Undef
11069   // mask values count as coming from any quadword, for better codegen.
11070   //
11071   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
11072   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
11073   unsigned LoQuad[] = { 0, 0, 0, 0 };
11074   unsigned HiQuad[] = { 0, 0, 0, 0 };
11075   // Indices of quads used.
11076   std::bitset<4> InputQuads;
11077   for (unsigned i = 0; i < 8; ++i) {
11078     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
11079     int EltIdx = SVOp->getMaskElt(i);
11080     MaskVals.push_back(EltIdx);
11081     if (EltIdx < 0) {
11082       ++Quad[0];
11083       ++Quad[1];
11084       ++Quad[2];
11085       ++Quad[3];
11086       continue;
11087     }
11088     ++Quad[EltIdx / 4];
11089     InputQuads.set(EltIdx / 4);
11090   }
11091
11092   int BestLoQuad = -1;
11093   unsigned MaxQuad = 1;
11094   for (unsigned i = 0; i < 4; ++i) {
11095     if (LoQuad[i] > MaxQuad) {
11096       BestLoQuad = i;
11097       MaxQuad = LoQuad[i];
11098     }
11099   }
11100
11101   int BestHiQuad = -1;
11102   MaxQuad = 1;
11103   for (unsigned i = 0; i < 4; ++i) {
11104     if (HiQuad[i] > MaxQuad) {
11105       BestHiQuad = i;
11106       MaxQuad = HiQuad[i];
11107     }
11108   }
11109
11110   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
11111   // of the two input vectors, shuffle them into one input vector so only a
11112   // single pshufb instruction is necessary. If there are more than 2 input
11113   // quads, disable the next transformation since it does not help SSSE3.
11114   bool V1Used = InputQuads[0] || InputQuads[1];
11115   bool V2Used = InputQuads[2] || InputQuads[3];
11116   if (Subtarget->hasSSSE3()) {
11117     if (InputQuads.count() == 2 && V1Used && V2Used) {
11118       BestLoQuad = InputQuads[0] ? 0 : 1;
11119       BestHiQuad = InputQuads[2] ? 2 : 3;
11120     }
11121     if (InputQuads.count() > 2) {
11122       BestLoQuad = -1;
11123       BestHiQuad = -1;
11124     }
11125   }
11126
11127   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
11128   // the shuffle mask.  If a quad is scored as -1, that means that it contains
11129   // words from all 4 input quadwords.
11130   SDValue NewV;
11131   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
11132     int MaskV[] = {
11133       BestLoQuad < 0 ? 0 : BestLoQuad,
11134       BestHiQuad < 0 ? 1 : BestHiQuad
11135     };
11136     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
11137                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
11138                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
11139     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
11140
11141     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
11142     // source words for the shuffle, to aid later transformations.
11143     bool AllWordsInNewV = true;
11144     bool InOrder[2] = { true, true };
11145     for (unsigned i = 0; i != 8; ++i) {
11146       int idx = MaskVals[i];
11147       if (idx != (int)i)
11148         InOrder[i/4] = false;
11149       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
11150         continue;
11151       AllWordsInNewV = false;
11152       break;
11153     }
11154
11155     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
11156     if (AllWordsInNewV) {
11157       for (int i = 0; i != 8; ++i) {
11158         int idx = MaskVals[i];
11159         if (idx < 0)
11160           continue;
11161         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
11162         if ((idx != i) && idx < 4)
11163           pshufhw = false;
11164         if ((idx != i) && idx > 3)
11165           pshuflw = false;
11166       }
11167       V1 = NewV;
11168       V2Used = false;
11169       BestLoQuad = 0;
11170       BestHiQuad = 1;
11171     }
11172
11173     // If we've eliminated the use of V2, and the new mask is a pshuflw or
11174     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
11175     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
11176       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
11177       unsigned TargetMask = 0;
11178       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
11179                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
11180       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11181       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
11182                              getShufflePSHUFLWImmediate(SVOp);
11183       V1 = NewV.getOperand(0);
11184       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
11185     }
11186   }
11187
11188   // Promote splats to a larger type which usually leads to more efficient code.
11189   // FIXME: Is this true if pshufb is available?
11190   if (SVOp->isSplat())
11191     return PromoteSplat(SVOp, DAG);
11192
11193   // If we have SSSE3, and all words of the result are from 1 input vector,
11194   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
11195   // is present, fall back to case 4.
11196   if (Subtarget->hasSSSE3()) {
11197     SmallVector<SDValue,16> pshufbMask;
11198
11199     // If we have elements from both input vectors, set the high bit of the
11200     // shuffle mask element to zero out elements that come from V2 in the V1
11201     // mask, and elements that come from V1 in the V2 mask, so that the two
11202     // results can be OR'd together.
11203     bool TwoInputs = V1Used && V2Used;
11204     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
11205     if (!TwoInputs)
11206       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11207
11208     // Calculate the shuffle mask for the second input, shuffle it, and
11209     // OR it with the first shuffled input.
11210     CommuteVectorShuffleMask(MaskVals, 8);
11211     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
11212     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11213     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11214   }
11215
11216   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
11217   // and update MaskVals with new element order.
11218   std::bitset<8> InOrder;
11219   if (BestLoQuad >= 0) {
11220     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
11221     for (int i = 0; i != 4; ++i) {
11222       int idx = MaskVals[i];
11223       if (idx < 0) {
11224         InOrder.set(i);
11225       } else if ((idx / 4) == BestLoQuad) {
11226         MaskV[i] = idx & 3;
11227         InOrder.set(i);
11228       }
11229     }
11230     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11231                                 &MaskV[0]);
11232
11233     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11234       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11235       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
11236                                   NewV.getOperand(0),
11237                                   getShufflePSHUFLWImmediate(SVOp), DAG);
11238     }
11239   }
11240
11241   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
11242   // and update MaskVals with the new element order.
11243   if (BestHiQuad >= 0) {
11244     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
11245     for (unsigned i = 4; i != 8; ++i) {
11246       int idx = MaskVals[i];
11247       if (idx < 0) {
11248         InOrder.set(i);
11249       } else if ((idx / 4) == BestHiQuad) {
11250         MaskV[i] = (idx & 3) + 4;
11251         InOrder.set(i);
11252       }
11253     }
11254     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11255                                 &MaskV[0]);
11256
11257     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11258       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11259       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
11260                                   NewV.getOperand(0),
11261                                   getShufflePSHUFHWImmediate(SVOp), DAG);
11262     }
11263   }
11264
11265   // In case BestHi & BestLo were both -1, which means each quadword has a word
11266   // from each of the four input quadwords, calculate the InOrder bitvector now
11267   // before falling through to the insert/extract cleanup.
11268   if (BestLoQuad == -1 && BestHiQuad == -1) {
11269     NewV = V1;
11270     for (int i = 0; i != 8; ++i)
11271       if (MaskVals[i] < 0 || MaskVals[i] == i)
11272         InOrder.set(i);
11273   }
11274
11275   // The other elements are put in the right place using pextrw and pinsrw.
11276   for (unsigned i = 0; i != 8; ++i) {
11277     if (InOrder[i])
11278       continue;
11279     int EltIdx = MaskVals[i];
11280     if (EltIdx < 0)
11281       continue;
11282     SDValue ExtOp = (EltIdx < 8) ?
11283       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
11284                   DAG.getIntPtrConstant(EltIdx)) :
11285       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
11286                   DAG.getIntPtrConstant(EltIdx - 8));
11287     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
11288                        DAG.getIntPtrConstant(i));
11289   }
11290   return NewV;
11291 }
11292
11293 /// \brief v16i16 shuffles
11294 ///
11295 /// FIXME: We only support generation of a single pshufb currently.  We can
11296 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
11297 /// well (e.g 2 x pshufb + 1 x por).
11298 static SDValue
11299 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
11300   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11301   SDValue V1 = SVOp->getOperand(0);
11302   SDValue V2 = SVOp->getOperand(1);
11303   SDLoc dl(SVOp);
11304
11305   if (V2.getOpcode() != ISD::UNDEF)
11306     return SDValue();
11307
11308   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11309   return getPSHUFB(MaskVals, V1, dl, DAG);
11310 }
11311
11312 // v16i8 shuffles - Prefer shuffles in the following order:
11313 // 1. [ssse3] 1 x pshufb
11314 // 2. [ssse3] 2 x pshufb + 1 x por
11315 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
11316 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
11317                                         const X86Subtarget* Subtarget,
11318                                         SelectionDAG &DAG) {
11319   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11320   SDValue V1 = SVOp->getOperand(0);
11321   SDValue V2 = SVOp->getOperand(1);
11322   SDLoc dl(SVOp);
11323   ArrayRef<int> MaskVals = SVOp->getMask();
11324
11325   // Promote splats to a larger type which usually leads to more efficient code.
11326   // FIXME: Is this true if pshufb is available?
11327   if (SVOp->isSplat())
11328     return PromoteSplat(SVOp, DAG);
11329
11330   // If we have SSSE3, case 1 is generated when all result bytes come from
11331   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
11332   // present, fall back to case 3.
11333
11334   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
11335   if (Subtarget->hasSSSE3()) {
11336     SmallVector<SDValue,16> pshufbMask;
11337
11338     // If all result elements are from one input vector, then only translate
11339     // undef mask values to 0x80 (zero out result) in the pshufb mask.
11340     //
11341     // Otherwise, we have elements from both input vectors, and must zero out
11342     // elements that come from V2 in the first mask, and V1 in the second mask
11343     // so that we can OR them together.
11344     for (unsigned i = 0; i != 16; ++i) {
11345       int EltIdx = MaskVals[i];
11346       if (EltIdx < 0 || EltIdx >= 16)
11347         EltIdx = 0x80;
11348       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11349     }
11350     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
11351                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11352                                  MVT::v16i8, pshufbMask));
11353
11354     // As PSHUFB will zero elements with negative indices, it's safe to ignore
11355     // the 2nd operand if it's undefined or zero.
11356     if (V2.getOpcode() == ISD::UNDEF ||
11357         ISD::isBuildVectorAllZeros(V2.getNode()))
11358       return V1;
11359
11360     // Calculate the shuffle mask for the second input, shuffle it, and
11361     // OR it with the first shuffled input.
11362     pshufbMask.clear();
11363     for (unsigned i = 0; i != 16; ++i) {
11364       int EltIdx = MaskVals[i];
11365       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
11366       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11367     }
11368     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
11369                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11370                                  MVT::v16i8, pshufbMask));
11371     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11372   }
11373
11374   // No SSSE3 - Calculate in place words and then fix all out of place words
11375   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
11376   // the 16 different words that comprise the two doublequadword input vectors.
11377   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11378   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
11379   SDValue NewV = V1;
11380   for (int i = 0; i != 8; ++i) {
11381     int Elt0 = MaskVals[i*2];
11382     int Elt1 = MaskVals[i*2+1];
11383
11384     // This word of the result is all undef, skip it.
11385     if (Elt0 < 0 && Elt1 < 0)
11386       continue;
11387
11388     // This word of the result is already in the correct place, skip it.
11389     if ((Elt0 == i*2) && (Elt1 == i*2+1))
11390       continue;
11391
11392     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
11393     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
11394     SDValue InsElt;
11395
11396     // If Elt0 and Elt1 are defined, are consecutive, and can be load
11397     // using a single extract together, load it and store it.
11398     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
11399       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11400                            DAG.getIntPtrConstant(Elt1 / 2));
11401       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11402                         DAG.getIntPtrConstant(i));
11403       continue;
11404     }
11405
11406     // If Elt1 is defined, extract it from the appropriate source.  If the
11407     // source byte is not also odd, shift the extracted word left 8 bits
11408     // otherwise clear the bottom 8 bits if we need to do an or.
11409     if (Elt1 >= 0) {
11410       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11411                            DAG.getIntPtrConstant(Elt1 / 2));
11412       if ((Elt1 & 1) == 0)
11413         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
11414                              DAG.getConstant(8,
11415                                   TLI.getShiftAmountTy(InsElt.getValueType())));
11416       else if (Elt0 >= 0)
11417         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
11418                              DAG.getConstant(0xFF00, MVT::i16));
11419     }
11420     // If Elt0 is defined, extract it from the appropriate source.  If the
11421     // source byte is not also even, shift the extracted word right 8 bits. If
11422     // Elt1 was also defined, OR the extracted values together before
11423     // inserting them in the result.
11424     if (Elt0 >= 0) {
11425       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
11426                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
11427       if ((Elt0 & 1) != 0)
11428         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
11429                               DAG.getConstant(8,
11430                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
11431       else if (Elt1 >= 0)
11432         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
11433                              DAG.getConstant(0x00FF, MVT::i16));
11434       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
11435                          : InsElt0;
11436     }
11437     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11438                        DAG.getIntPtrConstant(i));
11439   }
11440   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
11441 }
11442
11443 // v32i8 shuffles - Translate to VPSHUFB if possible.
11444 static
11445 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
11446                                  const X86Subtarget *Subtarget,
11447                                  SelectionDAG &DAG) {
11448   MVT VT = SVOp->getSimpleValueType(0);
11449   SDValue V1 = SVOp->getOperand(0);
11450   SDValue V2 = SVOp->getOperand(1);
11451   SDLoc dl(SVOp);
11452   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11453
11454   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11455   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
11456   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
11457
11458   // VPSHUFB may be generated if
11459   // (1) one of input vector is undefined or zeroinitializer.
11460   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
11461   // And (2) the mask indexes don't cross the 128-bit lane.
11462   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
11463       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
11464     return SDValue();
11465
11466   if (V1IsAllZero && !V2IsAllZero) {
11467     CommuteVectorShuffleMask(MaskVals, 32);
11468     V1 = V2;
11469   }
11470   return getPSHUFB(MaskVals, V1, dl, DAG);
11471 }
11472
11473 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
11474 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
11475 /// done when every pair / quad of shuffle mask elements point to elements in
11476 /// the right sequence. e.g.
11477 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
11478 static
11479 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
11480                                  SelectionDAG &DAG) {
11481   MVT VT = SVOp->getSimpleValueType(0);
11482   SDLoc dl(SVOp);
11483   unsigned NumElems = VT.getVectorNumElements();
11484   MVT NewVT;
11485   unsigned Scale;
11486   switch (VT.SimpleTy) {
11487   default: llvm_unreachable("Unexpected!");
11488   case MVT::v2i64:
11489   case MVT::v2f64:
11490            return SDValue(SVOp, 0);
11491   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
11492   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
11493   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
11494   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
11495   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
11496   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
11497   }
11498
11499   SmallVector<int, 8> MaskVec;
11500   for (unsigned i = 0; i != NumElems; i += Scale) {
11501     int StartIdx = -1;
11502     for (unsigned j = 0; j != Scale; ++j) {
11503       int EltIdx = SVOp->getMaskElt(i+j);
11504       if (EltIdx < 0)
11505         continue;
11506       if (StartIdx < 0)
11507         StartIdx = (EltIdx / Scale);
11508       if (EltIdx != (int)(StartIdx*Scale + j))
11509         return SDValue();
11510     }
11511     MaskVec.push_back(StartIdx);
11512   }
11513
11514   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
11515   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
11516   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
11517 }
11518
11519 /// getVZextMovL - Return a zero-extending vector move low node.
11520 ///
11521 static SDValue getVZextMovL(MVT VT, MVT OpVT,
11522                             SDValue SrcOp, SelectionDAG &DAG,
11523                             const X86Subtarget *Subtarget, SDLoc dl) {
11524   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
11525     LoadSDNode *LD = nullptr;
11526     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
11527       LD = dyn_cast<LoadSDNode>(SrcOp);
11528     if (!LD) {
11529       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
11530       // instead.
11531       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
11532       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
11533           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11534           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
11535           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
11536         // PR2108
11537         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
11538         return DAG.getNode(ISD::BITCAST, dl, VT,
11539                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11540                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11541                                                    OpVT,
11542                                                    SrcOp.getOperand(0)
11543                                                           .getOperand(0))));
11544       }
11545     }
11546   }
11547
11548   return DAG.getNode(ISD::BITCAST, dl, VT,
11549                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11550                                  DAG.getNode(ISD::BITCAST, dl,
11551                                              OpVT, SrcOp)));
11552 }
11553
11554 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
11555 /// which could not be matched by any known target speficic shuffle
11556 static SDValue
11557 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11558
11559   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
11560   if (NewOp.getNode())
11561     return NewOp;
11562
11563   MVT VT = SVOp->getSimpleValueType(0);
11564
11565   unsigned NumElems = VT.getVectorNumElements();
11566   unsigned NumLaneElems = NumElems / 2;
11567
11568   SDLoc dl(SVOp);
11569   MVT EltVT = VT.getVectorElementType();
11570   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
11571   SDValue Output[2];
11572
11573   SmallVector<int, 16> Mask;
11574   for (unsigned l = 0; l < 2; ++l) {
11575     // Build a shuffle mask for the output, discovering on the fly which
11576     // input vectors to use as shuffle operands (recorded in InputUsed).
11577     // If building a suitable shuffle vector proves too hard, then bail
11578     // out with UseBuildVector set.
11579     bool UseBuildVector = false;
11580     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
11581     unsigned LaneStart = l * NumLaneElems;
11582     for (unsigned i = 0; i != NumLaneElems; ++i) {
11583       // The mask element.  This indexes into the input.
11584       int Idx = SVOp->getMaskElt(i+LaneStart);
11585       if (Idx < 0) {
11586         // the mask element does not index into any input vector.
11587         Mask.push_back(-1);
11588         continue;
11589       }
11590
11591       // The input vector this mask element indexes into.
11592       int Input = Idx / NumLaneElems;
11593
11594       // Turn the index into an offset from the start of the input vector.
11595       Idx -= Input * NumLaneElems;
11596
11597       // Find or create a shuffle vector operand to hold this input.
11598       unsigned OpNo;
11599       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
11600         if (InputUsed[OpNo] == Input)
11601           // This input vector is already an operand.
11602           break;
11603         if (InputUsed[OpNo] < 0) {
11604           // Create a new operand for this input vector.
11605           InputUsed[OpNo] = Input;
11606           break;
11607         }
11608       }
11609
11610       if (OpNo >= array_lengthof(InputUsed)) {
11611         // More than two input vectors used!  Give up on trying to create a
11612         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
11613         UseBuildVector = true;
11614         break;
11615       }
11616
11617       // Add the mask index for the new shuffle vector.
11618       Mask.push_back(Idx + OpNo * NumLaneElems);
11619     }
11620
11621     if (UseBuildVector) {
11622       SmallVector<SDValue, 16> SVOps;
11623       for (unsigned i = 0; i != NumLaneElems; ++i) {
11624         // The mask element.  This indexes into the input.
11625         int Idx = SVOp->getMaskElt(i+LaneStart);
11626         if (Idx < 0) {
11627           SVOps.push_back(DAG.getUNDEF(EltVT));
11628           continue;
11629         }
11630
11631         // The input vector this mask element indexes into.
11632         int Input = Idx / NumElems;
11633
11634         // Turn the index into an offset from the start of the input vector.
11635         Idx -= Input * NumElems;
11636
11637         // Extract the vector element by hand.
11638         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
11639                                     SVOp->getOperand(Input),
11640                                     DAG.getIntPtrConstant(Idx)));
11641       }
11642
11643       // Construct the output using a BUILD_VECTOR.
11644       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
11645     } else if (InputUsed[0] < 0) {
11646       // No input vectors were used! The result is undefined.
11647       Output[l] = DAG.getUNDEF(NVT);
11648     } else {
11649       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
11650                                         (InputUsed[0] % 2) * NumLaneElems,
11651                                         DAG, dl);
11652       // If only one input was used, use an undefined vector for the other.
11653       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
11654         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
11655                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
11656       // At least one input vector was used. Create a new shuffle vector.
11657       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
11658     }
11659
11660     Mask.clear();
11661   }
11662
11663   // Concatenate the result back
11664   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
11665 }
11666
11667 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
11668 /// 4 elements, and match them with several different shuffle types.
11669 static SDValue
11670 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11671   SDValue V1 = SVOp->getOperand(0);
11672   SDValue V2 = SVOp->getOperand(1);
11673   SDLoc dl(SVOp);
11674   MVT VT = SVOp->getSimpleValueType(0);
11675
11676   assert(VT.is128BitVector() && "Unsupported vector size");
11677
11678   std::pair<int, int> Locs[4];
11679   int Mask1[] = { -1, -1, -1, -1 };
11680   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
11681
11682   unsigned NumHi = 0;
11683   unsigned NumLo = 0;
11684   for (unsigned i = 0; i != 4; ++i) {
11685     int Idx = PermMask[i];
11686     if (Idx < 0) {
11687       Locs[i] = std::make_pair(-1, -1);
11688     } else {
11689       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
11690       if (Idx < 4) {
11691         Locs[i] = std::make_pair(0, NumLo);
11692         Mask1[NumLo] = Idx;
11693         NumLo++;
11694       } else {
11695         Locs[i] = std::make_pair(1, NumHi);
11696         if (2+NumHi < 4)
11697           Mask1[2+NumHi] = Idx;
11698         NumHi++;
11699       }
11700     }
11701   }
11702
11703   if (NumLo <= 2 && NumHi <= 2) {
11704     // If no more than two elements come from either vector. This can be
11705     // implemented with two shuffles. First shuffle gather the elements.
11706     // The second shuffle, which takes the first shuffle as both of its
11707     // vector operands, put the elements into the right order.
11708     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11709
11710     int Mask2[] = { -1, -1, -1, -1 };
11711
11712     for (unsigned i = 0; i != 4; ++i)
11713       if (Locs[i].first != -1) {
11714         unsigned Idx = (i < 2) ? 0 : 4;
11715         Idx += Locs[i].first * 2 + Locs[i].second;
11716         Mask2[i] = Idx;
11717       }
11718
11719     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
11720   }
11721
11722   if (NumLo == 3 || NumHi == 3) {
11723     // Otherwise, we must have three elements from one vector, call it X, and
11724     // one element from the other, call it Y.  First, use a shufps to build an
11725     // intermediate vector with the one element from Y and the element from X
11726     // that will be in the same half in the final destination (the indexes don't
11727     // matter). Then, use a shufps to build the final vector, taking the half
11728     // containing the element from Y from the intermediate, and the other half
11729     // from X.
11730     if (NumHi == 3) {
11731       // Normalize it so the 3 elements come from V1.
11732       CommuteVectorShuffleMask(PermMask, 4);
11733       std::swap(V1, V2);
11734     }
11735
11736     // Find the element from V2.
11737     unsigned HiIndex;
11738     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
11739       int Val = PermMask[HiIndex];
11740       if (Val < 0)
11741         continue;
11742       if (Val >= 4)
11743         break;
11744     }
11745
11746     Mask1[0] = PermMask[HiIndex];
11747     Mask1[1] = -1;
11748     Mask1[2] = PermMask[HiIndex^1];
11749     Mask1[3] = -1;
11750     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11751
11752     if (HiIndex >= 2) {
11753       Mask1[0] = PermMask[0];
11754       Mask1[1] = PermMask[1];
11755       Mask1[2] = HiIndex & 1 ? 6 : 4;
11756       Mask1[3] = HiIndex & 1 ? 4 : 6;
11757       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11758     }
11759
11760     Mask1[0] = HiIndex & 1 ? 2 : 0;
11761     Mask1[1] = HiIndex & 1 ? 0 : 2;
11762     Mask1[2] = PermMask[2];
11763     Mask1[3] = PermMask[3];
11764     if (Mask1[2] >= 0)
11765       Mask1[2] += 4;
11766     if (Mask1[3] >= 0)
11767       Mask1[3] += 4;
11768     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
11769   }
11770
11771   // Break it into (shuffle shuffle_hi, shuffle_lo).
11772   int LoMask[] = { -1, -1, -1, -1 };
11773   int HiMask[] = { -1, -1, -1, -1 };
11774
11775   int *MaskPtr = LoMask;
11776   unsigned MaskIdx = 0;
11777   unsigned LoIdx = 0;
11778   unsigned HiIdx = 2;
11779   for (unsigned i = 0; i != 4; ++i) {
11780     if (i == 2) {
11781       MaskPtr = HiMask;
11782       MaskIdx = 1;
11783       LoIdx = 0;
11784       HiIdx = 2;
11785     }
11786     int Idx = PermMask[i];
11787     if (Idx < 0) {
11788       Locs[i] = std::make_pair(-1, -1);
11789     } else if (Idx < 4) {
11790       Locs[i] = std::make_pair(MaskIdx, LoIdx);
11791       MaskPtr[LoIdx] = Idx;
11792       LoIdx++;
11793     } else {
11794       Locs[i] = std::make_pair(MaskIdx, HiIdx);
11795       MaskPtr[HiIdx] = Idx;
11796       HiIdx++;
11797     }
11798   }
11799
11800   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
11801   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
11802   int MaskOps[] = { -1, -1, -1, -1 };
11803   for (unsigned i = 0; i != 4; ++i)
11804     if (Locs[i].first != -1)
11805       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
11806   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
11807 }
11808
11809 static bool MayFoldVectorLoad(SDValue V) {
11810   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
11811     V = V.getOperand(0);
11812
11813   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
11814     V = V.getOperand(0);
11815   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
11816       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
11817     // BUILD_VECTOR (load), undef
11818     V = V.getOperand(0);
11819
11820   return MayFoldLoad(V);
11821 }
11822
11823 static
11824 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
11825   MVT VT = Op.getSimpleValueType();
11826
11827   // Canonizalize to v2f64.
11828   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
11829   return DAG.getNode(ISD::BITCAST, dl, VT,
11830                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
11831                                           V1, DAG));
11832 }
11833
11834 static
11835 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
11836                         bool HasSSE2) {
11837   SDValue V1 = Op.getOperand(0);
11838   SDValue V2 = Op.getOperand(1);
11839   MVT VT = Op.getSimpleValueType();
11840
11841   assert(VT != MVT::v2i64 && "unsupported shuffle type");
11842
11843   if (HasSSE2 && VT == MVT::v2f64)
11844     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
11845
11846   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
11847   return DAG.getNode(ISD::BITCAST, dl, VT,
11848                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
11849                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
11850                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
11851 }
11852
11853 static
11854 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
11855   SDValue V1 = Op.getOperand(0);
11856   SDValue V2 = Op.getOperand(1);
11857   MVT VT = Op.getSimpleValueType();
11858
11859   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
11860          "unsupported shuffle type");
11861
11862   if (V2.getOpcode() == ISD::UNDEF)
11863     V2 = V1;
11864
11865   // v4i32 or v4f32
11866   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
11867 }
11868
11869 static
11870 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
11871   SDValue V1 = Op.getOperand(0);
11872   SDValue V2 = Op.getOperand(1);
11873   MVT VT = Op.getSimpleValueType();
11874   unsigned NumElems = VT.getVectorNumElements();
11875
11876   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
11877   // operand of these instructions is only memory, so check if there's a
11878   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
11879   // same masks.
11880   bool CanFoldLoad = false;
11881
11882   // Trivial case, when V2 comes from a load.
11883   if (MayFoldVectorLoad(V2))
11884     CanFoldLoad = true;
11885
11886   // When V1 is a load, it can be folded later into a store in isel, example:
11887   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
11888   //    turns into:
11889   //  (MOVLPSmr addr:$src1, VR128:$src2)
11890   // So, recognize this potential and also use MOVLPS or MOVLPD
11891   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
11892     CanFoldLoad = true;
11893
11894   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11895   if (CanFoldLoad) {
11896     if (HasSSE2 && NumElems == 2)
11897       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
11898
11899     if (NumElems == 4)
11900       // If we don't care about the second element, proceed to use movss.
11901       if (SVOp->getMaskElt(1) != -1)
11902         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
11903   }
11904
11905   // movl and movlp will both match v2i64, but v2i64 is never matched by
11906   // movl earlier because we make it strict to avoid messing with the movlp load
11907   // folding logic (see the code above getMOVLP call). Match it here then,
11908   // this is horrible, but will stay like this until we move all shuffle
11909   // matching to x86 specific nodes. Note that for the 1st condition all
11910   // types are matched with movsd.
11911   if (HasSSE2) {
11912     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
11913     // as to remove this logic from here, as much as possible
11914     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
11915       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
11916     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
11917   }
11918
11919   assert(VT != MVT::v4i32 && "unsupported shuffle type");
11920
11921   // Invert the operand order and use SHUFPS to match it.
11922   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
11923                               getShuffleSHUFImmediate(SVOp), DAG);
11924 }
11925
11926 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
11927                                          SelectionDAG &DAG) {
11928   SDLoc dl(Load);
11929   MVT VT = Load->getSimpleValueType(0);
11930   MVT EVT = VT.getVectorElementType();
11931   SDValue Addr = Load->getOperand(1);
11932   SDValue NewAddr = DAG.getNode(
11933       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
11934       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
11935
11936   SDValue NewLoad =
11937       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
11938                   DAG.getMachineFunction().getMachineMemOperand(
11939                       Load->getMemOperand(), 0, EVT.getStoreSize()));
11940   return NewLoad;
11941 }
11942
11943 // It is only safe to call this function if isINSERTPSMask is true for
11944 // this shufflevector mask.
11945 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
11946                            SelectionDAG &DAG) {
11947   // Generate an insertps instruction when inserting an f32 from memory onto a
11948   // v4f32 or when copying a member from one v4f32 to another.
11949   // We also use it for transferring i32 from one register to another,
11950   // since it simply copies the same bits.
11951   // If we're transferring an i32 from memory to a specific element in a
11952   // register, we output a generic DAG that will match the PINSRD
11953   // instruction.
11954   MVT VT = SVOp->getSimpleValueType(0);
11955   MVT EVT = VT.getVectorElementType();
11956   SDValue V1 = SVOp->getOperand(0);
11957   SDValue V2 = SVOp->getOperand(1);
11958   auto Mask = SVOp->getMask();
11959   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
11960          "unsupported vector type for insertps/pinsrd");
11961
11962   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
11963   auto FromV2Predicate = [](const int &i) { return i >= 4; };
11964   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
11965
11966   SDValue From;
11967   SDValue To;
11968   unsigned DestIndex;
11969   if (FromV1 == 1) {
11970     From = V1;
11971     To = V2;
11972     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
11973                 Mask.begin();
11974
11975     // If we have 1 element from each vector, we have to check if we're
11976     // changing V1's element's place. If so, we're done. Otherwise, we
11977     // should assume we're changing V2's element's place and behave
11978     // accordingly.
11979     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
11980     assert(DestIndex <= INT32_MAX && "truncated destination index");
11981     if (FromV1 == FromV2 &&
11982         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
11983       From = V2;
11984       To = V1;
11985       DestIndex =
11986           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
11987     }
11988   } else {
11989     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
11990            "More than one element from V1 and from V2, or no elements from one "
11991            "of the vectors. This case should not have returned true from "
11992            "isINSERTPSMask");
11993     From = V2;
11994     To = V1;
11995     DestIndex =
11996         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
11997   }
11998
11999   // Get an index into the source vector in the range [0,4) (the mask is
12000   // in the range [0,8) because it can address V1 and V2)
12001   unsigned SrcIndex = Mask[DestIndex] % 4;
12002   if (MayFoldLoad(From)) {
12003     // Trivial case, when From comes from a load and is only used by the
12004     // shuffle. Make it use insertps from the vector that we need from that
12005     // load.
12006     SDValue NewLoad =
12007         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
12008     if (!NewLoad.getNode())
12009       return SDValue();
12010
12011     if (EVT == MVT::f32) {
12012       // Create this as a scalar to vector to match the instruction pattern.
12013       SDValue LoadScalarToVector =
12014           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
12015       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
12016       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
12017                          InsertpsMask);
12018     } else { // EVT == MVT::i32
12019       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
12020       // instruction, to match the PINSRD instruction, which loads an i32 to a
12021       // certain vector element.
12022       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
12023                          DAG.getConstant(DestIndex, MVT::i32));
12024     }
12025   }
12026
12027   // Vector-element-to-vector
12028   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
12029   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
12030 }
12031
12032 // Reduce a vector shuffle to zext.
12033 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
12034                                     SelectionDAG &DAG) {
12035   // PMOVZX is only available from SSE41.
12036   if (!Subtarget->hasSSE41())
12037     return SDValue();
12038
12039   MVT VT = Op.getSimpleValueType();
12040
12041   // Only AVX2 support 256-bit vector integer extending.
12042   if (!Subtarget->hasInt256() && VT.is256BitVector())
12043     return SDValue();
12044
12045   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12046   SDLoc DL(Op);
12047   SDValue V1 = Op.getOperand(0);
12048   SDValue V2 = Op.getOperand(1);
12049   unsigned NumElems = VT.getVectorNumElements();
12050
12051   // Extending is an unary operation and the element type of the source vector
12052   // won't be equal to or larger than i64.
12053   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
12054       VT.getVectorElementType() == MVT::i64)
12055     return SDValue();
12056
12057   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
12058   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
12059   while ((1U << Shift) < NumElems) {
12060     if (SVOp->getMaskElt(1U << Shift) == 1)
12061       break;
12062     Shift += 1;
12063     // The maximal ratio is 8, i.e. from i8 to i64.
12064     if (Shift > 3)
12065       return SDValue();
12066   }
12067
12068   // Check the shuffle mask.
12069   unsigned Mask = (1U << Shift) - 1;
12070   for (unsigned i = 0; i != NumElems; ++i) {
12071     int EltIdx = SVOp->getMaskElt(i);
12072     if ((i & Mask) != 0 && EltIdx != -1)
12073       return SDValue();
12074     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
12075       return SDValue();
12076   }
12077
12078   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
12079   MVT NeVT = MVT::getIntegerVT(NBits);
12080   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
12081
12082   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
12083     return SDValue();
12084
12085   return DAG.getNode(ISD::BITCAST, DL, VT,
12086                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
12087 }
12088
12089 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
12090                                       SelectionDAG &DAG) {
12091   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12092   MVT VT = Op.getSimpleValueType();
12093   SDLoc dl(Op);
12094   SDValue V1 = Op.getOperand(0);
12095   SDValue V2 = Op.getOperand(1);
12096
12097   if (isZeroShuffle(SVOp))
12098     return getZeroVector(VT, Subtarget, DAG, dl);
12099
12100   // Handle splat operations
12101   if (SVOp->isSplat()) {
12102     // Use vbroadcast whenever the splat comes from a foldable load
12103     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
12104     if (Broadcast.getNode())
12105       return Broadcast;
12106   }
12107
12108   // Check integer expanding shuffles.
12109   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
12110   if (NewOp.getNode())
12111     return NewOp;
12112
12113   // If the shuffle can be profitably rewritten as a narrower shuffle, then
12114   // do it!
12115   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
12116       VT == MVT::v32i8) {
12117     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12118     if (NewOp.getNode())
12119       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
12120   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
12121     // FIXME: Figure out a cleaner way to do this.
12122     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
12123       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12124       if (NewOp.getNode()) {
12125         MVT NewVT = NewOp.getSimpleValueType();
12126         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
12127                                NewVT, true, false))
12128           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
12129                               dl);
12130       }
12131     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
12132       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12133       if (NewOp.getNode()) {
12134         MVT NewVT = NewOp.getSimpleValueType();
12135         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
12136           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
12137                               dl);
12138       }
12139     }
12140   }
12141   return SDValue();
12142 }
12143
12144 SDValue
12145 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
12146   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12147   SDValue V1 = Op.getOperand(0);
12148   SDValue V2 = Op.getOperand(1);
12149   MVT VT = Op.getSimpleValueType();
12150   SDLoc dl(Op);
12151   unsigned NumElems = VT.getVectorNumElements();
12152   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
12153   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
12154   bool V1IsSplat = false;
12155   bool V2IsSplat = false;
12156   bool HasSSE2 = Subtarget->hasSSE2();
12157   bool HasFp256    = Subtarget->hasFp256();
12158   bool HasInt256   = Subtarget->hasInt256();
12159   MachineFunction &MF = DAG.getMachineFunction();
12160   bool OptForSize = MF.getFunction()->getAttributes().
12161     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
12162
12163   // Check if we should use the experimental vector shuffle lowering. If so,
12164   // delegate completely to that code path.
12165   if (ExperimentalVectorShuffleLowering)
12166     return lowerVectorShuffle(Op, Subtarget, DAG);
12167
12168   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
12169
12170   if (V1IsUndef && V2IsUndef)
12171     return DAG.getUNDEF(VT);
12172
12173   // When we create a shuffle node we put the UNDEF node to second operand,
12174   // but in some cases the first operand may be transformed to UNDEF.
12175   // In this case we should just commute the node.
12176   if (V1IsUndef)
12177     return DAG.getCommutedVectorShuffle(*SVOp);
12178
12179   // Vector shuffle lowering takes 3 steps:
12180   //
12181   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
12182   //    narrowing and commutation of operands should be handled.
12183   // 2) Matching of shuffles with known shuffle masks to x86 target specific
12184   //    shuffle nodes.
12185   // 3) Rewriting of unmatched masks into new generic shuffle operations,
12186   //    so the shuffle can be broken into other shuffles and the legalizer can
12187   //    try the lowering again.
12188   //
12189   // The general idea is that no vector_shuffle operation should be left to
12190   // be matched during isel, all of them must be converted to a target specific
12191   // node here.
12192
12193   // Normalize the input vectors. Here splats, zeroed vectors, profitable
12194   // narrowing and commutation of operands should be handled. The actual code
12195   // doesn't include all of those, work in progress...
12196   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
12197   if (NewOp.getNode())
12198     return NewOp;
12199
12200   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
12201
12202   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
12203   // unpckh_undef). Only use pshufd if speed is more important than size.
12204   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12205     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12206   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12207     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12208
12209   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
12210       V2IsUndef && MayFoldVectorLoad(V1))
12211     return getMOVDDup(Op, dl, V1, DAG);
12212
12213   if (isMOVHLPS_v_undef_Mask(M, VT))
12214     return getMOVHighToLow(Op, dl, DAG);
12215
12216   // Use to match splats
12217   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
12218       (VT == MVT::v2f64 || VT == MVT::v2i64))
12219     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12220
12221   if (isPSHUFDMask(M, VT)) {
12222     // The actual implementation will match the mask in the if above and then
12223     // during isel it can match several different instructions, not only pshufd
12224     // as its name says, sad but true, emulate the behavior for now...
12225     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
12226       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
12227
12228     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
12229
12230     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
12231       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
12232
12233     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
12234       return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1, TargetMask,
12235                                   DAG);
12236
12237     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
12238                                 TargetMask, DAG);
12239   }
12240
12241   if (isPALIGNRMask(M, VT, Subtarget))
12242     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
12243                                 getShufflePALIGNRImmediate(SVOp),
12244                                 DAG);
12245
12246   if (isVALIGNMask(M, VT, Subtarget))
12247     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
12248                                 getShuffleVALIGNImmediate(SVOp),
12249                                 DAG);
12250
12251   // Check if this can be converted into a logical shift.
12252   bool isLeft = false;
12253   unsigned ShAmt = 0;
12254   SDValue ShVal;
12255   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
12256   if (isShift && ShVal.hasOneUse()) {
12257     // If the shifted value has multiple uses, it may be cheaper to use
12258     // v_set0 + movlhps or movhlps, etc.
12259     MVT EltVT = VT.getVectorElementType();
12260     ShAmt *= EltVT.getSizeInBits();
12261     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12262   }
12263
12264   if (isMOVLMask(M, VT)) {
12265     if (ISD::isBuildVectorAllZeros(V1.getNode()))
12266       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
12267     if (!isMOVLPMask(M, VT)) {
12268       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
12269         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
12270
12271       if (VT == MVT::v4i32 || VT == MVT::v4f32)
12272         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
12273     }
12274   }
12275
12276   // FIXME: fold these into legal mask.
12277   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
12278     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
12279
12280   if (isMOVHLPSMask(M, VT))
12281     return getMOVHighToLow(Op, dl, DAG);
12282
12283   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
12284     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
12285
12286   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
12287     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
12288
12289   if (isMOVLPMask(M, VT))
12290     return getMOVLP(Op, dl, DAG, HasSSE2);
12291
12292   if (ShouldXformToMOVHLPS(M, VT) ||
12293       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
12294     return DAG.getCommutedVectorShuffle(*SVOp);
12295
12296   if (isShift) {
12297     // No better options. Use a vshldq / vsrldq.
12298     MVT EltVT = VT.getVectorElementType();
12299     ShAmt *= EltVT.getSizeInBits();
12300     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12301   }
12302
12303   bool Commuted = false;
12304   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
12305   // 1,1,1,1 -> v8i16 though.
12306   BitVector UndefElements;
12307   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
12308     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12309       V1IsSplat = true;
12310   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
12311     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12312       V2IsSplat = true;
12313
12314   // Canonicalize the splat or undef, if present, to be on the RHS.
12315   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
12316     CommuteVectorShuffleMask(M, NumElems);
12317     std::swap(V1, V2);
12318     std::swap(V1IsSplat, V2IsSplat);
12319     Commuted = true;
12320   }
12321
12322   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
12323     // Shuffling low element of v1 into undef, just return v1.
12324     if (V2IsUndef)
12325       return V1;
12326     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
12327     // the instruction selector will not match, so get a canonical MOVL with
12328     // swapped operands to undo the commute.
12329     return getMOVL(DAG, dl, VT, V2, V1);
12330   }
12331
12332   if (isUNPCKLMask(M, VT, HasInt256))
12333     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12334
12335   if (isUNPCKHMask(M, VT, HasInt256))
12336     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12337
12338   if (V2IsSplat) {
12339     // Normalize mask so all entries that point to V2 points to its first
12340     // element then try to match unpck{h|l} again. If match, return a
12341     // new vector_shuffle with the corrected mask.p
12342     SmallVector<int, 8> NewMask(M.begin(), M.end());
12343     NormalizeMask(NewMask, NumElems);
12344     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
12345       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12346     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
12347       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12348   }
12349
12350   if (Commuted) {
12351     // Commute is back and try unpck* again.
12352     // FIXME: this seems wrong.
12353     CommuteVectorShuffleMask(M, NumElems);
12354     std::swap(V1, V2);
12355     std::swap(V1IsSplat, V2IsSplat);
12356
12357     if (isUNPCKLMask(M, VT, HasInt256))
12358       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12359
12360     if (isUNPCKHMask(M, VT, HasInt256))
12361       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12362   }
12363
12364   // Normalize the node to match x86 shuffle ops if needed
12365   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
12366     return DAG.getCommutedVectorShuffle(*SVOp);
12367
12368   // The checks below are all present in isShuffleMaskLegal, but they are
12369   // inlined here right now to enable us to directly emit target specific
12370   // nodes, and remove one by one until they don't return Op anymore.
12371
12372   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
12373       SVOp->getSplatIndex() == 0 && V2IsUndef) {
12374     if (VT == MVT::v2f64 || VT == MVT::v2i64)
12375       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12376   }
12377
12378   if (isPSHUFHWMask(M, VT, HasInt256))
12379     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
12380                                 getShufflePSHUFHWImmediate(SVOp),
12381                                 DAG);
12382
12383   if (isPSHUFLWMask(M, VT, HasInt256))
12384     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
12385                                 getShufflePSHUFLWImmediate(SVOp),
12386                                 DAG);
12387
12388   unsigned MaskValue;
12389   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
12390                   &MaskValue))
12391     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
12392
12393   if (isSHUFPMask(M, VT))
12394     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
12395                                 getShuffleSHUFImmediate(SVOp), DAG);
12396
12397   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12398     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12399   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12400     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12401
12402   //===--------------------------------------------------------------------===//
12403   // Generate target specific nodes for 128 or 256-bit shuffles only
12404   // supported in the AVX instruction set.
12405   //
12406
12407   // Handle VMOVDDUPY permutations
12408   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
12409     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
12410
12411   // Handle VPERMILPS/D* permutations
12412   if (isVPERMILPMask(M, VT)) {
12413     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
12414       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
12415                                   getShuffleSHUFImmediate(SVOp), DAG);
12416     return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1,
12417                                 getShuffleSHUFImmediate(SVOp), DAG);
12418   }
12419
12420   unsigned Idx;
12421   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
12422     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
12423                               Idx*(NumElems/2), DAG, dl);
12424
12425   // Handle VPERM2F128/VPERM2I128 permutations
12426   if (isVPERM2X128Mask(M, VT, HasFp256))
12427     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
12428                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
12429
12430   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
12431     return getINSERTPS(SVOp, dl, DAG);
12432
12433   unsigned Imm8;
12434   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
12435     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
12436
12437   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
12438       VT.is512BitVector()) {
12439     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
12440     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
12441     SmallVector<SDValue, 16> permclMask;
12442     for (unsigned i = 0; i != NumElems; ++i) {
12443       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
12444     }
12445
12446     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
12447     if (V2IsUndef)
12448       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
12449       return DAG.getNode(X86ISD::VPERMV, dl, VT,
12450                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
12451     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
12452                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
12453   }
12454
12455   //===--------------------------------------------------------------------===//
12456   // Since no target specific shuffle was selected for this generic one,
12457   // lower it into other known shuffles. FIXME: this isn't true yet, but
12458   // this is the plan.
12459   //
12460
12461   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
12462   if (VT == MVT::v8i16) {
12463     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
12464     if (NewOp.getNode())
12465       return NewOp;
12466   }
12467
12468   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
12469     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
12470     if (NewOp.getNode())
12471       return NewOp;
12472   }
12473
12474   if (VT == MVT::v16i8) {
12475     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
12476     if (NewOp.getNode())
12477       return NewOp;
12478   }
12479
12480   if (VT == MVT::v32i8) {
12481     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
12482     if (NewOp.getNode())
12483       return NewOp;
12484   }
12485
12486   // Handle all 128-bit wide vectors with 4 elements, and match them with
12487   // several different shuffle types.
12488   if (NumElems == 4 && VT.is128BitVector())
12489     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
12490
12491   // Handle general 256-bit shuffles
12492   if (VT.is256BitVector())
12493     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
12494
12495   return SDValue();
12496 }
12497
12498 // This function assumes its argument is a BUILD_VECTOR of constants or
12499 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
12500 // true.
12501 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
12502                                     unsigned &MaskValue) {
12503   MaskValue = 0;
12504   unsigned NumElems = BuildVector->getNumOperands();
12505   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
12506   unsigned NumLanes = (NumElems - 1) / 8 + 1;
12507   unsigned NumElemsInLane = NumElems / NumLanes;
12508
12509   // Blend for v16i16 should be symetric for the both lanes.
12510   for (unsigned i = 0; i < NumElemsInLane; ++i) {
12511     SDValue EltCond = BuildVector->getOperand(i);
12512     SDValue SndLaneEltCond =
12513         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
12514
12515     int Lane1Cond = -1, Lane2Cond = -1;
12516     if (isa<ConstantSDNode>(EltCond))
12517       Lane1Cond = !isZero(EltCond);
12518     if (isa<ConstantSDNode>(SndLaneEltCond))
12519       Lane2Cond = !isZero(SndLaneEltCond);
12520
12521     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
12522       // Lane1Cond != 0, means we want the first argument.
12523       // Lane1Cond == 0, means we want the second argument.
12524       // The encoding of this argument is 0 for the first argument, 1
12525       // for the second. Therefore, invert the condition.
12526       MaskValue |= !Lane1Cond << i;
12527     else if (Lane1Cond < 0)
12528       MaskValue |= !Lane2Cond << i;
12529     else
12530       return false;
12531   }
12532   return true;
12533 }
12534
12535 /// \brief Try to lower a VSELECT instruction to an immediate-controlled blend
12536 /// instruction.
12537 static SDValue lowerVSELECTtoBLENDI(SDValue Op, const X86Subtarget *Subtarget,
12538                                     SelectionDAG &DAG) {
12539   SDValue Cond = Op.getOperand(0);
12540   SDValue LHS = Op.getOperand(1);
12541   SDValue RHS = Op.getOperand(2);
12542   SDLoc dl(Op);
12543   MVT VT = Op.getSimpleValueType();
12544   MVT EltVT = VT.getVectorElementType();
12545   unsigned NumElems = VT.getVectorNumElements();
12546
12547   // There is no blend with immediate in AVX-512.
12548   if (VT.is512BitVector())
12549     return SDValue();
12550
12551   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
12552     return SDValue();
12553   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
12554     return SDValue();
12555
12556   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
12557     return SDValue();
12558
12559   // Check the mask for BLEND and build the value.
12560   unsigned MaskValue = 0;
12561   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
12562     return SDValue();
12563
12564   // Convert i32 vectors to floating point if it is not AVX2.
12565   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
12566   MVT BlendVT = VT;
12567   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
12568     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
12569                                NumElems);
12570     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
12571     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
12572   }
12573
12574   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
12575                             DAG.getConstant(MaskValue, MVT::i32));
12576   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
12577 }
12578
12579 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
12580   // A vselect where all conditions and data are constants can be optimized into
12581   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
12582   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
12583       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
12584       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
12585     return SDValue();
12586
12587   SDValue BlendOp = lowerVSELECTtoBLENDI(Op, Subtarget, DAG);
12588   if (BlendOp.getNode())
12589     return BlendOp;
12590
12591   // Some types for vselect were previously set to Expand, not Legal or
12592   // Custom. Return an empty SDValue so we fall-through to Expand, after
12593   // the Custom lowering phase.
12594   MVT VT = Op.getSimpleValueType();
12595   switch (VT.SimpleTy) {
12596   default:
12597     break;
12598   case MVT::v8i16:
12599   case MVT::v16i16:
12600     if (Subtarget->hasBWI() && Subtarget->hasVLX())
12601       break;
12602     return SDValue();
12603   }
12604
12605   // We couldn't create a "Blend with immediate" node.
12606   // This node should still be legal, but we'll have to emit a blendv*
12607   // instruction.
12608   return Op;
12609 }
12610
12611 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
12612   MVT VT = Op.getSimpleValueType();
12613   SDLoc dl(Op);
12614
12615   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
12616     return SDValue();
12617
12618   if (VT.getSizeInBits() == 8) {
12619     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
12620                                   Op.getOperand(0), Op.getOperand(1));
12621     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12622                                   DAG.getValueType(VT));
12623     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12624   }
12625
12626   if (VT.getSizeInBits() == 16) {
12627     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12628     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
12629     if (Idx == 0)
12630       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12631                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12632                                      DAG.getNode(ISD::BITCAST, dl,
12633                                                  MVT::v4i32,
12634                                                  Op.getOperand(0)),
12635                                      Op.getOperand(1)));
12636     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
12637                                   Op.getOperand(0), Op.getOperand(1));
12638     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12639                                   DAG.getValueType(VT));
12640     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12641   }
12642
12643   if (VT == MVT::f32) {
12644     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
12645     // the result back to FR32 register. It's only worth matching if the
12646     // result has a single use which is a store or a bitcast to i32.  And in
12647     // the case of a store, it's not worth it if the index is a constant 0,
12648     // because a MOVSSmr can be used instead, which is smaller and faster.
12649     if (!Op.hasOneUse())
12650       return SDValue();
12651     SDNode *User = *Op.getNode()->use_begin();
12652     if ((User->getOpcode() != ISD::STORE ||
12653          (isa<ConstantSDNode>(Op.getOperand(1)) &&
12654           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
12655         (User->getOpcode() != ISD::BITCAST ||
12656          User->getValueType(0) != MVT::i32))
12657       return SDValue();
12658     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12659                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
12660                                               Op.getOperand(0)),
12661                                               Op.getOperand(1));
12662     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
12663   }
12664
12665   if (VT == MVT::i32 || VT == MVT::i64) {
12666     // ExtractPS/pextrq works with constant index.
12667     if (isa<ConstantSDNode>(Op.getOperand(1)))
12668       return Op;
12669   }
12670   return SDValue();
12671 }
12672
12673 /// Extract one bit from mask vector, like v16i1 or v8i1.
12674 /// AVX-512 feature.
12675 SDValue
12676 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
12677   SDValue Vec = Op.getOperand(0);
12678   SDLoc dl(Vec);
12679   MVT VecVT = Vec.getSimpleValueType();
12680   SDValue Idx = Op.getOperand(1);
12681   MVT EltVT = Op.getSimpleValueType();
12682
12683   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
12684
12685   // variable index can't be handled in mask registers,
12686   // extend vector to VR512
12687   if (!isa<ConstantSDNode>(Idx)) {
12688     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12689     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
12690     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
12691                               ExtVT.getVectorElementType(), Ext, Idx);
12692     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
12693   }
12694
12695   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12696   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12697   unsigned MaxSift = rc->getSize()*8 - 1;
12698   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
12699                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12700   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
12701                     DAG.getConstant(MaxSift, MVT::i8));
12702   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
12703                        DAG.getIntPtrConstant(0));
12704 }
12705
12706 SDValue
12707 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
12708                                            SelectionDAG &DAG) const {
12709   SDLoc dl(Op);
12710   SDValue Vec = Op.getOperand(0);
12711   MVT VecVT = Vec.getSimpleValueType();
12712   SDValue Idx = Op.getOperand(1);
12713
12714   if (Op.getSimpleValueType() == MVT::i1)
12715     return ExtractBitFromMaskVector(Op, DAG);
12716
12717   if (!isa<ConstantSDNode>(Idx)) {
12718     if (VecVT.is512BitVector() ||
12719         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
12720          VecVT.getVectorElementType().getSizeInBits() == 32)) {
12721
12722       MVT MaskEltVT =
12723         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
12724       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
12725                                     MaskEltVT.getSizeInBits());
12726
12727       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
12728       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
12729                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
12730                                 Idx, DAG.getConstant(0, getPointerTy()));
12731       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
12732       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
12733                         Perm, DAG.getConstant(0, getPointerTy()));
12734     }
12735     return SDValue();
12736   }
12737
12738   // If this is a 256-bit vector result, first extract the 128-bit vector and
12739   // then extract the element from the 128-bit vector.
12740   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
12741
12742     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12743     // Get the 128-bit vector.
12744     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
12745     MVT EltVT = VecVT.getVectorElementType();
12746
12747     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
12748
12749     //if (IdxVal >= NumElems/2)
12750     //  IdxVal -= NumElems/2;
12751     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
12752     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
12753                        DAG.getConstant(IdxVal, MVT::i32));
12754   }
12755
12756   assert(VecVT.is128BitVector() && "Unexpected vector length");
12757
12758   if (Subtarget->hasSSE41()) {
12759     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
12760     if (Res.getNode())
12761       return Res;
12762   }
12763
12764   MVT VT = Op.getSimpleValueType();
12765   // TODO: handle v16i8.
12766   if (VT.getSizeInBits() == 16) {
12767     SDValue Vec = Op.getOperand(0);
12768     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12769     if (Idx == 0)
12770       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12771                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12772                                      DAG.getNode(ISD::BITCAST, dl,
12773                                                  MVT::v4i32, Vec),
12774                                      Op.getOperand(1)));
12775     // Transform it so it match pextrw which produces a 32-bit result.
12776     MVT EltVT = MVT::i32;
12777     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
12778                                   Op.getOperand(0), Op.getOperand(1));
12779     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
12780                                   DAG.getValueType(VT));
12781     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12782   }
12783
12784   if (VT.getSizeInBits() == 32) {
12785     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12786     if (Idx == 0)
12787       return Op;
12788
12789     // SHUFPS the element to the lowest double word, then movss.
12790     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
12791     MVT VVT = Op.getOperand(0).getSimpleValueType();
12792     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12793                                        DAG.getUNDEF(VVT), Mask);
12794     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12795                        DAG.getIntPtrConstant(0));
12796   }
12797
12798   if (VT.getSizeInBits() == 64) {
12799     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
12800     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
12801     //        to match extract_elt for f64.
12802     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12803     if (Idx == 0)
12804       return Op;
12805
12806     // UNPCKHPD the element to the lowest double word, then movsd.
12807     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
12808     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
12809     int Mask[2] = { 1, -1 };
12810     MVT VVT = Op.getOperand(0).getSimpleValueType();
12811     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12812                                        DAG.getUNDEF(VVT), Mask);
12813     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12814                        DAG.getIntPtrConstant(0));
12815   }
12816
12817   return SDValue();
12818 }
12819
12820 /// Insert one bit to mask vector, like v16i1 or v8i1.
12821 /// AVX-512 feature.
12822 SDValue
12823 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
12824   SDLoc dl(Op);
12825   SDValue Vec = Op.getOperand(0);
12826   SDValue Elt = Op.getOperand(1);
12827   SDValue Idx = Op.getOperand(2);
12828   MVT VecVT = Vec.getSimpleValueType();
12829
12830   if (!isa<ConstantSDNode>(Idx)) {
12831     // Non constant index. Extend source and destination,
12832     // insert element and then truncate the result.
12833     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12834     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
12835     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
12836       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
12837       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
12838     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
12839   }
12840
12841   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12842   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
12843   if (Vec.getOpcode() == ISD::UNDEF)
12844     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12845                        DAG.getConstant(IdxVal, MVT::i8));
12846   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12847   unsigned MaxSift = rc->getSize()*8 - 1;
12848   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12849                     DAG.getConstant(MaxSift, MVT::i8));
12850   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
12851                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12852   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
12853 }
12854
12855 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12856                                                   SelectionDAG &DAG) const {
12857   MVT VT = Op.getSimpleValueType();
12858   MVT EltVT = VT.getVectorElementType();
12859
12860   if (EltVT == MVT::i1)
12861     return InsertBitToMaskVector(Op, DAG);
12862
12863   SDLoc dl(Op);
12864   SDValue N0 = Op.getOperand(0);
12865   SDValue N1 = Op.getOperand(1);
12866   SDValue N2 = Op.getOperand(2);
12867   if (!isa<ConstantSDNode>(N2))
12868     return SDValue();
12869   auto *N2C = cast<ConstantSDNode>(N2);
12870   unsigned IdxVal = N2C->getZExtValue();
12871
12872   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
12873   // into that, and then insert the subvector back into the result.
12874   if (VT.is256BitVector() || VT.is512BitVector()) {
12875     // Get the desired 128-bit vector half.
12876     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
12877
12878     // Insert the element into the desired half.
12879     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
12880     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
12881
12882     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
12883                     DAG.getConstant(IdxIn128, MVT::i32));
12884
12885     // Insert the changed part back to the 256-bit vector
12886     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
12887   }
12888   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
12889
12890   if (Subtarget->hasSSE41()) {
12891     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
12892       unsigned Opc;
12893       if (VT == MVT::v8i16) {
12894         Opc = X86ISD::PINSRW;
12895       } else {
12896         assert(VT == MVT::v16i8);
12897         Opc = X86ISD::PINSRB;
12898       }
12899
12900       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
12901       // argument.
12902       if (N1.getValueType() != MVT::i32)
12903         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12904       if (N2.getValueType() != MVT::i32)
12905         N2 = DAG.getIntPtrConstant(IdxVal);
12906       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
12907     }
12908
12909     if (EltVT == MVT::f32) {
12910       // Bits [7:6] of the constant are the source select.  This will always be
12911       //  zero here.  The DAG Combiner may combine an extract_elt index into
12912       //  these
12913       //  bits.  For example (insert (extract, 3), 2) could be matched by
12914       //  putting
12915       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
12916       // Bits [5:4] of the constant are the destination select.  This is the
12917       //  value of the incoming immediate.
12918       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
12919       //   combine either bitwise AND or insert of float 0.0 to set these bits.
12920       N2 = DAG.getIntPtrConstant(IdxVal << 4);
12921       // Create this as a scalar to vector..
12922       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
12923       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
12924     }
12925
12926     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
12927       // PINSR* works with constant index.
12928       return Op;
12929     }
12930   }
12931
12932   if (EltVT == MVT::i8)
12933     return SDValue();
12934
12935   if (EltVT.getSizeInBits() == 16) {
12936     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12937     // as its second argument.
12938     if (N1.getValueType() != MVT::i32)
12939       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12940     if (N2.getValueType() != MVT::i32)
12941       N2 = DAG.getIntPtrConstant(IdxVal);
12942     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12943   }
12944   return SDValue();
12945 }
12946
12947 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12948   SDLoc dl(Op);
12949   MVT OpVT = Op.getSimpleValueType();
12950
12951   // If this is a 256-bit vector result, first insert into a 128-bit
12952   // vector and then insert into the 256-bit vector.
12953   if (!OpVT.is128BitVector()) {
12954     // Insert into a 128-bit vector.
12955     unsigned SizeFactor = OpVT.getSizeInBits()/128;
12956     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12957                                  OpVT.getVectorNumElements() / SizeFactor);
12958
12959     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12960
12961     // Insert the 128-bit vector.
12962     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12963   }
12964
12965   if (OpVT == MVT::v1i64 &&
12966       Op.getOperand(0).getValueType() == MVT::i64)
12967     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12968
12969   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12970   assert(OpVT.is128BitVector() && "Expected an SSE type!");
12971   return DAG.getNode(ISD::BITCAST, dl, OpVT,
12972                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
12973 }
12974
12975 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
12976 // a simple subregister reference or explicit instructions to grab
12977 // upper bits of a vector.
12978 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12979                                       SelectionDAG &DAG) {
12980   SDLoc dl(Op);
12981   SDValue In =  Op.getOperand(0);
12982   SDValue Idx = Op.getOperand(1);
12983   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12984   MVT ResVT   = Op.getSimpleValueType();
12985   MVT InVT    = In.getSimpleValueType();
12986
12987   if (Subtarget->hasFp256()) {
12988     if (ResVT.is128BitVector() &&
12989         (InVT.is256BitVector() || InVT.is512BitVector()) &&
12990         isa<ConstantSDNode>(Idx)) {
12991       return Extract128BitVector(In, IdxVal, DAG, dl);
12992     }
12993     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12994         isa<ConstantSDNode>(Idx)) {
12995       return Extract256BitVector(In, IdxVal, DAG, dl);
12996     }
12997   }
12998   return SDValue();
12999 }
13000
13001 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
13002 // simple superregister reference or explicit instructions to insert
13003 // the upper bits of a vector.
13004 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
13005                                      SelectionDAG &DAG) {
13006   if (Subtarget->hasFp256()) {
13007     SDLoc dl(Op.getNode());
13008     SDValue Vec = Op.getNode()->getOperand(0);
13009     SDValue SubVec = Op.getNode()->getOperand(1);
13010     SDValue Idx = Op.getNode()->getOperand(2);
13011
13012     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
13013          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
13014         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
13015         isa<ConstantSDNode>(Idx)) {
13016       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13017       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
13018     }
13019
13020     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
13021         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
13022         isa<ConstantSDNode>(Idx)) {
13023       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13024       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
13025     }
13026   }
13027   return SDValue();
13028 }
13029
13030 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
13031 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
13032 // one of the above mentioned nodes. It has to be wrapped because otherwise
13033 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
13034 // be used to form addressing mode. These wrapped nodes will be selected
13035 // into MOV32ri.
13036 SDValue
13037 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
13038   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
13039
13040   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13041   // global base reg.
13042   unsigned char OpFlag = 0;
13043   unsigned WrapperKind = X86ISD::Wrapper;
13044   CodeModel::Model M = DAG.getTarget().getCodeModel();
13045
13046   if (Subtarget->isPICStyleRIPRel() &&
13047       (M == CodeModel::Small || M == CodeModel::Kernel))
13048     WrapperKind = X86ISD::WrapperRIP;
13049   else if (Subtarget->isPICStyleGOT())
13050     OpFlag = X86II::MO_GOTOFF;
13051   else if (Subtarget->isPICStyleStubPIC())
13052     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13053
13054   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
13055                                              CP->getAlignment(),
13056                                              CP->getOffset(), OpFlag);
13057   SDLoc DL(CP);
13058   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13059   // With PIC, the address is actually $g + Offset.
13060   if (OpFlag) {
13061     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13062                          DAG.getNode(X86ISD::GlobalBaseReg,
13063                                      SDLoc(), getPointerTy()),
13064                          Result);
13065   }
13066
13067   return Result;
13068 }
13069
13070 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
13071   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
13072
13073   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13074   // global base reg.
13075   unsigned char OpFlag = 0;
13076   unsigned WrapperKind = X86ISD::Wrapper;
13077   CodeModel::Model M = DAG.getTarget().getCodeModel();
13078
13079   if (Subtarget->isPICStyleRIPRel() &&
13080       (M == CodeModel::Small || M == CodeModel::Kernel))
13081     WrapperKind = X86ISD::WrapperRIP;
13082   else if (Subtarget->isPICStyleGOT())
13083     OpFlag = X86II::MO_GOTOFF;
13084   else if (Subtarget->isPICStyleStubPIC())
13085     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13086
13087   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
13088                                           OpFlag);
13089   SDLoc DL(JT);
13090   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13091
13092   // With PIC, the address is actually $g + Offset.
13093   if (OpFlag)
13094     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13095                          DAG.getNode(X86ISD::GlobalBaseReg,
13096                                      SDLoc(), getPointerTy()),
13097                          Result);
13098
13099   return Result;
13100 }
13101
13102 SDValue
13103 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
13104   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13105
13106   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13107   // global base reg.
13108   unsigned char OpFlag = 0;
13109   unsigned WrapperKind = X86ISD::Wrapper;
13110   CodeModel::Model M = DAG.getTarget().getCodeModel();
13111
13112   if (Subtarget->isPICStyleRIPRel() &&
13113       (M == CodeModel::Small || M == CodeModel::Kernel)) {
13114     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
13115       OpFlag = X86II::MO_GOTPCREL;
13116     WrapperKind = X86ISD::WrapperRIP;
13117   } else if (Subtarget->isPICStyleGOT()) {
13118     OpFlag = X86II::MO_GOT;
13119   } else if (Subtarget->isPICStyleStubPIC()) {
13120     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
13121   } else if (Subtarget->isPICStyleStubNoDynamic()) {
13122     OpFlag = X86II::MO_DARWIN_NONLAZY;
13123   }
13124
13125   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
13126
13127   SDLoc DL(Op);
13128   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13129
13130   // With PIC, the address is actually $g + Offset.
13131   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
13132       !Subtarget->is64Bit()) {
13133     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13134                          DAG.getNode(X86ISD::GlobalBaseReg,
13135                                      SDLoc(), getPointerTy()),
13136                          Result);
13137   }
13138
13139   // For symbols that require a load from a stub to get the address, emit the
13140   // load.
13141   if (isGlobalStubReference(OpFlag))
13142     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
13143                          MachinePointerInfo::getGOT(), false, false, false, 0);
13144
13145   return Result;
13146 }
13147
13148 SDValue
13149 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
13150   // Create the TargetBlockAddressAddress node.
13151   unsigned char OpFlags =
13152     Subtarget->ClassifyBlockAddressReference();
13153   CodeModel::Model M = DAG.getTarget().getCodeModel();
13154   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
13155   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
13156   SDLoc dl(Op);
13157   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
13158                                              OpFlags);
13159
13160   if (Subtarget->isPICStyleRIPRel() &&
13161       (M == CodeModel::Small || M == CodeModel::Kernel))
13162     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13163   else
13164     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13165
13166   // With PIC, the address is actually $g + Offset.
13167   if (isGlobalRelativeToPICBase(OpFlags)) {
13168     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13169                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13170                          Result);
13171   }
13172
13173   return Result;
13174 }
13175
13176 SDValue
13177 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
13178                                       int64_t Offset, SelectionDAG &DAG) const {
13179   // Create the TargetGlobalAddress node, folding in the constant
13180   // offset if it is legal.
13181   unsigned char OpFlags =
13182       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
13183   CodeModel::Model M = DAG.getTarget().getCodeModel();
13184   SDValue Result;
13185   if (OpFlags == X86II::MO_NO_FLAG &&
13186       X86::isOffsetSuitableForCodeModel(Offset, M)) {
13187     // A direct static reference to a global.
13188     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
13189     Offset = 0;
13190   } else {
13191     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
13192   }
13193
13194   if (Subtarget->isPICStyleRIPRel() &&
13195       (M == CodeModel::Small || M == CodeModel::Kernel))
13196     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13197   else
13198     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13199
13200   // With PIC, the address is actually $g + Offset.
13201   if (isGlobalRelativeToPICBase(OpFlags)) {
13202     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13203                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13204                          Result);
13205   }
13206
13207   // For globals that require a load from a stub to get the address, emit the
13208   // load.
13209   if (isGlobalStubReference(OpFlags))
13210     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
13211                          MachinePointerInfo::getGOT(), false, false, false, 0);
13212
13213   // If there was a non-zero offset that we didn't fold, create an explicit
13214   // addition for it.
13215   if (Offset != 0)
13216     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
13217                          DAG.getConstant(Offset, getPointerTy()));
13218
13219   return Result;
13220 }
13221
13222 SDValue
13223 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
13224   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
13225   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
13226   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
13227 }
13228
13229 static SDValue
13230 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
13231            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
13232            unsigned char OperandFlags, bool LocalDynamic = false) {
13233   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13234   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13235   SDLoc dl(GA);
13236   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13237                                            GA->getValueType(0),
13238                                            GA->getOffset(),
13239                                            OperandFlags);
13240
13241   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
13242                                            : X86ISD::TLSADDR;
13243
13244   if (InFlag) {
13245     SDValue Ops[] = { Chain,  TGA, *InFlag };
13246     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13247   } else {
13248     SDValue Ops[]  = { Chain, TGA };
13249     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13250   }
13251
13252   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
13253   MFI->setAdjustsStack(true);
13254   MFI->setHasCalls(true);
13255
13256   SDValue Flag = Chain.getValue(1);
13257   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
13258 }
13259
13260 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
13261 static SDValue
13262 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13263                                 const EVT PtrVT) {
13264   SDValue InFlag;
13265   SDLoc dl(GA);  // ? function entry point might be better
13266   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13267                                    DAG.getNode(X86ISD::GlobalBaseReg,
13268                                                SDLoc(), PtrVT), InFlag);
13269   InFlag = Chain.getValue(1);
13270
13271   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
13272 }
13273
13274 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
13275 static SDValue
13276 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13277                                 const EVT PtrVT) {
13278   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
13279                     X86::RAX, X86II::MO_TLSGD);
13280 }
13281
13282 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
13283                                            SelectionDAG &DAG,
13284                                            const EVT PtrVT,
13285                                            bool is64Bit) {
13286   SDLoc dl(GA);
13287
13288   // Get the start address of the TLS block for this module.
13289   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
13290       .getInfo<X86MachineFunctionInfo>();
13291   MFI->incNumLocalDynamicTLSAccesses();
13292
13293   SDValue Base;
13294   if (is64Bit) {
13295     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
13296                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
13297   } else {
13298     SDValue InFlag;
13299     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13300         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
13301     InFlag = Chain.getValue(1);
13302     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
13303                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
13304   }
13305
13306   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
13307   // of Base.
13308
13309   // Build x@dtpoff.
13310   unsigned char OperandFlags = X86II::MO_DTPOFF;
13311   unsigned WrapperKind = X86ISD::Wrapper;
13312   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13313                                            GA->getValueType(0),
13314                                            GA->getOffset(), OperandFlags);
13315   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13316
13317   // Add x@dtpoff with the base.
13318   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
13319 }
13320
13321 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
13322 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13323                                    const EVT PtrVT, TLSModel::Model model,
13324                                    bool is64Bit, bool isPIC) {
13325   SDLoc dl(GA);
13326
13327   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
13328   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
13329                                                          is64Bit ? 257 : 256));
13330
13331   SDValue ThreadPointer =
13332       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
13333                   MachinePointerInfo(Ptr), false, false, false, 0);
13334
13335   unsigned char OperandFlags = 0;
13336   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
13337   // initialexec.
13338   unsigned WrapperKind = X86ISD::Wrapper;
13339   if (model == TLSModel::LocalExec) {
13340     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
13341   } else if (model == TLSModel::InitialExec) {
13342     if (is64Bit) {
13343       OperandFlags = X86II::MO_GOTTPOFF;
13344       WrapperKind = X86ISD::WrapperRIP;
13345     } else {
13346       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
13347     }
13348   } else {
13349     llvm_unreachable("Unexpected model");
13350   }
13351
13352   // emit "addl x@ntpoff,%eax" (local exec)
13353   // or "addl x@indntpoff,%eax" (initial exec)
13354   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
13355   SDValue TGA =
13356       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
13357                                  GA->getOffset(), OperandFlags);
13358   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13359
13360   if (model == TLSModel::InitialExec) {
13361     if (isPIC && !is64Bit) {
13362       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
13363                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
13364                            Offset);
13365     }
13366
13367     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
13368                          MachinePointerInfo::getGOT(), false, false, false, 0);
13369   }
13370
13371   // The address of the thread local variable is the add of the thread
13372   // pointer with the offset of the variable.
13373   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
13374 }
13375
13376 SDValue
13377 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
13378
13379   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
13380   const GlobalValue *GV = GA->getGlobal();
13381
13382   if (Subtarget->isTargetELF()) {
13383     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
13384
13385     switch (model) {
13386       case TLSModel::GeneralDynamic:
13387         if (Subtarget->is64Bit())
13388           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
13389         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
13390       case TLSModel::LocalDynamic:
13391         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
13392                                            Subtarget->is64Bit());
13393       case TLSModel::InitialExec:
13394       case TLSModel::LocalExec:
13395         return LowerToTLSExecModel(
13396             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
13397             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
13398     }
13399     llvm_unreachable("Unknown TLS model.");
13400   }
13401
13402   if (Subtarget->isTargetDarwin()) {
13403     // Darwin only has one model of TLS.  Lower to that.
13404     unsigned char OpFlag = 0;
13405     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
13406                            X86ISD::WrapperRIP : X86ISD::Wrapper;
13407
13408     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13409     // global base reg.
13410     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
13411                  !Subtarget->is64Bit();
13412     if (PIC32)
13413       OpFlag = X86II::MO_TLVP_PIC_BASE;
13414     else
13415       OpFlag = X86II::MO_TLVP;
13416     SDLoc DL(Op);
13417     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
13418                                                 GA->getValueType(0),
13419                                                 GA->getOffset(), OpFlag);
13420     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13421
13422     // With PIC32, the address is actually $g + Offset.
13423     if (PIC32)
13424       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13425                            DAG.getNode(X86ISD::GlobalBaseReg,
13426                                        SDLoc(), getPointerTy()),
13427                            Offset);
13428
13429     // Lowering the machine isd will make sure everything is in the right
13430     // location.
13431     SDValue Chain = DAG.getEntryNode();
13432     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13433     SDValue Args[] = { Chain, Offset };
13434     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
13435
13436     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
13437     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13438     MFI->setAdjustsStack(true);
13439
13440     // And our return value (tls address) is in the standard call return value
13441     // location.
13442     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13443     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
13444                               Chain.getValue(1));
13445   }
13446
13447   if (Subtarget->isTargetKnownWindowsMSVC() ||
13448       Subtarget->isTargetWindowsGNU()) {
13449     // Just use the implicit TLS architecture
13450     // Need to generate someting similar to:
13451     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
13452     //                                  ; from TEB
13453     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
13454     //   mov     rcx, qword [rdx+rcx*8]
13455     //   mov     eax, .tls$:tlsvar
13456     //   [rax+rcx] contains the address
13457     // Windows 64bit: gs:0x58
13458     // Windows 32bit: fs:__tls_array
13459
13460     SDLoc dl(GA);
13461     SDValue Chain = DAG.getEntryNode();
13462
13463     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
13464     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
13465     // use its literal value of 0x2C.
13466     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
13467                                         ? Type::getInt8PtrTy(*DAG.getContext(),
13468                                                              256)
13469                                         : Type::getInt32PtrTy(*DAG.getContext(),
13470                                                               257));
13471
13472     SDValue TlsArray =
13473         Subtarget->is64Bit()
13474             ? DAG.getIntPtrConstant(0x58)
13475             : (Subtarget->isTargetWindowsGNU()
13476                    ? DAG.getIntPtrConstant(0x2C)
13477                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
13478
13479     SDValue ThreadPointer =
13480         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
13481                     MachinePointerInfo(Ptr), false, false, false, 0);
13482
13483     // Load the _tls_index variable
13484     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
13485     if (Subtarget->is64Bit())
13486       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
13487                            IDX, MachinePointerInfo(), MVT::i32,
13488                            false, false, false, 0);
13489     else
13490       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
13491                         false, false, false, 0);
13492
13493     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
13494                                     getPointerTy());
13495     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
13496
13497     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
13498     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
13499                       false, false, false, 0);
13500
13501     // Get the offset of start of .tls section
13502     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13503                                              GA->getValueType(0),
13504                                              GA->getOffset(), X86II::MO_SECREL);
13505     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
13506
13507     // The address of the thread local variable is the add of the thread
13508     // pointer with the offset of the variable.
13509     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
13510   }
13511
13512   llvm_unreachable("TLS not implemented for this target.");
13513 }
13514
13515 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
13516 /// and take a 2 x i32 value to shift plus a shift amount.
13517 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
13518   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
13519   MVT VT = Op.getSimpleValueType();
13520   unsigned VTBits = VT.getSizeInBits();
13521   SDLoc dl(Op);
13522   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
13523   SDValue ShOpLo = Op.getOperand(0);
13524   SDValue ShOpHi = Op.getOperand(1);
13525   SDValue ShAmt  = Op.getOperand(2);
13526   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
13527   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
13528   // during isel.
13529   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13530                                   DAG.getConstant(VTBits - 1, MVT::i8));
13531   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
13532                                      DAG.getConstant(VTBits - 1, MVT::i8))
13533                        : DAG.getConstant(0, VT);
13534
13535   SDValue Tmp2, Tmp3;
13536   if (Op.getOpcode() == ISD::SHL_PARTS) {
13537     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
13538     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
13539   } else {
13540     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
13541     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
13542   }
13543
13544   // If the shift amount is larger or equal than the width of a part we can't
13545   // rely on the results of shld/shrd. Insert a test and select the appropriate
13546   // values for large shift amounts.
13547   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13548                                 DAG.getConstant(VTBits, MVT::i8));
13549   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13550                              AndNode, DAG.getConstant(0, MVT::i8));
13551
13552   SDValue Hi, Lo;
13553   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13554   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
13555   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
13556
13557   if (Op.getOpcode() == ISD::SHL_PARTS) {
13558     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13559     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13560   } else {
13561     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13562     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13563   }
13564
13565   SDValue Ops[2] = { Lo, Hi };
13566   return DAG.getMergeValues(Ops, dl);
13567 }
13568
13569 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
13570                                            SelectionDAG &DAG) const {
13571   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13572   SDLoc dl(Op);
13573
13574   if (SrcVT.isVector()) {
13575     if (SrcVT.getVectorElementType() == MVT::i1) {
13576       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
13577       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13578                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
13579                                      Op.getOperand(0)));
13580     }
13581     return SDValue();
13582   }
13583
13584   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
13585          "Unknown SINT_TO_FP to lower!");
13586
13587   // These are really Legal; return the operand so the caller accepts it as
13588   // Legal.
13589   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
13590     return Op;
13591   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
13592       Subtarget->is64Bit()) {
13593     return Op;
13594   }
13595
13596   unsigned Size = SrcVT.getSizeInBits()/8;
13597   MachineFunction &MF = DAG.getMachineFunction();
13598   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
13599   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13600   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13601                                StackSlot,
13602                                MachinePointerInfo::getFixedStack(SSFI),
13603                                false, false, 0);
13604   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
13605 }
13606
13607 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
13608                                      SDValue StackSlot,
13609                                      SelectionDAG &DAG) const {
13610   // Build the FILD
13611   SDLoc DL(Op);
13612   SDVTList Tys;
13613   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
13614   if (useSSE)
13615     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
13616   else
13617     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
13618
13619   unsigned ByteSize = SrcVT.getSizeInBits()/8;
13620
13621   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
13622   MachineMemOperand *MMO;
13623   if (FI) {
13624     int SSFI = FI->getIndex();
13625     MMO =
13626       DAG.getMachineFunction()
13627       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13628                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
13629   } else {
13630     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
13631     StackSlot = StackSlot.getOperand(1);
13632   }
13633   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
13634   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
13635                                            X86ISD::FILD, DL,
13636                                            Tys, Ops, SrcVT, MMO);
13637
13638   if (useSSE) {
13639     Chain = Result.getValue(1);
13640     SDValue InFlag = Result.getValue(2);
13641
13642     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
13643     // shouldn't be necessary except that RFP cannot be live across
13644     // multiple blocks. When stackifier is fixed, they can be uncoupled.
13645     MachineFunction &MF = DAG.getMachineFunction();
13646     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
13647     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
13648     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13649     Tys = DAG.getVTList(MVT::Other);
13650     SDValue Ops[] = {
13651       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
13652     };
13653     MachineMemOperand *MMO =
13654       DAG.getMachineFunction()
13655       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13656                             MachineMemOperand::MOStore, SSFISize, SSFISize);
13657
13658     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
13659                                     Ops, Op.getValueType(), MMO);
13660     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
13661                          MachinePointerInfo::getFixedStack(SSFI),
13662                          false, false, false, 0);
13663   }
13664
13665   return Result;
13666 }
13667
13668 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
13669 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
13670                                                SelectionDAG &DAG) const {
13671   // This algorithm is not obvious. Here it is what we're trying to output:
13672   /*
13673      movq       %rax,  %xmm0
13674      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
13675      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
13676      #ifdef __SSE3__
13677        haddpd   %xmm0, %xmm0
13678      #else
13679        pshufd   $0x4e, %xmm0, %xmm1
13680        addpd    %xmm1, %xmm0
13681      #endif
13682   */
13683
13684   SDLoc dl(Op);
13685   LLVMContext *Context = DAG.getContext();
13686
13687   // Build some magic constants.
13688   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
13689   Constant *C0 = ConstantDataVector::get(*Context, CV0);
13690   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
13691
13692   SmallVector<Constant*,2> CV1;
13693   CV1.push_back(
13694     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13695                                       APInt(64, 0x4330000000000000ULL))));
13696   CV1.push_back(
13697     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13698                                       APInt(64, 0x4530000000000000ULL))));
13699   Constant *C1 = ConstantVector::get(CV1);
13700   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
13701
13702   // Load the 64-bit value into an XMM register.
13703   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
13704                             Op.getOperand(0));
13705   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
13706                               MachinePointerInfo::getConstantPool(),
13707                               false, false, false, 16);
13708   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
13709                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
13710                               CLod0);
13711
13712   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
13713                               MachinePointerInfo::getConstantPool(),
13714                               false, false, false, 16);
13715   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
13716   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
13717   SDValue Result;
13718
13719   if (Subtarget->hasSSE3()) {
13720     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
13721     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
13722   } else {
13723     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
13724     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
13725                                            S2F, 0x4E, DAG);
13726     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
13727                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
13728                          Sub);
13729   }
13730
13731   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
13732                      DAG.getIntPtrConstant(0));
13733 }
13734
13735 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
13736 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
13737                                                SelectionDAG &DAG) const {
13738   SDLoc dl(Op);
13739   // FP constant to bias correct the final result.
13740   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13741                                    MVT::f64);
13742
13743   // Load the 32-bit value into an XMM register.
13744   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
13745                              Op.getOperand(0));
13746
13747   // Zero out the upper parts of the register.
13748   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
13749
13750   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13751                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
13752                      DAG.getIntPtrConstant(0));
13753
13754   // Or the load with the bias.
13755   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
13756                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13757                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13758                                                    MVT::v2f64, Load)),
13759                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13760                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13761                                                    MVT::v2f64, Bias)));
13762   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13763                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
13764                    DAG.getIntPtrConstant(0));
13765
13766   // Subtract the bias.
13767   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
13768
13769   // Handle final rounding.
13770   EVT DestVT = Op.getValueType();
13771
13772   if (DestVT.bitsLT(MVT::f64))
13773     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
13774                        DAG.getIntPtrConstant(0));
13775   if (DestVT.bitsGT(MVT::f64))
13776     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
13777
13778   // Handle final rounding.
13779   return Sub;
13780 }
13781
13782 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
13783                                      const X86Subtarget &Subtarget) {
13784   // The algorithm is the following:
13785   // #ifdef __SSE4_1__
13786   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13787   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13788   //                                 (uint4) 0x53000000, 0xaa);
13789   // #else
13790   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13791   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13792   // #endif
13793   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13794   //     return (float4) lo + fhi;
13795
13796   SDLoc DL(Op);
13797   SDValue V = Op->getOperand(0);
13798   EVT VecIntVT = V.getValueType();
13799   bool Is128 = VecIntVT == MVT::v4i32;
13800   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
13801   // If we convert to something else than the supported type, e.g., to v4f64,
13802   // abort early.
13803   if (VecFloatVT != Op->getValueType(0))
13804     return SDValue();
13805
13806   unsigned NumElts = VecIntVT.getVectorNumElements();
13807   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
13808          "Unsupported custom type");
13809   assert(NumElts <= 8 && "The size of the constant array must be fixed");
13810
13811   // In the #idef/#else code, we have in common:
13812   // - The vector of constants:
13813   // -- 0x4b000000
13814   // -- 0x53000000
13815   // - A shift:
13816   // -- v >> 16
13817
13818   // Create the splat vector for 0x4b000000.
13819   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
13820   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
13821                            CstLow, CstLow, CstLow, CstLow};
13822   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13823                                   makeArrayRef(&CstLowArray[0], NumElts));
13824   // Create the splat vector for 0x53000000.
13825   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
13826   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
13827                             CstHigh, CstHigh, CstHigh, CstHigh};
13828   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13829                                    makeArrayRef(&CstHighArray[0], NumElts));
13830
13831   // Create the right shift.
13832   SDValue CstShift = DAG.getConstant(16, MVT::i32);
13833   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
13834                              CstShift, CstShift, CstShift, CstShift};
13835   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13836                                     makeArrayRef(&CstShiftArray[0], NumElts));
13837   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
13838
13839   SDValue Low, High;
13840   if (Subtarget.hasSSE41()) {
13841     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
13842     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13843     SDValue VecCstLowBitcast =
13844         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
13845     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
13846     // Low will be bitcasted right away, so do not bother bitcasting back to its
13847     // original type.
13848     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
13849                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
13850     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13851     //                                 (uint4) 0x53000000, 0xaa);
13852     SDValue VecCstHighBitcast =
13853         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
13854     SDValue VecShiftBitcast =
13855         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
13856     // High will be bitcasted right away, so do not bother bitcasting back to
13857     // its original type.
13858     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
13859                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
13860   } else {
13861     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
13862     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13863                                      CstMask, CstMask, CstMask);
13864     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13865     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13866     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13867
13868     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13869     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13870   }
13871
13872   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13873   SDValue CstFAdd = DAG.getConstantFP(
13874       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
13875   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13876                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13877   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13878                                    makeArrayRef(&CstFAddArray[0], NumElts));
13879
13880   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13881   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
13882   SDValue FHigh =
13883       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13884   //     return (float4) lo + fhi;
13885   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
13886   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13887 }
13888
13889 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13890                                                SelectionDAG &DAG) const {
13891   SDValue N0 = Op.getOperand(0);
13892   MVT SVT = N0.getSimpleValueType();
13893   SDLoc dl(Op);
13894
13895   switch (SVT.SimpleTy) {
13896   default:
13897     llvm_unreachable("Custom UINT_TO_FP is not supported!");
13898   case MVT::v4i8:
13899   case MVT::v4i16:
13900   case MVT::v8i8:
13901   case MVT::v8i16: {
13902     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13903     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13904                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13905   }
13906   case MVT::v4i32:
13907   case MVT::v8i32:
13908     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13909   }
13910   llvm_unreachable(nullptr);
13911 }
13912
13913 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13914                                            SelectionDAG &DAG) const {
13915   SDValue N0 = Op.getOperand(0);
13916   SDLoc dl(Op);
13917
13918   if (Op.getValueType().isVector())
13919     return lowerUINT_TO_FP_vec(Op, DAG);
13920
13921   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13922   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13923   // the optimization here.
13924   if (DAG.SignBitIsZero(N0))
13925     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13926
13927   MVT SrcVT = N0.getSimpleValueType();
13928   MVT DstVT = Op.getSimpleValueType();
13929   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13930     return LowerUINT_TO_FP_i64(Op, DAG);
13931   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13932     return LowerUINT_TO_FP_i32(Op, DAG);
13933   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13934     return SDValue();
13935
13936   // Make a 64-bit buffer, and use it to build an FILD.
13937   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13938   if (SrcVT == MVT::i32) {
13939     SDValue WordOff = DAG.getConstant(4, getPointerTy());
13940     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
13941                                      getPointerTy(), StackSlot, WordOff);
13942     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13943                                   StackSlot, MachinePointerInfo(),
13944                                   false, false, 0);
13945     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
13946                                   OffsetSlot, MachinePointerInfo(),
13947                                   false, false, 0);
13948     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13949     return Fild;
13950   }
13951
13952   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13953   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13954                                StackSlot, MachinePointerInfo(),
13955                                false, false, 0);
13956   // For i64 source, we need to add the appropriate power of 2 if the input
13957   // was negative.  This is the same as the optimization in
13958   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13959   // we must be careful to do the computation in x87 extended precision, not
13960   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13961   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13962   MachineMemOperand *MMO =
13963     DAG.getMachineFunction()
13964     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13965                           MachineMemOperand::MOLoad, 8, 8);
13966
13967   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13968   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13969   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13970                                          MVT::i64, MMO);
13971
13972   APInt FF(32, 0x5F800000ULL);
13973
13974   // Check whether the sign bit is set.
13975   SDValue SignSet = DAG.getSetCC(dl,
13976                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
13977                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
13978                                  ISD::SETLT);
13979
13980   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13981   SDValue FudgePtr = DAG.getConstantPool(
13982                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
13983                                          getPointerTy());
13984
13985   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13986   SDValue Zero = DAG.getIntPtrConstant(0);
13987   SDValue Four = DAG.getIntPtrConstant(4);
13988   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13989                                Zero, Four);
13990   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
13991
13992   // Load the value out, extending it from f32 to f80.
13993   // FIXME: Avoid the extend by constructing the right constant pool?
13994   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
13995                                  FudgePtr, MachinePointerInfo::getConstantPool(),
13996                                  MVT::f32, false, false, false, 4);
13997   // Extend everything to 80 bits to force it to be done on x87.
13998   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13999   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
14000 }
14001
14002 std::pair<SDValue,SDValue>
14003 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
14004                                     bool IsSigned, bool IsReplace) const {
14005   SDLoc DL(Op);
14006
14007   EVT DstTy = Op.getValueType();
14008
14009   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
14010     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
14011     DstTy = MVT::i64;
14012   }
14013
14014   assert(DstTy.getSimpleVT() <= MVT::i64 &&
14015          DstTy.getSimpleVT() >= MVT::i16 &&
14016          "Unknown FP_TO_INT to lower!");
14017
14018   // These are really Legal.
14019   if (DstTy == MVT::i32 &&
14020       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14021     return std::make_pair(SDValue(), SDValue());
14022   if (Subtarget->is64Bit() &&
14023       DstTy == MVT::i64 &&
14024       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14025     return std::make_pair(SDValue(), SDValue());
14026
14027   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
14028   // stack slot, or into the FTOL runtime function.
14029   MachineFunction &MF = DAG.getMachineFunction();
14030   unsigned MemSize = DstTy.getSizeInBits()/8;
14031   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14032   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14033
14034   unsigned Opc;
14035   if (!IsSigned && isIntegerTypeFTOL(DstTy))
14036     Opc = X86ISD::WIN_FTOL;
14037   else
14038     switch (DstTy.getSimpleVT().SimpleTy) {
14039     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
14040     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
14041     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
14042     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
14043     }
14044
14045   SDValue Chain = DAG.getEntryNode();
14046   SDValue Value = Op.getOperand(0);
14047   EVT TheVT = Op.getOperand(0).getValueType();
14048   // FIXME This causes a redundant load/store if the SSE-class value is already
14049   // in memory, such as if it is on the callstack.
14050   if (isScalarFPTypeInSSEReg(TheVT)) {
14051     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
14052     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
14053                          MachinePointerInfo::getFixedStack(SSFI),
14054                          false, false, 0);
14055     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
14056     SDValue Ops[] = {
14057       Chain, StackSlot, DAG.getValueType(TheVT)
14058     };
14059
14060     MachineMemOperand *MMO =
14061       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14062                               MachineMemOperand::MOLoad, MemSize, MemSize);
14063     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
14064     Chain = Value.getValue(1);
14065     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14066     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14067   }
14068
14069   MachineMemOperand *MMO =
14070     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14071                             MachineMemOperand::MOStore, MemSize, MemSize);
14072
14073   if (Opc != X86ISD::WIN_FTOL) {
14074     // Build the FP_TO_INT*_IN_MEM
14075     SDValue Ops[] = { Chain, Value, StackSlot };
14076     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
14077                                            Ops, DstTy, MMO);
14078     return std::make_pair(FIST, StackSlot);
14079   } else {
14080     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
14081       DAG.getVTList(MVT::Other, MVT::Glue),
14082       Chain, Value);
14083     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
14084       MVT::i32, ftol.getValue(1));
14085     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
14086       MVT::i32, eax.getValue(2));
14087     SDValue Ops[] = { eax, edx };
14088     SDValue pair = IsReplace
14089       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
14090       : DAG.getMergeValues(Ops, DL);
14091     return std::make_pair(pair, SDValue());
14092   }
14093 }
14094
14095 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
14096                               const X86Subtarget *Subtarget) {
14097   MVT VT = Op->getSimpleValueType(0);
14098   SDValue In = Op->getOperand(0);
14099   MVT InVT = In.getSimpleValueType();
14100   SDLoc dl(Op);
14101
14102   // Optimize vectors in AVX mode:
14103   //
14104   //   v8i16 -> v8i32
14105   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
14106   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
14107   //   Concat upper and lower parts.
14108   //
14109   //   v4i32 -> v4i64
14110   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
14111   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
14112   //   Concat upper and lower parts.
14113   //
14114
14115   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
14116       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
14117       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
14118     return SDValue();
14119
14120   if (Subtarget->hasInt256())
14121     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
14122
14123   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
14124   SDValue Undef = DAG.getUNDEF(InVT);
14125   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
14126   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14127   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14128
14129   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
14130                              VT.getVectorNumElements()/2);
14131
14132   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
14133   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
14134
14135   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14136 }
14137
14138 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
14139                                         SelectionDAG &DAG) {
14140   MVT VT = Op->getSimpleValueType(0);
14141   SDValue In = Op->getOperand(0);
14142   MVT InVT = In.getSimpleValueType();
14143   SDLoc DL(Op);
14144   unsigned int NumElts = VT.getVectorNumElements();
14145   if (NumElts != 8 && NumElts != 16)
14146     return SDValue();
14147
14148   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
14149     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
14150
14151   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
14152   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14153   // Now we have only mask extension
14154   assert(InVT.getVectorElementType() == MVT::i1);
14155   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
14156   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14157   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
14158   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14159   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14160                            MachinePointerInfo::getConstantPool(),
14161                            false, false, false, Alignment);
14162
14163   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
14164   if (VT.is512BitVector())
14165     return Brcst;
14166   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
14167 }
14168
14169 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14170                                SelectionDAG &DAG) {
14171   if (Subtarget->hasFp256()) {
14172     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14173     if (Res.getNode())
14174       return Res;
14175   }
14176
14177   return SDValue();
14178 }
14179
14180 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14181                                 SelectionDAG &DAG) {
14182   SDLoc DL(Op);
14183   MVT VT = Op.getSimpleValueType();
14184   SDValue In = Op.getOperand(0);
14185   MVT SVT = In.getSimpleValueType();
14186
14187   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
14188     return LowerZERO_EXTEND_AVX512(Op, DAG);
14189
14190   if (Subtarget->hasFp256()) {
14191     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14192     if (Res.getNode())
14193       return Res;
14194   }
14195
14196   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
14197          VT.getVectorNumElements() != SVT.getVectorNumElements());
14198   return SDValue();
14199 }
14200
14201 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
14202   SDLoc DL(Op);
14203   MVT VT = Op.getSimpleValueType();
14204   SDValue In = Op.getOperand(0);
14205   MVT InVT = In.getSimpleValueType();
14206
14207   if (VT == MVT::i1) {
14208     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
14209            "Invalid scalar TRUNCATE operation");
14210     if (InVT.getSizeInBits() >= 32)
14211       return SDValue();
14212     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
14213     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
14214   }
14215   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
14216          "Invalid TRUNCATE operation");
14217
14218   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
14219     if (VT.getVectorElementType().getSizeInBits() >=8)
14220       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
14221
14222     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14223     unsigned NumElts = InVT.getVectorNumElements();
14224     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
14225     if (InVT.getSizeInBits() < 512) {
14226       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
14227       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
14228       InVT = ExtVT;
14229     }
14230
14231     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
14232     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14233     SDValue CP = DAG.getConstantPool(C, getPointerTy());
14234     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14235     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14236                            MachinePointerInfo::getConstantPool(),
14237                            false, false, false, Alignment);
14238     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
14239     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
14240     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
14241   }
14242
14243   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
14244     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
14245     if (Subtarget->hasInt256()) {
14246       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14247       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
14248       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
14249                                 ShufMask);
14250       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
14251                          DAG.getIntPtrConstant(0));
14252     }
14253
14254     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14255                                DAG.getIntPtrConstant(0));
14256     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14257                                DAG.getIntPtrConstant(2));
14258     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14259     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14260     static const int ShufMask[] = {0, 2, 4, 6};
14261     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
14262   }
14263
14264   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
14265     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
14266     if (Subtarget->hasInt256()) {
14267       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
14268
14269       SmallVector<SDValue,32> pshufbMask;
14270       for (unsigned i = 0; i < 2; ++i) {
14271         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14272         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14273         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14274         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14275         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14276         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14277         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14278         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14279         for (unsigned j = 0; j < 8; ++j)
14280           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14281       }
14282       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
14283       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
14284       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
14285
14286       static const int ShufMask[] = {0,  2,  -1,  -1};
14287       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
14288                                 &ShufMask[0]);
14289       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14290                        DAG.getIntPtrConstant(0));
14291       return DAG.getNode(ISD::BITCAST, DL, VT, In);
14292     }
14293
14294     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14295                                DAG.getIntPtrConstant(0));
14296
14297     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14298                                DAG.getIntPtrConstant(4));
14299
14300     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
14301     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
14302
14303     // The PSHUFB mask:
14304     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14305                                    -1, -1, -1, -1, -1, -1, -1, -1};
14306
14307     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14308     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
14309     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
14310
14311     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14312     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14313
14314     // The MOVLHPS Mask:
14315     static const int ShufMask2[] = {0, 1, 4, 5};
14316     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
14317     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
14318   }
14319
14320   // Handle truncation of V256 to V128 using shuffles.
14321   if (!VT.is128BitVector() || !InVT.is256BitVector())
14322     return SDValue();
14323
14324   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
14325
14326   unsigned NumElems = VT.getVectorNumElements();
14327   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
14328
14329   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
14330   // Prepare truncation shuffle mask
14331   for (unsigned i = 0; i != NumElems; ++i)
14332     MaskVec[i] = i * 2;
14333   SDValue V = DAG.getVectorShuffle(NVT, DL,
14334                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
14335                                    DAG.getUNDEF(NVT), &MaskVec[0]);
14336   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
14337                      DAG.getIntPtrConstant(0));
14338 }
14339
14340 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
14341                                            SelectionDAG &DAG) const {
14342   assert(!Op.getSimpleValueType().isVector());
14343
14344   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14345     /*IsSigned=*/ true, /*IsReplace=*/ false);
14346   SDValue FIST = Vals.first, StackSlot = Vals.second;
14347   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
14348   if (!FIST.getNode()) return Op;
14349
14350   if (StackSlot.getNode())
14351     // Load the result.
14352     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14353                        FIST, StackSlot, MachinePointerInfo(),
14354                        false, false, false, 0);
14355
14356   // The node is the result.
14357   return FIST;
14358 }
14359
14360 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
14361                                            SelectionDAG &DAG) const {
14362   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14363     /*IsSigned=*/ false, /*IsReplace=*/ false);
14364   SDValue FIST = Vals.first, StackSlot = Vals.second;
14365   assert(FIST.getNode() && "Unexpected failure");
14366
14367   if (StackSlot.getNode())
14368     // Load the result.
14369     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14370                        FIST, StackSlot, MachinePointerInfo(),
14371                        false, false, false, 0);
14372
14373   // The node is the result.
14374   return FIST;
14375 }
14376
14377 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
14378   SDLoc DL(Op);
14379   MVT VT = Op.getSimpleValueType();
14380   SDValue In = Op.getOperand(0);
14381   MVT SVT = In.getSimpleValueType();
14382
14383   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
14384
14385   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
14386                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
14387                                  In, DAG.getUNDEF(SVT)));
14388 }
14389
14390 /// The only differences between FABS and FNEG are the mask and the logic op.
14391 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
14392 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
14393   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
14394          "Wrong opcode for lowering FABS or FNEG.");
14395
14396   bool IsFABS = (Op.getOpcode() == ISD::FABS);
14397
14398   // If this is a FABS and it has an FNEG user, bail out to fold the combination
14399   // into an FNABS. We'll lower the FABS after that if it is still in use.
14400   if (IsFABS)
14401     for (SDNode *User : Op->uses())
14402       if (User->getOpcode() == ISD::FNEG)
14403         return Op;
14404
14405   SDValue Op0 = Op.getOperand(0);
14406   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
14407
14408   SDLoc dl(Op);
14409   MVT VT = Op.getSimpleValueType();
14410   // Assume scalar op for initialization; update for vector if needed.
14411   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
14412   // generate a 16-byte vector constant and logic op even for the scalar case.
14413   // Using a 16-byte mask allows folding the load of the mask with
14414   // the logic op, so it can save (~4 bytes) on code size.
14415   MVT EltVT = VT;
14416   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
14417   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
14418   // decide if we should generate a 16-byte constant mask when we only need 4 or
14419   // 8 bytes for the scalar case.
14420   if (VT.isVector()) {
14421     EltVT = VT.getVectorElementType();
14422     NumElts = VT.getVectorNumElements();
14423   }
14424
14425   unsigned EltBits = EltVT.getSizeInBits();
14426   LLVMContext *Context = DAG.getContext();
14427   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
14428   APInt MaskElt =
14429     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
14430   Constant *C = ConstantInt::get(*Context, MaskElt);
14431   C = ConstantVector::getSplat(NumElts, C);
14432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14433   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
14434   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14435   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14436                              MachinePointerInfo::getConstantPool(),
14437                              false, false, false, Alignment);
14438
14439   if (VT.isVector()) {
14440     // For a vector, cast operands to a vector type, perform the logic op,
14441     // and cast the result back to the original value type.
14442     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
14443     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
14444     SDValue Operand = IsFNABS ?
14445       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
14446       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
14447     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
14448     return DAG.getNode(ISD::BITCAST, dl, VT,
14449                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
14450   }
14451
14452   // If not vector, then scalar.
14453   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
14454   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
14455   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
14456 }
14457
14458 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
14459   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14460   LLVMContext *Context = DAG.getContext();
14461   SDValue Op0 = Op.getOperand(0);
14462   SDValue Op1 = Op.getOperand(1);
14463   SDLoc dl(Op);
14464   MVT VT = Op.getSimpleValueType();
14465   MVT SrcVT = Op1.getSimpleValueType();
14466
14467   // If second operand is smaller, extend it first.
14468   if (SrcVT.bitsLT(VT)) {
14469     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
14470     SrcVT = VT;
14471   }
14472   // And if it is bigger, shrink it first.
14473   if (SrcVT.bitsGT(VT)) {
14474     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
14475     SrcVT = VT;
14476   }
14477
14478   // At this point the operands and the result should have the same
14479   // type, and that won't be f80 since that is not custom lowered.
14480
14481   const fltSemantics &Sem =
14482       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
14483   const unsigned SizeInBits = VT.getSizeInBits();
14484
14485   SmallVector<Constant *, 4> CV(
14486       VT == MVT::f64 ? 2 : 4,
14487       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
14488
14489   // First, clear all bits but the sign bit from the second operand (sign).
14490   CV[0] = ConstantFP::get(*Context,
14491                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
14492   Constant *C = ConstantVector::get(CV);
14493   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14494   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
14495                               MachinePointerInfo::getConstantPool(),
14496                               false, false, false, 16);
14497   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
14498
14499   // Next, clear the sign bit from the first operand (magnitude).
14500   CV[0] = ConstantFP::get(
14501       *Context, APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
14502   C = ConstantVector::get(CV);
14503   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14504   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14505                               MachinePointerInfo::getConstantPool(),
14506                               false, false, false, 16);
14507   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
14508
14509   // OR the magnitude value with the sign bit.
14510   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
14511 }
14512
14513 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
14514   SDValue N0 = Op.getOperand(0);
14515   SDLoc dl(Op);
14516   MVT VT = Op.getSimpleValueType();
14517
14518   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
14519   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
14520                                   DAG.getConstant(1, VT));
14521   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
14522 }
14523
14524 // Check whether an OR'd tree is PTEST-able.
14525 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
14526                                       SelectionDAG &DAG) {
14527   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
14528
14529   if (!Subtarget->hasSSE41())
14530     return SDValue();
14531
14532   if (!Op->hasOneUse())
14533     return SDValue();
14534
14535   SDNode *N = Op.getNode();
14536   SDLoc DL(N);
14537
14538   SmallVector<SDValue, 8> Opnds;
14539   DenseMap<SDValue, unsigned> VecInMap;
14540   SmallVector<SDValue, 8> VecIns;
14541   EVT VT = MVT::Other;
14542
14543   // Recognize a special case where a vector is casted into wide integer to
14544   // test all 0s.
14545   Opnds.push_back(N->getOperand(0));
14546   Opnds.push_back(N->getOperand(1));
14547
14548   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14549     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
14550     // BFS traverse all OR'd operands.
14551     if (I->getOpcode() == ISD::OR) {
14552       Opnds.push_back(I->getOperand(0));
14553       Opnds.push_back(I->getOperand(1));
14554       // Re-evaluate the number of nodes to be traversed.
14555       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14556       continue;
14557     }
14558
14559     // Quit if a non-EXTRACT_VECTOR_ELT
14560     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14561       return SDValue();
14562
14563     // Quit if without a constant index.
14564     SDValue Idx = I->getOperand(1);
14565     if (!isa<ConstantSDNode>(Idx))
14566       return SDValue();
14567
14568     SDValue ExtractedFromVec = I->getOperand(0);
14569     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
14570     if (M == VecInMap.end()) {
14571       VT = ExtractedFromVec.getValueType();
14572       // Quit if not 128/256-bit vector.
14573       if (!VT.is128BitVector() && !VT.is256BitVector())
14574         return SDValue();
14575       // Quit if not the same type.
14576       if (VecInMap.begin() != VecInMap.end() &&
14577           VT != VecInMap.begin()->first.getValueType())
14578         return SDValue();
14579       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
14580       VecIns.push_back(ExtractedFromVec);
14581     }
14582     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14583   }
14584
14585   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14586          "Not extracted from 128-/256-bit vector.");
14587
14588   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
14589
14590   for (DenseMap<SDValue, unsigned>::const_iterator
14591         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
14592     // Quit if not all elements are used.
14593     if (I->second != FullMask)
14594       return SDValue();
14595   }
14596
14597   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
14598
14599   // Cast all vectors into TestVT for PTEST.
14600   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
14601     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
14602
14603   // If more than one full vectors are evaluated, OR them first before PTEST.
14604   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
14605     // Each iteration will OR 2 nodes and append the result until there is only
14606     // 1 node left, i.e. the final OR'd value of all vectors.
14607     SDValue LHS = VecIns[Slot];
14608     SDValue RHS = VecIns[Slot + 1];
14609     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
14610   }
14611
14612   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
14613                      VecIns.back(), VecIns.back());
14614 }
14615
14616 /// \brief return true if \c Op has a use that doesn't just read flags.
14617 static bool hasNonFlagsUse(SDValue Op) {
14618   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
14619        ++UI) {
14620     SDNode *User = *UI;
14621     unsigned UOpNo = UI.getOperandNo();
14622     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
14623       // Look pass truncate.
14624       UOpNo = User->use_begin().getOperandNo();
14625       User = *User->use_begin();
14626     }
14627
14628     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
14629         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
14630       return true;
14631   }
14632   return false;
14633 }
14634
14635 /// Emit nodes that will be selected as "test Op0,Op0", or something
14636 /// equivalent.
14637 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
14638                                     SelectionDAG &DAG) const {
14639   if (Op.getValueType() == MVT::i1)
14640     // KORTEST instruction should be selected
14641     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14642                        DAG.getConstant(0, Op.getValueType()));
14643
14644   // CF and OF aren't always set the way we want. Determine which
14645   // of these we need.
14646   bool NeedCF = false;
14647   bool NeedOF = false;
14648   switch (X86CC) {
14649   default: break;
14650   case X86::COND_A: case X86::COND_AE:
14651   case X86::COND_B: case X86::COND_BE:
14652     NeedCF = true;
14653     break;
14654   case X86::COND_G: case X86::COND_GE:
14655   case X86::COND_L: case X86::COND_LE:
14656   case X86::COND_O: case X86::COND_NO: {
14657     // Check if we really need to set the
14658     // Overflow flag. If NoSignedWrap is present
14659     // that is not actually needed.
14660     switch (Op->getOpcode()) {
14661     case ISD::ADD:
14662     case ISD::SUB:
14663     case ISD::MUL:
14664     case ISD::SHL: {
14665       const BinaryWithFlagsSDNode *BinNode =
14666           cast<BinaryWithFlagsSDNode>(Op.getNode());
14667       if (BinNode->hasNoSignedWrap())
14668         break;
14669     }
14670     default:
14671       NeedOF = true;
14672       break;
14673     }
14674     break;
14675   }
14676   }
14677   // See if we can use the EFLAGS value from the operand instead of
14678   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14679   // we prove that the arithmetic won't overflow, we can't use OF or CF.
14680   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14681     // Emit a CMP with 0, which is the TEST pattern.
14682     //if (Op.getValueType() == MVT::i1)
14683     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14684     //                     DAG.getConstant(0, MVT::i1));
14685     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14686                        DAG.getConstant(0, Op.getValueType()));
14687   }
14688   unsigned Opcode = 0;
14689   unsigned NumOperands = 0;
14690
14691   // Truncate operations may prevent the merge of the SETCC instruction
14692   // and the arithmetic instruction before it. Attempt to truncate the operands
14693   // of the arithmetic instruction and use a reduced bit-width instruction.
14694   bool NeedTruncation = false;
14695   SDValue ArithOp = Op;
14696   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14697     SDValue Arith = Op->getOperand(0);
14698     // Both the trunc and the arithmetic op need to have one user each.
14699     if (Arith->hasOneUse())
14700       switch (Arith.getOpcode()) {
14701         default: break;
14702         case ISD::ADD:
14703         case ISD::SUB:
14704         case ISD::AND:
14705         case ISD::OR:
14706         case ISD::XOR: {
14707           NeedTruncation = true;
14708           ArithOp = Arith;
14709         }
14710       }
14711   }
14712
14713   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14714   // which may be the result of a CAST.  We use the variable 'Op', which is the
14715   // non-casted variable when we check for possible users.
14716   switch (ArithOp.getOpcode()) {
14717   case ISD::ADD:
14718     // Due to an isel shortcoming, be conservative if this add is likely to be
14719     // selected as part of a load-modify-store instruction. When the root node
14720     // in a match is a store, isel doesn't know how to remap non-chain non-flag
14721     // uses of other nodes in the match, such as the ADD in this case. This
14722     // leads to the ADD being left around and reselected, with the result being
14723     // two adds in the output.  Alas, even if none our users are stores, that
14724     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
14725     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
14726     // climbing the DAG back to the root, and it doesn't seem to be worth the
14727     // effort.
14728     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14729          UE = Op.getNode()->use_end(); UI != UE; ++UI)
14730       if (UI->getOpcode() != ISD::CopyToReg &&
14731           UI->getOpcode() != ISD::SETCC &&
14732           UI->getOpcode() != ISD::STORE)
14733         goto default_case;
14734
14735     if (ConstantSDNode *C =
14736         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14737       // An add of one will be selected as an INC.
14738       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
14739         Opcode = X86ISD::INC;
14740         NumOperands = 1;
14741         break;
14742       }
14743
14744       // An add of negative one (subtract of one) will be selected as a DEC.
14745       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
14746         Opcode = X86ISD::DEC;
14747         NumOperands = 1;
14748         break;
14749       }
14750     }
14751
14752     // Otherwise use a regular EFLAGS-setting add.
14753     Opcode = X86ISD::ADD;
14754     NumOperands = 2;
14755     break;
14756   case ISD::SHL:
14757   case ISD::SRL:
14758     // If we have a constant logical shift that's only used in a comparison
14759     // against zero turn it into an equivalent AND. This allows turning it into
14760     // a TEST instruction later.
14761     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14762         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14763       EVT VT = Op.getValueType();
14764       unsigned BitWidth = VT.getSizeInBits();
14765       unsigned ShAmt = Op->getConstantOperandVal(1);
14766       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14767         break;
14768       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14769                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14770                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14771       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14772         break;
14773       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14774                                 DAG.getConstant(Mask, VT));
14775       DAG.ReplaceAllUsesWith(Op, New);
14776       Op = New;
14777     }
14778     break;
14779
14780   case ISD::AND:
14781     // If the primary and result isn't used, don't bother using X86ISD::AND,
14782     // because a TEST instruction will be better.
14783     if (!hasNonFlagsUse(Op))
14784       break;
14785     // FALL THROUGH
14786   case ISD::SUB:
14787   case ISD::OR:
14788   case ISD::XOR:
14789     // Due to the ISEL shortcoming noted above, be conservative if this op is
14790     // likely to be selected as part of a load-modify-store instruction.
14791     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14792            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14793       if (UI->getOpcode() == ISD::STORE)
14794         goto default_case;
14795
14796     // Otherwise use a regular EFLAGS-setting instruction.
14797     switch (ArithOp.getOpcode()) {
14798     default: llvm_unreachable("unexpected operator!");
14799     case ISD::SUB: Opcode = X86ISD::SUB; break;
14800     case ISD::XOR: Opcode = X86ISD::XOR; break;
14801     case ISD::AND: Opcode = X86ISD::AND; break;
14802     case ISD::OR: {
14803       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14804         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14805         if (EFLAGS.getNode())
14806           return EFLAGS;
14807       }
14808       Opcode = X86ISD::OR;
14809       break;
14810     }
14811     }
14812
14813     NumOperands = 2;
14814     break;
14815   case X86ISD::ADD:
14816   case X86ISD::SUB:
14817   case X86ISD::INC:
14818   case X86ISD::DEC:
14819   case X86ISD::OR:
14820   case X86ISD::XOR:
14821   case X86ISD::AND:
14822     return SDValue(Op.getNode(), 1);
14823   default:
14824   default_case:
14825     break;
14826   }
14827
14828   // If we found that truncation is beneficial, perform the truncation and
14829   // update 'Op'.
14830   if (NeedTruncation) {
14831     EVT VT = Op.getValueType();
14832     SDValue WideVal = Op->getOperand(0);
14833     EVT WideVT = WideVal.getValueType();
14834     unsigned ConvertedOp = 0;
14835     // Use a target machine opcode to prevent further DAGCombine
14836     // optimizations that may separate the arithmetic operations
14837     // from the setcc node.
14838     switch (WideVal.getOpcode()) {
14839       default: break;
14840       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14841       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14842       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14843       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14844       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14845     }
14846
14847     if (ConvertedOp) {
14848       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14849       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14850         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14851         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14852         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14853       }
14854     }
14855   }
14856
14857   if (Opcode == 0)
14858     // Emit a CMP with 0, which is the TEST pattern.
14859     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14860                        DAG.getConstant(0, Op.getValueType()));
14861
14862   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14863   SmallVector<SDValue, 4> Ops;
14864   for (unsigned i = 0; i != NumOperands; ++i)
14865     Ops.push_back(Op.getOperand(i));
14866
14867   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14868   DAG.ReplaceAllUsesWith(Op, New);
14869   return SDValue(New.getNode(), 1);
14870 }
14871
14872 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14873 /// equivalent.
14874 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14875                                    SDLoc dl, SelectionDAG &DAG) const {
14876   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
14877     if (C->getAPIntValue() == 0)
14878       return EmitTest(Op0, X86CC, dl, DAG);
14879
14880      if (Op0.getValueType() == MVT::i1)
14881        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
14882   }
14883
14884   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14885        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14886     // Do the comparison at i32 if it's smaller, besides the Atom case.
14887     // This avoids subregister aliasing issues. Keep the smaller reference
14888     // if we're optimizing for size, however, as that'll allow better folding
14889     // of memory operations.
14890     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14891         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
14892              AttributeSet::FunctionIndex, Attribute::MinSize) &&
14893         !Subtarget->isAtom()) {
14894       unsigned ExtendOp =
14895           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14896       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14897       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14898     }
14899     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14900     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14901     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14902                               Op0, Op1);
14903     return SDValue(Sub.getNode(), 1);
14904   }
14905   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14906 }
14907
14908 /// Convert a comparison if required by the subtarget.
14909 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14910                                                  SelectionDAG &DAG) const {
14911   // If the subtarget does not support the FUCOMI instruction, floating-point
14912   // comparisons have to be converted.
14913   if (Subtarget->hasCMov() ||
14914       Cmp.getOpcode() != X86ISD::CMP ||
14915       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14916       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14917     return Cmp;
14918
14919   // The instruction selector will select an FUCOM instruction instead of
14920   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14921   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14922   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14923   SDLoc dl(Cmp);
14924   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14925   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14926   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14927                             DAG.getConstant(8, MVT::i8));
14928   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14929   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14930 }
14931
14932 /// The minimum architected relative accuracy is 2^-12. We need one
14933 /// Newton-Raphson step to have a good float result (24 bits of precision).
14934 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14935                                             DAGCombinerInfo &DCI,
14936                                             unsigned &RefinementSteps,
14937                                             bool &UseOneConstNR) const {
14938   // FIXME: We should use instruction latency models to calculate the cost of
14939   // each potential sequence, but this is very hard to do reliably because
14940   // at least Intel's Core* chips have variable timing based on the number of
14941   // significant digits in the divisor and/or sqrt operand.
14942   if (!Subtarget->useSqrtEst())
14943     return SDValue();
14944
14945   EVT VT = Op.getValueType();
14946
14947   // SSE1 has rsqrtss and rsqrtps.
14948   // TODO: Add support for AVX512 (v16f32).
14949   // It is likely not profitable to do this for f64 because a double-precision
14950   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14951   // instructions: convert to single, rsqrtss, convert back to double, refine
14952   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14953   // along with FMA, this could be a throughput win.
14954   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14955       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14956     RefinementSteps = 1;
14957     UseOneConstNR = false;
14958     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14959   }
14960   return SDValue();
14961 }
14962
14963 /// The minimum architected relative accuracy is 2^-12. We need one
14964 /// Newton-Raphson step to have a good float result (24 bits of precision).
14965 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14966                                             DAGCombinerInfo &DCI,
14967                                             unsigned &RefinementSteps) const {
14968   // FIXME: We should use instruction latency models to calculate the cost of
14969   // each potential sequence, but this is very hard to do reliably because
14970   // at least Intel's Core* chips have variable timing based on the number of
14971   // significant digits in the divisor.
14972   if (!Subtarget->useReciprocalEst())
14973     return SDValue();
14974
14975   EVT VT = Op.getValueType();
14976
14977   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14978   // TODO: Add support for AVX512 (v16f32).
14979   // It is likely not profitable to do this for f64 because a double-precision
14980   // reciprocal estimate with refinement on x86 prior to FMA requires
14981   // 15 instructions: convert to single, rcpss, convert back to double, refine
14982   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14983   // along with FMA, this could be a throughput win.
14984   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14985       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14986     RefinementSteps = ReciprocalEstimateRefinementSteps;
14987     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14988   }
14989   return SDValue();
14990 }
14991
14992 static bool isAllOnes(SDValue V) {
14993   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
14994   return C && C->isAllOnesValue();
14995 }
14996
14997 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14998 /// if it's possible.
14999 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
15000                                      SDLoc dl, SelectionDAG &DAG) const {
15001   SDValue Op0 = And.getOperand(0);
15002   SDValue Op1 = And.getOperand(1);
15003   if (Op0.getOpcode() == ISD::TRUNCATE)
15004     Op0 = Op0.getOperand(0);
15005   if (Op1.getOpcode() == ISD::TRUNCATE)
15006     Op1 = Op1.getOperand(0);
15007
15008   SDValue LHS, RHS;
15009   if (Op1.getOpcode() == ISD::SHL)
15010     std::swap(Op0, Op1);
15011   if (Op0.getOpcode() == ISD::SHL) {
15012     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
15013       if (And00C->getZExtValue() == 1) {
15014         // If we looked past a truncate, check that it's only truncating away
15015         // known zeros.
15016         unsigned BitWidth = Op0.getValueSizeInBits();
15017         unsigned AndBitWidth = And.getValueSizeInBits();
15018         if (BitWidth > AndBitWidth) {
15019           APInt Zeros, Ones;
15020           DAG.computeKnownBits(Op0, Zeros, Ones);
15021           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
15022             return SDValue();
15023         }
15024         LHS = Op1;
15025         RHS = Op0.getOperand(1);
15026       }
15027   } else if (Op1.getOpcode() == ISD::Constant) {
15028     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
15029     uint64_t AndRHSVal = AndRHS->getZExtValue();
15030     SDValue AndLHS = Op0;
15031
15032     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
15033       LHS = AndLHS.getOperand(0);
15034       RHS = AndLHS.getOperand(1);
15035     }
15036
15037     // Use BT if the immediate can't be encoded in a TEST instruction.
15038     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
15039       LHS = AndLHS;
15040       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
15041     }
15042   }
15043
15044   if (LHS.getNode()) {
15045     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
15046     // instruction.  Since the shift amount is in-range-or-undefined, we know
15047     // that doing a bittest on the i32 value is ok.  We extend to i32 because
15048     // the encoding for the i16 version is larger than the i32 version.
15049     // Also promote i16 to i32 for performance / code size reason.
15050     if (LHS.getValueType() == MVT::i8 ||
15051         LHS.getValueType() == MVT::i16)
15052       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
15053
15054     // If the operand types disagree, extend the shift amount to match.  Since
15055     // BT ignores high bits (like shifts) we can use anyextend.
15056     if (LHS.getValueType() != RHS.getValueType())
15057       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
15058
15059     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
15060     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
15061     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15062                        DAG.getConstant(Cond, MVT::i8), BT);
15063   }
15064
15065   return SDValue();
15066 }
15067
15068 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
15069 /// mask CMPs.
15070 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
15071                               SDValue &Op1) {
15072   unsigned SSECC;
15073   bool Swap = false;
15074
15075   // SSE Condition code mapping:
15076   //  0 - EQ
15077   //  1 - LT
15078   //  2 - LE
15079   //  3 - UNORD
15080   //  4 - NEQ
15081   //  5 - NLT
15082   //  6 - NLE
15083   //  7 - ORD
15084   switch (SetCCOpcode) {
15085   default: llvm_unreachable("Unexpected SETCC condition");
15086   case ISD::SETOEQ:
15087   case ISD::SETEQ:  SSECC = 0; break;
15088   case ISD::SETOGT:
15089   case ISD::SETGT:  Swap = true; // Fallthrough
15090   case ISD::SETLT:
15091   case ISD::SETOLT: SSECC = 1; break;
15092   case ISD::SETOGE:
15093   case ISD::SETGE:  Swap = true; // Fallthrough
15094   case ISD::SETLE:
15095   case ISD::SETOLE: SSECC = 2; break;
15096   case ISD::SETUO:  SSECC = 3; break;
15097   case ISD::SETUNE:
15098   case ISD::SETNE:  SSECC = 4; break;
15099   case ISD::SETULE: Swap = true; // Fallthrough
15100   case ISD::SETUGE: SSECC = 5; break;
15101   case ISD::SETULT: Swap = true; // Fallthrough
15102   case ISD::SETUGT: SSECC = 6; break;
15103   case ISD::SETO:   SSECC = 7; break;
15104   case ISD::SETUEQ:
15105   case ISD::SETONE: SSECC = 8; break;
15106   }
15107   if (Swap)
15108     std::swap(Op0, Op1);
15109
15110   return SSECC;
15111 }
15112
15113 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
15114 // ones, and then concatenate the result back.
15115 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
15116   MVT VT = Op.getSimpleValueType();
15117
15118   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
15119          "Unsupported value type for operation");
15120
15121   unsigned NumElems = VT.getVectorNumElements();
15122   SDLoc dl(Op);
15123   SDValue CC = Op.getOperand(2);
15124
15125   // Extract the LHS vectors
15126   SDValue LHS = Op.getOperand(0);
15127   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15128   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15129
15130   // Extract the RHS vectors
15131   SDValue RHS = Op.getOperand(1);
15132   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15133   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15134
15135   // Issue the operation on the smaller types and concatenate the result back
15136   MVT EltVT = VT.getVectorElementType();
15137   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15138   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15139                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
15140                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
15141 }
15142
15143 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
15144                                      const X86Subtarget *Subtarget) {
15145   SDValue Op0 = Op.getOperand(0);
15146   SDValue Op1 = Op.getOperand(1);
15147   SDValue CC = Op.getOperand(2);
15148   MVT VT = Op.getSimpleValueType();
15149   SDLoc dl(Op);
15150
15151   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
15152          Op.getValueType().getScalarType() == MVT::i1 &&
15153          "Cannot set masked compare for this operation");
15154
15155   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15156   unsigned  Opc = 0;
15157   bool Unsigned = false;
15158   bool Swap = false;
15159   unsigned SSECC;
15160   switch (SetCCOpcode) {
15161   default: llvm_unreachable("Unexpected SETCC condition");
15162   case ISD::SETNE:  SSECC = 4; break;
15163   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
15164   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
15165   case ISD::SETLT:  Swap = true; //fall-through
15166   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
15167   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
15168   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
15169   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
15170   case ISD::SETULE: Unsigned = true; //fall-through
15171   case ISD::SETLE:  SSECC = 2; break;
15172   }
15173
15174   if (Swap)
15175     std::swap(Op0, Op1);
15176   if (Opc)
15177     return DAG.getNode(Opc, dl, VT, Op0, Op1);
15178   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
15179   return DAG.getNode(Opc, dl, VT, Op0, Op1,
15180                      DAG.getConstant(SSECC, MVT::i8));
15181 }
15182
15183 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
15184 /// operand \p Op1.  If non-trivial (for example because it's not constant)
15185 /// return an empty value.
15186 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
15187 {
15188   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
15189   if (!BV)
15190     return SDValue();
15191
15192   MVT VT = Op1.getSimpleValueType();
15193   MVT EVT = VT.getVectorElementType();
15194   unsigned n = VT.getVectorNumElements();
15195   SmallVector<SDValue, 8> ULTOp1;
15196
15197   for (unsigned i = 0; i < n; ++i) {
15198     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
15199     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
15200       return SDValue();
15201
15202     // Avoid underflow.
15203     APInt Val = Elt->getAPIntValue();
15204     if (Val == 0)
15205       return SDValue();
15206
15207     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
15208   }
15209
15210   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
15211 }
15212
15213 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
15214                            SelectionDAG &DAG) {
15215   SDValue Op0 = Op.getOperand(0);
15216   SDValue Op1 = Op.getOperand(1);
15217   SDValue CC = Op.getOperand(2);
15218   MVT VT = Op.getSimpleValueType();
15219   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15220   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
15221   SDLoc dl(Op);
15222
15223   if (isFP) {
15224 #ifndef NDEBUG
15225     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
15226     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
15227 #endif
15228
15229     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
15230     unsigned Opc = X86ISD::CMPP;
15231     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
15232       assert(VT.getVectorNumElements() <= 16);
15233       Opc = X86ISD::CMPM;
15234     }
15235     // In the two special cases we can't handle, emit two comparisons.
15236     if (SSECC == 8) {
15237       unsigned CC0, CC1;
15238       unsigned CombineOpc;
15239       if (SetCCOpcode == ISD::SETUEQ) {
15240         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
15241       } else {
15242         assert(SetCCOpcode == ISD::SETONE);
15243         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
15244       }
15245
15246       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15247                                  DAG.getConstant(CC0, MVT::i8));
15248       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15249                                  DAG.getConstant(CC1, MVT::i8));
15250       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
15251     }
15252     // Handle all other FP comparisons here.
15253     return DAG.getNode(Opc, dl, VT, Op0, Op1,
15254                        DAG.getConstant(SSECC, MVT::i8));
15255   }
15256
15257   // Break 256-bit integer vector compare into smaller ones.
15258   if (VT.is256BitVector() && !Subtarget->hasInt256())
15259     return Lower256IntVSETCC(Op, DAG);
15260
15261   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
15262   EVT OpVT = Op1.getValueType();
15263   if (Subtarget->hasAVX512()) {
15264     if (Op1.getValueType().is512BitVector() ||
15265         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
15266         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
15267       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
15268
15269     // In AVX-512 architecture setcc returns mask with i1 elements,
15270     // But there is no compare instruction for i8 and i16 elements in KNL.
15271     // We are not talking about 512-bit operands in this case, these
15272     // types are illegal.
15273     if (MaskResult &&
15274         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
15275          OpVT.getVectorElementType().getSizeInBits() >= 8))
15276       return DAG.getNode(ISD::TRUNCATE, dl, VT,
15277                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
15278   }
15279
15280   // We are handling one of the integer comparisons here.  Since SSE only has
15281   // GT and EQ comparisons for integer, swapping operands and multiple
15282   // operations may be required for some comparisons.
15283   unsigned Opc;
15284   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
15285   bool Subus = false;
15286
15287   switch (SetCCOpcode) {
15288   default: llvm_unreachable("Unexpected SETCC condition");
15289   case ISD::SETNE:  Invert = true;
15290   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
15291   case ISD::SETLT:  Swap = true;
15292   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
15293   case ISD::SETGE:  Swap = true;
15294   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
15295                     Invert = true; break;
15296   case ISD::SETULT: Swap = true;
15297   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
15298                     FlipSigns = true; break;
15299   case ISD::SETUGE: Swap = true;
15300   case ISD::SETULE: Opc = X86ISD::PCMPGT;
15301                     FlipSigns = true; Invert = true; break;
15302   }
15303
15304   // Special case: Use min/max operations for SETULE/SETUGE
15305   MVT VET = VT.getVectorElementType();
15306   bool hasMinMax =
15307        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
15308     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
15309
15310   if (hasMinMax) {
15311     switch (SetCCOpcode) {
15312     default: break;
15313     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
15314     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
15315     }
15316
15317     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
15318   }
15319
15320   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
15321   if (!MinMax && hasSubus) {
15322     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
15323     // Op0 u<= Op1:
15324     //   t = psubus Op0, Op1
15325     //   pcmpeq t, <0..0>
15326     switch (SetCCOpcode) {
15327     default: break;
15328     case ISD::SETULT: {
15329       // If the comparison is against a constant we can turn this into a
15330       // setule.  With psubus, setule does not require a swap.  This is
15331       // beneficial because the constant in the register is no longer
15332       // destructed as the destination so it can be hoisted out of a loop.
15333       // Only do this pre-AVX since vpcmp* is no longer destructive.
15334       if (Subtarget->hasAVX())
15335         break;
15336       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
15337       if (ULEOp1.getNode()) {
15338         Op1 = ULEOp1;
15339         Subus = true; Invert = false; Swap = false;
15340       }
15341       break;
15342     }
15343     // Psubus is better than flip-sign because it requires no inversion.
15344     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
15345     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
15346     }
15347
15348     if (Subus) {
15349       Opc = X86ISD::SUBUS;
15350       FlipSigns = false;
15351     }
15352   }
15353
15354   if (Swap)
15355     std::swap(Op0, Op1);
15356
15357   // Check that the operation in question is available (most are plain SSE2,
15358   // but PCMPGTQ and PCMPEQQ have different requirements).
15359   if (VT == MVT::v2i64) {
15360     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
15361       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
15362
15363       // First cast everything to the right type.
15364       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15365       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15366
15367       // Since SSE has no unsigned integer comparisons, we need to flip the sign
15368       // bits of the inputs before performing those operations. The lower
15369       // compare is always unsigned.
15370       SDValue SB;
15371       if (FlipSigns) {
15372         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
15373       } else {
15374         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
15375         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
15376         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
15377                          Sign, Zero, Sign, Zero);
15378       }
15379       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
15380       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
15381
15382       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
15383       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
15384       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
15385
15386       // Create masks for only the low parts/high parts of the 64 bit integers.
15387       static const int MaskHi[] = { 1, 1, 3, 3 };
15388       static const int MaskLo[] = { 0, 0, 2, 2 };
15389       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
15390       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
15391       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
15392
15393       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
15394       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
15395
15396       if (Invert)
15397         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15398
15399       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15400     }
15401
15402     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
15403       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
15404       // pcmpeqd + pshufd + pand.
15405       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
15406
15407       // First cast everything to the right type.
15408       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15409       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15410
15411       // Do the compare.
15412       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
15413
15414       // Make sure the lower and upper halves are both all-ones.
15415       static const int Mask[] = { 1, 0, 3, 2 };
15416       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
15417       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
15418
15419       if (Invert)
15420         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15421
15422       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15423     }
15424   }
15425
15426   // Since SSE has no unsigned integer comparisons, we need to flip the sign
15427   // bits of the inputs before performing those operations.
15428   if (FlipSigns) {
15429     EVT EltVT = VT.getVectorElementType();
15430     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
15431     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
15432     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
15433   }
15434
15435   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
15436
15437   // If the logical-not of the result is required, perform that now.
15438   if (Invert)
15439     Result = DAG.getNOT(dl, Result, VT);
15440
15441   if (MinMax)
15442     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
15443
15444   if (Subus)
15445     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
15446                          getZeroVector(VT, Subtarget, DAG, dl));
15447
15448   return Result;
15449 }
15450
15451 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
15452
15453   MVT VT = Op.getSimpleValueType();
15454
15455   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
15456
15457   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
15458          && "SetCC type must be 8-bit or 1-bit integer");
15459   SDValue Op0 = Op.getOperand(0);
15460   SDValue Op1 = Op.getOperand(1);
15461   SDLoc dl(Op);
15462   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
15463
15464   // Optimize to BT if possible.
15465   // Lower (X & (1 << N)) == 0 to BT(X, N).
15466   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
15467   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
15468   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
15469       Op1.getOpcode() == ISD::Constant &&
15470       cast<ConstantSDNode>(Op1)->isNullValue() &&
15471       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15472     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
15473     if (NewSetCC.getNode()) {
15474       if (VT == MVT::i1)
15475         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
15476       return NewSetCC;
15477     }
15478   }
15479
15480   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
15481   // these.
15482   if (Op1.getOpcode() == ISD::Constant &&
15483       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
15484        cast<ConstantSDNode>(Op1)->isNullValue()) &&
15485       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15486
15487     // If the input is a setcc, then reuse the input setcc or use a new one with
15488     // the inverted condition.
15489     if (Op0.getOpcode() == X86ISD::SETCC) {
15490       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
15491       bool Invert = (CC == ISD::SETNE) ^
15492         cast<ConstantSDNode>(Op1)->isNullValue();
15493       if (!Invert)
15494         return Op0;
15495
15496       CCode = X86::GetOppositeBranchCondition(CCode);
15497       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15498                                   DAG.getConstant(CCode, MVT::i8),
15499                                   Op0.getOperand(1));
15500       if (VT == MVT::i1)
15501         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15502       return SetCC;
15503     }
15504   }
15505   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
15506       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
15507       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15508
15509     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
15510     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
15511   }
15512
15513   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
15514   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
15515   if (X86CC == X86::COND_INVALID)
15516     return SDValue();
15517
15518   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
15519   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
15520   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15521                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
15522   if (VT == MVT::i1)
15523     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15524   return SetCC;
15525 }
15526
15527 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
15528 static bool isX86LogicalCmp(SDValue Op) {
15529   unsigned Opc = Op.getNode()->getOpcode();
15530   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
15531       Opc == X86ISD::SAHF)
15532     return true;
15533   if (Op.getResNo() == 1 &&
15534       (Opc == X86ISD::ADD ||
15535        Opc == X86ISD::SUB ||
15536        Opc == X86ISD::ADC ||
15537        Opc == X86ISD::SBB ||
15538        Opc == X86ISD::SMUL ||
15539        Opc == X86ISD::UMUL ||
15540        Opc == X86ISD::INC ||
15541        Opc == X86ISD::DEC ||
15542        Opc == X86ISD::OR ||
15543        Opc == X86ISD::XOR ||
15544        Opc == X86ISD::AND))
15545     return true;
15546
15547   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15548     return true;
15549
15550   return false;
15551 }
15552
15553 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15554   if (V.getOpcode() != ISD::TRUNCATE)
15555     return false;
15556
15557   SDValue VOp0 = V.getOperand(0);
15558   unsigned InBits = VOp0.getValueSizeInBits();
15559   unsigned Bits = V.getValueSizeInBits();
15560   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15561 }
15562
15563 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15564   bool addTest = true;
15565   SDValue Cond  = Op.getOperand(0);
15566   SDValue Op1 = Op.getOperand(1);
15567   SDValue Op2 = Op.getOperand(2);
15568   SDLoc DL(Op);
15569   EVT VT = Op1.getValueType();
15570   SDValue CC;
15571
15572   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15573   // are available. Otherwise fp cmovs get lowered into a less efficient branch
15574   // sequence later on.
15575   if (Cond.getOpcode() == ISD::SETCC &&
15576       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15577        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15578       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
15579     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15580     int SSECC = translateX86FSETCC(
15581         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15582
15583     if (SSECC != 8) {
15584       if (Subtarget->hasAVX512()) {
15585         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15586                                   DAG.getConstant(SSECC, MVT::i8));
15587         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15588       }
15589       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15590                                 DAG.getConstant(SSECC, MVT::i8));
15591       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15592       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15593       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15594     }
15595   }
15596
15597   if (Cond.getOpcode() == ISD::SETCC) {
15598     SDValue NewCond = LowerSETCC(Cond, DAG);
15599     if (NewCond.getNode())
15600       Cond = NewCond;
15601   }
15602
15603   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15604   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15605   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15606   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15607   if (Cond.getOpcode() == X86ISD::SETCC &&
15608       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15609       isZero(Cond.getOperand(1).getOperand(1))) {
15610     SDValue Cmp = Cond.getOperand(1);
15611
15612     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15613
15614     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
15615         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15616       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
15617
15618       SDValue CmpOp0 = Cmp.getOperand(0);
15619       // Apply further optimizations for special cases
15620       // (select (x != 0), -1, 0) -> neg & sbb
15621       // (select (x == 0), 0, -1) -> neg & sbb
15622       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
15623         if (YC->isNullValue() &&
15624             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
15625           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15626           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15627                                     DAG.getConstant(0, CmpOp0.getValueType()),
15628                                     CmpOp0);
15629           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15630                                     DAG.getConstant(X86::COND_B, MVT::i8),
15631                                     SDValue(Neg.getNode(), 1));
15632           return Res;
15633         }
15634
15635       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15636                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
15637       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15638
15639       SDValue Res =   // Res = 0 or -1.
15640         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15641                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
15642
15643       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
15644         Res = DAG.getNOT(DL, Res, Res.getValueType());
15645
15646       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
15647       if (!N2C || !N2C->isNullValue())
15648         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15649       return Res;
15650     }
15651   }
15652
15653   // Look past (and (setcc_carry (cmp ...)), 1).
15654   if (Cond.getOpcode() == ISD::AND &&
15655       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15656     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15657     if (C && C->getAPIntValue() == 1)
15658       Cond = Cond.getOperand(0);
15659   }
15660
15661   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15662   // setting operand in place of the X86ISD::SETCC.
15663   unsigned CondOpcode = Cond.getOpcode();
15664   if (CondOpcode == X86ISD::SETCC ||
15665       CondOpcode == X86ISD::SETCC_CARRY) {
15666     CC = Cond.getOperand(0);
15667
15668     SDValue Cmp = Cond.getOperand(1);
15669     unsigned Opc = Cmp.getOpcode();
15670     MVT VT = Op.getSimpleValueType();
15671
15672     bool IllegalFPCMov = false;
15673     if (VT.isFloatingPoint() && !VT.isVector() &&
15674         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15675       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15676
15677     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15678         Opc == X86ISD::BT) { // FIXME
15679       Cond = Cmp;
15680       addTest = false;
15681     }
15682   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15683              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15684              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15685               Cond.getOperand(0).getValueType() != MVT::i8)) {
15686     SDValue LHS = Cond.getOperand(0);
15687     SDValue RHS = Cond.getOperand(1);
15688     unsigned X86Opcode;
15689     unsigned X86Cond;
15690     SDVTList VTs;
15691     switch (CondOpcode) {
15692     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15693     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15694     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15695     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15696     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15697     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15698     default: llvm_unreachable("unexpected overflowing operator");
15699     }
15700     if (CondOpcode == ISD::UMULO)
15701       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15702                           MVT::i32);
15703     else
15704       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15705
15706     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15707
15708     if (CondOpcode == ISD::UMULO)
15709       Cond = X86Op.getValue(2);
15710     else
15711       Cond = X86Op.getValue(1);
15712
15713     CC = DAG.getConstant(X86Cond, MVT::i8);
15714     addTest = false;
15715   }
15716
15717   if (addTest) {
15718     // Look pass the truncate if the high bits are known zero.
15719     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15720         Cond = Cond.getOperand(0);
15721
15722     // We know the result of AND is compared against zero. Try to match
15723     // it to BT.
15724     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15725       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
15726       if (NewSetCC.getNode()) {
15727         CC = NewSetCC.getOperand(0);
15728         Cond = NewSetCC.getOperand(1);
15729         addTest = false;
15730       }
15731     }
15732   }
15733
15734   if (addTest) {
15735     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15736     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15737   }
15738
15739   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15740   // a <  b ?  0 : -1 -> RES = setcc_carry
15741   // a >= b ? -1 :  0 -> RES = setcc_carry
15742   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15743   if (Cond.getOpcode() == X86ISD::SUB) {
15744     Cond = ConvertCmpIfNecessary(Cond, DAG);
15745     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15746
15747     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15748         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
15749       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15750                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
15751       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
15752         return DAG.getNOT(DL, Res, Res.getValueType());
15753       return Res;
15754     }
15755   }
15756
15757   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15758   // widen the cmov and push the truncate through. This avoids introducing a new
15759   // branch during isel and doesn't add any extensions.
15760   if (Op.getValueType() == MVT::i8 &&
15761       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15762     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15763     if (T1.getValueType() == T2.getValueType() &&
15764         // Blacklist CopyFromReg to avoid partial register stalls.
15765         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15766       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15767       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15768       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15769     }
15770   }
15771
15772   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15773   // condition is true.
15774   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15775   SDValue Ops[] = { Op2, Op1, CC, Cond };
15776   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15777 }
15778
15779 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
15780                                        SelectionDAG &DAG) {
15781   MVT VT = Op->getSimpleValueType(0);
15782   SDValue In = Op->getOperand(0);
15783   MVT InVT = In.getSimpleValueType();
15784   MVT VTElt = VT.getVectorElementType();
15785   MVT InVTElt = InVT.getVectorElementType();
15786   SDLoc dl(Op);
15787
15788   // SKX processor
15789   if ((InVTElt == MVT::i1) &&
15790       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15791         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15792
15793        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15794         VTElt.getSizeInBits() <= 16)) ||
15795
15796        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15797         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15798
15799        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15800         VTElt.getSizeInBits() >= 32))))
15801     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15802
15803   unsigned int NumElts = VT.getVectorNumElements();
15804
15805   if (NumElts != 8 && NumElts != 16)
15806     return SDValue();
15807
15808   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15809     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15810       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15811     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15812   }
15813
15814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15815   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15816
15817   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
15818   Constant *C = ConstantInt::get(*DAG.getContext(),
15819     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
15820
15821   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
15822   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
15823   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
15824                           MachinePointerInfo::getConstantPool(),
15825                           false, false, false, Alignment);
15826   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
15827   if (VT.is512BitVector())
15828     return Brcst;
15829   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
15830 }
15831
15832 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15833                                 SelectionDAG &DAG) {
15834   MVT VT = Op->getSimpleValueType(0);
15835   SDValue In = Op->getOperand(0);
15836   MVT InVT = In.getSimpleValueType();
15837   SDLoc dl(Op);
15838
15839   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15840     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15841
15842   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15843       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15844       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15845     return SDValue();
15846
15847   if (Subtarget->hasInt256())
15848     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15849
15850   // Optimize vectors in AVX mode
15851   // Sign extend  v8i16 to v8i32 and
15852   //              v4i32 to v4i64
15853   //
15854   // Divide input vector into two parts
15855   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15856   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15857   // concat the vectors to original VT
15858
15859   unsigned NumElems = InVT.getVectorNumElements();
15860   SDValue Undef = DAG.getUNDEF(InVT);
15861
15862   SmallVector<int,8> ShufMask1(NumElems, -1);
15863   for (unsigned i = 0; i != NumElems/2; ++i)
15864     ShufMask1[i] = i;
15865
15866   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15867
15868   SmallVector<int,8> ShufMask2(NumElems, -1);
15869   for (unsigned i = 0; i != NumElems/2; ++i)
15870     ShufMask2[i] = i + NumElems/2;
15871
15872   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15873
15874   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15875                                 VT.getVectorNumElements()/2);
15876
15877   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15878   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15879
15880   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15881 }
15882
15883 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15884 // may emit an illegal shuffle but the expansion is still better than scalar
15885 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15886 // we'll emit a shuffle and a arithmetic shift.
15887 // TODO: It is possible to support ZExt by zeroing the undef values during
15888 // the shuffle phase or after the shuffle.
15889 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15890                                  SelectionDAG &DAG) {
15891   MVT RegVT = Op.getSimpleValueType();
15892   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15893   assert(RegVT.isInteger() &&
15894          "We only custom lower integer vector sext loads.");
15895
15896   // Nothing useful we can do without SSE2 shuffles.
15897   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15898
15899   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15900   SDLoc dl(Ld);
15901   EVT MemVT = Ld->getMemoryVT();
15902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15903   unsigned RegSz = RegVT.getSizeInBits();
15904
15905   ISD::LoadExtType Ext = Ld->getExtensionType();
15906
15907   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15908          && "Only anyext and sext are currently implemented.");
15909   assert(MemVT != RegVT && "Cannot extend to the same type");
15910   assert(MemVT.isVector() && "Must load a vector from memory");
15911
15912   unsigned NumElems = RegVT.getVectorNumElements();
15913   unsigned MemSz = MemVT.getSizeInBits();
15914   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15915
15916   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15917     // The only way in which we have a legal 256-bit vector result but not the
15918     // integer 256-bit operations needed to directly lower a sextload is if we
15919     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15920     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15921     // correctly legalized. We do this late to allow the canonical form of
15922     // sextload to persist throughout the rest of the DAG combiner -- it wants
15923     // to fold together any extensions it can, and so will fuse a sign_extend
15924     // of an sextload into a sextload targeting a wider value.
15925     SDValue Load;
15926     if (MemSz == 128) {
15927       // Just switch this to a normal load.
15928       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15929                                        "it must be a legal 128-bit vector "
15930                                        "type!");
15931       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15932                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15933                   Ld->isInvariant(), Ld->getAlignment());
15934     } else {
15935       assert(MemSz < 128 &&
15936              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15937       // Do an sext load to a 128-bit vector type. We want to use the same
15938       // number of elements, but elements half as wide. This will end up being
15939       // recursively lowered by this routine, but will succeed as we definitely
15940       // have all the necessary features if we're using AVX1.
15941       EVT HalfEltVT =
15942           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15943       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15944       Load =
15945           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15946                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15947                          Ld->isNonTemporal(), Ld->isInvariant(),
15948                          Ld->getAlignment());
15949     }
15950
15951     // Replace chain users with the new chain.
15952     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15953     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15954
15955     // Finally, do a normal sign-extend to the desired register.
15956     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15957   }
15958
15959   // All sizes must be a power of two.
15960   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15961          "Non-power-of-two elements are not custom lowered!");
15962
15963   // Attempt to load the original value using scalar loads.
15964   // Find the largest scalar type that divides the total loaded size.
15965   MVT SclrLoadTy = MVT::i8;
15966   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15967        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15968     MVT Tp = (MVT::SimpleValueType)tp;
15969     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15970       SclrLoadTy = Tp;
15971     }
15972   }
15973
15974   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15975   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15976       (64 <= MemSz))
15977     SclrLoadTy = MVT::f64;
15978
15979   // Calculate the number of scalar loads that we need to perform
15980   // in order to load our vector from memory.
15981   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15982
15983   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15984          "Can only lower sext loads with a single scalar load!");
15985
15986   unsigned loadRegZize = RegSz;
15987   if (Ext == ISD::SEXTLOAD && RegSz == 256)
15988     loadRegZize /= 2;
15989
15990   // Represent our vector as a sequence of elements which are the
15991   // largest scalar that we can load.
15992   EVT LoadUnitVecVT = EVT::getVectorVT(
15993       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15994
15995   // Represent the data using the same element type that is stored in
15996   // memory. In practice, we ''widen'' MemVT.
15997   EVT WideVecVT =
15998       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15999                        loadRegZize / MemVT.getScalarType().getSizeInBits());
16000
16001   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16002          "Invalid vector type");
16003
16004   // We can't shuffle using an illegal type.
16005   assert(TLI.isTypeLegal(WideVecVT) &&
16006          "We only lower types that form legal widened vector types");
16007
16008   SmallVector<SDValue, 8> Chains;
16009   SDValue Ptr = Ld->getBasePtr();
16010   SDValue Increment =
16011       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
16012   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16013
16014   for (unsigned i = 0; i < NumLoads; ++i) {
16015     // Perform a single load.
16016     SDValue ScalarLoad =
16017         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
16018                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
16019                     Ld->getAlignment());
16020     Chains.push_back(ScalarLoad.getValue(1));
16021     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16022     // another round of DAGCombining.
16023     if (i == 0)
16024       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16025     else
16026       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16027                         ScalarLoad, DAG.getIntPtrConstant(i));
16028
16029     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16030   }
16031
16032   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
16033
16034   // Bitcast the loaded value to a vector of the original element type, in
16035   // the size of the target vector type.
16036   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16037   unsigned SizeRatio = RegSz / MemSz;
16038
16039   if (Ext == ISD::SEXTLOAD) {
16040     // If we have SSE4.1, we can directly emit a VSEXT node.
16041     if (Subtarget->hasSSE41()) {
16042       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16043       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16044       return Sext;
16045     }
16046
16047     // Otherwise we'll shuffle the small elements in the high bits of the
16048     // larger type and perform an arithmetic shift. If the shift is not legal
16049     // it's better to scalarize.
16050     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
16051            "We can't implement a sext load without an arithmetic right shift!");
16052
16053     // Redistribute the loaded elements into the different locations.
16054     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16055     for (unsigned i = 0; i != NumElems; ++i)
16056       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
16057
16058     SDValue Shuff = DAG.getVectorShuffle(
16059         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16060
16061     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16062
16063     // Build the arithmetic shift.
16064     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16065                    MemVT.getVectorElementType().getSizeInBits();
16066     Shuff =
16067         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
16068
16069     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16070     return Shuff;
16071   }
16072
16073   // Redistribute the loaded elements into the different locations.
16074   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16075   for (unsigned i = 0; i != NumElems; ++i)
16076     ShuffleVec[i * SizeRatio] = i;
16077
16078   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16079                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16080
16081   // Bitcast to the requested type.
16082   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16083   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16084   return Shuff;
16085 }
16086
16087 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
16088 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
16089 // from the AND / OR.
16090 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
16091   Opc = Op.getOpcode();
16092   if (Opc != ISD::OR && Opc != ISD::AND)
16093     return false;
16094   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16095           Op.getOperand(0).hasOneUse() &&
16096           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
16097           Op.getOperand(1).hasOneUse());
16098 }
16099
16100 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
16101 // 1 and that the SETCC node has a single use.
16102 static bool isXor1OfSetCC(SDValue Op) {
16103   if (Op.getOpcode() != ISD::XOR)
16104     return false;
16105   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
16106   if (N1C && N1C->getAPIntValue() == 1) {
16107     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16108       Op.getOperand(0).hasOneUse();
16109   }
16110   return false;
16111 }
16112
16113 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
16114   bool addTest = true;
16115   SDValue Chain = Op.getOperand(0);
16116   SDValue Cond  = Op.getOperand(1);
16117   SDValue Dest  = Op.getOperand(2);
16118   SDLoc dl(Op);
16119   SDValue CC;
16120   bool Inverted = false;
16121
16122   if (Cond.getOpcode() == ISD::SETCC) {
16123     // Check for setcc([su]{add,sub,mul}o == 0).
16124     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
16125         isa<ConstantSDNode>(Cond.getOperand(1)) &&
16126         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
16127         Cond.getOperand(0).getResNo() == 1 &&
16128         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
16129          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
16130          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
16131          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
16132          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
16133          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
16134       Inverted = true;
16135       Cond = Cond.getOperand(0);
16136     } else {
16137       SDValue NewCond = LowerSETCC(Cond, DAG);
16138       if (NewCond.getNode())
16139         Cond = NewCond;
16140     }
16141   }
16142 #if 0
16143   // FIXME: LowerXALUO doesn't handle these!!
16144   else if (Cond.getOpcode() == X86ISD::ADD  ||
16145            Cond.getOpcode() == X86ISD::SUB  ||
16146            Cond.getOpcode() == X86ISD::SMUL ||
16147            Cond.getOpcode() == X86ISD::UMUL)
16148     Cond = LowerXALUO(Cond, DAG);
16149 #endif
16150
16151   // Look pass (and (setcc_carry (cmp ...)), 1).
16152   if (Cond.getOpcode() == ISD::AND &&
16153       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
16154     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
16155     if (C && C->getAPIntValue() == 1)
16156       Cond = Cond.getOperand(0);
16157   }
16158
16159   // If condition flag is set by a X86ISD::CMP, then use it as the condition
16160   // setting operand in place of the X86ISD::SETCC.
16161   unsigned CondOpcode = Cond.getOpcode();
16162   if (CondOpcode == X86ISD::SETCC ||
16163       CondOpcode == X86ISD::SETCC_CARRY) {
16164     CC = Cond.getOperand(0);
16165
16166     SDValue Cmp = Cond.getOperand(1);
16167     unsigned Opc = Cmp.getOpcode();
16168     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
16169     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
16170       Cond = Cmp;
16171       addTest = false;
16172     } else {
16173       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
16174       default: break;
16175       case X86::COND_O:
16176       case X86::COND_B:
16177         // These can only come from an arithmetic instruction with overflow,
16178         // e.g. SADDO, UADDO.
16179         Cond = Cond.getNode()->getOperand(1);
16180         addTest = false;
16181         break;
16182       }
16183     }
16184   }
16185   CondOpcode = Cond.getOpcode();
16186   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
16187       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
16188       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
16189        Cond.getOperand(0).getValueType() != MVT::i8)) {
16190     SDValue LHS = Cond.getOperand(0);
16191     SDValue RHS = Cond.getOperand(1);
16192     unsigned X86Opcode;
16193     unsigned X86Cond;
16194     SDVTList VTs;
16195     // Keep this in sync with LowerXALUO, otherwise we might create redundant
16196     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
16197     // X86ISD::INC).
16198     switch (CondOpcode) {
16199     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
16200     case ISD::SADDO:
16201       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16202         if (C->isOne()) {
16203           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
16204           break;
16205         }
16206       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
16207     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
16208     case ISD::SSUBO:
16209       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16210         if (C->isOne()) {
16211           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
16212           break;
16213         }
16214       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
16215     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
16216     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
16217     default: llvm_unreachable("unexpected overflowing operator");
16218     }
16219     if (Inverted)
16220       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
16221     if (CondOpcode == ISD::UMULO)
16222       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
16223                           MVT::i32);
16224     else
16225       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
16226
16227     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
16228
16229     if (CondOpcode == ISD::UMULO)
16230       Cond = X86Op.getValue(2);
16231     else
16232       Cond = X86Op.getValue(1);
16233
16234     CC = DAG.getConstant(X86Cond, MVT::i8);
16235     addTest = false;
16236   } else {
16237     unsigned CondOpc;
16238     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
16239       SDValue Cmp = Cond.getOperand(0).getOperand(1);
16240       if (CondOpc == ISD::OR) {
16241         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
16242         // two branches instead of an explicit OR instruction with a
16243         // separate test.
16244         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16245             isX86LogicalCmp(Cmp)) {
16246           CC = Cond.getOperand(0).getOperand(0);
16247           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16248                               Chain, Dest, CC, Cmp);
16249           CC = Cond.getOperand(1).getOperand(0);
16250           Cond = Cmp;
16251           addTest = false;
16252         }
16253       } else { // ISD::AND
16254         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
16255         // two branches instead of an explicit AND instruction with a
16256         // separate test. However, we only do this if this block doesn't
16257         // have a fall-through edge, because this requires an explicit
16258         // jmp when the condition is false.
16259         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16260             isX86LogicalCmp(Cmp) &&
16261             Op.getNode()->hasOneUse()) {
16262           X86::CondCode CCode =
16263             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16264           CCode = X86::GetOppositeBranchCondition(CCode);
16265           CC = DAG.getConstant(CCode, MVT::i8);
16266           SDNode *User = *Op.getNode()->use_begin();
16267           // Look for an unconditional branch following this conditional branch.
16268           // We need this because we need to reverse the successors in order
16269           // to implement FCMP_OEQ.
16270           if (User->getOpcode() == ISD::BR) {
16271             SDValue FalseBB = User->getOperand(1);
16272             SDNode *NewBR =
16273               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16274             assert(NewBR == User);
16275             (void)NewBR;
16276             Dest = FalseBB;
16277
16278             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16279                                 Chain, Dest, CC, Cmp);
16280             X86::CondCode CCode =
16281               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
16282             CCode = X86::GetOppositeBranchCondition(CCode);
16283             CC = DAG.getConstant(CCode, MVT::i8);
16284             Cond = Cmp;
16285             addTest = false;
16286           }
16287         }
16288       }
16289     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
16290       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
16291       // It should be transformed during dag combiner except when the condition
16292       // is set by a arithmetics with overflow node.
16293       X86::CondCode CCode =
16294         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16295       CCode = X86::GetOppositeBranchCondition(CCode);
16296       CC = DAG.getConstant(CCode, MVT::i8);
16297       Cond = Cond.getOperand(0).getOperand(1);
16298       addTest = false;
16299     } else if (Cond.getOpcode() == ISD::SETCC &&
16300                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
16301       // For FCMP_OEQ, we can emit
16302       // two branches instead of an explicit AND instruction with a
16303       // separate test. However, we only do this if this block doesn't
16304       // have a fall-through edge, because this requires an explicit
16305       // jmp when the condition is false.
16306       if (Op.getNode()->hasOneUse()) {
16307         SDNode *User = *Op.getNode()->use_begin();
16308         // Look for an unconditional branch following this conditional branch.
16309         // We need this because we need to reverse the successors in order
16310         // to implement FCMP_OEQ.
16311         if (User->getOpcode() == ISD::BR) {
16312           SDValue FalseBB = User->getOperand(1);
16313           SDNode *NewBR =
16314             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16315           assert(NewBR == User);
16316           (void)NewBR;
16317           Dest = FalseBB;
16318
16319           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16320                                     Cond.getOperand(0), Cond.getOperand(1));
16321           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16322           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16323           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16324                               Chain, Dest, CC, Cmp);
16325           CC = DAG.getConstant(X86::COND_P, MVT::i8);
16326           Cond = Cmp;
16327           addTest = false;
16328         }
16329       }
16330     } else if (Cond.getOpcode() == ISD::SETCC &&
16331                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
16332       // For FCMP_UNE, we can emit
16333       // two branches instead of an explicit AND instruction with a
16334       // separate test. However, we only do this if this block doesn't
16335       // have a fall-through edge, because this requires an explicit
16336       // jmp when the condition is false.
16337       if (Op.getNode()->hasOneUse()) {
16338         SDNode *User = *Op.getNode()->use_begin();
16339         // Look for an unconditional branch following this conditional branch.
16340         // We need this because we need to reverse the successors in order
16341         // to implement FCMP_UNE.
16342         if (User->getOpcode() == ISD::BR) {
16343           SDValue FalseBB = User->getOperand(1);
16344           SDNode *NewBR =
16345             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16346           assert(NewBR == User);
16347           (void)NewBR;
16348
16349           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16350                                     Cond.getOperand(0), Cond.getOperand(1));
16351           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16352           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16353           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16354                               Chain, Dest, CC, Cmp);
16355           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
16356           Cond = Cmp;
16357           addTest = false;
16358           Dest = FalseBB;
16359         }
16360       }
16361     }
16362   }
16363
16364   if (addTest) {
16365     // Look pass the truncate if the high bits are known zero.
16366     if (isTruncWithZeroHighBitsInput(Cond, DAG))
16367         Cond = Cond.getOperand(0);
16368
16369     // We know the result of AND is compared against zero. Try to match
16370     // it to BT.
16371     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
16372       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
16373       if (NewSetCC.getNode()) {
16374         CC = NewSetCC.getOperand(0);
16375         Cond = NewSetCC.getOperand(1);
16376         addTest = false;
16377       }
16378     }
16379   }
16380
16381   if (addTest) {
16382     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
16383     CC = DAG.getConstant(X86Cond, MVT::i8);
16384     Cond = EmitTest(Cond, X86Cond, dl, DAG);
16385   }
16386   Cond = ConvertCmpIfNecessary(Cond, DAG);
16387   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16388                      Chain, Dest, CC, Cond);
16389 }
16390
16391 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
16392 // Calls to _alloca are needed to probe the stack when allocating more than 4k
16393 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
16394 // that the guard pages used by the OS virtual memory manager are allocated in
16395 // correct sequence.
16396 SDValue
16397 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
16398                                            SelectionDAG &DAG) const {
16399   MachineFunction &MF = DAG.getMachineFunction();
16400   bool SplitStack = MF.shouldSplitStack();
16401   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
16402                SplitStack;
16403   SDLoc dl(Op);
16404
16405   if (!Lower) {
16406     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16407     SDNode* Node = Op.getNode();
16408
16409     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
16410     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
16411         " not tell us which reg is the stack pointer!");
16412     EVT VT = Node->getValueType(0);
16413     SDValue Tmp1 = SDValue(Node, 0);
16414     SDValue Tmp2 = SDValue(Node, 1);
16415     SDValue Tmp3 = Node->getOperand(2);
16416     SDValue Chain = Tmp1.getOperand(0);
16417
16418     // Chain the dynamic stack allocation so that it doesn't modify the stack
16419     // pointer when other instructions are using the stack.
16420     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
16421         SDLoc(Node));
16422
16423     SDValue Size = Tmp2.getOperand(1);
16424     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
16425     Chain = SP.getValue(1);
16426     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
16427     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
16428     unsigned StackAlign = TFI.getStackAlignment();
16429     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
16430     if (Align > StackAlign)
16431       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
16432           DAG.getConstant(-(uint64_t)Align, VT));
16433     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
16434
16435     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
16436         DAG.getIntPtrConstant(0, true), SDValue(),
16437         SDLoc(Node));
16438
16439     SDValue Ops[2] = { Tmp1, Tmp2 };
16440     return DAG.getMergeValues(Ops, dl);
16441   }
16442
16443   // Get the inputs.
16444   SDValue Chain = Op.getOperand(0);
16445   SDValue Size  = Op.getOperand(1);
16446   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16447   EVT VT = Op.getNode()->getValueType(0);
16448
16449   bool Is64Bit = Subtarget->is64Bit();
16450   EVT SPTy = getPointerTy();
16451
16452   if (SplitStack) {
16453     MachineRegisterInfo &MRI = MF.getRegInfo();
16454
16455     if (Is64Bit) {
16456       // The 64 bit implementation of segmented stacks needs to clobber both r10
16457       // r11. This makes it impossible to use it along with nested parameters.
16458       const Function *F = MF.getFunction();
16459
16460       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16461            I != E; ++I)
16462         if (I->hasNestAttr())
16463           report_fatal_error("Cannot use segmented stacks with functions that "
16464                              "have nested arguments.");
16465     }
16466
16467     const TargetRegisterClass *AddrRegClass =
16468       getRegClassFor(getPointerTy());
16469     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16470     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16471     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16472                                 DAG.getRegister(Vreg, SPTy));
16473     SDValue Ops1[2] = { Value, Chain };
16474     return DAG.getMergeValues(Ops1, dl);
16475   } else {
16476     SDValue Flag;
16477     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16478
16479     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16480     Flag = Chain.getValue(1);
16481     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16482
16483     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16484
16485     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16486         DAG.getSubtarget().getRegisterInfo());
16487     unsigned SPReg = RegInfo->getStackRegister();
16488     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16489     Chain = SP.getValue(1);
16490
16491     if (Align) {
16492       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16493                        DAG.getConstant(-(uint64_t)Align, VT));
16494       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16495     }
16496
16497     SDValue Ops1[2] = { SP, Chain };
16498     return DAG.getMergeValues(Ops1, dl);
16499   }
16500 }
16501
16502 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16503   MachineFunction &MF = DAG.getMachineFunction();
16504   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16505
16506   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16507   SDLoc DL(Op);
16508
16509   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
16510     // vastart just stores the address of the VarArgsFrameIndex slot into the
16511     // memory location argument.
16512     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16513                                    getPointerTy());
16514     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16515                         MachinePointerInfo(SV), false, false, 0);
16516   }
16517
16518   // __va_list_tag:
16519   //   gp_offset         (0 - 6 * 8)
16520   //   fp_offset         (48 - 48 + 8 * 16)
16521   //   overflow_arg_area (point to parameters coming in memory).
16522   //   reg_save_area
16523   SmallVector<SDValue, 8> MemOps;
16524   SDValue FIN = Op.getOperand(1);
16525   // Store gp_offset
16526   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16527                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16528                                                MVT::i32),
16529                                FIN, MachinePointerInfo(SV), false, false, 0);
16530   MemOps.push_back(Store);
16531
16532   // Store fp_offset
16533   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16534                     FIN, DAG.getIntPtrConstant(4));
16535   Store = DAG.getStore(Op.getOperand(0), DL,
16536                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
16537                                        MVT::i32),
16538                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16539   MemOps.push_back(Store);
16540
16541   // Store ptr to overflow_arg_area
16542   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16543                     FIN, DAG.getIntPtrConstant(4));
16544   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16545                                     getPointerTy());
16546   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16547                        MachinePointerInfo(SV, 8),
16548                        false, false, 0);
16549   MemOps.push_back(Store);
16550
16551   // Store ptr to reg_save_area.
16552   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16553                     FIN, DAG.getIntPtrConstant(8));
16554   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
16555                                     getPointerTy());
16556   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
16557                        MachinePointerInfo(SV, 16), false, false, 0);
16558   MemOps.push_back(Store);
16559   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16560 }
16561
16562 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16563   assert(Subtarget->is64Bit() &&
16564          "LowerVAARG only handles 64-bit va_arg!");
16565   assert((Subtarget->isTargetLinux() ||
16566           Subtarget->isTargetDarwin()) &&
16567           "Unhandled target in LowerVAARG");
16568   assert(Op.getNode()->getNumOperands() == 4);
16569   SDValue Chain = Op.getOperand(0);
16570   SDValue SrcPtr = Op.getOperand(1);
16571   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16572   unsigned Align = Op.getConstantOperandVal(3);
16573   SDLoc dl(Op);
16574
16575   EVT ArgVT = Op.getNode()->getValueType(0);
16576   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16577   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
16578   uint8_t ArgMode;
16579
16580   // Decide which area this value should be read from.
16581   // TODO: Implement the AMD64 ABI in its entirety. This simple
16582   // selection mechanism works only for the basic types.
16583   if (ArgVT == MVT::f80) {
16584     llvm_unreachable("va_arg for f80 not yet implemented");
16585   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16586     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16587   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16588     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16589   } else {
16590     llvm_unreachable("Unhandled argument type in LowerVAARG");
16591   }
16592
16593   if (ArgMode == 2) {
16594     // Sanity Check: Make sure using fp_offset makes sense.
16595     assert(!DAG.getTarget().Options.UseSoftFloat &&
16596            !(DAG.getMachineFunction()
16597                 .getFunction()->getAttributes()
16598                 .hasAttribute(AttributeSet::FunctionIndex,
16599                               Attribute::NoImplicitFloat)) &&
16600            Subtarget->hasSSE1());
16601   }
16602
16603   // Insert VAARG_64 node into the DAG
16604   // VAARG_64 returns two values: Variable Argument Address, Chain
16605   SmallVector<SDValue, 11> InstOps;
16606   InstOps.push_back(Chain);
16607   InstOps.push_back(SrcPtr);
16608   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
16609   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
16610   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
16611   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
16612   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16613                                           VTs, InstOps, MVT::i64,
16614                                           MachinePointerInfo(SV),
16615                                           /*Align=*/0,
16616                                           /*Volatile=*/false,
16617                                           /*ReadMem=*/true,
16618                                           /*WriteMem=*/true);
16619   Chain = VAARG.getValue(1);
16620
16621   // Load the next argument and return it
16622   return DAG.getLoad(ArgVT, dl,
16623                      Chain,
16624                      VAARG,
16625                      MachinePointerInfo(),
16626                      false, false, false, 0);
16627 }
16628
16629 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16630                            SelectionDAG &DAG) {
16631   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
16632   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16633   SDValue Chain = Op.getOperand(0);
16634   SDValue DstPtr = Op.getOperand(1);
16635   SDValue SrcPtr = Op.getOperand(2);
16636   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16637   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16638   SDLoc DL(Op);
16639
16640   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16641                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
16642                        false,
16643                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16644 }
16645
16646 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16647 // amount is a constant. Takes immediate version of shift as input.
16648 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16649                                           SDValue SrcOp, uint64_t ShiftAmt,
16650                                           SelectionDAG &DAG) {
16651   MVT ElementType = VT.getVectorElementType();
16652
16653   // Fold this packed shift into its first operand if ShiftAmt is 0.
16654   if (ShiftAmt == 0)
16655     return SrcOp;
16656
16657   // Check for ShiftAmt >= element width
16658   if (ShiftAmt >= ElementType.getSizeInBits()) {
16659     if (Opc == X86ISD::VSRAI)
16660       ShiftAmt = ElementType.getSizeInBits() - 1;
16661     else
16662       return DAG.getConstant(0, VT);
16663   }
16664
16665   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16666          && "Unknown target vector shift-by-constant node");
16667
16668   // Fold this packed vector shift into a build vector if SrcOp is a
16669   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16670   if (VT == SrcOp.getSimpleValueType() &&
16671       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16672     SmallVector<SDValue, 8> Elts;
16673     unsigned NumElts = SrcOp->getNumOperands();
16674     ConstantSDNode *ND;
16675
16676     switch(Opc) {
16677     default: llvm_unreachable(nullptr);
16678     case X86ISD::VSHLI:
16679       for (unsigned i=0; i!=NumElts; ++i) {
16680         SDValue CurrentOp = SrcOp->getOperand(i);
16681         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16682           Elts.push_back(CurrentOp);
16683           continue;
16684         }
16685         ND = cast<ConstantSDNode>(CurrentOp);
16686         const APInt &C = ND->getAPIntValue();
16687         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
16688       }
16689       break;
16690     case X86ISD::VSRLI:
16691       for (unsigned i=0; i!=NumElts; ++i) {
16692         SDValue CurrentOp = SrcOp->getOperand(i);
16693         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16694           Elts.push_back(CurrentOp);
16695           continue;
16696         }
16697         ND = cast<ConstantSDNode>(CurrentOp);
16698         const APInt &C = ND->getAPIntValue();
16699         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
16700       }
16701       break;
16702     case X86ISD::VSRAI:
16703       for (unsigned i=0; i!=NumElts; ++i) {
16704         SDValue CurrentOp = SrcOp->getOperand(i);
16705         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16706           Elts.push_back(CurrentOp);
16707           continue;
16708         }
16709         ND = cast<ConstantSDNode>(CurrentOp);
16710         const APInt &C = ND->getAPIntValue();
16711         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
16712       }
16713       break;
16714     }
16715
16716     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16717   }
16718
16719   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
16720 }
16721
16722 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16723 // may or may not be a constant. Takes immediate version of shift as input.
16724 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16725                                    SDValue SrcOp, SDValue ShAmt,
16726                                    SelectionDAG &DAG) {
16727   MVT SVT = ShAmt.getSimpleValueType();
16728   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16729
16730   // Catch shift-by-constant.
16731   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16732     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16733                                       CShAmt->getZExtValue(), DAG);
16734
16735   // Change opcode to non-immediate version
16736   switch (Opc) {
16737     default: llvm_unreachable("Unknown target vector shift node");
16738     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16739     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16740     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16741   }
16742
16743   const X86Subtarget &Subtarget =
16744       DAG.getTarget().getSubtarget<X86Subtarget>();
16745   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16746       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16747     // Let the shuffle legalizer expand this shift amount node.
16748     SDValue Op0 = ShAmt.getOperand(0);
16749     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16750     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16751   } else {
16752     // Need to build a vector containing shift amount.
16753     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16754     SmallVector<SDValue, 4> ShOps;
16755     ShOps.push_back(ShAmt);
16756     if (SVT == MVT::i32) {
16757       ShOps.push_back(DAG.getConstant(0, SVT));
16758       ShOps.push_back(DAG.getUNDEF(SVT));
16759     }
16760     ShOps.push_back(DAG.getUNDEF(SVT));
16761
16762     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16763     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16764   }
16765
16766   // The return type has to be a 128-bit type with the same element
16767   // type as the input type.
16768   MVT EltVT = VT.getVectorElementType();
16769   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16770
16771   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
16772   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16773 }
16774
16775 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16776 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16777 /// necessary casting for \p Mask when lowering masking intrinsics.
16778 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16779                                     SDValue PreservedSrc,
16780                                     const X86Subtarget *Subtarget,
16781                                     SelectionDAG &DAG) {
16782     EVT VT = Op.getValueType();
16783     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16784                                   MVT::i1, VT.getVectorNumElements());
16785     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16786                                      Mask.getValueType().getSizeInBits());
16787     SDLoc dl(Op);
16788
16789     assert(MaskVT.isSimple() && "invalid mask type");
16790
16791     if (isAllOnes(Mask))
16792       return Op;
16793
16794     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16795     // are extracted by EXTRACT_SUBVECTOR.
16796     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16797                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
16798                               DAG.getIntPtrConstant(0));
16799
16800     switch (Op.getOpcode()) {
16801       default: break;
16802       case X86ISD::PCMPEQM:
16803       case X86ISD::PCMPGTM:
16804       case X86ISD::CMPM:
16805       case X86ISD::CMPMU:
16806         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16807     }
16808     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16809       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16810     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
16811 }
16812
16813 /// \brief Creates an SDNode for a predicated scalar operation.
16814 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16815 /// The mask is comming as MVT::i8 and it should be truncated
16816 /// to MVT::i1 while lowering masking intrinsics.
16817 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16818 /// "X86select" instead of "vselect". We just can't create the "vselect" node for 
16819 /// a scalar instruction.
16820 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16821                                     SDValue PreservedSrc,
16822                                     const X86Subtarget *Subtarget,
16823                                     SelectionDAG &DAG) {
16824     if (isAllOnes(Mask))
16825       return Op;
16826
16827     EVT VT = Op.getValueType();
16828     SDLoc dl(Op);
16829     // The mask should be of type MVT::i1
16830     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16831
16832     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16833       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16834     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16835 }
16836
16837 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
16838     switch (IntNo) {
16839     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16840     case Intrinsic::x86_fma_vfmadd_ps:
16841     case Intrinsic::x86_fma_vfmadd_pd:
16842     case Intrinsic::x86_fma_vfmadd_ps_256:
16843     case Intrinsic::x86_fma_vfmadd_pd_256:
16844     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
16845     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
16846       return X86ISD::FMADD;
16847     case Intrinsic::x86_fma_vfmsub_ps:
16848     case Intrinsic::x86_fma_vfmsub_pd:
16849     case Intrinsic::x86_fma_vfmsub_ps_256:
16850     case Intrinsic::x86_fma_vfmsub_pd_256:
16851     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
16852     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
16853       return X86ISD::FMSUB;
16854     case Intrinsic::x86_fma_vfnmadd_ps:
16855     case Intrinsic::x86_fma_vfnmadd_pd:
16856     case Intrinsic::x86_fma_vfnmadd_ps_256:
16857     case Intrinsic::x86_fma_vfnmadd_pd_256:
16858     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
16859     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
16860       return X86ISD::FNMADD;
16861     case Intrinsic::x86_fma_vfnmsub_ps:
16862     case Intrinsic::x86_fma_vfnmsub_pd:
16863     case Intrinsic::x86_fma_vfnmsub_ps_256:
16864     case Intrinsic::x86_fma_vfnmsub_pd_256:
16865     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
16866     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
16867       return X86ISD::FNMSUB;
16868     case Intrinsic::x86_fma_vfmaddsub_ps:
16869     case Intrinsic::x86_fma_vfmaddsub_pd:
16870     case Intrinsic::x86_fma_vfmaddsub_ps_256:
16871     case Intrinsic::x86_fma_vfmaddsub_pd_256:
16872     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
16873     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
16874       return X86ISD::FMADDSUB;
16875     case Intrinsic::x86_fma_vfmsubadd_ps:
16876     case Intrinsic::x86_fma_vfmsubadd_pd:
16877     case Intrinsic::x86_fma_vfmsubadd_ps_256:
16878     case Intrinsic::x86_fma_vfmsubadd_pd_256:
16879     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
16880     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
16881       return X86ISD::FMSUBADD;
16882     }
16883 }
16884
16885 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16886                                        SelectionDAG &DAG) {
16887   SDLoc dl(Op);
16888   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16889   EVT VT = Op.getValueType();
16890   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16891   if (IntrData) {
16892     switch(IntrData->Type) {
16893     case INTR_TYPE_1OP:
16894       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16895     case INTR_TYPE_2OP:
16896       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16897         Op.getOperand(2));
16898     case INTR_TYPE_3OP:
16899       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16900         Op.getOperand(2), Op.getOperand(3));
16901     case INTR_TYPE_1OP_MASK_RM: {
16902       SDValue Src = Op.getOperand(1);
16903       SDValue Src0 = Op.getOperand(2);
16904       SDValue Mask = Op.getOperand(3);
16905       SDValue RoundingMode = Op.getOperand(4);
16906       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16907                                               RoundingMode),
16908                                   Mask, Src0, Subtarget, DAG);
16909     }
16910     case INTR_TYPE_SCALAR_MASK_RM: {
16911       SDValue Src1 = Op.getOperand(1);
16912       SDValue Src2 = Op.getOperand(2);
16913       SDValue Src0 = Op.getOperand(3);
16914       SDValue Mask = Op.getOperand(4);
16915       SDValue RoundingMode = Op.getOperand(5);
16916       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16917                                               RoundingMode),
16918                                   Mask, Src0, Subtarget, DAG);
16919     }
16920     case INTR_TYPE_2OP_MASK: {
16921       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Op.getOperand(1),
16922                                               Op.getOperand(2)),
16923                                   Op.getOperand(4), Op.getOperand(3), Subtarget, DAG);
16924     }
16925     case CMP_MASK:
16926     case CMP_MASK_CC: {
16927       // Comparison intrinsics with masks.
16928       // Example of transformation:
16929       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16930       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16931       // (i8 (bitcast
16932       //   (v8i1 (insert_subvector undef,
16933       //           (v2i1 (and (PCMPEQM %a, %b),
16934       //                      (extract_subvector
16935       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16936       EVT VT = Op.getOperand(1).getValueType();
16937       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16938                                     VT.getVectorNumElements());
16939       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16940       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16941                                        Mask.getValueType().getSizeInBits());
16942       SDValue Cmp;
16943       if (IntrData->Type == CMP_MASK_CC) {
16944         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16945                     Op.getOperand(2), Op.getOperand(3));
16946       } else {
16947         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16948         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16949                     Op.getOperand(2));
16950       }
16951       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16952                                              DAG.getTargetConstant(0, MaskVT),
16953                                              Subtarget, DAG);
16954       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16955                                 DAG.getUNDEF(BitcastVT), CmpMask,
16956                                 DAG.getIntPtrConstant(0));
16957       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
16958     }
16959     case COMI: { // Comparison intrinsics
16960       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16961       SDValue LHS = Op.getOperand(1);
16962       SDValue RHS = Op.getOperand(2);
16963       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
16964       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16965       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16966       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16967                                   DAG.getConstant(X86CC, MVT::i8), Cond);
16968       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16969     }
16970     case VSHIFT:
16971       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16972                                  Op.getOperand(1), Op.getOperand(2), DAG);
16973     case VSHIFT_MASK:
16974       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16975                                                       Op.getSimpleValueType(),
16976                                                       Op.getOperand(1),
16977                                                       Op.getOperand(2), DAG),
16978                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16979                                   DAG);
16980     case COMPRESS_EXPAND_IN_REG: {
16981       SDValue Mask = Op.getOperand(3);
16982       SDValue DataToCompress = Op.getOperand(1);
16983       SDValue PassThru = Op.getOperand(2);
16984       if (isAllOnes(Mask)) // return data as is
16985         return Op.getOperand(1);
16986       EVT VT = Op.getValueType();
16987       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16988                                     VT.getVectorNumElements());
16989       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16990                                        Mask.getValueType().getSizeInBits());
16991       SDLoc dl(Op);
16992       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16993                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
16994                                   DAG.getIntPtrConstant(0));
16995
16996       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
16997                          PassThru);
16998     }
16999     default:
17000       break;
17001     }
17002   }
17003
17004   switch (IntNo) {
17005   default: return SDValue();    // Don't custom lower most intrinsics.
17006
17007   case Intrinsic::x86_avx512_mask_valign_q_512:
17008   case Intrinsic::x86_avx512_mask_valign_d_512:
17009     // Vector source operands are swapped.
17010     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
17011                                             Op.getValueType(), Op.getOperand(2),
17012                                             Op.getOperand(1),
17013                                             Op.getOperand(3)),
17014                                 Op.getOperand(5), Op.getOperand(4),
17015                                 Subtarget, DAG);
17016
17017   // ptest and testp intrinsics. The intrinsic these come from are designed to
17018   // return an integer value, not just an instruction so lower it to the ptest
17019   // or testp pattern and a setcc for the result.
17020   case Intrinsic::x86_sse41_ptestz:
17021   case Intrinsic::x86_sse41_ptestc:
17022   case Intrinsic::x86_sse41_ptestnzc:
17023   case Intrinsic::x86_avx_ptestz_256:
17024   case Intrinsic::x86_avx_ptestc_256:
17025   case Intrinsic::x86_avx_ptestnzc_256:
17026   case Intrinsic::x86_avx_vtestz_ps:
17027   case Intrinsic::x86_avx_vtestc_ps:
17028   case Intrinsic::x86_avx_vtestnzc_ps:
17029   case Intrinsic::x86_avx_vtestz_pd:
17030   case Intrinsic::x86_avx_vtestc_pd:
17031   case Intrinsic::x86_avx_vtestnzc_pd:
17032   case Intrinsic::x86_avx_vtestz_ps_256:
17033   case Intrinsic::x86_avx_vtestc_ps_256:
17034   case Intrinsic::x86_avx_vtestnzc_ps_256:
17035   case Intrinsic::x86_avx_vtestz_pd_256:
17036   case Intrinsic::x86_avx_vtestc_pd_256:
17037   case Intrinsic::x86_avx_vtestnzc_pd_256: {
17038     bool IsTestPacked = false;
17039     unsigned X86CC;
17040     switch (IntNo) {
17041     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17042     case Intrinsic::x86_avx_vtestz_ps:
17043     case Intrinsic::x86_avx_vtestz_pd:
17044     case Intrinsic::x86_avx_vtestz_ps_256:
17045     case Intrinsic::x86_avx_vtestz_pd_256:
17046       IsTestPacked = true; // Fallthrough
17047     case Intrinsic::x86_sse41_ptestz:
17048     case Intrinsic::x86_avx_ptestz_256:
17049       // ZF = 1
17050       X86CC = X86::COND_E;
17051       break;
17052     case Intrinsic::x86_avx_vtestc_ps:
17053     case Intrinsic::x86_avx_vtestc_pd:
17054     case Intrinsic::x86_avx_vtestc_ps_256:
17055     case Intrinsic::x86_avx_vtestc_pd_256:
17056       IsTestPacked = true; // Fallthrough
17057     case Intrinsic::x86_sse41_ptestc:
17058     case Intrinsic::x86_avx_ptestc_256:
17059       // CF = 1
17060       X86CC = X86::COND_B;
17061       break;
17062     case Intrinsic::x86_avx_vtestnzc_ps:
17063     case Intrinsic::x86_avx_vtestnzc_pd:
17064     case Intrinsic::x86_avx_vtestnzc_ps_256:
17065     case Intrinsic::x86_avx_vtestnzc_pd_256:
17066       IsTestPacked = true; // Fallthrough
17067     case Intrinsic::x86_sse41_ptestnzc:
17068     case Intrinsic::x86_avx_ptestnzc_256:
17069       // ZF and CF = 0
17070       X86CC = X86::COND_A;
17071       break;
17072     }
17073
17074     SDValue LHS = Op.getOperand(1);
17075     SDValue RHS = Op.getOperand(2);
17076     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17077     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17078     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17079     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17080     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17081   }
17082   case Intrinsic::x86_avx512_kortestz_w:
17083   case Intrinsic::x86_avx512_kortestc_w: {
17084     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17085     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
17086     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
17087     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17088     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17089     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17090     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17091   }
17092
17093   case Intrinsic::x86_sse42_pcmpistria128:
17094   case Intrinsic::x86_sse42_pcmpestria128:
17095   case Intrinsic::x86_sse42_pcmpistric128:
17096   case Intrinsic::x86_sse42_pcmpestric128:
17097   case Intrinsic::x86_sse42_pcmpistrio128:
17098   case Intrinsic::x86_sse42_pcmpestrio128:
17099   case Intrinsic::x86_sse42_pcmpistris128:
17100   case Intrinsic::x86_sse42_pcmpestris128:
17101   case Intrinsic::x86_sse42_pcmpistriz128:
17102   case Intrinsic::x86_sse42_pcmpestriz128: {
17103     unsigned Opcode;
17104     unsigned X86CC;
17105     switch (IntNo) {
17106     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17107     case Intrinsic::x86_sse42_pcmpistria128:
17108       Opcode = X86ISD::PCMPISTRI;
17109       X86CC = X86::COND_A;
17110       break;
17111     case Intrinsic::x86_sse42_pcmpestria128:
17112       Opcode = X86ISD::PCMPESTRI;
17113       X86CC = X86::COND_A;
17114       break;
17115     case Intrinsic::x86_sse42_pcmpistric128:
17116       Opcode = X86ISD::PCMPISTRI;
17117       X86CC = X86::COND_B;
17118       break;
17119     case Intrinsic::x86_sse42_pcmpestric128:
17120       Opcode = X86ISD::PCMPESTRI;
17121       X86CC = X86::COND_B;
17122       break;
17123     case Intrinsic::x86_sse42_pcmpistrio128:
17124       Opcode = X86ISD::PCMPISTRI;
17125       X86CC = X86::COND_O;
17126       break;
17127     case Intrinsic::x86_sse42_pcmpestrio128:
17128       Opcode = X86ISD::PCMPESTRI;
17129       X86CC = X86::COND_O;
17130       break;
17131     case Intrinsic::x86_sse42_pcmpistris128:
17132       Opcode = X86ISD::PCMPISTRI;
17133       X86CC = X86::COND_S;
17134       break;
17135     case Intrinsic::x86_sse42_pcmpestris128:
17136       Opcode = X86ISD::PCMPESTRI;
17137       X86CC = X86::COND_S;
17138       break;
17139     case Intrinsic::x86_sse42_pcmpistriz128:
17140       Opcode = X86ISD::PCMPISTRI;
17141       X86CC = X86::COND_E;
17142       break;
17143     case Intrinsic::x86_sse42_pcmpestriz128:
17144       Opcode = X86ISD::PCMPESTRI;
17145       X86CC = X86::COND_E;
17146       break;
17147     }
17148     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17149     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17150     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17151     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17152                                 DAG.getConstant(X86CC, MVT::i8),
17153                                 SDValue(PCMP.getNode(), 1));
17154     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17155   }
17156
17157   case Intrinsic::x86_sse42_pcmpistri128:
17158   case Intrinsic::x86_sse42_pcmpestri128: {
17159     unsigned Opcode;
17160     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17161       Opcode = X86ISD::PCMPISTRI;
17162     else
17163       Opcode = X86ISD::PCMPESTRI;
17164
17165     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17166     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17167     return DAG.getNode(Opcode, dl, VTs, NewOps);
17168   }
17169
17170   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
17171   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
17172   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
17173   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
17174   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
17175   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
17176   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
17177   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
17178   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
17179   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
17180   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
17181   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
17182     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
17183     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
17184       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
17185                                               dl, Op.getValueType(),
17186                                               Op.getOperand(1),
17187                                               Op.getOperand(2),
17188                                               Op.getOperand(3)),
17189                                   Op.getOperand(4), Op.getOperand(1),
17190                                   Subtarget, DAG);
17191     else
17192       return SDValue();
17193   }
17194
17195   case Intrinsic::x86_fma_vfmadd_ps:
17196   case Intrinsic::x86_fma_vfmadd_pd:
17197   case Intrinsic::x86_fma_vfmsub_ps:
17198   case Intrinsic::x86_fma_vfmsub_pd:
17199   case Intrinsic::x86_fma_vfnmadd_ps:
17200   case Intrinsic::x86_fma_vfnmadd_pd:
17201   case Intrinsic::x86_fma_vfnmsub_ps:
17202   case Intrinsic::x86_fma_vfnmsub_pd:
17203   case Intrinsic::x86_fma_vfmaddsub_ps:
17204   case Intrinsic::x86_fma_vfmaddsub_pd:
17205   case Intrinsic::x86_fma_vfmsubadd_ps:
17206   case Intrinsic::x86_fma_vfmsubadd_pd:
17207   case Intrinsic::x86_fma_vfmadd_ps_256:
17208   case Intrinsic::x86_fma_vfmadd_pd_256:
17209   case Intrinsic::x86_fma_vfmsub_ps_256:
17210   case Intrinsic::x86_fma_vfmsub_pd_256:
17211   case Intrinsic::x86_fma_vfnmadd_ps_256:
17212   case Intrinsic::x86_fma_vfnmadd_pd_256:
17213   case Intrinsic::x86_fma_vfnmsub_ps_256:
17214   case Intrinsic::x86_fma_vfnmsub_pd_256:
17215   case Intrinsic::x86_fma_vfmaddsub_ps_256:
17216   case Intrinsic::x86_fma_vfmaddsub_pd_256:
17217   case Intrinsic::x86_fma_vfmsubadd_ps_256:
17218   case Intrinsic::x86_fma_vfmsubadd_pd_256:
17219     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
17220                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
17221   }
17222 }
17223
17224 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17225                               SDValue Src, SDValue Mask, SDValue Base,
17226                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17227                               const X86Subtarget * Subtarget) {
17228   SDLoc dl(Op);
17229   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17230   assert(C && "Invalid scale type");
17231   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17232   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17233                              Index.getSimpleValueType().getVectorNumElements());
17234   SDValue MaskInReg;
17235   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17236   if (MaskC)
17237     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17238   else
17239     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17240   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17241   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17242   SDValue Segment = DAG.getRegister(0, MVT::i32);
17243   if (Src.getOpcode() == ISD::UNDEF)
17244     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
17245   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17246   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17247   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17248   return DAG.getMergeValues(RetOps, dl);
17249 }
17250
17251 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17252                                SDValue Src, SDValue Mask, SDValue Base,
17253                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17254   SDLoc dl(Op);
17255   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17256   assert(C && "Invalid scale type");
17257   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17258   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17259   SDValue Segment = DAG.getRegister(0, MVT::i32);
17260   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17261                              Index.getSimpleValueType().getVectorNumElements());
17262   SDValue MaskInReg;
17263   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17264   if (MaskC)
17265     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17266   else
17267     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17268   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17269   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17270   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17271   return SDValue(Res, 1);
17272 }
17273
17274 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17275                                SDValue Mask, SDValue Base, SDValue Index,
17276                                SDValue ScaleOp, SDValue Chain) {
17277   SDLoc dl(Op);
17278   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17279   assert(C && "Invalid scale type");
17280   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17281   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17282   SDValue Segment = DAG.getRegister(0, MVT::i32);
17283   EVT MaskVT =
17284     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17285   SDValue MaskInReg;
17286   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17287   if (MaskC)
17288     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17289   else
17290     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17291   //SDVTList VTs = DAG.getVTList(MVT::Other);
17292   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17293   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17294   return SDValue(Res, 0);
17295 }
17296
17297 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17298 // read performance monitor counters (x86_rdpmc).
17299 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17300                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17301                               SmallVectorImpl<SDValue> &Results) {
17302   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17303   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17304   SDValue LO, HI;
17305
17306   // The ECX register is used to select the index of the performance counter
17307   // to read.
17308   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17309                                    N->getOperand(2));
17310   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17311
17312   // Reads the content of a 64-bit performance counter and returns it in the
17313   // registers EDX:EAX.
17314   if (Subtarget->is64Bit()) {
17315     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17316     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17317                             LO.getValue(2));
17318   } else {
17319     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17320     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17321                             LO.getValue(2));
17322   }
17323   Chain = HI.getValue(1);
17324
17325   if (Subtarget->is64Bit()) {
17326     // The EAX register is loaded with the low-order 32 bits. The EDX register
17327     // is loaded with the supported high-order bits of the counter.
17328     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17329                               DAG.getConstant(32, MVT::i8));
17330     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17331     Results.push_back(Chain);
17332     return;
17333   }
17334
17335   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17336   SDValue Ops[] = { LO, HI };
17337   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17338   Results.push_back(Pair);
17339   Results.push_back(Chain);
17340 }
17341
17342 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17343 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17344 // also used to custom lower READCYCLECOUNTER nodes.
17345 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17346                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17347                               SmallVectorImpl<SDValue> &Results) {
17348   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17349   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17350   SDValue LO, HI;
17351
17352   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17353   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17354   // and the EAX register is loaded with the low-order 32 bits.
17355   if (Subtarget->is64Bit()) {
17356     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17357     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17358                             LO.getValue(2));
17359   } else {
17360     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17361     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17362                             LO.getValue(2));
17363   }
17364   SDValue Chain = HI.getValue(1);
17365
17366   if (Opcode == X86ISD::RDTSCP_DAG) {
17367     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17368
17369     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17370     // the ECX register. Add 'ecx' explicitly to the chain.
17371     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17372                                      HI.getValue(2));
17373     // Explicitly store the content of ECX at the location passed in input
17374     // to the 'rdtscp' intrinsic.
17375     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17376                          MachinePointerInfo(), false, false, 0);
17377   }
17378
17379   if (Subtarget->is64Bit()) {
17380     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17381     // the EAX register is loaded with the low-order 32 bits.
17382     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17383                               DAG.getConstant(32, MVT::i8));
17384     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17385     Results.push_back(Chain);
17386     return;
17387   }
17388
17389   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17390   SDValue Ops[] = { LO, HI };
17391   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17392   Results.push_back(Pair);
17393   Results.push_back(Chain);
17394 }
17395
17396 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17397                                      SelectionDAG &DAG) {
17398   SmallVector<SDValue, 2> Results;
17399   SDLoc DL(Op);
17400   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17401                           Results);
17402   return DAG.getMergeValues(Results, DL);
17403 }
17404
17405
17406 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17407                                       SelectionDAG &DAG) {
17408   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17409
17410   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17411   if (!IntrData)
17412     return SDValue();
17413
17414   SDLoc dl(Op);
17415   switch(IntrData->Type) {
17416   default:
17417     llvm_unreachable("Unknown Intrinsic Type");
17418     break;
17419   case RDSEED:
17420   case RDRAND: {
17421     // Emit the node with the right value type.
17422     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17423     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17424
17425     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17426     // Otherwise return the value from Rand, which is always 0, casted to i32.
17427     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17428                       DAG.getConstant(1, Op->getValueType(1)),
17429                       DAG.getConstant(X86::COND_B, MVT::i32),
17430                       SDValue(Result.getNode(), 1) };
17431     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17432                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17433                                   Ops);
17434
17435     // Return { result, isValid, chain }.
17436     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17437                        SDValue(Result.getNode(), 2));
17438   }
17439   case GATHER: {
17440   //gather(v1, mask, index, base, scale);
17441     SDValue Chain = Op.getOperand(0);
17442     SDValue Src   = Op.getOperand(2);
17443     SDValue Base  = Op.getOperand(3);
17444     SDValue Index = Op.getOperand(4);
17445     SDValue Mask  = Op.getOperand(5);
17446     SDValue Scale = Op.getOperand(6);
17447     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
17448                           Subtarget);
17449   }
17450   case SCATTER: {
17451   //scatter(base, mask, index, v1, scale);
17452     SDValue Chain = Op.getOperand(0);
17453     SDValue Base  = Op.getOperand(2);
17454     SDValue Mask  = Op.getOperand(3);
17455     SDValue Index = Op.getOperand(4);
17456     SDValue Src   = Op.getOperand(5);
17457     SDValue Scale = Op.getOperand(6);
17458     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
17459   }
17460   case PREFETCH: {
17461     SDValue Hint = Op.getOperand(6);
17462     unsigned HintVal;
17463     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
17464         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
17465       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
17466     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17467     SDValue Chain = Op.getOperand(0);
17468     SDValue Mask  = Op.getOperand(2);
17469     SDValue Index = Op.getOperand(3);
17470     SDValue Base  = Op.getOperand(4);
17471     SDValue Scale = Op.getOperand(5);
17472     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17473   }
17474   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17475   case RDTSC: {
17476     SmallVector<SDValue, 2> Results;
17477     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
17478     return DAG.getMergeValues(Results, dl);
17479   }
17480   // Read Performance Monitoring Counters.
17481   case RDPMC: {
17482     SmallVector<SDValue, 2> Results;
17483     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17484     return DAG.getMergeValues(Results, dl);
17485   }
17486   // XTEST intrinsics.
17487   case XTEST: {
17488     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17489     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17490     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17491                                 DAG.getConstant(X86::COND_NE, MVT::i8),
17492                                 InTrans);
17493     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17494     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17495                        Ret, SDValue(InTrans.getNode(), 1));
17496   }
17497   // ADC/ADCX/SBB
17498   case ADX: {
17499     SmallVector<SDValue, 2> Results;
17500     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17501     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17502     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17503                                 DAG.getConstant(-1, MVT::i8));
17504     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17505                               Op.getOperand(4), GenCF.getValue(1));
17506     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17507                                  Op.getOperand(5), MachinePointerInfo(),
17508                                  false, false, 0);
17509     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17510                                 DAG.getConstant(X86::COND_B, MVT::i8),
17511                                 Res.getValue(1));
17512     Results.push_back(SetCC);
17513     Results.push_back(Store);
17514     return DAG.getMergeValues(Results, dl);
17515   }
17516   case COMPRESS_TO_MEM: {
17517     SDLoc dl(Op);
17518     SDValue Mask = Op.getOperand(4);
17519     SDValue DataToCompress = Op.getOperand(3);
17520     SDValue Addr = Op.getOperand(2);
17521     SDValue Chain = Op.getOperand(0);
17522
17523     if (isAllOnes(Mask)) // return just a store
17524       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17525                           MachinePointerInfo(), false, false, 0);
17526
17527     EVT VT = DataToCompress.getValueType();
17528     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17529                                   VT.getVectorNumElements());
17530     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17531                                      Mask.getValueType().getSizeInBits());
17532     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17533                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17534                                 DAG.getIntPtrConstant(0));
17535
17536     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
17537                                       DataToCompress, DAG.getUNDEF(VT));
17538     return DAG.getStore(Chain, dl, Compressed, Addr,
17539                         MachinePointerInfo(), false, false, 0);
17540   }
17541   case EXPAND_FROM_MEM: {
17542     SDLoc dl(Op);
17543     SDValue Mask = Op.getOperand(4);
17544     SDValue PathThru = Op.getOperand(3);
17545     SDValue Addr = Op.getOperand(2);
17546     SDValue Chain = Op.getOperand(0);
17547     EVT VT = Op.getValueType();
17548
17549     if (isAllOnes(Mask)) // return just a load
17550       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17551                          false, 0);
17552     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17553                                   VT.getVectorNumElements());
17554     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17555                                      Mask.getValueType().getSizeInBits());
17556     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17557                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17558                                 DAG.getIntPtrConstant(0));
17559
17560     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17561                                    false, false, false, 0);
17562
17563     SmallVector<SDValue, 2> Results;
17564     Results.push_back(DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand,
17565                                   PathThru));
17566     Results.push_back(Chain);
17567     return DAG.getMergeValues(Results, dl);
17568   }
17569   }
17570 }
17571
17572 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17573                                            SelectionDAG &DAG) const {
17574   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17575   MFI->setReturnAddressIsTaken(true);
17576
17577   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17578     return SDValue();
17579
17580   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17581   SDLoc dl(Op);
17582   EVT PtrVT = getPointerTy();
17583
17584   if (Depth > 0) {
17585     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17586     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17587         DAG.getSubtarget().getRegisterInfo());
17588     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
17589     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17590                        DAG.getNode(ISD::ADD, dl, PtrVT,
17591                                    FrameAddr, Offset),
17592                        MachinePointerInfo(), false, false, false, 0);
17593   }
17594
17595   // Just load the return address.
17596   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17597   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17598                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17599 }
17600
17601 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17602   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17603   MFI->setFrameAddressIsTaken(true);
17604
17605   EVT VT = Op.getValueType();
17606   SDLoc dl(Op);  // FIXME probably not meaningful
17607   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17608   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17609       DAG.getSubtarget().getRegisterInfo());
17610   unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(
17611       DAG.getMachineFunction());
17612   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17613           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17614          "Invalid Frame Register!");
17615   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17616   while (Depth--)
17617     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17618                             MachinePointerInfo(),
17619                             false, false, false, 0);
17620   return FrameAddr;
17621 }
17622
17623 // FIXME? Maybe this could be a TableGen attribute on some registers and
17624 // this table could be generated automatically from RegInfo.
17625 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
17626                                               EVT VT) const {
17627   unsigned Reg = StringSwitch<unsigned>(RegName)
17628                        .Case("esp", X86::ESP)
17629                        .Case("rsp", X86::RSP)
17630                        .Default(0);
17631   if (Reg)
17632     return Reg;
17633   report_fatal_error("Invalid register name global variable");
17634 }
17635
17636 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17637                                                      SelectionDAG &DAG) const {
17638   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17639       DAG.getSubtarget().getRegisterInfo());
17640   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
17641 }
17642
17643 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17644   SDValue Chain     = Op.getOperand(0);
17645   SDValue Offset    = Op.getOperand(1);
17646   SDValue Handler   = Op.getOperand(2);
17647   SDLoc dl      (Op);
17648
17649   EVT PtrVT = getPointerTy();
17650   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17651       DAG.getSubtarget().getRegisterInfo());
17652   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17653   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17654           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17655          "Invalid Frame Register!");
17656   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17657   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17658
17659   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17660                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
17661   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17662   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17663                        false, false, 0);
17664   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17665
17666   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17667                      DAG.getRegister(StoreAddrReg, PtrVT));
17668 }
17669
17670 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17671                                                SelectionDAG &DAG) const {
17672   SDLoc DL(Op);
17673   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17674                      DAG.getVTList(MVT::i32, MVT::Other),
17675                      Op.getOperand(0), Op.getOperand(1));
17676 }
17677
17678 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17679                                                 SelectionDAG &DAG) const {
17680   SDLoc DL(Op);
17681   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17682                      Op.getOperand(0), Op.getOperand(1));
17683 }
17684
17685 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17686   return Op.getOperand(0);
17687 }
17688
17689 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17690                                                 SelectionDAG &DAG) const {
17691   SDValue Root = Op.getOperand(0);
17692   SDValue Trmp = Op.getOperand(1); // trampoline
17693   SDValue FPtr = Op.getOperand(2); // nested function
17694   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17695   SDLoc dl (Op);
17696
17697   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17698   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
17699
17700   if (Subtarget->is64Bit()) {
17701     SDValue OutChains[6];
17702
17703     // Large code-model.
17704     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17705     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17706
17707     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17708     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17709
17710     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17711
17712     // Load the pointer to the nested function into R11.
17713     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17714     SDValue Addr = Trmp;
17715     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17716                                 Addr, MachinePointerInfo(TrmpAddr),
17717                                 false, false, 0);
17718
17719     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17720                        DAG.getConstant(2, MVT::i64));
17721     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17722                                 MachinePointerInfo(TrmpAddr, 2),
17723                                 false, false, 2);
17724
17725     // Load the 'nest' parameter value into R10.
17726     // R10 is specified in X86CallingConv.td
17727     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17728     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17729                        DAG.getConstant(10, MVT::i64));
17730     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17731                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17732                                 false, false, 0);
17733
17734     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17735                        DAG.getConstant(12, MVT::i64));
17736     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17737                                 MachinePointerInfo(TrmpAddr, 12),
17738                                 false, false, 2);
17739
17740     // Jump to the nested function.
17741     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17742     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17743                        DAG.getConstant(20, MVT::i64));
17744     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17745                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17746                                 false, false, 0);
17747
17748     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17749     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17750                        DAG.getConstant(22, MVT::i64));
17751     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
17752                                 MachinePointerInfo(TrmpAddr, 22),
17753                                 false, false, 0);
17754
17755     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17756   } else {
17757     const Function *Func =
17758       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17759     CallingConv::ID CC = Func->getCallingConv();
17760     unsigned NestReg;
17761
17762     switch (CC) {
17763     default:
17764       llvm_unreachable("Unsupported calling convention");
17765     case CallingConv::C:
17766     case CallingConv::X86_StdCall: {
17767       // Pass 'nest' parameter in ECX.
17768       // Must be kept in sync with X86CallingConv.td
17769       NestReg = X86::ECX;
17770
17771       // Check that ECX wasn't needed by an 'inreg' parameter.
17772       FunctionType *FTy = Func->getFunctionType();
17773       const AttributeSet &Attrs = Func->getAttributes();
17774
17775       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17776         unsigned InRegCount = 0;
17777         unsigned Idx = 1;
17778
17779         for (FunctionType::param_iterator I = FTy->param_begin(),
17780              E = FTy->param_end(); I != E; ++I, ++Idx)
17781           if (Attrs.hasAttribute(Idx, Attribute::InReg))
17782             // FIXME: should only count parameters that are lowered to integers.
17783             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
17784
17785         if (InRegCount > 2) {
17786           report_fatal_error("Nest register in use - reduce number of inreg"
17787                              " parameters!");
17788         }
17789       }
17790       break;
17791     }
17792     case CallingConv::X86_FastCall:
17793     case CallingConv::X86_ThisCall:
17794     case CallingConv::Fast:
17795       // Pass 'nest' parameter in EAX.
17796       // Must be kept in sync with X86CallingConv.td
17797       NestReg = X86::EAX;
17798       break;
17799     }
17800
17801     SDValue OutChains[4];
17802     SDValue Addr, Disp;
17803
17804     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17805                        DAG.getConstant(10, MVT::i32));
17806     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17807
17808     // This is storing the opcode for MOV32ri.
17809     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17810     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17811     OutChains[0] = DAG.getStore(Root, dl,
17812                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
17813                                 Trmp, MachinePointerInfo(TrmpAddr),
17814                                 false, false, 0);
17815
17816     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17817                        DAG.getConstant(1, MVT::i32));
17818     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17819                                 MachinePointerInfo(TrmpAddr, 1),
17820                                 false, false, 1);
17821
17822     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17823     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17824                        DAG.getConstant(5, MVT::i32));
17825     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
17826                                 MachinePointerInfo(TrmpAddr, 5),
17827                                 false, false, 1);
17828
17829     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17830                        DAG.getConstant(6, MVT::i32));
17831     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17832                                 MachinePointerInfo(TrmpAddr, 6),
17833                                 false, false, 1);
17834
17835     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17836   }
17837 }
17838
17839 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17840                                             SelectionDAG &DAG) const {
17841   /*
17842    The rounding mode is in bits 11:10 of FPSR, and has the following
17843    settings:
17844      00 Round to nearest
17845      01 Round to -inf
17846      10 Round to +inf
17847      11 Round to 0
17848
17849   FLT_ROUNDS, on the other hand, expects the following:
17850     -1 Undefined
17851      0 Round to 0
17852      1 Round to nearest
17853      2 Round to +inf
17854      3 Round to -inf
17855
17856   To perform the conversion, we do:
17857     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17858   */
17859
17860   MachineFunction &MF = DAG.getMachineFunction();
17861   const TargetMachine &TM = MF.getTarget();
17862   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
17863   unsigned StackAlignment = TFI.getStackAlignment();
17864   MVT VT = Op.getSimpleValueType();
17865   SDLoc DL(Op);
17866
17867   // Save FP Control Word to stack slot
17868   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17869   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
17870
17871   MachineMemOperand *MMO =
17872    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
17873                            MachineMemOperand::MOStore, 2, 2);
17874
17875   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17876   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17877                                           DAG.getVTList(MVT::Other),
17878                                           Ops, MVT::i16, MMO);
17879
17880   // Load FP Control Word from stack slot
17881   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17882                             MachinePointerInfo(), false, false, false, 0);
17883
17884   // Transform as necessary
17885   SDValue CWD1 =
17886     DAG.getNode(ISD::SRL, DL, MVT::i16,
17887                 DAG.getNode(ISD::AND, DL, MVT::i16,
17888                             CWD, DAG.getConstant(0x800, MVT::i16)),
17889                 DAG.getConstant(11, MVT::i8));
17890   SDValue CWD2 =
17891     DAG.getNode(ISD::SRL, DL, MVT::i16,
17892                 DAG.getNode(ISD::AND, DL, MVT::i16,
17893                             CWD, DAG.getConstant(0x400, MVT::i16)),
17894                 DAG.getConstant(9, MVT::i8));
17895
17896   SDValue RetVal =
17897     DAG.getNode(ISD::AND, DL, MVT::i16,
17898                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17899                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17900                             DAG.getConstant(1, MVT::i16)),
17901                 DAG.getConstant(3, MVT::i16));
17902
17903   return DAG.getNode((VT.getSizeInBits() < 16 ?
17904                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17905 }
17906
17907 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17908   MVT VT = Op.getSimpleValueType();
17909   EVT OpVT = VT;
17910   unsigned NumBits = VT.getSizeInBits();
17911   SDLoc dl(Op);
17912
17913   Op = Op.getOperand(0);
17914   if (VT == MVT::i8) {
17915     // Zero extend to i32 since there is not an i8 bsr.
17916     OpVT = MVT::i32;
17917     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17918   }
17919
17920   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17921   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17922   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17923
17924   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17925   SDValue Ops[] = {
17926     Op,
17927     DAG.getConstant(NumBits+NumBits-1, OpVT),
17928     DAG.getConstant(X86::COND_E, MVT::i8),
17929     Op.getValue(1)
17930   };
17931   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17932
17933   // Finally xor with NumBits-1.
17934   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17935
17936   if (VT == MVT::i8)
17937     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17938   return Op;
17939 }
17940
17941 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17942   MVT VT = Op.getSimpleValueType();
17943   EVT OpVT = VT;
17944   unsigned NumBits = VT.getSizeInBits();
17945   SDLoc dl(Op);
17946
17947   Op = Op.getOperand(0);
17948   if (VT == MVT::i8) {
17949     // Zero extend to i32 since there is not an i8 bsr.
17950     OpVT = MVT::i32;
17951     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17952   }
17953
17954   // Issue a bsr (scan bits in reverse).
17955   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17956   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17957
17958   // And xor with NumBits-1.
17959   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17960
17961   if (VT == MVT::i8)
17962     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17963   return Op;
17964 }
17965
17966 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17967   MVT VT = Op.getSimpleValueType();
17968   unsigned NumBits = VT.getSizeInBits();
17969   SDLoc dl(Op);
17970   Op = Op.getOperand(0);
17971
17972   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17973   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17974   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17975
17976   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17977   SDValue Ops[] = {
17978     Op,
17979     DAG.getConstant(NumBits, VT),
17980     DAG.getConstant(X86::COND_E, MVT::i8),
17981     Op.getValue(1)
17982   };
17983   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17984 }
17985
17986 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17987 // ones, and then concatenate the result back.
17988 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17989   MVT VT = Op.getSimpleValueType();
17990
17991   assert(VT.is256BitVector() && VT.isInteger() &&
17992          "Unsupported value type for operation");
17993
17994   unsigned NumElems = VT.getVectorNumElements();
17995   SDLoc dl(Op);
17996
17997   // Extract the LHS vectors
17998   SDValue LHS = Op.getOperand(0);
17999   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18000   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18001
18002   // Extract the RHS vectors
18003   SDValue RHS = Op.getOperand(1);
18004   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18005   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18006
18007   MVT EltVT = VT.getVectorElementType();
18008   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18009
18010   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18011                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18012                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18013 }
18014
18015 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18016   assert(Op.getSimpleValueType().is256BitVector() &&
18017          Op.getSimpleValueType().isInteger() &&
18018          "Only handle AVX 256-bit vector integer operation");
18019   return Lower256IntArith(Op, DAG);
18020 }
18021
18022 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18023   assert(Op.getSimpleValueType().is256BitVector() &&
18024          Op.getSimpleValueType().isInteger() &&
18025          "Only handle AVX 256-bit vector integer operation");
18026   return Lower256IntArith(Op, DAG);
18027 }
18028
18029 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18030                         SelectionDAG &DAG) {
18031   SDLoc dl(Op);
18032   MVT VT = Op.getSimpleValueType();
18033
18034   // Decompose 256-bit ops into smaller 128-bit ops.
18035   if (VT.is256BitVector() && !Subtarget->hasInt256())
18036     return Lower256IntArith(Op, DAG);
18037
18038   SDValue A = Op.getOperand(0);
18039   SDValue B = Op.getOperand(1);
18040
18041   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18042   if (VT == MVT::v4i32) {
18043     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18044            "Should not custom lower when pmuldq is available!");
18045
18046     // Extract the odd parts.
18047     static const int UnpackMask[] = { 1, -1, 3, -1 };
18048     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18049     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18050
18051     // Multiply the even parts.
18052     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18053     // Now multiply odd parts.
18054     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18055
18056     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
18057     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
18058
18059     // Merge the two vectors back together with a shuffle. This expands into 2
18060     // shuffles.
18061     static const int ShufMask[] = { 0, 4, 2, 6 };
18062     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18063   }
18064
18065   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18066          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18067
18068   //  Ahi = psrlqi(a, 32);
18069   //  Bhi = psrlqi(b, 32);
18070   //
18071   //  AloBlo = pmuludq(a, b);
18072   //  AloBhi = pmuludq(a, Bhi);
18073   //  AhiBlo = pmuludq(Ahi, b);
18074
18075   //  AloBhi = psllqi(AloBhi, 32);
18076   //  AhiBlo = psllqi(AhiBlo, 32);
18077   //  return AloBlo + AloBhi + AhiBlo;
18078
18079   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18080   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18081
18082   // Bit cast to 32-bit vectors for MULUDQ
18083   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18084                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18085   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
18086   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
18087   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
18088   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
18089
18090   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18091   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18092   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18093
18094   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18095   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18096
18097   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18098   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18099 }
18100
18101 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18102   assert(Subtarget->isTargetWin64() && "Unexpected target");
18103   EVT VT = Op.getValueType();
18104   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18105          "Unexpected return type for lowering");
18106
18107   RTLIB::Libcall LC;
18108   bool isSigned;
18109   switch (Op->getOpcode()) {
18110   default: llvm_unreachable("Unexpected request for libcall!");
18111   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18112   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18113   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18114   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18115   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18116   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18117   }
18118
18119   SDLoc dl(Op);
18120   SDValue InChain = DAG.getEntryNode();
18121
18122   TargetLowering::ArgListTy Args;
18123   TargetLowering::ArgListEntry Entry;
18124   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18125     EVT ArgVT = Op->getOperand(i).getValueType();
18126     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18127            "Unexpected argument type for lowering");
18128     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18129     Entry.Node = StackPtr;
18130     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18131                            false, false, 16);
18132     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18133     Entry.Ty = PointerType::get(ArgTy,0);
18134     Entry.isSExt = false;
18135     Entry.isZExt = false;
18136     Args.push_back(Entry);
18137   }
18138
18139   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18140                                          getPointerTy());
18141
18142   TargetLowering::CallLoweringInfo CLI(DAG);
18143   CLI.setDebugLoc(dl).setChain(InChain)
18144     .setCallee(getLibcallCallingConv(LC),
18145                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18146                Callee, std::move(Args), 0)
18147     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18148
18149   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18150   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
18151 }
18152
18153 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18154                              SelectionDAG &DAG) {
18155   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18156   EVT VT = Op0.getValueType();
18157   SDLoc dl(Op);
18158
18159   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18160          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18161
18162   // PMULxD operations multiply each even value (starting at 0) of LHS with
18163   // the related value of RHS and produce a widen result.
18164   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18165   // => <2 x i64> <ae|cg>
18166   //
18167   // In other word, to have all the results, we need to perform two PMULxD:
18168   // 1. one with the even values.
18169   // 2. one with the odd values.
18170   // To achieve #2, with need to place the odd values at an even position.
18171   //
18172   // Place the odd value at an even position (basically, shift all values 1
18173   // step to the left):
18174   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18175   // <a|b|c|d> => <b|undef|d|undef>
18176   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18177   // <e|f|g|h> => <f|undef|h|undef>
18178   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18179
18180   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18181   // ints.
18182   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18183   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18184   unsigned Opcode =
18185       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18186   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18187   // => <2 x i64> <ae|cg>
18188   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
18189                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18190   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18191   // => <2 x i64> <bf|dh>
18192   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
18193                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18194
18195   // Shuffle it back into the right order.
18196   SDValue Highs, Lows;
18197   if (VT == MVT::v8i32) {
18198     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18199     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18200     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18201     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18202   } else {
18203     const int HighMask[] = {1, 5, 3, 7};
18204     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18205     const int LowMask[] = {0, 4, 2, 6};
18206     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18207   }
18208
18209   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18210   // unsigned multiply.
18211   if (IsSigned && !Subtarget->hasSSE41()) {
18212     SDValue ShAmt =
18213         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
18214     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18215                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18216     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18217                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18218
18219     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18220     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18221   }
18222
18223   // The first result of MUL_LOHI is actually the low value, followed by the
18224   // high value.
18225   SDValue Ops[] = {Lows, Highs};
18226   return DAG.getMergeValues(Ops, dl);
18227 }
18228
18229 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18230                                          const X86Subtarget *Subtarget) {
18231   MVT VT = Op.getSimpleValueType();
18232   SDLoc dl(Op);
18233   SDValue R = Op.getOperand(0);
18234   SDValue Amt = Op.getOperand(1);
18235
18236   // Optimize shl/srl/sra with constant shift amount.
18237   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18238     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18239       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18240
18241       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
18242           (Subtarget->hasInt256() &&
18243            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18244           (Subtarget->hasAVX512() &&
18245            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18246         if (Op.getOpcode() == ISD::SHL)
18247           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18248                                             DAG);
18249         if (Op.getOpcode() == ISD::SRL)
18250           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18251                                             DAG);
18252         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
18253           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18254                                             DAG);
18255       }
18256
18257       if (VT == MVT::v16i8) {
18258         if (Op.getOpcode() == ISD::SHL) {
18259           // Make a large shift.
18260           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18261                                                    MVT::v8i16, R, ShiftAmt,
18262                                                    DAG);
18263           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18264           // Zero out the rightmost bits.
18265           SmallVector<SDValue, 16> V(16,
18266                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18267                                                      MVT::i8));
18268           return DAG.getNode(ISD::AND, dl, VT, SHL,
18269                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18270         }
18271         if (Op.getOpcode() == ISD::SRL) {
18272           // Make a large shift.
18273           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18274                                                    MVT::v8i16, R, ShiftAmt,
18275                                                    DAG);
18276           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18277           // Zero out the leftmost bits.
18278           SmallVector<SDValue, 16> V(16,
18279                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18280                                                      MVT::i8));
18281           return DAG.getNode(ISD::AND, dl, VT, SRL,
18282                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18283         }
18284         if (Op.getOpcode() == ISD::SRA) {
18285           if (ShiftAmt == 7) {
18286             // R s>> 7  ===  R s< 0
18287             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18288             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18289           }
18290
18291           // R s>> a === ((R u>> a) ^ m) - m
18292           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18293           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
18294                                                          MVT::i8));
18295           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18296           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18297           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18298           return Res;
18299         }
18300         llvm_unreachable("Unknown shift opcode.");
18301       }
18302
18303       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
18304         if (Op.getOpcode() == ISD::SHL) {
18305           // Make a large shift.
18306           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18307                                                    MVT::v16i16, R, ShiftAmt,
18308                                                    DAG);
18309           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18310           // Zero out the rightmost bits.
18311           SmallVector<SDValue, 32> V(32,
18312                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18313                                                      MVT::i8));
18314           return DAG.getNode(ISD::AND, dl, VT, SHL,
18315                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18316         }
18317         if (Op.getOpcode() == ISD::SRL) {
18318           // Make a large shift.
18319           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18320                                                    MVT::v16i16, R, ShiftAmt,
18321                                                    DAG);
18322           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18323           // Zero out the leftmost bits.
18324           SmallVector<SDValue, 32> V(32,
18325                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18326                                                      MVT::i8));
18327           return DAG.getNode(ISD::AND, dl, VT, SRL,
18328                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18329         }
18330         if (Op.getOpcode() == ISD::SRA) {
18331           if (ShiftAmt == 7) {
18332             // R s>> 7  ===  R s< 0
18333             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18334             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18335           }
18336
18337           // R s>> a === ((R u>> a) ^ m) - m
18338           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18339           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
18340                                                          MVT::i8));
18341           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18342           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18343           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18344           return Res;
18345         }
18346         llvm_unreachable("Unknown shift opcode.");
18347       }
18348     }
18349   }
18350
18351   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18352   if (!Subtarget->is64Bit() &&
18353       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18354       Amt.getOpcode() == ISD::BITCAST &&
18355       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18356     Amt = Amt.getOperand(0);
18357     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18358                      VT.getVectorNumElements();
18359     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18360     uint64_t ShiftAmt = 0;
18361     for (unsigned i = 0; i != Ratio; ++i) {
18362       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
18363       if (!C)
18364         return SDValue();
18365       // 6 == Log2(64)
18366       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18367     }
18368     // Check remaining shift amounts.
18369     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18370       uint64_t ShAmt = 0;
18371       for (unsigned j = 0; j != Ratio; ++j) {
18372         ConstantSDNode *C =
18373           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18374         if (!C)
18375           return SDValue();
18376         // 6 == Log2(64)
18377         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18378       }
18379       if (ShAmt != ShiftAmt)
18380         return SDValue();
18381     }
18382     switch (Op.getOpcode()) {
18383     default:
18384       llvm_unreachable("Unknown shift opcode!");
18385     case ISD::SHL:
18386       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18387                                         DAG);
18388     case ISD::SRL:
18389       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18390                                         DAG);
18391     case ISD::SRA:
18392       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18393                                         DAG);
18394     }
18395   }
18396
18397   return SDValue();
18398 }
18399
18400 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18401                                         const X86Subtarget* Subtarget) {
18402   MVT VT = Op.getSimpleValueType();
18403   SDLoc dl(Op);
18404   SDValue R = Op.getOperand(0);
18405   SDValue Amt = Op.getOperand(1);
18406
18407   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
18408       VT == MVT::v4i32 || VT == MVT::v8i16 ||
18409       (Subtarget->hasInt256() &&
18410        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
18411         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18412        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18413     SDValue BaseShAmt;
18414     EVT EltVT = VT.getVectorElementType();
18415
18416     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18417       // Check if this build_vector node is doing a splat.
18418       // If so, then set BaseShAmt equal to the splat value.
18419       BaseShAmt = BV->getSplatValue();
18420       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18421         BaseShAmt = SDValue();
18422     } else {
18423       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18424         Amt = Amt.getOperand(0);
18425
18426       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18427       if (SVN && SVN->isSplat()) {
18428         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18429         SDValue InVec = Amt.getOperand(0);
18430         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18431           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18432                  "Unexpected shuffle index found!");
18433           BaseShAmt = InVec.getOperand(SplatIdx);
18434         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18435            if (ConstantSDNode *C =
18436                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18437              if (C->getZExtValue() == SplatIdx)
18438                BaseShAmt = InVec.getOperand(1);
18439            }
18440         }
18441
18442         if (!BaseShAmt)
18443           // Avoid introducing an extract element from a shuffle.
18444           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18445                                     DAG.getIntPtrConstant(SplatIdx));
18446       }
18447     }
18448
18449     if (BaseShAmt.getNode()) {
18450       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18451       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18452         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18453       else if (EltVT.bitsLT(MVT::i32))
18454         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18455
18456       switch (Op.getOpcode()) {
18457       default:
18458         llvm_unreachable("Unknown shift opcode!");
18459       case ISD::SHL:
18460         switch (VT.SimpleTy) {
18461         default: return SDValue();
18462         case MVT::v2i64:
18463         case MVT::v4i32:
18464         case MVT::v8i16:
18465         case MVT::v4i64:
18466         case MVT::v8i32:
18467         case MVT::v16i16:
18468         case MVT::v16i32:
18469         case MVT::v8i64:
18470           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
18471         }
18472       case ISD::SRA:
18473         switch (VT.SimpleTy) {
18474         default: return SDValue();
18475         case MVT::v4i32:
18476         case MVT::v8i16:
18477         case MVT::v8i32:
18478         case MVT::v16i16:
18479         case MVT::v16i32:
18480         case MVT::v8i64:
18481           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
18482         }
18483       case ISD::SRL:
18484         switch (VT.SimpleTy) {
18485         default: return SDValue();
18486         case MVT::v2i64:
18487         case MVT::v4i32:
18488         case MVT::v8i16:
18489         case MVT::v4i64:
18490         case MVT::v8i32:
18491         case MVT::v16i16:
18492         case MVT::v16i32:
18493         case MVT::v8i64:
18494           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
18495         }
18496       }
18497     }
18498   }
18499
18500   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18501   if (!Subtarget->is64Bit() &&
18502       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
18503       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
18504       Amt.getOpcode() == ISD::BITCAST &&
18505       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18506     Amt = Amt.getOperand(0);
18507     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18508                      VT.getVectorNumElements();
18509     std::vector<SDValue> Vals(Ratio);
18510     for (unsigned i = 0; i != Ratio; ++i)
18511       Vals[i] = Amt.getOperand(i);
18512     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18513       for (unsigned j = 0; j != Ratio; ++j)
18514         if (Vals[j] != Amt.getOperand(i + j))
18515           return SDValue();
18516     }
18517     switch (Op.getOpcode()) {
18518     default:
18519       llvm_unreachable("Unknown shift opcode!");
18520     case ISD::SHL:
18521       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
18522     case ISD::SRL:
18523       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
18524     case ISD::SRA:
18525       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
18526     }
18527   }
18528
18529   return SDValue();
18530 }
18531
18532 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18533                           SelectionDAG &DAG) {
18534   MVT VT = Op.getSimpleValueType();
18535   SDLoc dl(Op);
18536   SDValue R = Op.getOperand(0);
18537   SDValue Amt = Op.getOperand(1);
18538   SDValue V;
18539
18540   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18541   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18542
18543   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
18544   if (V.getNode())
18545     return V;
18546
18547   V = LowerScalarVariableShift(Op, DAG, Subtarget);
18548   if (V.getNode())
18549       return V;
18550
18551   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
18552     return Op;
18553   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
18554   if (Subtarget->hasInt256()) {
18555     if (Op.getOpcode() == ISD::SRL &&
18556         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18557          VT == MVT::v4i64 || VT == MVT::v8i32))
18558       return Op;
18559     if (Op.getOpcode() == ISD::SHL &&
18560         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18561          VT == MVT::v4i64 || VT == MVT::v8i32))
18562       return Op;
18563     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
18564       return Op;
18565   }
18566
18567   // If possible, lower this packed shift into a vector multiply instead of
18568   // expanding it into a sequence of scalar shifts.
18569   // Do this only if the vector shift count is a constant build_vector.
18570   if (Op.getOpcode() == ISD::SHL &&
18571       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18572        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18573       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18574     SmallVector<SDValue, 8> Elts;
18575     EVT SVT = VT.getScalarType();
18576     unsigned SVTBits = SVT.getSizeInBits();
18577     const APInt &One = APInt(SVTBits, 1);
18578     unsigned NumElems = VT.getVectorNumElements();
18579
18580     for (unsigned i=0; i !=NumElems; ++i) {
18581       SDValue Op = Amt->getOperand(i);
18582       if (Op->getOpcode() == ISD::UNDEF) {
18583         Elts.push_back(Op);
18584         continue;
18585       }
18586
18587       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18588       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18589       uint64_t ShAmt = C.getZExtValue();
18590       if (ShAmt >= SVTBits) {
18591         Elts.push_back(DAG.getUNDEF(SVT));
18592         continue;
18593       }
18594       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
18595     }
18596     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18597     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18598   }
18599
18600   // Lower SHL with variable shift amount.
18601   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18602     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
18603
18604     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
18605     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
18606     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18607     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18608   }
18609
18610   // If possible, lower this shift as a sequence of two shifts by
18611   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18612   // Example:
18613   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18614   //
18615   // Could be rewritten as:
18616   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18617   //
18618   // The advantage is that the two shifts from the example would be
18619   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18620   // the vector shift into four scalar shifts plus four pairs of vector
18621   // insert/extract.
18622   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18623       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18624     unsigned TargetOpcode = X86ISD::MOVSS;
18625     bool CanBeSimplified;
18626     // The splat value for the first packed shift (the 'X' from the example).
18627     SDValue Amt1 = Amt->getOperand(0);
18628     // The splat value for the second packed shift (the 'Y' from the example).
18629     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18630                                         Amt->getOperand(2);
18631
18632     // See if it is possible to replace this node with a sequence of
18633     // two shifts followed by a MOVSS/MOVSD
18634     if (VT == MVT::v4i32) {
18635       // Check if it is legal to use a MOVSS.
18636       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18637                         Amt2 == Amt->getOperand(3);
18638       if (!CanBeSimplified) {
18639         // Otherwise, check if we can still simplify this node using a MOVSD.
18640         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18641                           Amt->getOperand(2) == Amt->getOperand(3);
18642         TargetOpcode = X86ISD::MOVSD;
18643         Amt2 = Amt->getOperand(2);
18644       }
18645     } else {
18646       // Do similar checks for the case where the machine value type
18647       // is MVT::v8i16.
18648       CanBeSimplified = Amt1 == Amt->getOperand(1);
18649       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18650         CanBeSimplified = Amt2 == Amt->getOperand(i);
18651
18652       if (!CanBeSimplified) {
18653         TargetOpcode = X86ISD::MOVSD;
18654         CanBeSimplified = true;
18655         Amt2 = Amt->getOperand(4);
18656         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18657           CanBeSimplified = Amt1 == Amt->getOperand(i);
18658         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18659           CanBeSimplified = Amt2 == Amt->getOperand(j);
18660       }
18661     }
18662
18663     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18664         isa<ConstantSDNode>(Amt2)) {
18665       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18666       EVT CastVT = MVT::v4i32;
18667       SDValue Splat1 =
18668         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
18669       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18670       SDValue Splat2 =
18671         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
18672       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18673       if (TargetOpcode == X86ISD::MOVSD)
18674         CastVT = MVT::v2i64;
18675       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
18676       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
18677       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18678                                             BitCast1, DAG);
18679       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
18680     }
18681   }
18682
18683   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
18684     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
18685
18686     // a = a << 5;
18687     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
18688     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
18689
18690     // Turn 'a' into a mask suitable for VSELECT
18691     SDValue VSelM = DAG.getConstant(0x80, VT);
18692     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18693     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18694
18695     SDValue CM1 = DAG.getConstant(0x0f, VT);
18696     SDValue CM2 = DAG.getConstant(0x3f, VT);
18697
18698     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
18699     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
18700     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
18701     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18702     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18703
18704     // a += a
18705     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18706     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18707     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18708
18709     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
18710     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
18711     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
18712     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18713     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18714
18715     // a += a
18716     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18717     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18718     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18719
18720     // return VSELECT(r, r+r, a);
18721     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
18722                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
18723     return R;
18724   }
18725
18726   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18727   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18728   // solution better.
18729   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18730     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
18731     unsigned ExtOpc =
18732         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18733     R = DAG.getNode(ExtOpc, dl, NewVT, R);
18734     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
18735     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18736                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
18737     }
18738
18739   // Decompose 256-bit shifts into smaller 128-bit shifts.
18740   if (VT.is256BitVector()) {
18741     unsigned NumElems = VT.getVectorNumElements();
18742     MVT EltVT = VT.getVectorElementType();
18743     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18744
18745     // Extract the two vectors
18746     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18747     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18748
18749     // Recreate the shift amount vectors
18750     SDValue Amt1, Amt2;
18751     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18752       // Constant shift amount
18753       SmallVector<SDValue, 4> Amt1Csts;
18754       SmallVector<SDValue, 4> Amt2Csts;
18755       for (unsigned i = 0; i != NumElems/2; ++i)
18756         Amt1Csts.push_back(Amt->getOperand(i));
18757       for (unsigned i = NumElems/2; i != NumElems; ++i)
18758         Amt2Csts.push_back(Amt->getOperand(i));
18759
18760       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18761       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18762     } else {
18763       // Variable shift amount
18764       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18765       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18766     }
18767
18768     // Issue new vector shifts for the smaller types
18769     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18770     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18771
18772     // Concatenate the result back
18773     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18774   }
18775
18776   return SDValue();
18777 }
18778
18779 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18780   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18781   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18782   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18783   // has only one use.
18784   SDNode *N = Op.getNode();
18785   SDValue LHS = N->getOperand(0);
18786   SDValue RHS = N->getOperand(1);
18787   unsigned BaseOp = 0;
18788   unsigned Cond = 0;
18789   SDLoc DL(Op);
18790   switch (Op.getOpcode()) {
18791   default: llvm_unreachable("Unknown ovf instruction!");
18792   case ISD::SADDO:
18793     // A subtract of one will be selected as a INC. Note that INC doesn't
18794     // set CF, so we can't do this for UADDO.
18795     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18796       if (C->isOne()) {
18797         BaseOp = X86ISD::INC;
18798         Cond = X86::COND_O;
18799         break;
18800       }
18801     BaseOp = X86ISD::ADD;
18802     Cond = X86::COND_O;
18803     break;
18804   case ISD::UADDO:
18805     BaseOp = X86ISD::ADD;
18806     Cond = X86::COND_B;
18807     break;
18808   case ISD::SSUBO:
18809     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18810     // set CF, so we can't do this for USUBO.
18811     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18812       if (C->isOne()) {
18813         BaseOp = X86ISD::DEC;
18814         Cond = X86::COND_O;
18815         break;
18816       }
18817     BaseOp = X86ISD::SUB;
18818     Cond = X86::COND_O;
18819     break;
18820   case ISD::USUBO:
18821     BaseOp = X86ISD::SUB;
18822     Cond = X86::COND_B;
18823     break;
18824   case ISD::SMULO:
18825     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18826     Cond = X86::COND_O;
18827     break;
18828   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18829     if (N->getValueType(0) == MVT::i8) {
18830       BaseOp = X86ISD::UMUL8;
18831       Cond = X86::COND_O;
18832       break;
18833     }
18834     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18835                                  MVT::i32);
18836     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18837
18838     SDValue SetCC =
18839       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18840                   DAG.getConstant(X86::COND_O, MVT::i32),
18841                   SDValue(Sum.getNode(), 2));
18842
18843     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18844   }
18845   }
18846
18847   // Also sets EFLAGS.
18848   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18849   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18850
18851   SDValue SetCC =
18852     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18853                 DAG.getConstant(Cond, MVT::i32),
18854                 SDValue(Sum.getNode(), 1));
18855
18856   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18857 }
18858
18859 // Sign extension of the low part of vector elements. This may be used either
18860 // when sign extend instructions are not available or if the vector element
18861 // sizes already match the sign-extended size. If the vector elements are in
18862 // their pre-extended size and sign extend instructions are available, that will
18863 // be handled by LowerSIGN_EXTEND.
18864 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
18865                                                   SelectionDAG &DAG) const {
18866   SDLoc dl(Op);
18867   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
18868   MVT VT = Op.getSimpleValueType();
18869
18870   if (!Subtarget->hasSSE2() || !VT.isVector())
18871     return SDValue();
18872
18873   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
18874                       ExtraVT.getScalarType().getSizeInBits();
18875
18876   switch (VT.SimpleTy) {
18877     default: return SDValue();
18878     case MVT::v8i32:
18879     case MVT::v16i16:
18880       if (!Subtarget->hasFp256())
18881         return SDValue();
18882       if (!Subtarget->hasInt256()) {
18883         // needs to be split
18884         unsigned NumElems = VT.getVectorNumElements();
18885
18886         // Extract the LHS vectors
18887         SDValue LHS = Op.getOperand(0);
18888         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18889         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18890
18891         MVT EltVT = VT.getVectorElementType();
18892         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18893
18894         EVT ExtraEltVT = ExtraVT.getVectorElementType();
18895         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
18896         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
18897                                    ExtraNumElems/2);
18898         SDValue Extra = DAG.getValueType(ExtraVT);
18899
18900         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
18901         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
18902
18903         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
18904       }
18905       // fall through
18906     case MVT::v4i32:
18907     case MVT::v8i16: {
18908       SDValue Op0 = Op.getOperand(0);
18909
18910       // This is a sign extension of some low part of vector elements without
18911       // changing the size of the vector elements themselves:
18912       // Shift-Left + Shift-Right-Algebraic.
18913       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
18914                                                BitsDiff, DAG);
18915       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
18916                                         DAG);
18917     }
18918   }
18919 }
18920
18921 /// Returns true if the operand type is exactly twice the native width, and
18922 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18923 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18924 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18925 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
18926   const X86Subtarget &Subtarget =
18927       getTargetMachine().getSubtarget<X86Subtarget>();
18928   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18929
18930   if (OpWidth == 64)
18931     return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18932   else if (OpWidth == 128)
18933     return Subtarget.hasCmpxchg16b();
18934   else
18935     return false;
18936 }
18937
18938 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18939   return needsCmpXchgNb(SI->getValueOperand()->getType());
18940 }
18941
18942 // Note: this turns large loads into lock cmpxchg8b/16b.
18943 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18944 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18945   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18946   return needsCmpXchgNb(PTy->getElementType());
18947 }
18948
18949 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18950   const X86Subtarget &Subtarget =
18951       getTargetMachine().getSubtarget<X86Subtarget>();
18952   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
18953   const Type *MemType = AI->getType();
18954
18955   // If the operand is too big, we must see if cmpxchg8/16b is available
18956   // and default to library calls otherwise.
18957   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18958     return needsCmpXchgNb(MemType);
18959
18960   AtomicRMWInst::BinOp Op = AI->getOperation();
18961   switch (Op) {
18962   default:
18963     llvm_unreachable("Unknown atomic operation");
18964   case AtomicRMWInst::Xchg:
18965   case AtomicRMWInst::Add:
18966   case AtomicRMWInst::Sub:
18967     // It's better to use xadd, xsub or xchg for these in all cases.
18968     return false;
18969   case AtomicRMWInst::Or:
18970   case AtomicRMWInst::And:
18971   case AtomicRMWInst::Xor:
18972     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18973     // prefix to a normal instruction for these operations.
18974     return !AI->use_empty();
18975   case AtomicRMWInst::Nand:
18976   case AtomicRMWInst::Max:
18977   case AtomicRMWInst::Min:
18978   case AtomicRMWInst::UMax:
18979   case AtomicRMWInst::UMin:
18980     // These always require a non-trivial set of data operations on x86. We must
18981     // use a cmpxchg loop.
18982     return true;
18983   }
18984 }
18985
18986 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18987   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18988   // no-sse2). There isn't any reason to disable it if the target processor
18989   // supports it.
18990   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18991 }
18992
18993 LoadInst *
18994 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18995   const X86Subtarget &Subtarget =
18996       getTargetMachine().getSubtarget<X86Subtarget>();
18997   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
18998   const Type *MemType = AI->getType();
18999   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19000   // there is no benefit in turning such RMWs into loads, and it is actually
19001   // harmful as it introduces a mfence.
19002   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19003     return nullptr;
19004
19005   auto Builder = IRBuilder<>(AI);
19006   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19007   auto SynchScope = AI->getSynchScope();
19008   // We must restrict the ordering to avoid generating loads with Release or
19009   // ReleaseAcquire orderings.
19010   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19011   auto Ptr = AI->getPointerOperand();
19012
19013   // Before the load we need a fence. Here is an example lifted from
19014   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19015   // is required:
19016   // Thread 0:
19017   //   x.store(1, relaxed);
19018   //   r1 = y.fetch_add(0, release);
19019   // Thread 1:
19020   //   y.fetch_add(42, acquire);
19021   //   r2 = x.load(relaxed);
19022   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19023   // lowered to just a load without a fence. A mfence flushes the store buffer,
19024   // making the optimization clearly correct.
19025   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19026   // otherwise, we might be able to be more agressive on relaxed idempotent
19027   // rmw. In practice, they do not look useful, so we don't try to be
19028   // especially clever.
19029   if (SynchScope == SingleThread) {
19030     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19031     // the IR level, so we must wrap it in an intrinsic.
19032     return nullptr;
19033   } else if (hasMFENCE(Subtarget)) {
19034     Function *MFence = llvm::Intrinsic::getDeclaration(M,
19035             Intrinsic::x86_sse2_mfence);
19036     Builder.CreateCall(MFence);
19037   } else {
19038     // FIXME: it might make sense to use a locked operation here but on a
19039     // different cache-line to prevent cache-line bouncing. In practice it
19040     // is probably a small win, and x86 processors without mfence are rare
19041     // enough that we do not bother.
19042     return nullptr;
19043   }
19044
19045   // Finally we can emit the atomic load.
19046   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19047           AI->getType()->getPrimitiveSizeInBits());
19048   Loaded->setAtomic(Order, SynchScope);
19049   AI->replaceAllUsesWith(Loaded);
19050   AI->eraseFromParent();
19051   return Loaded;
19052 }
19053
19054 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19055                                  SelectionDAG &DAG) {
19056   SDLoc dl(Op);
19057   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19058     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19059   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19060     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19061
19062   // The only fence that needs an instruction is a sequentially-consistent
19063   // cross-thread fence.
19064   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19065     if (hasMFENCE(*Subtarget))
19066       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19067
19068     SDValue Chain = Op.getOperand(0);
19069     SDValue Zero = DAG.getConstant(0, MVT::i32);
19070     SDValue Ops[] = {
19071       DAG.getRegister(X86::ESP, MVT::i32), // Base
19072       DAG.getTargetConstant(1, MVT::i8),   // Scale
19073       DAG.getRegister(0, MVT::i32),        // Index
19074       DAG.getTargetConstant(0, MVT::i32),  // Disp
19075       DAG.getRegister(0, MVT::i32),        // Segment.
19076       Zero,
19077       Chain
19078     };
19079     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19080     return SDValue(Res, 0);
19081   }
19082
19083   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19084   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19085 }
19086
19087 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19088                              SelectionDAG &DAG) {
19089   MVT T = Op.getSimpleValueType();
19090   SDLoc DL(Op);
19091   unsigned Reg = 0;
19092   unsigned size = 0;
19093   switch(T.SimpleTy) {
19094   default: llvm_unreachable("Invalid value type!");
19095   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19096   case MVT::i16: Reg = X86::AX;  size = 2; break;
19097   case MVT::i32: Reg = X86::EAX; size = 4; break;
19098   case MVT::i64:
19099     assert(Subtarget->is64Bit() && "Node not type legal!");
19100     Reg = X86::RAX; size = 8;
19101     break;
19102   }
19103   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19104                                   Op.getOperand(2), SDValue());
19105   SDValue Ops[] = { cpIn.getValue(0),
19106                     Op.getOperand(1),
19107                     Op.getOperand(3),
19108                     DAG.getTargetConstant(size, MVT::i8),
19109                     cpIn.getValue(1) };
19110   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19111   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19112   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19113                                            Ops, T, MMO);
19114
19115   SDValue cpOut =
19116     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19117   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19118                                       MVT::i32, cpOut.getValue(2));
19119   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19120                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19121
19122   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19123   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19124   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19125   return SDValue();
19126 }
19127
19128 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19129                             SelectionDAG &DAG) {
19130   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19131   MVT DstVT = Op.getSimpleValueType();
19132
19133   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19134     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19135     if (DstVT != MVT::f64)
19136       // This conversion needs to be expanded.
19137       return SDValue();
19138
19139     SDValue InVec = Op->getOperand(0);
19140     SDLoc dl(Op);
19141     unsigned NumElts = SrcVT.getVectorNumElements();
19142     EVT SVT = SrcVT.getVectorElementType();
19143
19144     // Widen the vector in input in the case of MVT::v2i32.
19145     // Example: from MVT::v2i32 to MVT::v4i32.
19146     SmallVector<SDValue, 16> Elts;
19147     for (unsigned i = 0, e = NumElts; i != e; ++i)
19148       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19149                                  DAG.getIntPtrConstant(i)));
19150
19151     // Explicitly mark the extra elements as Undef.
19152     SDValue Undef = DAG.getUNDEF(SVT);
19153     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
19154       Elts.push_back(Undef);
19155
19156     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19157     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19158     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
19159     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19160                        DAG.getIntPtrConstant(0));
19161   }
19162
19163   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19164          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19165   assert((DstVT == MVT::i64 ||
19166           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19167          "Unexpected custom BITCAST");
19168   // i64 <=> MMX conversions are Legal.
19169   if (SrcVT==MVT::i64 && DstVT.isVector())
19170     return Op;
19171   if (DstVT==MVT::i64 && SrcVT.isVector())
19172     return Op;
19173   // MMX <=> MMX conversions are Legal.
19174   if (SrcVT.isVector() && DstVT.isVector())
19175     return Op;
19176   // All other conversions need to be expanded.
19177   return SDValue();
19178 }
19179
19180 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19181   SDNode *Node = Op.getNode();
19182   SDLoc dl(Node);
19183   EVT T = Node->getValueType(0);
19184   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19185                               DAG.getConstant(0, T), Node->getOperand(2));
19186   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19187                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19188                        Node->getOperand(0),
19189                        Node->getOperand(1), negOp,
19190                        cast<AtomicSDNode>(Node)->getMemOperand(),
19191                        cast<AtomicSDNode>(Node)->getOrdering(),
19192                        cast<AtomicSDNode>(Node)->getSynchScope());
19193 }
19194
19195 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19196   SDNode *Node = Op.getNode();
19197   SDLoc dl(Node);
19198   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19199
19200   // Convert seq_cst store -> xchg
19201   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19202   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19203   //        (The only way to get a 16-byte store is cmpxchg16b)
19204   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19205   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19206       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19207     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19208                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19209                                  Node->getOperand(0),
19210                                  Node->getOperand(1), Node->getOperand(2),
19211                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19212                                  cast<AtomicSDNode>(Node)->getOrdering(),
19213                                  cast<AtomicSDNode>(Node)->getSynchScope());
19214     return Swap.getValue(1);
19215   }
19216   // Other atomic stores have a simple pattern.
19217   return Op;
19218 }
19219
19220 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19221   EVT VT = Op.getNode()->getSimpleValueType(0);
19222
19223   // Let legalize expand this if it isn't a legal type yet.
19224   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19225     return SDValue();
19226
19227   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19228
19229   unsigned Opc;
19230   bool ExtraOp = false;
19231   switch (Op.getOpcode()) {
19232   default: llvm_unreachable("Invalid code");
19233   case ISD::ADDC: Opc = X86ISD::ADD; break;
19234   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19235   case ISD::SUBC: Opc = X86ISD::SUB; break;
19236   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19237   }
19238
19239   if (!ExtraOp)
19240     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19241                        Op.getOperand(1));
19242   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19243                      Op.getOperand(1), Op.getOperand(2));
19244 }
19245
19246 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19247                             SelectionDAG &DAG) {
19248   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19249
19250   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19251   // which returns the values as { float, float } (in XMM0) or
19252   // { double, double } (which is returned in XMM0, XMM1).
19253   SDLoc dl(Op);
19254   SDValue Arg = Op.getOperand(0);
19255   EVT ArgVT = Arg.getValueType();
19256   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19257
19258   TargetLowering::ArgListTy Args;
19259   TargetLowering::ArgListEntry Entry;
19260
19261   Entry.Node = Arg;
19262   Entry.Ty = ArgTy;
19263   Entry.isSExt = false;
19264   Entry.isZExt = false;
19265   Args.push_back(Entry);
19266
19267   bool isF64 = ArgVT == MVT::f64;
19268   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19269   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19270   // the results are returned via SRet in memory.
19271   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19272   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19273   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
19274
19275   Type *RetTy = isF64
19276     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19277     : (Type*)VectorType::get(ArgTy, 4);
19278
19279   TargetLowering::CallLoweringInfo CLI(DAG);
19280   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19281     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19282
19283   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19284
19285   if (isF64)
19286     // Returned in xmm0 and xmm1.
19287     return CallResult.first;
19288
19289   // Returned in bits 0:31 and 32:64 xmm0.
19290   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19291                                CallResult.first, DAG.getIntPtrConstant(0));
19292   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19293                                CallResult.first, DAG.getIntPtrConstant(1));
19294   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19295   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19296 }
19297
19298 /// LowerOperation - Provide custom lowering hooks for some operations.
19299 ///
19300 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19301   switch (Op.getOpcode()) {
19302   default: llvm_unreachable("Should not custom lower this!");
19303   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
19304   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19305   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19306     return LowerCMP_SWAP(Op, Subtarget, DAG);
19307   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19308   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19309   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19310   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
19311   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
19312   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19313   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19314   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19315   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19316   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19317   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19318   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19319   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19320   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19321   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19322   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19323   case ISD::SHL_PARTS:
19324   case ISD::SRA_PARTS:
19325   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19326   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19327   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19328   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19329   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19330   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19331   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19332   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19333   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19334   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19335   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19336   case ISD::FABS:
19337   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19338   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19339   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19340   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19341   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19342   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19343   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19344   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19345   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19346   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19347   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19348   case ISD::INTRINSIC_VOID:
19349   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19350   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19351   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19352   case ISD::FRAME_TO_ARGS_OFFSET:
19353                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19354   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19355   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19356   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19357   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19358   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19359   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19360   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19361   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19362   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19363   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
19364   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19365   case ISD::UMUL_LOHI:
19366   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19367   case ISD::SRA:
19368   case ISD::SRL:
19369   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19370   case ISD::SADDO:
19371   case ISD::UADDO:
19372   case ISD::SSUBO:
19373   case ISD::USUBO:
19374   case ISD::SMULO:
19375   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19376   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19377   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19378   case ISD::ADDC:
19379   case ISD::ADDE:
19380   case ISD::SUBC:
19381   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19382   case ISD::ADD:                return LowerADD(Op, DAG);
19383   case ISD::SUB:                return LowerSUB(Op, DAG);
19384   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19385   }
19386 }
19387
19388 /// ReplaceNodeResults - Replace a node with an illegal result type
19389 /// with a new node built out of custom code.
19390 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19391                                            SmallVectorImpl<SDValue>&Results,
19392                                            SelectionDAG &DAG) const {
19393   SDLoc dl(N);
19394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19395   switch (N->getOpcode()) {
19396   default:
19397     llvm_unreachable("Do not know how to custom type legalize this operation!");
19398   case ISD::SIGN_EXTEND_INREG:
19399   case ISD::ADDC:
19400   case ISD::ADDE:
19401   case ISD::SUBC:
19402   case ISD::SUBE:
19403     // We don't want to expand or promote these.
19404     return;
19405   case ISD::SDIV:
19406   case ISD::UDIV:
19407   case ISD::SREM:
19408   case ISD::UREM:
19409   case ISD::SDIVREM:
19410   case ISD::UDIVREM: {
19411     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19412     Results.push_back(V);
19413     return;
19414   }
19415   case ISD::FP_TO_SINT:
19416   case ISD::FP_TO_UINT: {
19417     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19418
19419     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
19420       return;
19421
19422     std::pair<SDValue,SDValue> Vals =
19423         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19424     SDValue FIST = Vals.first, StackSlot = Vals.second;
19425     if (FIST.getNode()) {
19426       EVT VT = N->getValueType(0);
19427       // Return a load from the stack slot.
19428       if (StackSlot.getNode())
19429         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19430                                       MachinePointerInfo(),
19431                                       false, false, false, 0));
19432       else
19433         Results.push_back(FIST);
19434     }
19435     return;
19436   }
19437   case ISD::UINT_TO_FP: {
19438     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19439     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19440         N->getValueType(0) != MVT::v2f32)
19441       return;
19442     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19443                                  N->getOperand(0));
19444     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
19445                                      MVT::f64);
19446     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19447     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19448                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
19449     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
19450     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19451     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19452     return;
19453   }
19454   case ISD::FP_ROUND: {
19455     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19456         return;
19457     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19458     Results.push_back(V);
19459     return;
19460   }
19461   case ISD::INTRINSIC_W_CHAIN: {
19462     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19463     switch (IntNo) {
19464     default : llvm_unreachable("Do not know how to custom type "
19465                                "legalize this intrinsic operation!");
19466     case Intrinsic::x86_rdtsc:
19467       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19468                                      Results);
19469     case Intrinsic::x86_rdtscp:
19470       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19471                                      Results);
19472     case Intrinsic::x86_rdpmc:
19473       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19474     }
19475   }
19476   case ISD::READCYCLECOUNTER: {
19477     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19478                                    Results);
19479   }
19480   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19481     EVT T = N->getValueType(0);
19482     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19483     bool Regs64bit = T == MVT::i128;
19484     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19485     SDValue cpInL, cpInH;
19486     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19487                         DAG.getConstant(0, HalfT));
19488     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19489                         DAG.getConstant(1, HalfT));
19490     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19491                              Regs64bit ? X86::RAX : X86::EAX,
19492                              cpInL, SDValue());
19493     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19494                              Regs64bit ? X86::RDX : X86::EDX,
19495                              cpInH, cpInL.getValue(1));
19496     SDValue swapInL, swapInH;
19497     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19498                           DAG.getConstant(0, HalfT));
19499     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19500                           DAG.getConstant(1, HalfT));
19501     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19502                                Regs64bit ? X86::RBX : X86::EBX,
19503                                swapInL, cpInH.getValue(1));
19504     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19505                                Regs64bit ? X86::RCX : X86::ECX,
19506                                swapInH, swapInL.getValue(1));
19507     SDValue Ops[] = { swapInH.getValue(0),
19508                       N->getOperand(1),
19509                       swapInH.getValue(1) };
19510     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19511     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19512     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19513                                   X86ISD::LCMPXCHG8_DAG;
19514     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19515     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19516                                         Regs64bit ? X86::RAX : X86::EAX,
19517                                         HalfT, Result.getValue(1));
19518     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19519                                         Regs64bit ? X86::RDX : X86::EDX,
19520                                         HalfT, cpOutL.getValue(2));
19521     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19522
19523     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19524                                         MVT::i32, cpOutH.getValue(2));
19525     SDValue Success =
19526         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19527                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19528     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19529
19530     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19531     Results.push_back(Success);
19532     Results.push_back(EFLAGS.getValue(1));
19533     return;
19534   }
19535   case ISD::ATOMIC_SWAP:
19536   case ISD::ATOMIC_LOAD_ADD:
19537   case ISD::ATOMIC_LOAD_SUB:
19538   case ISD::ATOMIC_LOAD_AND:
19539   case ISD::ATOMIC_LOAD_OR:
19540   case ISD::ATOMIC_LOAD_XOR:
19541   case ISD::ATOMIC_LOAD_NAND:
19542   case ISD::ATOMIC_LOAD_MIN:
19543   case ISD::ATOMIC_LOAD_MAX:
19544   case ISD::ATOMIC_LOAD_UMIN:
19545   case ISD::ATOMIC_LOAD_UMAX:
19546   case ISD::ATOMIC_LOAD: {
19547     // Delegate to generic TypeLegalization. Situations we can really handle
19548     // should have already been dealt with by AtomicExpandPass.cpp.
19549     break;
19550   }
19551   case ISD::BITCAST: {
19552     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19553     EVT DstVT = N->getValueType(0);
19554     EVT SrcVT = N->getOperand(0)->getValueType(0);
19555
19556     if (SrcVT != MVT::f64 ||
19557         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19558       return;
19559
19560     unsigned NumElts = DstVT.getVectorNumElements();
19561     EVT SVT = DstVT.getVectorElementType();
19562     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19563     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19564                                    MVT::v2f64, N->getOperand(0));
19565     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
19566
19567     if (ExperimentalVectorWideningLegalization) {
19568       // If we are legalizing vectors by widening, we already have the desired
19569       // legal vector type, just return it.
19570       Results.push_back(ToVecInt);
19571       return;
19572     }
19573
19574     SmallVector<SDValue, 8> Elts;
19575     for (unsigned i = 0, e = NumElts; i != e; ++i)
19576       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19577                                    ToVecInt, DAG.getIntPtrConstant(i)));
19578
19579     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19580   }
19581   }
19582 }
19583
19584 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19585   switch (Opcode) {
19586   default: return nullptr;
19587   case X86ISD::BSF:                return "X86ISD::BSF";
19588   case X86ISD::BSR:                return "X86ISD::BSR";
19589   case X86ISD::SHLD:               return "X86ISD::SHLD";
19590   case X86ISD::SHRD:               return "X86ISD::SHRD";
19591   case X86ISD::FAND:               return "X86ISD::FAND";
19592   case X86ISD::FANDN:              return "X86ISD::FANDN";
19593   case X86ISD::FOR:                return "X86ISD::FOR";
19594   case X86ISD::FXOR:               return "X86ISD::FXOR";
19595   case X86ISD::FSRL:               return "X86ISD::FSRL";
19596   case X86ISD::FILD:               return "X86ISD::FILD";
19597   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19598   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19599   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19600   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19601   case X86ISD::FLD:                return "X86ISD::FLD";
19602   case X86ISD::FST:                return "X86ISD::FST";
19603   case X86ISD::CALL:               return "X86ISD::CALL";
19604   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19605   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19606   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19607   case X86ISD::BT:                 return "X86ISD::BT";
19608   case X86ISD::CMP:                return "X86ISD::CMP";
19609   case X86ISD::COMI:               return "X86ISD::COMI";
19610   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19611   case X86ISD::CMPM:               return "X86ISD::CMPM";
19612   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19613   case X86ISD::SETCC:              return "X86ISD::SETCC";
19614   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19615   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19616   case X86ISD::CMOV:               return "X86ISD::CMOV";
19617   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19618   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19619   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19620   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19621   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19622   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19623   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19624   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19625   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19626   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19627   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19628   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19629   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19630   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19631   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19632   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19633   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19634   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19635   case X86ISD::HADD:               return "X86ISD::HADD";
19636   case X86ISD::HSUB:               return "X86ISD::HSUB";
19637   case X86ISD::FHADD:              return "X86ISD::FHADD";
19638   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19639   case X86ISD::UMAX:               return "X86ISD::UMAX";
19640   case X86ISD::UMIN:               return "X86ISD::UMIN";
19641   case X86ISD::SMAX:               return "X86ISD::SMAX";
19642   case X86ISD::SMIN:               return "X86ISD::SMIN";
19643   case X86ISD::FMAX:               return "X86ISD::FMAX";
19644   case X86ISD::FMIN:               return "X86ISD::FMIN";
19645   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19646   case X86ISD::FMINC:              return "X86ISD::FMINC";
19647   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19648   case X86ISD::FRCP:               return "X86ISD::FRCP";
19649   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19650   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19651   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19652   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19653   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19654   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19655   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19656   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19657   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19658   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19659   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19660   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19661   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19662   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19663   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19664   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19665   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19666   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
19667   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19668   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19669   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19670   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19671   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19672   case X86ISD::VSHL:               return "X86ISD::VSHL";
19673   case X86ISD::VSRL:               return "X86ISD::VSRL";
19674   case X86ISD::VSRA:               return "X86ISD::VSRA";
19675   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19676   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19677   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19678   case X86ISD::CMPP:               return "X86ISD::CMPP";
19679   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19680   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19681   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19682   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19683   case X86ISD::ADD:                return "X86ISD::ADD";
19684   case X86ISD::SUB:                return "X86ISD::SUB";
19685   case X86ISD::ADC:                return "X86ISD::ADC";
19686   case X86ISD::SBB:                return "X86ISD::SBB";
19687   case X86ISD::SMUL:               return "X86ISD::SMUL";
19688   case X86ISD::UMUL:               return "X86ISD::UMUL";
19689   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19690   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19691   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19692   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19693   case X86ISD::INC:                return "X86ISD::INC";
19694   case X86ISD::DEC:                return "X86ISD::DEC";
19695   case X86ISD::OR:                 return "X86ISD::OR";
19696   case X86ISD::XOR:                return "X86ISD::XOR";
19697   case X86ISD::AND:                return "X86ISD::AND";
19698   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19699   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19700   case X86ISD::PTEST:              return "X86ISD::PTEST";
19701   case X86ISD::TESTP:              return "X86ISD::TESTP";
19702   case X86ISD::TESTM:              return "X86ISD::TESTM";
19703   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19704   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19705   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19706   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19707   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19708   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19709   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19710   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19711   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19712   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19713   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19714   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19715   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19716   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19717   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19718   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19719   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19720   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19721   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19722   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19723   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19724   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19725   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19726   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
19727   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19728   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19729   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19730   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19731   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19732   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19733   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19734   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19735   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19736   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19737   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19738   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19739   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19740   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19741   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19742   case X86ISD::SAHF:               return "X86ISD::SAHF";
19743   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19744   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19745   case X86ISD::FMADD:              return "X86ISD::FMADD";
19746   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19747   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19748   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19749   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19750   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19751   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19752   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19753   case X86ISD::XTEST:              return "X86ISD::XTEST";
19754   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19755   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19756   }
19757 }
19758
19759 // isLegalAddressingMode - Return true if the addressing mode represented
19760 // by AM is legal for this target, for a load/store of the specified type.
19761 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
19762                                               Type *Ty) const {
19763   // X86 supports extremely general addressing modes.
19764   CodeModel::Model M = getTargetMachine().getCodeModel();
19765   Reloc::Model R = getTargetMachine().getRelocationModel();
19766
19767   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19768   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19769     return false;
19770
19771   if (AM.BaseGV) {
19772     unsigned GVFlags =
19773       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19774
19775     // If a reference to this global requires an extra load, we can't fold it.
19776     if (isGlobalStubReference(GVFlags))
19777       return false;
19778
19779     // If BaseGV requires a register for the PIC base, we cannot also have a
19780     // BaseReg specified.
19781     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19782       return false;
19783
19784     // If lower 4G is not available, then we must use rip-relative addressing.
19785     if ((M != CodeModel::Small || R != Reloc::Static) &&
19786         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19787       return false;
19788   }
19789
19790   switch (AM.Scale) {
19791   case 0:
19792   case 1:
19793   case 2:
19794   case 4:
19795   case 8:
19796     // These scales always work.
19797     break;
19798   case 3:
19799   case 5:
19800   case 9:
19801     // These scales are formed with basereg+scalereg.  Only accept if there is
19802     // no basereg yet.
19803     if (AM.HasBaseReg)
19804       return false;
19805     break;
19806   default:  // Other stuff never works.
19807     return false;
19808   }
19809
19810   return true;
19811 }
19812
19813 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19814   unsigned Bits = Ty->getScalarSizeInBits();
19815
19816   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19817   // particularly cheaper than those without.
19818   if (Bits == 8)
19819     return false;
19820
19821   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19822   // variable shifts just as cheap as scalar ones.
19823   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19824     return false;
19825
19826   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19827   // fully general vector.
19828   return true;
19829 }
19830
19831 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19832   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19833     return false;
19834   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19835   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19836   return NumBits1 > NumBits2;
19837 }
19838
19839 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19840   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19841     return false;
19842
19843   if (!isTypeLegal(EVT::getEVT(Ty1)))
19844     return false;
19845
19846   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19847
19848   // Assuming the caller doesn't have a zeroext or signext return parameter,
19849   // truncation all the way down to i1 is valid.
19850   return true;
19851 }
19852
19853 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19854   return isInt<32>(Imm);
19855 }
19856
19857 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19858   // Can also use sub to handle negated immediates.
19859   return isInt<32>(Imm);
19860 }
19861
19862 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19863   if (!VT1.isInteger() || !VT2.isInteger())
19864     return false;
19865   unsigned NumBits1 = VT1.getSizeInBits();
19866   unsigned NumBits2 = VT2.getSizeInBits();
19867   return NumBits1 > NumBits2;
19868 }
19869
19870 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19871   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19872   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19873 }
19874
19875 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19876   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19877   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19878 }
19879
19880 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19881   EVT VT1 = Val.getValueType();
19882   if (isZExtFree(VT1, VT2))
19883     return true;
19884
19885   if (Val.getOpcode() != ISD::LOAD)
19886     return false;
19887
19888   if (!VT1.isSimple() || !VT1.isInteger() ||
19889       !VT2.isSimple() || !VT2.isInteger())
19890     return false;
19891
19892   switch (VT1.getSimpleVT().SimpleTy) {
19893   default: break;
19894   case MVT::i8:
19895   case MVT::i16:
19896   case MVT::i32:
19897     // X86 has 8, 16, and 32-bit zero-extending loads.
19898     return true;
19899   }
19900
19901   return false;
19902 }
19903
19904 bool
19905 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19906   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
19907     return false;
19908
19909   VT = VT.getScalarType();
19910
19911   if (!VT.isSimple())
19912     return false;
19913
19914   switch (VT.getSimpleVT().SimpleTy) {
19915   case MVT::f32:
19916   case MVT::f64:
19917     return true;
19918   default:
19919     break;
19920   }
19921
19922   return false;
19923 }
19924
19925 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19926   // i16 instructions are longer (0x66 prefix) and potentially slower.
19927   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19928 }
19929
19930 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19931 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19932 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19933 /// are assumed to be legal.
19934 bool
19935 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19936                                       EVT VT) const {
19937   if (!VT.isSimple())
19938     return false;
19939
19940   MVT SVT = VT.getSimpleVT();
19941
19942   // Very little shuffling can be done for 64-bit vectors right now.
19943   if (VT.getSizeInBits() == 64)
19944     return false;
19945
19946   // If this is a single-input shuffle with no 128 bit lane crossings we can
19947   // lower it into pshufb.
19948   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
19949       (SVT.is256BitVector() && Subtarget->hasInt256())) {
19950     bool isLegal = true;
19951     for (unsigned I = 0, E = M.size(); I != E; ++I) {
19952       if (M[I] >= (int)SVT.getVectorNumElements() ||
19953           ShuffleCrosses128bitLane(SVT, I, M[I])) {
19954         isLegal = false;
19955         break;
19956       }
19957     }
19958     if (isLegal)
19959       return true;
19960   }
19961
19962   // FIXME: blends, shifts.
19963   return (SVT.getVectorNumElements() == 2 ||
19964           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
19965           isMOVLMask(M, SVT) ||
19966           isCommutedMOVLMask(M, SVT) ||
19967           isMOVHLPSMask(M, SVT) ||
19968           isSHUFPMask(M, SVT) ||
19969           isSHUFPMask(M, SVT, /* Commuted */ true) ||
19970           isPSHUFDMask(M, SVT) ||
19971           isPSHUFDMask(M, SVT, /* SecondOperand */ true) ||
19972           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
19973           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
19974           isPALIGNRMask(M, SVT, Subtarget) ||
19975           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
19976           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
19977           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
19978           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
19979           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()) ||
19980           (Subtarget->hasSSE41() && isINSERTPSMask(M, SVT)));
19981 }
19982
19983 bool
19984 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19985                                           EVT VT) const {
19986   if (!VT.isSimple())
19987     return false;
19988
19989   MVT SVT = VT.getSimpleVT();
19990   unsigned NumElts = SVT.getVectorNumElements();
19991   // FIXME: This collection of masks seems suspect.
19992   if (NumElts == 2)
19993     return true;
19994   if (NumElts == 4 && SVT.is128BitVector()) {
19995     return (isMOVLMask(Mask, SVT)  ||
19996             isCommutedMOVLMask(Mask, SVT, true) ||
19997             isSHUFPMask(Mask, SVT) ||
19998             isSHUFPMask(Mask, SVT, /* Commuted */ true) ||
19999             isBlendMask(Mask, SVT, Subtarget->hasSSE41(),
20000                         Subtarget->hasInt256()));
20001   }
20002   return false;
20003 }
20004
20005 //===----------------------------------------------------------------------===//
20006 //                           X86 Scheduler Hooks
20007 //===----------------------------------------------------------------------===//
20008
20009 /// Utility function to emit xbegin specifying the start of an RTM region.
20010 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20011                                      const TargetInstrInfo *TII) {
20012   DebugLoc DL = MI->getDebugLoc();
20013
20014   const BasicBlock *BB = MBB->getBasicBlock();
20015   MachineFunction::iterator I = MBB;
20016   ++I;
20017
20018   // For the v = xbegin(), we generate
20019   //
20020   // thisMBB:
20021   //  xbegin sinkMBB
20022   //
20023   // mainMBB:
20024   //  eax = -1
20025   //
20026   // sinkMBB:
20027   //  v = eax
20028
20029   MachineBasicBlock *thisMBB = MBB;
20030   MachineFunction *MF = MBB->getParent();
20031   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20032   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20033   MF->insert(I, mainMBB);
20034   MF->insert(I, sinkMBB);
20035
20036   // Transfer the remainder of BB and its successor edges to sinkMBB.
20037   sinkMBB->splice(sinkMBB->begin(), MBB,
20038                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20039   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20040
20041   // thisMBB:
20042   //  xbegin sinkMBB
20043   //  # fallthrough to mainMBB
20044   //  # abortion to sinkMBB
20045   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20046   thisMBB->addSuccessor(mainMBB);
20047   thisMBB->addSuccessor(sinkMBB);
20048
20049   // mainMBB:
20050   //  EAX = -1
20051   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20052   mainMBB->addSuccessor(sinkMBB);
20053
20054   // sinkMBB:
20055   // EAX is live into the sinkMBB
20056   sinkMBB->addLiveIn(X86::EAX);
20057   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20058           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20059     .addReg(X86::EAX);
20060
20061   MI->eraseFromParent();
20062   return sinkMBB;
20063 }
20064
20065 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20066 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20067 // in the .td file.
20068 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20069                                        const TargetInstrInfo *TII) {
20070   unsigned Opc;
20071   switch (MI->getOpcode()) {
20072   default: llvm_unreachable("illegal opcode!");
20073   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20074   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20075   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20076   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20077   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20078   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20079   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20080   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20081   }
20082
20083   DebugLoc dl = MI->getDebugLoc();
20084   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20085
20086   unsigned NumArgs = MI->getNumOperands();
20087   for (unsigned i = 1; i < NumArgs; ++i) {
20088     MachineOperand &Op = MI->getOperand(i);
20089     if (!(Op.isReg() && Op.isImplicit()))
20090       MIB.addOperand(Op);
20091   }
20092   if (MI->hasOneMemOperand())
20093     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20094
20095   BuildMI(*BB, MI, dl,
20096     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20097     .addReg(X86::XMM0);
20098
20099   MI->eraseFromParent();
20100   return BB;
20101 }
20102
20103 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20104 // defs in an instruction pattern
20105 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20106                                        const TargetInstrInfo *TII) {
20107   unsigned Opc;
20108   switch (MI->getOpcode()) {
20109   default: llvm_unreachable("illegal opcode!");
20110   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20111   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20112   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20113   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20114   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20115   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20116   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20117   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20118   }
20119
20120   DebugLoc dl = MI->getDebugLoc();
20121   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20122
20123   unsigned NumArgs = MI->getNumOperands(); // remove the results
20124   for (unsigned i = 1; i < NumArgs; ++i) {
20125     MachineOperand &Op = MI->getOperand(i);
20126     if (!(Op.isReg() && Op.isImplicit()))
20127       MIB.addOperand(Op);
20128   }
20129   if (MI->hasOneMemOperand())
20130     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20131
20132   BuildMI(*BB, MI, dl,
20133     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20134     .addReg(X86::ECX);
20135
20136   MI->eraseFromParent();
20137   return BB;
20138 }
20139
20140 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20141                                        const TargetInstrInfo *TII,
20142                                        const X86Subtarget* Subtarget) {
20143   DebugLoc dl = MI->getDebugLoc();
20144
20145   // Address into RAX/EAX, other two args into ECX, EDX.
20146   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20147   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20148   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20149   for (int i = 0; i < X86::AddrNumOperands; ++i)
20150     MIB.addOperand(MI->getOperand(i));
20151
20152   unsigned ValOps = X86::AddrNumOperands;
20153   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20154     .addReg(MI->getOperand(ValOps).getReg());
20155   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20156     .addReg(MI->getOperand(ValOps+1).getReg());
20157
20158   // The instruction doesn't actually take any operands though.
20159   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20160
20161   MI->eraseFromParent(); // The pseudo is gone now.
20162   return BB;
20163 }
20164
20165 MachineBasicBlock *
20166 X86TargetLowering::EmitVAARG64WithCustomInserter(
20167                    MachineInstr *MI,
20168                    MachineBasicBlock *MBB) const {
20169   // Emit va_arg instruction on X86-64.
20170
20171   // Operands to this pseudo-instruction:
20172   // 0  ) Output        : destination address (reg)
20173   // 1-5) Input         : va_list address (addr, i64mem)
20174   // 6  ) ArgSize       : Size (in bytes) of vararg type
20175   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20176   // 8  ) Align         : Alignment of type
20177   // 9  ) EFLAGS (implicit-def)
20178
20179   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20180   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
20181
20182   unsigned DestReg = MI->getOperand(0).getReg();
20183   MachineOperand &Base = MI->getOperand(1);
20184   MachineOperand &Scale = MI->getOperand(2);
20185   MachineOperand &Index = MI->getOperand(3);
20186   MachineOperand &Disp = MI->getOperand(4);
20187   MachineOperand &Segment = MI->getOperand(5);
20188   unsigned ArgSize = MI->getOperand(6).getImm();
20189   unsigned ArgMode = MI->getOperand(7).getImm();
20190   unsigned Align = MI->getOperand(8).getImm();
20191
20192   // Memory Reference
20193   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20194   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20195   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20196
20197   // Machine Information
20198   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20199   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20200   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20201   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20202   DebugLoc DL = MI->getDebugLoc();
20203
20204   // struct va_list {
20205   //   i32   gp_offset
20206   //   i32   fp_offset
20207   //   i64   overflow_area (address)
20208   //   i64   reg_save_area (address)
20209   // }
20210   // sizeof(va_list) = 24
20211   // alignment(va_list) = 8
20212
20213   unsigned TotalNumIntRegs = 6;
20214   unsigned TotalNumXMMRegs = 8;
20215   bool UseGPOffset = (ArgMode == 1);
20216   bool UseFPOffset = (ArgMode == 2);
20217   unsigned MaxOffset = TotalNumIntRegs * 8 +
20218                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20219
20220   /* Align ArgSize to a multiple of 8 */
20221   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20222   bool NeedsAlign = (Align > 8);
20223
20224   MachineBasicBlock *thisMBB = MBB;
20225   MachineBasicBlock *overflowMBB;
20226   MachineBasicBlock *offsetMBB;
20227   MachineBasicBlock *endMBB;
20228
20229   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20230   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20231   unsigned OffsetReg = 0;
20232
20233   if (!UseGPOffset && !UseFPOffset) {
20234     // If we only pull from the overflow region, we don't create a branch.
20235     // We don't need to alter control flow.
20236     OffsetDestReg = 0; // unused
20237     OverflowDestReg = DestReg;
20238
20239     offsetMBB = nullptr;
20240     overflowMBB = thisMBB;
20241     endMBB = thisMBB;
20242   } else {
20243     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20244     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20245     // If not, pull from overflow_area. (branch to overflowMBB)
20246     //
20247     //       thisMBB
20248     //         |     .
20249     //         |        .
20250     //     offsetMBB   overflowMBB
20251     //         |        .
20252     //         |     .
20253     //        endMBB
20254
20255     // Registers for the PHI in endMBB
20256     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20257     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20258
20259     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20260     MachineFunction *MF = MBB->getParent();
20261     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20262     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20263     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20264
20265     MachineFunction::iterator MBBIter = MBB;
20266     ++MBBIter;
20267
20268     // Insert the new basic blocks
20269     MF->insert(MBBIter, offsetMBB);
20270     MF->insert(MBBIter, overflowMBB);
20271     MF->insert(MBBIter, endMBB);
20272
20273     // Transfer the remainder of MBB and its successor edges to endMBB.
20274     endMBB->splice(endMBB->begin(), thisMBB,
20275                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20276     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20277
20278     // Make offsetMBB and overflowMBB successors of thisMBB
20279     thisMBB->addSuccessor(offsetMBB);
20280     thisMBB->addSuccessor(overflowMBB);
20281
20282     // endMBB is a successor of both offsetMBB and overflowMBB
20283     offsetMBB->addSuccessor(endMBB);
20284     overflowMBB->addSuccessor(endMBB);
20285
20286     // Load the offset value into a register
20287     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20288     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20289       .addOperand(Base)
20290       .addOperand(Scale)
20291       .addOperand(Index)
20292       .addDisp(Disp, UseFPOffset ? 4 : 0)
20293       .addOperand(Segment)
20294       .setMemRefs(MMOBegin, MMOEnd);
20295
20296     // Check if there is enough room left to pull this argument.
20297     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20298       .addReg(OffsetReg)
20299       .addImm(MaxOffset + 8 - ArgSizeA8);
20300
20301     // Branch to "overflowMBB" if offset >= max
20302     // Fall through to "offsetMBB" otherwise
20303     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20304       .addMBB(overflowMBB);
20305   }
20306
20307   // In offsetMBB, emit code to use the reg_save_area.
20308   if (offsetMBB) {
20309     assert(OffsetReg != 0);
20310
20311     // Read the reg_save_area address.
20312     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20313     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20314       .addOperand(Base)
20315       .addOperand(Scale)
20316       .addOperand(Index)
20317       .addDisp(Disp, 16)
20318       .addOperand(Segment)
20319       .setMemRefs(MMOBegin, MMOEnd);
20320
20321     // Zero-extend the offset
20322     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20323       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20324         .addImm(0)
20325         .addReg(OffsetReg)
20326         .addImm(X86::sub_32bit);
20327
20328     // Add the offset to the reg_save_area to get the final address.
20329     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20330       .addReg(OffsetReg64)
20331       .addReg(RegSaveReg);
20332
20333     // Compute the offset for the next argument
20334     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20335     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20336       .addReg(OffsetReg)
20337       .addImm(UseFPOffset ? 16 : 8);
20338
20339     // Store it back into the va_list.
20340     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20341       .addOperand(Base)
20342       .addOperand(Scale)
20343       .addOperand(Index)
20344       .addDisp(Disp, UseFPOffset ? 4 : 0)
20345       .addOperand(Segment)
20346       .addReg(NextOffsetReg)
20347       .setMemRefs(MMOBegin, MMOEnd);
20348
20349     // Jump to endMBB
20350     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
20351       .addMBB(endMBB);
20352   }
20353
20354   //
20355   // Emit code to use overflow area
20356   //
20357
20358   // Load the overflow_area address into a register.
20359   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20360   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20361     .addOperand(Base)
20362     .addOperand(Scale)
20363     .addOperand(Index)
20364     .addDisp(Disp, 8)
20365     .addOperand(Segment)
20366     .setMemRefs(MMOBegin, MMOEnd);
20367
20368   // If we need to align it, do so. Otherwise, just copy the address
20369   // to OverflowDestReg.
20370   if (NeedsAlign) {
20371     // Align the overflow address
20372     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20373     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20374
20375     // aligned_addr = (addr + (align-1)) & ~(align-1)
20376     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20377       .addReg(OverflowAddrReg)
20378       .addImm(Align-1);
20379
20380     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20381       .addReg(TmpReg)
20382       .addImm(~(uint64_t)(Align-1));
20383   } else {
20384     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20385       .addReg(OverflowAddrReg);
20386   }
20387
20388   // Compute the next overflow address after this argument.
20389   // (the overflow address should be kept 8-byte aligned)
20390   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20391   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20392     .addReg(OverflowDestReg)
20393     .addImm(ArgSizeA8);
20394
20395   // Store the new overflow address.
20396   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20397     .addOperand(Base)
20398     .addOperand(Scale)
20399     .addOperand(Index)
20400     .addDisp(Disp, 8)
20401     .addOperand(Segment)
20402     .addReg(NextAddrReg)
20403     .setMemRefs(MMOBegin, MMOEnd);
20404
20405   // If we branched, emit the PHI to the front of endMBB.
20406   if (offsetMBB) {
20407     BuildMI(*endMBB, endMBB->begin(), DL,
20408             TII->get(X86::PHI), DestReg)
20409       .addReg(OffsetDestReg).addMBB(offsetMBB)
20410       .addReg(OverflowDestReg).addMBB(overflowMBB);
20411   }
20412
20413   // Erase the pseudo instruction
20414   MI->eraseFromParent();
20415
20416   return endMBB;
20417 }
20418
20419 MachineBasicBlock *
20420 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20421                                                  MachineInstr *MI,
20422                                                  MachineBasicBlock *MBB) const {
20423   // Emit code to save XMM registers to the stack. The ABI says that the
20424   // number of registers to save is given in %al, so it's theoretically
20425   // possible to do an indirect jump trick to avoid saving all of them,
20426   // however this code takes a simpler approach and just executes all
20427   // of the stores if %al is non-zero. It's less code, and it's probably
20428   // easier on the hardware branch predictor, and stores aren't all that
20429   // expensive anyway.
20430
20431   // Create the new basic blocks. One block contains all the XMM stores,
20432   // and one block is the final destination regardless of whether any
20433   // stores were performed.
20434   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20435   MachineFunction *F = MBB->getParent();
20436   MachineFunction::iterator MBBIter = MBB;
20437   ++MBBIter;
20438   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20439   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20440   F->insert(MBBIter, XMMSaveMBB);
20441   F->insert(MBBIter, EndMBB);
20442
20443   // Transfer the remainder of MBB and its successor edges to EndMBB.
20444   EndMBB->splice(EndMBB->begin(), MBB,
20445                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20446   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20447
20448   // The original block will now fall through to the XMM save block.
20449   MBB->addSuccessor(XMMSaveMBB);
20450   // The XMMSaveMBB will fall through to the end block.
20451   XMMSaveMBB->addSuccessor(EndMBB);
20452
20453   // Now add the instructions.
20454   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20455   DebugLoc DL = MI->getDebugLoc();
20456
20457   unsigned CountReg = MI->getOperand(0).getReg();
20458   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20459   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20460
20461   if (!Subtarget->isTargetWin64()) {
20462     // If %al is 0, branch around the XMM save block.
20463     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20464     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
20465     MBB->addSuccessor(EndMBB);
20466   }
20467
20468   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20469   // that was just emitted, but clearly shouldn't be "saved".
20470   assert((MI->getNumOperands() <= 3 ||
20471           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20472           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20473          && "Expected last argument to be EFLAGS");
20474   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20475   // In the XMM save block, save all the XMM argument registers.
20476   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20477     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20478     MachineMemOperand *MMO =
20479       F->getMachineMemOperand(
20480           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
20481         MachineMemOperand::MOStore,
20482         /*Size=*/16, /*Align=*/16);
20483     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20484       .addFrameIndex(RegSaveFrameIndex)
20485       .addImm(/*Scale=*/1)
20486       .addReg(/*IndexReg=*/0)
20487       .addImm(/*Disp=*/Offset)
20488       .addReg(/*Segment=*/0)
20489       .addReg(MI->getOperand(i).getReg())
20490       .addMemOperand(MMO);
20491   }
20492
20493   MI->eraseFromParent();   // The pseudo instruction is gone now.
20494
20495   return EndMBB;
20496 }
20497
20498 // The EFLAGS operand of SelectItr might be missing a kill marker
20499 // because there were multiple uses of EFLAGS, and ISel didn't know
20500 // which to mark. Figure out whether SelectItr should have had a
20501 // kill marker, and set it if it should. Returns the correct kill
20502 // marker value.
20503 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20504                                      MachineBasicBlock* BB,
20505                                      const TargetRegisterInfo* TRI) {
20506   // Scan forward through BB for a use/def of EFLAGS.
20507   MachineBasicBlock::iterator miI(std::next(SelectItr));
20508   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20509     const MachineInstr& mi = *miI;
20510     if (mi.readsRegister(X86::EFLAGS))
20511       return false;
20512     if (mi.definesRegister(X86::EFLAGS))
20513       break; // Should have kill-flag - update below.
20514   }
20515
20516   // If we hit the end of the block, check whether EFLAGS is live into a
20517   // successor.
20518   if (miI == BB->end()) {
20519     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20520                                           sEnd = BB->succ_end();
20521          sItr != sEnd; ++sItr) {
20522       MachineBasicBlock* succ = *sItr;
20523       if (succ->isLiveIn(X86::EFLAGS))
20524         return false;
20525     }
20526   }
20527
20528   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20529   // out. SelectMI should have a kill flag on EFLAGS.
20530   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20531   return true;
20532 }
20533
20534 MachineBasicBlock *
20535 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20536                                      MachineBasicBlock *BB) const {
20537   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20538   DebugLoc DL = MI->getDebugLoc();
20539
20540   // To "insert" a SELECT_CC instruction, we actually have to insert the
20541   // diamond control-flow pattern.  The incoming instruction knows the
20542   // destination vreg to set, the condition code register to branch on, the
20543   // true/false values to select between, and a branch opcode to use.
20544   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20545   MachineFunction::iterator It = BB;
20546   ++It;
20547
20548   //  thisMBB:
20549   //  ...
20550   //   TrueVal = ...
20551   //   cmpTY ccX, r1, r2
20552   //   bCC copy1MBB
20553   //   fallthrough --> copy0MBB
20554   MachineBasicBlock *thisMBB = BB;
20555   MachineFunction *F = BB->getParent();
20556   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20557   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20558   F->insert(It, copy0MBB);
20559   F->insert(It, sinkMBB);
20560
20561   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20562   // live into the sink and copy blocks.
20563   const TargetRegisterInfo *TRI =
20564       BB->getParent()->getSubtarget().getRegisterInfo();
20565   if (!MI->killsRegister(X86::EFLAGS) &&
20566       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
20567     copy0MBB->addLiveIn(X86::EFLAGS);
20568     sinkMBB->addLiveIn(X86::EFLAGS);
20569   }
20570
20571   // Transfer the remainder of BB and its successor edges to sinkMBB.
20572   sinkMBB->splice(sinkMBB->begin(), BB,
20573                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
20574   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20575
20576   // Add the true and fallthrough blocks as its successors.
20577   BB->addSuccessor(copy0MBB);
20578   BB->addSuccessor(sinkMBB);
20579
20580   // Create the conditional branch instruction.
20581   unsigned Opc =
20582     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20583   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20584
20585   //  copy0MBB:
20586   //   %FalseValue = ...
20587   //   # fallthrough to sinkMBB
20588   copy0MBB->addSuccessor(sinkMBB);
20589
20590   //  sinkMBB:
20591   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20592   //  ...
20593   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20594           TII->get(X86::PHI), MI->getOperand(0).getReg())
20595     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20596     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20597
20598   MI->eraseFromParent();   // The pseudo instruction is gone now.
20599   return sinkMBB;
20600 }
20601
20602 MachineBasicBlock *
20603 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20604                                         MachineBasicBlock *BB) const {
20605   MachineFunction *MF = BB->getParent();
20606   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20607   DebugLoc DL = MI->getDebugLoc();
20608   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20609
20610   assert(MF->shouldSplitStack());
20611
20612   const bool Is64Bit = Subtarget->is64Bit();
20613   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20614
20615   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20616   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20617
20618   // BB:
20619   //  ... [Till the alloca]
20620   // If stacklet is not large enough, jump to mallocMBB
20621   //
20622   // bumpMBB:
20623   //  Allocate by subtracting from RSP
20624   //  Jump to continueMBB
20625   //
20626   // mallocMBB:
20627   //  Allocate by call to runtime
20628   //
20629   // continueMBB:
20630   //  ...
20631   //  [rest of original BB]
20632   //
20633
20634   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20635   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20636   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20637
20638   MachineRegisterInfo &MRI = MF->getRegInfo();
20639   const TargetRegisterClass *AddrRegClass =
20640     getRegClassFor(getPointerTy());
20641
20642   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20643     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20644     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20645     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20646     sizeVReg = MI->getOperand(1).getReg(),
20647     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20648
20649   MachineFunction::iterator MBBIter = BB;
20650   ++MBBIter;
20651
20652   MF->insert(MBBIter, bumpMBB);
20653   MF->insert(MBBIter, mallocMBB);
20654   MF->insert(MBBIter, continueMBB);
20655
20656   continueMBB->splice(continueMBB->begin(), BB,
20657                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20658   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20659
20660   // Add code to the main basic block to check if the stack limit has been hit,
20661   // and if so, jump to mallocMBB otherwise to bumpMBB.
20662   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20663   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20664     .addReg(tmpSPVReg).addReg(sizeVReg);
20665   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20666     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20667     .addReg(SPLimitVReg);
20668   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
20669
20670   // bumpMBB simply decreases the stack pointer, since we know the current
20671   // stacklet has enough space.
20672   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20673     .addReg(SPLimitVReg);
20674   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20675     .addReg(SPLimitVReg);
20676   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20677
20678   // Calls into a routine in libgcc to allocate more space from the heap.
20679   const uint32_t *RegMask = MF->getTarget()
20680                                 .getSubtargetImpl()
20681                                 ->getRegisterInfo()
20682                                 ->getCallPreservedMask(CallingConv::C);
20683   if (IsLP64) {
20684     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20685       .addReg(sizeVReg);
20686     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20687       .addExternalSymbol("__morestack_allocate_stack_space")
20688       .addRegMask(RegMask)
20689       .addReg(X86::RDI, RegState::Implicit)
20690       .addReg(X86::RAX, RegState::ImplicitDefine);
20691   } else if (Is64Bit) {
20692     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20693       .addReg(sizeVReg);
20694     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20695       .addExternalSymbol("__morestack_allocate_stack_space")
20696       .addRegMask(RegMask)
20697       .addReg(X86::EDI, RegState::Implicit)
20698       .addReg(X86::EAX, RegState::ImplicitDefine);
20699   } else {
20700     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20701       .addImm(12);
20702     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20703     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20704       .addExternalSymbol("__morestack_allocate_stack_space")
20705       .addRegMask(RegMask)
20706       .addReg(X86::EAX, RegState::ImplicitDefine);
20707   }
20708
20709   if (!Is64Bit)
20710     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20711       .addImm(16);
20712
20713   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20714     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20715   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20716
20717   // Set up the CFG correctly.
20718   BB->addSuccessor(bumpMBB);
20719   BB->addSuccessor(mallocMBB);
20720   mallocMBB->addSuccessor(continueMBB);
20721   bumpMBB->addSuccessor(continueMBB);
20722
20723   // Take care of the PHI nodes.
20724   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20725           MI->getOperand(0).getReg())
20726     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20727     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20728
20729   // Delete the original pseudo instruction.
20730   MI->eraseFromParent();
20731
20732   // And we're done.
20733   return continueMBB;
20734 }
20735
20736 MachineBasicBlock *
20737 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20738                                         MachineBasicBlock *BB) const {
20739   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20740   DebugLoc DL = MI->getDebugLoc();
20741
20742   assert(!Subtarget->isTargetMachO());
20743
20744   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
20745   // non-trivial part is impdef of ESP.
20746
20747   if (Subtarget->isTargetWin64()) {
20748     if (Subtarget->isTargetCygMing()) {
20749       // ___chkstk(Mingw64):
20750       // Clobbers R10, R11, RAX and EFLAGS.
20751       // Updates RSP.
20752       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20753         .addExternalSymbol("___chkstk")
20754         .addReg(X86::RAX, RegState::Implicit)
20755         .addReg(X86::RSP, RegState::Implicit)
20756         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
20757         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
20758         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20759     } else {
20760       // __chkstk(MSVCRT): does not update stack pointer.
20761       // Clobbers R10, R11 and EFLAGS.
20762       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20763         .addExternalSymbol("__chkstk")
20764         .addReg(X86::RAX, RegState::Implicit)
20765         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20766       // RAX has the offset to be subtracted from RSP.
20767       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
20768         .addReg(X86::RSP)
20769         .addReg(X86::RAX);
20770     }
20771   } else {
20772     const char *StackProbeSymbol = (Subtarget->isTargetKnownWindowsMSVC() ||
20773                                     Subtarget->isTargetWindowsItanium())
20774                                        ? "_chkstk"
20775                                        : "_alloca";
20776
20777     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
20778       .addExternalSymbol(StackProbeSymbol)
20779       .addReg(X86::EAX, RegState::Implicit)
20780       .addReg(X86::ESP, RegState::Implicit)
20781       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
20782       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
20783       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20784   }
20785
20786   MI->eraseFromParent();   // The pseudo instruction is gone now.
20787   return BB;
20788 }
20789
20790 MachineBasicBlock *
20791 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20792                                       MachineBasicBlock *BB) const {
20793   // This is pretty easy.  We're taking the value that we received from
20794   // our load from the relocation, sticking it in either RDI (x86-64)
20795   // or EAX and doing an indirect call.  The return value will then
20796   // be in the normal return register.
20797   MachineFunction *F = BB->getParent();
20798   const X86InstrInfo *TII =
20799       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
20800   DebugLoc DL = MI->getDebugLoc();
20801
20802   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20803   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20804
20805   // Get a register mask for the lowered call.
20806   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20807   // proper register mask.
20808   const uint32_t *RegMask = F->getTarget()
20809                                 .getSubtargetImpl()
20810                                 ->getRegisterInfo()
20811                                 ->getCallPreservedMask(CallingConv::C);
20812   if (Subtarget->is64Bit()) {
20813     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20814                                       TII->get(X86::MOV64rm), X86::RDI)
20815     .addReg(X86::RIP)
20816     .addImm(0).addReg(0)
20817     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20818                       MI->getOperand(3).getTargetFlags())
20819     .addReg(0);
20820     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20821     addDirectMem(MIB, X86::RDI);
20822     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20823   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20824     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20825                                       TII->get(X86::MOV32rm), X86::EAX)
20826     .addReg(0)
20827     .addImm(0).addReg(0)
20828     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20829                       MI->getOperand(3).getTargetFlags())
20830     .addReg(0);
20831     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20832     addDirectMem(MIB, X86::EAX);
20833     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20834   } else {
20835     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20836                                       TII->get(X86::MOV32rm), X86::EAX)
20837     .addReg(TII->getGlobalBaseReg(F))
20838     .addImm(0).addReg(0)
20839     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20840                       MI->getOperand(3).getTargetFlags())
20841     .addReg(0);
20842     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20843     addDirectMem(MIB, X86::EAX);
20844     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20845   }
20846
20847   MI->eraseFromParent(); // The pseudo instruction is gone now.
20848   return BB;
20849 }
20850
20851 MachineBasicBlock *
20852 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20853                                     MachineBasicBlock *MBB) const {
20854   DebugLoc DL = MI->getDebugLoc();
20855   MachineFunction *MF = MBB->getParent();
20856   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20857   MachineRegisterInfo &MRI = MF->getRegInfo();
20858
20859   const BasicBlock *BB = MBB->getBasicBlock();
20860   MachineFunction::iterator I = MBB;
20861   ++I;
20862
20863   // Memory Reference
20864   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20865   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20866
20867   unsigned DstReg;
20868   unsigned MemOpndSlot = 0;
20869
20870   unsigned CurOp = 0;
20871
20872   DstReg = MI->getOperand(CurOp++).getReg();
20873   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20874   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20875   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20876   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20877
20878   MemOpndSlot = CurOp;
20879
20880   MVT PVT = getPointerTy();
20881   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20882          "Invalid Pointer Size!");
20883
20884   // For v = setjmp(buf), we generate
20885   //
20886   // thisMBB:
20887   //  buf[LabelOffset] = restoreMBB
20888   //  SjLjSetup restoreMBB
20889   //
20890   // mainMBB:
20891   //  v_main = 0
20892   //
20893   // sinkMBB:
20894   //  v = phi(main, restore)
20895   //
20896   // restoreMBB:
20897   //  if base pointer being used, load it from frame
20898   //  v_restore = 1
20899
20900   MachineBasicBlock *thisMBB = MBB;
20901   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20902   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20903   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20904   MF->insert(I, mainMBB);
20905   MF->insert(I, sinkMBB);
20906   MF->push_back(restoreMBB);
20907
20908   MachineInstrBuilder MIB;
20909
20910   // Transfer the remainder of BB and its successor edges to sinkMBB.
20911   sinkMBB->splice(sinkMBB->begin(), MBB,
20912                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20913   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20914
20915   // thisMBB:
20916   unsigned PtrStoreOpc = 0;
20917   unsigned LabelReg = 0;
20918   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20919   Reloc::Model RM = MF->getTarget().getRelocationModel();
20920   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20921                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20922
20923   // Prepare IP either in reg or imm.
20924   if (!UseImmLabel) {
20925     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20926     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20927     LabelReg = MRI.createVirtualRegister(PtrRC);
20928     if (Subtarget->is64Bit()) {
20929       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20930               .addReg(X86::RIP)
20931               .addImm(0)
20932               .addReg(0)
20933               .addMBB(restoreMBB)
20934               .addReg(0);
20935     } else {
20936       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20937       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20938               .addReg(XII->getGlobalBaseReg(MF))
20939               .addImm(0)
20940               .addReg(0)
20941               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20942               .addReg(0);
20943     }
20944   } else
20945     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20946   // Store IP
20947   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20948   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20949     if (i == X86::AddrDisp)
20950       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20951     else
20952       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20953   }
20954   if (!UseImmLabel)
20955     MIB.addReg(LabelReg);
20956   else
20957     MIB.addMBB(restoreMBB);
20958   MIB.setMemRefs(MMOBegin, MMOEnd);
20959   // Setup
20960   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20961           .addMBB(restoreMBB);
20962
20963   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
20964       MF->getSubtarget().getRegisterInfo());
20965   MIB.addRegMask(RegInfo->getNoPreservedMask());
20966   thisMBB->addSuccessor(mainMBB);
20967   thisMBB->addSuccessor(restoreMBB);
20968
20969   // mainMBB:
20970   //  EAX = 0
20971   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20972   mainMBB->addSuccessor(sinkMBB);
20973
20974   // sinkMBB:
20975   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20976           TII->get(X86::PHI), DstReg)
20977     .addReg(mainDstReg).addMBB(mainMBB)
20978     .addReg(restoreDstReg).addMBB(restoreMBB);
20979
20980   // restoreMBB:
20981   if (RegInfo->hasBasePointer(*MF)) {
20982     const X86Subtarget &STI = MF->getTarget().getSubtarget<X86Subtarget>();
20983     const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
20984     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20985     X86FI->setRestoreBasePointer(MF);
20986     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20987     unsigned BasePtr = RegInfo->getBaseRegister();
20988     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20989     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20990                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20991       .setMIFlag(MachineInstr::FrameSetup);
20992   }
20993   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20994   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
20995   restoreMBB->addSuccessor(sinkMBB);
20996
20997   MI->eraseFromParent();
20998   return sinkMBB;
20999 }
21000
21001 MachineBasicBlock *
21002 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21003                                      MachineBasicBlock *MBB) const {
21004   DebugLoc DL = MI->getDebugLoc();
21005   MachineFunction *MF = MBB->getParent();
21006   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
21007   MachineRegisterInfo &MRI = MF->getRegInfo();
21008
21009   // Memory Reference
21010   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21011   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21012
21013   MVT PVT = getPointerTy();
21014   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21015          "Invalid Pointer Size!");
21016
21017   const TargetRegisterClass *RC =
21018     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21019   unsigned Tmp = MRI.createVirtualRegister(RC);
21020   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21021   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
21022       MF->getSubtarget().getRegisterInfo());
21023   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21024   unsigned SP = RegInfo->getStackRegister();
21025
21026   MachineInstrBuilder MIB;
21027
21028   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21029   const int64_t SPOffset = 2 * PVT.getStoreSize();
21030
21031   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21032   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21033
21034   // Reload FP
21035   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21036   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21037     MIB.addOperand(MI->getOperand(i));
21038   MIB.setMemRefs(MMOBegin, MMOEnd);
21039   // Reload IP
21040   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21041   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21042     if (i == X86::AddrDisp)
21043       MIB.addDisp(MI->getOperand(i), LabelOffset);
21044     else
21045       MIB.addOperand(MI->getOperand(i));
21046   }
21047   MIB.setMemRefs(MMOBegin, MMOEnd);
21048   // Reload SP
21049   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21050   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21051     if (i == X86::AddrDisp)
21052       MIB.addDisp(MI->getOperand(i), SPOffset);
21053     else
21054       MIB.addOperand(MI->getOperand(i));
21055   }
21056   MIB.setMemRefs(MMOBegin, MMOEnd);
21057   // Jump
21058   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21059
21060   MI->eraseFromParent();
21061   return MBB;
21062 }
21063
21064 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21065 // accumulator loops. Writing back to the accumulator allows the coalescer
21066 // to remove extra copies in the loop.
21067 MachineBasicBlock *
21068 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21069                                  MachineBasicBlock *MBB) const {
21070   MachineOperand &AddendOp = MI->getOperand(3);
21071
21072   // Bail out early if the addend isn't a register - we can't switch these.
21073   if (!AddendOp.isReg())
21074     return MBB;
21075
21076   MachineFunction &MF = *MBB->getParent();
21077   MachineRegisterInfo &MRI = MF.getRegInfo();
21078
21079   // Check whether the addend is defined by a PHI:
21080   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21081   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21082   if (!AddendDef.isPHI())
21083     return MBB;
21084
21085   // Look for the following pattern:
21086   // loop:
21087   //   %addend = phi [%entry, 0], [%loop, %result]
21088   //   ...
21089   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21090
21091   // Replace with:
21092   //   loop:
21093   //   %addend = phi [%entry, 0], [%loop, %result]
21094   //   ...
21095   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21096
21097   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21098     assert(AddendDef.getOperand(i).isReg());
21099     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21100     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21101     if (&PHISrcInst == MI) {
21102       // Found a matching instruction.
21103       unsigned NewFMAOpc = 0;
21104       switch (MI->getOpcode()) {
21105         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21106         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21107         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21108         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21109         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21110         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21111         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21112         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21113         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21114         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21115         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21116         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21117         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21118         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21119         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21120         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21121         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21122         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21123         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21124         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21125
21126         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21127         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21128         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21129         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21130         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21131         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21132         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21133         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21134         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21135         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21136         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21137         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21138         default: llvm_unreachable("Unrecognized FMA variant.");
21139       }
21140
21141       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
21142       MachineInstrBuilder MIB =
21143         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21144         .addOperand(MI->getOperand(0))
21145         .addOperand(MI->getOperand(3))
21146         .addOperand(MI->getOperand(2))
21147         .addOperand(MI->getOperand(1));
21148       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21149       MI->eraseFromParent();
21150     }
21151   }
21152
21153   return MBB;
21154 }
21155
21156 MachineBasicBlock *
21157 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21158                                                MachineBasicBlock *BB) const {
21159   switch (MI->getOpcode()) {
21160   default: llvm_unreachable("Unexpected instr type to insert");
21161   case X86::TAILJMPd64:
21162   case X86::TAILJMPr64:
21163   case X86::TAILJMPm64:
21164     llvm_unreachable("TAILJMP64 would not be touched here.");
21165   case X86::TCRETURNdi64:
21166   case X86::TCRETURNri64:
21167   case X86::TCRETURNmi64:
21168     return BB;
21169   case X86::WIN_ALLOCA:
21170     return EmitLoweredWinAlloca(MI, BB);
21171   case X86::SEG_ALLOCA_32:
21172   case X86::SEG_ALLOCA_64:
21173     return EmitLoweredSegAlloca(MI, BB);
21174   case X86::TLSCall_32:
21175   case X86::TLSCall_64:
21176     return EmitLoweredTLSCall(MI, BB);
21177   case X86::CMOV_GR8:
21178   case X86::CMOV_FR32:
21179   case X86::CMOV_FR64:
21180   case X86::CMOV_V4F32:
21181   case X86::CMOV_V2F64:
21182   case X86::CMOV_V2I64:
21183   case X86::CMOV_V8F32:
21184   case X86::CMOV_V4F64:
21185   case X86::CMOV_V4I64:
21186   case X86::CMOV_V16F32:
21187   case X86::CMOV_V8F64:
21188   case X86::CMOV_V8I64:
21189   case X86::CMOV_GR16:
21190   case X86::CMOV_GR32:
21191   case X86::CMOV_RFP32:
21192   case X86::CMOV_RFP64:
21193   case X86::CMOV_RFP80:
21194     return EmitLoweredSelect(MI, BB);
21195
21196   case X86::FP32_TO_INT16_IN_MEM:
21197   case X86::FP32_TO_INT32_IN_MEM:
21198   case X86::FP32_TO_INT64_IN_MEM:
21199   case X86::FP64_TO_INT16_IN_MEM:
21200   case X86::FP64_TO_INT32_IN_MEM:
21201   case X86::FP64_TO_INT64_IN_MEM:
21202   case X86::FP80_TO_INT16_IN_MEM:
21203   case X86::FP80_TO_INT32_IN_MEM:
21204   case X86::FP80_TO_INT64_IN_MEM: {
21205     MachineFunction *F = BB->getParent();
21206     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
21207     DebugLoc DL = MI->getDebugLoc();
21208
21209     // Change the floating point control register to use "round towards zero"
21210     // mode when truncating to an integer value.
21211     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21212     addFrameReference(BuildMI(*BB, MI, DL,
21213                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21214
21215     // Load the old value of the high byte of the control word...
21216     unsigned OldCW =
21217       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21218     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21219                       CWFrameIdx);
21220
21221     // Set the high part to be round to zero...
21222     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21223       .addImm(0xC7F);
21224
21225     // Reload the modified control word now...
21226     addFrameReference(BuildMI(*BB, MI, DL,
21227                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21228
21229     // Restore the memory image of control word to original value
21230     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21231       .addReg(OldCW);
21232
21233     // Get the X86 opcode to use.
21234     unsigned Opc;
21235     switch (MI->getOpcode()) {
21236     default: llvm_unreachable("illegal opcode!");
21237     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21238     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21239     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21240     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21241     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21242     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21243     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21244     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21245     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21246     }
21247
21248     X86AddressMode AM;
21249     MachineOperand &Op = MI->getOperand(0);
21250     if (Op.isReg()) {
21251       AM.BaseType = X86AddressMode::RegBase;
21252       AM.Base.Reg = Op.getReg();
21253     } else {
21254       AM.BaseType = X86AddressMode::FrameIndexBase;
21255       AM.Base.FrameIndex = Op.getIndex();
21256     }
21257     Op = MI->getOperand(1);
21258     if (Op.isImm())
21259       AM.Scale = Op.getImm();
21260     Op = MI->getOperand(2);
21261     if (Op.isImm())
21262       AM.IndexReg = Op.getImm();
21263     Op = MI->getOperand(3);
21264     if (Op.isGlobal()) {
21265       AM.GV = Op.getGlobal();
21266     } else {
21267       AM.Disp = Op.getImm();
21268     }
21269     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21270                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21271
21272     // Reload the original control word now.
21273     addFrameReference(BuildMI(*BB, MI, DL,
21274                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21275
21276     MI->eraseFromParent();   // The pseudo instruction is gone now.
21277     return BB;
21278   }
21279     // String/text processing lowering.
21280   case X86::PCMPISTRM128REG:
21281   case X86::VPCMPISTRM128REG:
21282   case X86::PCMPISTRM128MEM:
21283   case X86::VPCMPISTRM128MEM:
21284   case X86::PCMPESTRM128REG:
21285   case X86::VPCMPESTRM128REG:
21286   case X86::PCMPESTRM128MEM:
21287   case X86::VPCMPESTRM128MEM:
21288     assert(Subtarget->hasSSE42() &&
21289            "Target must have SSE4.2 or AVX features enabled");
21290     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21291
21292   // String/text processing lowering.
21293   case X86::PCMPISTRIREG:
21294   case X86::VPCMPISTRIREG:
21295   case X86::PCMPISTRIMEM:
21296   case X86::VPCMPISTRIMEM:
21297   case X86::PCMPESTRIREG:
21298   case X86::VPCMPESTRIREG:
21299   case X86::PCMPESTRIMEM:
21300   case X86::VPCMPESTRIMEM:
21301     assert(Subtarget->hasSSE42() &&
21302            "Target must have SSE4.2 or AVX features enabled");
21303     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21304
21305   // Thread synchronization.
21306   case X86::MONITOR:
21307     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
21308                        Subtarget);
21309
21310   // xbegin
21311   case X86::XBEGIN:
21312     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21313
21314   case X86::VASTART_SAVE_XMM_REGS:
21315     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21316
21317   case X86::VAARG_64:
21318     return EmitVAARG64WithCustomInserter(MI, BB);
21319
21320   case X86::EH_SjLj_SetJmp32:
21321   case X86::EH_SjLj_SetJmp64:
21322     return emitEHSjLjSetJmp(MI, BB);
21323
21324   case X86::EH_SjLj_LongJmp32:
21325   case X86::EH_SjLj_LongJmp64:
21326     return emitEHSjLjLongJmp(MI, BB);
21327
21328   case TargetOpcode::STATEPOINT:
21329     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21330     // this point in the process.  We diverge later.
21331     return emitPatchPoint(MI, BB);
21332
21333   case TargetOpcode::STACKMAP:
21334   case TargetOpcode::PATCHPOINT:
21335     return emitPatchPoint(MI, BB);
21336
21337   case X86::VFMADDPDr213r:
21338   case X86::VFMADDPSr213r:
21339   case X86::VFMADDSDr213r:
21340   case X86::VFMADDSSr213r:
21341   case X86::VFMSUBPDr213r:
21342   case X86::VFMSUBPSr213r:
21343   case X86::VFMSUBSDr213r:
21344   case X86::VFMSUBSSr213r:
21345   case X86::VFNMADDPDr213r:
21346   case X86::VFNMADDPSr213r:
21347   case X86::VFNMADDSDr213r:
21348   case X86::VFNMADDSSr213r:
21349   case X86::VFNMSUBPDr213r:
21350   case X86::VFNMSUBPSr213r:
21351   case X86::VFNMSUBSDr213r:
21352   case X86::VFNMSUBSSr213r:
21353   case X86::VFMADDSUBPDr213r:
21354   case X86::VFMADDSUBPSr213r:
21355   case X86::VFMSUBADDPDr213r:
21356   case X86::VFMSUBADDPSr213r:
21357   case X86::VFMADDPDr213rY:
21358   case X86::VFMADDPSr213rY:
21359   case X86::VFMSUBPDr213rY:
21360   case X86::VFMSUBPSr213rY:
21361   case X86::VFNMADDPDr213rY:
21362   case X86::VFNMADDPSr213rY:
21363   case X86::VFNMSUBPDr213rY:
21364   case X86::VFNMSUBPSr213rY:
21365   case X86::VFMADDSUBPDr213rY:
21366   case X86::VFMADDSUBPSr213rY:
21367   case X86::VFMSUBADDPDr213rY:
21368   case X86::VFMSUBADDPSr213rY:
21369     return emitFMA3Instr(MI, BB);
21370   }
21371 }
21372
21373 //===----------------------------------------------------------------------===//
21374 //                           X86 Optimization Hooks
21375 //===----------------------------------------------------------------------===//
21376
21377 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21378                                                       APInt &KnownZero,
21379                                                       APInt &KnownOne,
21380                                                       const SelectionDAG &DAG,
21381                                                       unsigned Depth) const {
21382   unsigned BitWidth = KnownZero.getBitWidth();
21383   unsigned Opc = Op.getOpcode();
21384   assert((Opc >= ISD::BUILTIN_OP_END ||
21385           Opc == ISD::INTRINSIC_WO_CHAIN ||
21386           Opc == ISD::INTRINSIC_W_CHAIN ||
21387           Opc == ISD::INTRINSIC_VOID) &&
21388          "Should use MaskedValueIsZero if you don't know whether Op"
21389          " is a target node!");
21390
21391   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21392   switch (Opc) {
21393   default: break;
21394   case X86ISD::ADD:
21395   case X86ISD::SUB:
21396   case X86ISD::ADC:
21397   case X86ISD::SBB:
21398   case X86ISD::SMUL:
21399   case X86ISD::UMUL:
21400   case X86ISD::INC:
21401   case X86ISD::DEC:
21402   case X86ISD::OR:
21403   case X86ISD::XOR:
21404   case X86ISD::AND:
21405     // These nodes' second result is a boolean.
21406     if (Op.getResNo() == 0)
21407       break;
21408     // Fallthrough
21409   case X86ISD::SETCC:
21410     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21411     break;
21412   case ISD::INTRINSIC_WO_CHAIN: {
21413     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21414     unsigned NumLoBits = 0;
21415     switch (IntId) {
21416     default: break;
21417     case Intrinsic::x86_sse_movmsk_ps:
21418     case Intrinsic::x86_avx_movmsk_ps_256:
21419     case Intrinsic::x86_sse2_movmsk_pd:
21420     case Intrinsic::x86_avx_movmsk_pd_256:
21421     case Intrinsic::x86_mmx_pmovmskb:
21422     case Intrinsic::x86_sse2_pmovmskb_128:
21423     case Intrinsic::x86_avx2_pmovmskb: {
21424       // High bits of movmskp{s|d}, pmovmskb are known zero.
21425       switch (IntId) {
21426         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21427         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21428         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21429         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21430         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21431         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21432         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21433         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21434       }
21435       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21436       break;
21437     }
21438     }
21439     break;
21440   }
21441   }
21442 }
21443
21444 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21445   SDValue Op,
21446   const SelectionDAG &,
21447   unsigned Depth) const {
21448   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21449   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21450     return Op.getValueType().getScalarType().getSizeInBits();
21451
21452   // Fallback case.
21453   return 1;
21454 }
21455
21456 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21457 /// node is a GlobalAddress + offset.
21458 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21459                                        const GlobalValue* &GA,
21460                                        int64_t &Offset) const {
21461   if (N->getOpcode() == X86ISD::Wrapper) {
21462     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21463       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21464       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21465       return true;
21466     }
21467   }
21468   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21469 }
21470
21471 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21472 /// same as extracting the high 128-bit part of 256-bit vector and then
21473 /// inserting the result into the low part of a new 256-bit vector
21474 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21475   EVT VT = SVOp->getValueType(0);
21476   unsigned NumElems = VT.getVectorNumElements();
21477
21478   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21479   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21480     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21481         SVOp->getMaskElt(j) >= 0)
21482       return false;
21483
21484   return true;
21485 }
21486
21487 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21488 /// same as extracting the low 128-bit part of 256-bit vector and then
21489 /// inserting the result into the high part of a new 256-bit vector
21490 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21491   EVT VT = SVOp->getValueType(0);
21492   unsigned NumElems = VT.getVectorNumElements();
21493
21494   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21495   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21496     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21497         SVOp->getMaskElt(j) >= 0)
21498       return false;
21499
21500   return true;
21501 }
21502
21503 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21504 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21505                                         TargetLowering::DAGCombinerInfo &DCI,
21506                                         const X86Subtarget* Subtarget) {
21507   SDLoc dl(N);
21508   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21509   SDValue V1 = SVOp->getOperand(0);
21510   SDValue V2 = SVOp->getOperand(1);
21511   EVT VT = SVOp->getValueType(0);
21512   unsigned NumElems = VT.getVectorNumElements();
21513
21514   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21515       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21516     //
21517     //                   0,0,0,...
21518     //                      |
21519     //    V      UNDEF    BUILD_VECTOR    UNDEF
21520     //     \      /           \           /
21521     //  CONCAT_VECTOR         CONCAT_VECTOR
21522     //         \                  /
21523     //          \                /
21524     //          RESULT: V + zero extended
21525     //
21526     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21527         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21528         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21529       return SDValue();
21530
21531     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21532       return SDValue();
21533
21534     // To match the shuffle mask, the first half of the mask should
21535     // be exactly the first vector, and all the rest a splat with the
21536     // first element of the second one.
21537     for (unsigned i = 0; i != NumElems/2; ++i)
21538       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21539           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21540         return SDValue();
21541
21542     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21543     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21544       if (Ld->hasNUsesOfValue(1, 0)) {
21545         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21546         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21547         SDValue ResNode =
21548           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21549                                   Ld->getMemoryVT(),
21550                                   Ld->getPointerInfo(),
21551                                   Ld->getAlignment(),
21552                                   false/*isVolatile*/, true/*ReadMem*/,
21553                                   false/*WriteMem*/);
21554
21555         // Make sure the newly-created LOAD is in the same position as Ld in
21556         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21557         // and update uses of Ld's output chain to use the TokenFactor.
21558         if (Ld->hasAnyUseOfValue(1)) {
21559           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21560                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21561           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21562           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21563                                  SDValue(ResNode.getNode(), 1));
21564         }
21565
21566         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
21567       }
21568     }
21569
21570     // Emit a zeroed vector and insert the desired subvector on its
21571     // first half.
21572     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21573     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21574     return DCI.CombineTo(N, InsV);
21575   }
21576
21577   //===--------------------------------------------------------------------===//
21578   // Combine some shuffles into subvector extracts and inserts:
21579   //
21580
21581   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21582   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21583     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21584     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21585     return DCI.CombineTo(N, InsV);
21586   }
21587
21588   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21589   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21590     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21591     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21592     return DCI.CombineTo(N, InsV);
21593   }
21594
21595   return SDValue();
21596 }
21597
21598 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21599 /// possible.
21600 ///
21601 /// This is the leaf of the recursive combinine below. When we have found some
21602 /// chain of single-use x86 shuffle instructions and accumulated the combined
21603 /// shuffle mask represented by them, this will try to pattern match that mask
21604 /// into either a single instruction if there is a special purpose instruction
21605 /// for this operation, or into a PSHUFB instruction which is a fully general
21606 /// instruction but should only be used to replace chains over a certain depth.
21607 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21608                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21609                                    TargetLowering::DAGCombinerInfo &DCI,
21610                                    const X86Subtarget *Subtarget) {
21611   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21612
21613   // Find the operand that enters the chain. Note that multiple uses are OK
21614   // here, we're not going to remove the operand we find.
21615   SDValue Input = Op.getOperand(0);
21616   while (Input.getOpcode() == ISD::BITCAST)
21617     Input = Input.getOperand(0);
21618
21619   MVT VT = Input.getSimpleValueType();
21620   MVT RootVT = Root.getSimpleValueType();
21621   SDLoc DL(Root);
21622
21623   // Just remove no-op shuffle masks.
21624   if (Mask.size() == 1) {
21625     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
21626                   /*AddTo*/ true);
21627     return true;
21628   }
21629
21630   // Use the float domain if the operand type is a floating point type.
21631   bool FloatDomain = VT.isFloatingPoint();
21632
21633   // For floating point shuffles, we don't have free copies in the shuffle
21634   // instructions or the ability to load as part of the instruction, so
21635   // canonicalize their shuffles to UNPCK or MOV variants.
21636   //
21637   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21638   // vectors because it can have a load folded into it that UNPCK cannot. This
21639   // doesn't preclude something switching to the shorter encoding post-RA.
21640   if (FloatDomain) {
21641     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
21642       bool Lo = Mask.equals(0, 0);
21643       unsigned Shuffle;
21644       MVT ShuffleVT;
21645       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21646       // is no slower than UNPCKLPD but has the option to fold the input operand
21647       // into even an unaligned memory load.
21648       if (Lo && Subtarget->hasSSE3()) {
21649         Shuffle = X86ISD::MOVDDUP;
21650         ShuffleVT = MVT::v2f64;
21651       } else {
21652         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21653         // than the UNPCK variants.
21654         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21655         ShuffleVT = MVT::v4f32;
21656       }
21657       if (Depth == 1 && Root->getOpcode() == Shuffle)
21658         return false; // Nothing to do!
21659       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21660       DCI.AddToWorklist(Op.getNode());
21661       if (Shuffle == X86ISD::MOVDDUP)
21662         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21663       else
21664         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21665       DCI.AddToWorklist(Op.getNode());
21666       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21667                     /*AddTo*/ true);
21668       return true;
21669     }
21670     if (Subtarget->hasSSE3() &&
21671         (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
21672       bool Lo = Mask.equals(0, 0, 2, 2);
21673       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21674       MVT ShuffleVT = MVT::v4f32;
21675       if (Depth == 1 && Root->getOpcode() == Shuffle)
21676         return false; // Nothing to do!
21677       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21678       DCI.AddToWorklist(Op.getNode());
21679       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21680       DCI.AddToWorklist(Op.getNode());
21681       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21682                     /*AddTo*/ true);
21683       return true;
21684     }
21685     if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
21686       bool Lo = Mask.equals(0, 0, 1, 1);
21687       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21688       MVT ShuffleVT = MVT::v4f32;
21689       if (Depth == 1 && Root->getOpcode() == Shuffle)
21690         return false; // Nothing to do!
21691       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21692       DCI.AddToWorklist(Op.getNode());
21693       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21694       DCI.AddToWorklist(Op.getNode());
21695       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21696                     /*AddTo*/ true);
21697       return true;
21698     }
21699   }
21700
21701   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21702   // variants as none of these have single-instruction variants that are
21703   // superior to the UNPCK formulation.
21704   if (!FloatDomain &&
21705       (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
21706        Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
21707        Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
21708        Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
21709                    15))) {
21710     bool Lo = Mask[0] == 0;
21711     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21712     if (Depth == 1 && Root->getOpcode() == Shuffle)
21713       return false; // Nothing to do!
21714     MVT ShuffleVT;
21715     switch (Mask.size()) {
21716     case 8:
21717       ShuffleVT = MVT::v8i16;
21718       break;
21719     case 16:
21720       ShuffleVT = MVT::v16i8;
21721       break;
21722     default:
21723       llvm_unreachable("Impossible mask size!");
21724     };
21725     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21726     DCI.AddToWorklist(Op.getNode());
21727     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21728     DCI.AddToWorklist(Op.getNode());
21729     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21730                   /*AddTo*/ true);
21731     return true;
21732   }
21733
21734   // Don't try to re-form single instruction chains under any circumstances now
21735   // that we've done encoding canonicalization for them.
21736   if (Depth < 2)
21737     return false;
21738
21739   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21740   // can replace them with a single PSHUFB instruction profitably. Intel's
21741   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21742   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21743   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21744     SmallVector<SDValue, 16> PSHUFBMask;
21745     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
21746     int Ratio = 16 / Mask.size();
21747     for (unsigned i = 0; i < 16; ++i) {
21748       if (Mask[i / Ratio] == SM_SentinelUndef) {
21749         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21750         continue;
21751       }
21752       int M = Mask[i / Ratio] != SM_SentinelZero
21753                   ? Ratio * Mask[i / Ratio] + i % Ratio
21754                   : 255;
21755       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
21756     }
21757     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
21758     DCI.AddToWorklist(Op.getNode());
21759     SDValue PSHUFBMaskOp =
21760         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
21761     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21762     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
21763     DCI.AddToWorklist(Op.getNode());
21764     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21765                   /*AddTo*/ true);
21766     return true;
21767   }
21768
21769   // Failed to find any combines.
21770   return false;
21771 }
21772
21773 /// \brief Fully generic combining of x86 shuffle instructions.
21774 ///
21775 /// This should be the last combine run over the x86 shuffle instructions. Once
21776 /// they have been fully optimized, this will recursively consider all chains
21777 /// of single-use shuffle instructions, build a generic model of the cumulative
21778 /// shuffle operation, and check for simpler instructions which implement this
21779 /// operation. We use this primarily for two purposes:
21780 ///
21781 /// 1) Collapse generic shuffles to specialized single instructions when
21782 ///    equivalent. In most cases, this is just an encoding size win, but
21783 ///    sometimes we will collapse multiple generic shuffles into a single
21784 ///    special-purpose shuffle.
21785 /// 2) Look for sequences of shuffle instructions with 3 or more total
21786 ///    instructions, and replace them with the slightly more expensive SSSE3
21787 ///    PSHUFB instruction if available. We do this as the last combining step
21788 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21789 ///    a suitable short sequence of other instructions. The PHUFB will either
21790 ///    use a register or have to read from memory and so is slightly (but only
21791 ///    slightly) more expensive than the other shuffle instructions.
21792 ///
21793 /// Because this is inherently a quadratic operation (for each shuffle in
21794 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21795 /// This should never be an issue in practice as the shuffle lowering doesn't
21796 /// produce sequences of more than 8 instructions.
21797 ///
21798 /// FIXME: We will currently miss some cases where the redundant shuffling
21799 /// would simplify under the threshold for PSHUFB formation because of
21800 /// combine-ordering. To fix this, we should do the redundant instruction
21801 /// combining in this recursive walk.
21802 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21803                                           ArrayRef<int> RootMask,
21804                                           int Depth, bool HasPSHUFB,
21805                                           SelectionDAG &DAG,
21806                                           TargetLowering::DAGCombinerInfo &DCI,
21807                                           const X86Subtarget *Subtarget) {
21808   // Bound the depth of our recursive combine because this is ultimately
21809   // quadratic in nature.
21810   if (Depth > 8)
21811     return false;
21812
21813   // Directly rip through bitcasts to find the underlying operand.
21814   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21815     Op = Op.getOperand(0);
21816
21817   MVT VT = Op.getSimpleValueType();
21818   if (!VT.isVector())
21819     return false; // Bail if we hit a non-vector.
21820   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
21821   // version should be added.
21822   if (VT.getSizeInBits() != 128)
21823     return false;
21824
21825   assert(Root.getSimpleValueType().isVector() &&
21826          "Shuffles operate on vector types!");
21827   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21828          "Can only combine shuffles of the same vector register size.");
21829
21830   if (!isTargetShuffle(Op.getOpcode()))
21831     return false;
21832   SmallVector<int, 16> OpMask;
21833   bool IsUnary;
21834   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21835   // We only can combine unary shuffles which we can decode the mask for.
21836   if (!HaveMask || !IsUnary)
21837     return false;
21838
21839   assert(VT.getVectorNumElements() == OpMask.size() &&
21840          "Different mask size from vector size!");
21841   assert(((RootMask.size() > OpMask.size() &&
21842            RootMask.size() % OpMask.size() == 0) ||
21843           (OpMask.size() > RootMask.size() &&
21844            OpMask.size() % RootMask.size() == 0) ||
21845           OpMask.size() == RootMask.size()) &&
21846          "The smaller number of elements must divide the larger.");
21847   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21848   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21849   assert(((RootRatio == 1 && OpRatio == 1) ||
21850           (RootRatio == 1) != (OpRatio == 1)) &&
21851          "Must not have a ratio for both incoming and op masks!");
21852
21853   SmallVector<int, 16> Mask;
21854   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21855
21856   // Merge this shuffle operation's mask into our accumulated mask. Note that
21857   // this shuffle's mask will be the first applied to the input, followed by the
21858   // root mask to get us all the way to the root value arrangement. The reason
21859   // for this order is that we are recursing up the operation chain.
21860   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21861     int RootIdx = i / RootRatio;
21862     if (RootMask[RootIdx] < 0) {
21863       // This is a zero or undef lane, we're done.
21864       Mask.push_back(RootMask[RootIdx]);
21865       continue;
21866     }
21867
21868     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21869     int OpIdx = RootMaskedIdx / OpRatio;
21870     if (OpMask[OpIdx] < 0) {
21871       // The incoming lanes are zero or undef, it doesn't matter which ones we
21872       // are using.
21873       Mask.push_back(OpMask[OpIdx]);
21874       continue;
21875     }
21876
21877     // Ok, we have non-zero lanes, map them through.
21878     Mask.push_back(OpMask[OpIdx] * OpRatio +
21879                    RootMaskedIdx % OpRatio);
21880   }
21881
21882   // See if we can recurse into the operand to combine more things.
21883   switch (Op.getOpcode()) {
21884     case X86ISD::PSHUFB:
21885       HasPSHUFB = true;
21886     case X86ISD::PSHUFD:
21887     case X86ISD::PSHUFHW:
21888     case X86ISD::PSHUFLW:
21889       if (Op.getOperand(0).hasOneUse() &&
21890           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21891                                         HasPSHUFB, DAG, DCI, Subtarget))
21892         return true;
21893       break;
21894
21895     case X86ISD::UNPCKL:
21896     case X86ISD::UNPCKH:
21897       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21898       // We can't check for single use, we have to check that this shuffle is the only user.
21899       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21900           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21901                                         HasPSHUFB, DAG, DCI, Subtarget))
21902           return true;
21903       break;
21904   }
21905
21906   // Minor canonicalization of the accumulated shuffle mask to make it easier
21907   // to match below. All this does is detect masks with squential pairs of
21908   // elements, and shrink them to the half-width mask. It does this in a loop
21909   // so it will reduce the size of the mask to the minimal width mask which
21910   // performs an equivalent shuffle.
21911   SmallVector<int, 16> WidenedMask;
21912   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21913     Mask = std::move(WidenedMask);
21914     WidenedMask.clear();
21915   }
21916
21917   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21918                                 Subtarget);
21919 }
21920
21921 /// \brief Get the PSHUF-style mask from PSHUF node.
21922 ///
21923 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21924 /// PSHUF-style masks that can be reused with such instructions.
21925 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21926   SmallVector<int, 4> Mask;
21927   bool IsUnary;
21928   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
21929   (void)HaveMask;
21930   assert(HaveMask);
21931
21932   switch (N.getOpcode()) {
21933   case X86ISD::PSHUFD:
21934     return Mask;
21935   case X86ISD::PSHUFLW:
21936     Mask.resize(4);
21937     return Mask;
21938   case X86ISD::PSHUFHW:
21939     Mask.erase(Mask.begin(), Mask.begin() + 4);
21940     for (int &M : Mask)
21941       M -= 4;
21942     return Mask;
21943   default:
21944     llvm_unreachable("No valid shuffle instruction found!");
21945   }
21946 }
21947
21948 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21949 ///
21950 /// We walk up the chain and look for a combinable shuffle, skipping over
21951 /// shuffles that we could hoist this shuffle's transformation past without
21952 /// altering anything.
21953 static SDValue
21954 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21955                              SelectionDAG &DAG,
21956                              TargetLowering::DAGCombinerInfo &DCI) {
21957   assert(N.getOpcode() == X86ISD::PSHUFD &&
21958          "Called with something other than an x86 128-bit half shuffle!");
21959   SDLoc DL(N);
21960
21961   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21962   // of the shuffles in the chain so that we can form a fresh chain to replace
21963   // this one.
21964   SmallVector<SDValue, 8> Chain;
21965   SDValue V = N.getOperand(0);
21966   for (; V.hasOneUse(); V = V.getOperand(0)) {
21967     switch (V.getOpcode()) {
21968     default:
21969       return SDValue(); // Nothing combined!
21970
21971     case ISD::BITCAST:
21972       // Skip bitcasts as we always know the type for the target specific
21973       // instructions.
21974       continue;
21975
21976     case X86ISD::PSHUFD:
21977       // Found another dword shuffle.
21978       break;
21979
21980     case X86ISD::PSHUFLW:
21981       // Check that the low words (being shuffled) are the identity in the
21982       // dword shuffle, and the high words are self-contained.
21983       if (Mask[0] != 0 || Mask[1] != 1 ||
21984           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21985         return SDValue();
21986
21987       Chain.push_back(V);
21988       continue;
21989
21990     case X86ISD::PSHUFHW:
21991       // Check that the high words (being shuffled) are the identity in the
21992       // dword shuffle, and the low words are self-contained.
21993       if (Mask[2] != 2 || Mask[3] != 3 ||
21994           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21995         return SDValue();
21996
21997       Chain.push_back(V);
21998       continue;
21999
22000     case X86ISD::UNPCKL:
22001     case X86ISD::UNPCKH:
22002       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22003       // shuffle into a preceding word shuffle.
22004       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
22005         return SDValue();
22006
22007       // Search for a half-shuffle which we can combine with.
22008       unsigned CombineOp =
22009           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22010       if (V.getOperand(0) != V.getOperand(1) ||
22011           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22012         return SDValue();
22013       Chain.push_back(V);
22014       V = V.getOperand(0);
22015       do {
22016         switch (V.getOpcode()) {
22017         default:
22018           return SDValue(); // Nothing to combine.
22019
22020         case X86ISD::PSHUFLW:
22021         case X86ISD::PSHUFHW:
22022           if (V.getOpcode() == CombineOp)
22023             break;
22024
22025           Chain.push_back(V);
22026
22027           // Fallthrough!
22028         case ISD::BITCAST:
22029           V = V.getOperand(0);
22030           continue;
22031         }
22032         break;
22033       } while (V.hasOneUse());
22034       break;
22035     }
22036     // Break out of the loop if we break out of the switch.
22037     break;
22038   }
22039
22040   if (!V.hasOneUse())
22041     // We fell out of the loop without finding a viable combining instruction.
22042     return SDValue();
22043
22044   // Merge this node's mask and our incoming mask.
22045   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22046   for (int &M : Mask)
22047     M = VMask[M];
22048   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22049                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22050
22051   // Rebuild the chain around this new shuffle.
22052   while (!Chain.empty()) {
22053     SDValue W = Chain.pop_back_val();
22054
22055     if (V.getValueType() != W.getOperand(0).getValueType())
22056       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
22057
22058     switch (W.getOpcode()) {
22059     default:
22060       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22061
22062     case X86ISD::UNPCKL:
22063     case X86ISD::UNPCKH:
22064       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22065       break;
22066
22067     case X86ISD::PSHUFD:
22068     case X86ISD::PSHUFLW:
22069     case X86ISD::PSHUFHW:
22070       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22071       break;
22072     }
22073   }
22074   if (V.getValueType() != N.getValueType())
22075     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
22076
22077   // Return the new chain to replace N.
22078   return V;
22079 }
22080
22081 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22082 ///
22083 /// We walk up the chain, skipping shuffles of the other half and looking
22084 /// through shuffles which switch halves trying to find a shuffle of the same
22085 /// pair of dwords.
22086 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22087                                         SelectionDAG &DAG,
22088                                         TargetLowering::DAGCombinerInfo &DCI) {
22089   assert(
22090       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22091       "Called with something other than an x86 128-bit half shuffle!");
22092   SDLoc DL(N);
22093   unsigned CombineOpcode = N.getOpcode();
22094
22095   // Walk up a single-use chain looking for a combinable shuffle.
22096   SDValue V = N.getOperand(0);
22097   for (; V.hasOneUse(); V = V.getOperand(0)) {
22098     switch (V.getOpcode()) {
22099     default:
22100       return false; // Nothing combined!
22101
22102     case ISD::BITCAST:
22103       // Skip bitcasts as we always know the type for the target specific
22104       // instructions.
22105       continue;
22106
22107     case X86ISD::PSHUFLW:
22108     case X86ISD::PSHUFHW:
22109       if (V.getOpcode() == CombineOpcode)
22110         break;
22111
22112       // Other-half shuffles are no-ops.
22113       continue;
22114     }
22115     // Break out of the loop if we break out of the switch.
22116     break;
22117   }
22118
22119   if (!V.hasOneUse())
22120     // We fell out of the loop without finding a viable combining instruction.
22121     return false;
22122
22123   // Combine away the bottom node as its shuffle will be accumulated into
22124   // a preceding shuffle.
22125   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22126
22127   // Record the old value.
22128   SDValue Old = V;
22129
22130   // Merge this node's mask and our incoming mask (adjusted to account for all
22131   // the pshufd instructions encountered).
22132   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22133   for (int &M : Mask)
22134     M = VMask[M];
22135   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22136                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22137
22138   // Check that the shuffles didn't cancel each other out. If not, we need to
22139   // combine to the new one.
22140   if (Old != V)
22141     // Replace the combinable shuffle with the combined one, updating all users
22142     // so that we re-evaluate the chain here.
22143     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22144
22145   return true;
22146 }
22147
22148 /// \brief Try to combine x86 target specific shuffles.
22149 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22150                                            TargetLowering::DAGCombinerInfo &DCI,
22151                                            const X86Subtarget *Subtarget) {
22152   SDLoc DL(N);
22153   MVT VT = N.getSimpleValueType();
22154   SmallVector<int, 4> Mask;
22155
22156   switch (N.getOpcode()) {
22157   case X86ISD::PSHUFD:
22158   case X86ISD::PSHUFLW:
22159   case X86ISD::PSHUFHW:
22160     Mask = getPSHUFShuffleMask(N);
22161     assert(Mask.size() == 4);
22162     break;
22163   default:
22164     return SDValue();
22165   }
22166
22167   // Nuke no-op shuffles that show up after combining.
22168   if (isNoopShuffleMask(Mask))
22169     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22170
22171   // Look for simplifications involving one or two shuffle instructions.
22172   SDValue V = N.getOperand(0);
22173   switch (N.getOpcode()) {
22174   default:
22175     break;
22176   case X86ISD::PSHUFLW:
22177   case X86ISD::PSHUFHW:
22178     assert(VT == MVT::v8i16);
22179     (void)VT;
22180
22181     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22182       return SDValue(); // We combined away this shuffle, so we're done.
22183
22184     // See if this reduces to a PSHUFD which is no more expensive and can
22185     // combine with more operations. Note that it has to at least flip the
22186     // dwords as otherwise it would have been removed as a no-op.
22187     if (Mask[0] == 2 && Mask[1] == 3 && Mask[2] == 0 && Mask[3] == 1) {
22188       int DMask[] = {0, 1, 2, 3};
22189       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22190       DMask[DOffset + 0] = DOffset + 1;
22191       DMask[DOffset + 1] = DOffset + 0;
22192       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
22193       DCI.AddToWorklist(V.getNode());
22194       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
22195                       getV4X86ShuffleImm8ForMask(DMask, DAG));
22196       DCI.AddToWorklist(V.getNode());
22197       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
22198     }
22199
22200     // Look for shuffle patterns which can be implemented as a single unpack.
22201     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22202     // only works when we have a PSHUFD followed by two half-shuffles.
22203     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22204         (V.getOpcode() == X86ISD::PSHUFLW ||
22205          V.getOpcode() == X86ISD::PSHUFHW) &&
22206         V.getOpcode() != N.getOpcode() &&
22207         V.hasOneUse()) {
22208       SDValue D = V.getOperand(0);
22209       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22210         D = D.getOperand(0);
22211       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22212         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22213         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22214         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22215         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22216         int WordMask[8];
22217         for (int i = 0; i < 4; ++i) {
22218           WordMask[i + NOffset] = Mask[i] + NOffset;
22219           WordMask[i + VOffset] = VMask[i] + VOffset;
22220         }
22221         // Map the word mask through the DWord mask.
22222         int MappedMask[8];
22223         for (int i = 0; i < 8; ++i)
22224           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22225         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
22226         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
22227         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
22228                        std::begin(UnpackLoMask)) ||
22229             std::equal(std::begin(MappedMask), std::end(MappedMask),
22230                        std::begin(UnpackHiMask))) {
22231           // We can replace all three shuffles with an unpack.
22232           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
22233           DCI.AddToWorklist(V.getNode());
22234           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22235                                                 : X86ISD::UNPCKH,
22236                              DL, MVT::v8i16, V, V);
22237         }
22238       }
22239     }
22240
22241     break;
22242
22243   case X86ISD::PSHUFD:
22244     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22245       return NewN;
22246
22247     break;
22248   }
22249
22250   return SDValue();
22251 }
22252
22253 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22254 ///
22255 /// We combine this directly on the abstract vector shuffle nodes so it is
22256 /// easier to generically match. We also insert dummy vector shuffle nodes for
22257 /// the operands which explicitly discard the lanes which are unused by this
22258 /// operation to try to flow through the rest of the combiner the fact that
22259 /// they're unused.
22260 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22261   SDLoc DL(N);
22262   EVT VT = N->getValueType(0);
22263
22264   // We only handle target-independent shuffles.
22265   // FIXME: It would be easy and harmless to use the target shuffle mask
22266   // extraction tool to support more.
22267   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22268     return SDValue();
22269
22270   auto *SVN = cast<ShuffleVectorSDNode>(N);
22271   ArrayRef<int> Mask = SVN->getMask();
22272   SDValue V1 = N->getOperand(0);
22273   SDValue V2 = N->getOperand(1);
22274
22275   // We require the first shuffle operand to be the SUB node, and the second to
22276   // be the ADD node.
22277   // FIXME: We should support the commuted patterns.
22278   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22279     return SDValue();
22280
22281   // If there are other uses of these operations we can't fold them.
22282   if (!V1->hasOneUse() || !V2->hasOneUse())
22283     return SDValue();
22284
22285   // Ensure that both operations have the same operands. Note that we can
22286   // commute the FADD operands.
22287   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22288   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22289       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22290     return SDValue();
22291
22292   // We're looking for blends between FADD and FSUB nodes. We insist on these
22293   // nodes being lined up in a specific expected pattern.
22294   if (!(isShuffleEquivalent(Mask, 0, 3) ||
22295         isShuffleEquivalent(Mask, 0, 5, 2, 7) ||
22296         isShuffleEquivalent(Mask, 0, 9, 2, 11, 4, 13, 6, 15)))
22297     return SDValue();
22298
22299   // Only specific types are legal at this point, assert so we notice if and
22300   // when these change.
22301   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22302           VT == MVT::v4f64) &&
22303          "Unknown vector type encountered!");
22304
22305   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22306 }
22307
22308 /// PerformShuffleCombine - Performs several different shuffle combines.
22309 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22310                                      TargetLowering::DAGCombinerInfo &DCI,
22311                                      const X86Subtarget *Subtarget) {
22312   SDLoc dl(N);
22313   SDValue N0 = N->getOperand(0);
22314   SDValue N1 = N->getOperand(1);
22315   EVT VT = N->getValueType(0);
22316
22317   // Don't create instructions with illegal types after legalize types has run.
22318   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22319   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22320     return SDValue();
22321
22322   // If we have legalized the vector types, look for blends of FADD and FSUB
22323   // nodes that we can fuse into an ADDSUB node.
22324   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22325     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22326       return AddSub;
22327
22328   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22329   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22330       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22331     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22332
22333   // During Type Legalization, when promoting illegal vector types,
22334   // the backend might introduce new shuffle dag nodes and bitcasts.
22335   //
22336   // This code performs the following transformation:
22337   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22338   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22339   //
22340   // We do this only if both the bitcast and the BINOP dag nodes have
22341   // one use. Also, perform this transformation only if the new binary
22342   // operation is legal. This is to avoid introducing dag nodes that
22343   // potentially need to be further expanded (or custom lowered) into a
22344   // less optimal sequence of dag nodes.
22345   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22346       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22347       N0.getOpcode() == ISD::BITCAST) {
22348     SDValue BC0 = N0.getOperand(0);
22349     EVT SVT = BC0.getValueType();
22350     unsigned Opcode = BC0.getOpcode();
22351     unsigned NumElts = VT.getVectorNumElements();
22352
22353     if (BC0.hasOneUse() && SVT.isVector() &&
22354         SVT.getVectorNumElements() * 2 == NumElts &&
22355         TLI.isOperationLegal(Opcode, VT)) {
22356       bool CanFold = false;
22357       switch (Opcode) {
22358       default : break;
22359       case ISD::ADD :
22360       case ISD::FADD :
22361       case ISD::SUB :
22362       case ISD::FSUB :
22363       case ISD::MUL :
22364       case ISD::FMUL :
22365         CanFold = true;
22366       }
22367
22368       unsigned SVTNumElts = SVT.getVectorNumElements();
22369       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22370       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22371         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22372       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22373         CanFold = SVOp->getMaskElt(i) < 0;
22374
22375       if (CanFold) {
22376         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
22377         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
22378         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22379         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22380       }
22381     }
22382   }
22383
22384   // Only handle 128 wide vector from here on.
22385   if (!VT.is128BitVector())
22386     return SDValue();
22387
22388   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22389   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22390   // consecutive, non-overlapping, and in the right order.
22391   SmallVector<SDValue, 16> Elts;
22392   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22393     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22394
22395   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
22396   if (LD.getNode())
22397     return LD;
22398
22399   if (isTargetShuffle(N->getOpcode())) {
22400     SDValue Shuffle =
22401         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22402     if (Shuffle.getNode())
22403       return Shuffle;
22404
22405     // Try recursively combining arbitrary sequences of x86 shuffle
22406     // instructions into higher-order shuffles. We do this after combining
22407     // specific PSHUF instruction sequences into their minimal form so that we
22408     // can evaluate how many specialized shuffle instructions are involved in
22409     // a particular chain.
22410     SmallVector<int, 1> NonceMask; // Just a placeholder.
22411     NonceMask.push_back(0);
22412     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22413                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22414                                       DCI, Subtarget))
22415       return SDValue(); // This routine will use CombineTo to replace N.
22416   }
22417
22418   return SDValue();
22419 }
22420
22421 /// PerformTruncateCombine - Converts truncate operation to
22422 /// a sequence of vector shuffle operations.
22423 /// It is possible when we truncate 256-bit vector to 128-bit vector
22424 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
22425                                       TargetLowering::DAGCombinerInfo &DCI,
22426                                       const X86Subtarget *Subtarget)  {
22427   return SDValue();
22428 }
22429
22430 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22431 /// specific shuffle of a load can be folded into a single element load.
22432 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22433 /// shuffles have been custom lowered so we need to handle those here.
22434 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22435                                          TargetLowering::DAGCombinerInfo &DCI) {
22436   if (DCI.isBeforeLegalizeOps())
22437     return SDValue();
22438
22439   SDValue InVec = N->getOperand(0);
22440   SDValue EltNo = N->getOperand(1);
22441
22442   if (!isa<ConstantSDNode>(EltNo))
22443     return SDValue();
22444
22445   EVT OriginalVT = InVec.getValueType();
22446
22447   if (InVec.getOpcode() == ISD::BITCAST) {
22448     // Don't duplicate a load with other uses.
22449     if (!InVec.hasOneUse())
22450       return SDValue();
22451     EVT BCVT = InVec.getOperand(0).getValueType();
22452     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22453       return SDValue();
22454     InVec = InVec.getOperand(0);
22455   }
22456
22457   EVT CurrentVT = InVec.getValueType();
22458
22459   if (!isTargetShuffle(InVec.getOpcode()))
22460     return SDValue();
22461
22462   // Don't duplicate a load with other uses.
22463   if (!InVec.hasOneUse())
22464     return SDValue();
22465
22466   SmallVector<int, 16> ShuffleMask;
22467   bool UnaryShuffle;
22468   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22469                             ShuffleMask, UnaryShuffle))
22470     return SDValue();
22471
22472   // Select the input vector, guarding against out of range extract vector.
22473   unsigned NumElems = CurrentVT.getVectorNumElements();
22474   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22475   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22476   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22477                                          : InVec.getOperand(1);
22478
22479   // If inputs to shuffle are the same for both ops, then allow 2 uses
22480   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22481
22482   if (LdNode.getOpcode() == ISD::BITCAST) {
22483     // Don't duplicate a load with other uses.
22484     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22485       return SDValue();
22486
22487     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22488     LdNode = LdNode.getOperand(0);
22489   }
22490
22491   if (!ISD::isNormalLoad(LdNode.getNode()))
22492     return SDValue();
22493
22494   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22495
22496   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22497     return SDValue();
22498
22499   EVT EltVT = N->getValueType(0);
22500   // If there's a bitcast before the shuffle, check if the load type and
22501   // alignment is valid.
22502   unsigned Align = LN0->getAlignment();
22503   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22504   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
22505       EltVT.getTypeForEVT(*DAG.getContext()));
22506
22507   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22508     return SDValue();
22509
22510   // All checks match so transform back to vector_shuffle so that DAG combiner
22511   // can finish the job
22512   SDLoc dl(N);
22513
22514   // Create shuffle node taking into account the case that its a unary shuffle
22515   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22516                                    : InVec.getOperand(1);
22517   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22518                                  InVec.getOperand(0), Shuffle,
22519                                  &ShuffleMask[0]);
22520   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
22521   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22522                      EltNo);
22523 }
22524
22525 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22526 /// generation and convert it from being a bunch of shuffles and extracts
22527 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22528 /// storing the value and loading scalars back, while for x64 we should
22529 /// use 64-bit extracts and shifts.
22530 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22531                                          TargetLowering::DAGCombinerInfo &DCI) {
22532   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
22533   if (NewOp.getNode())
22534     return NewOp;
22535
22536   SDValue InputVector = N->getOperand(0);
22537
22538   // Detect whether we are trying to convert from mmx to i32 and the bitcast
22539   // from mmx to v2i32 has a single usage.
22540   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
22541       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
22542       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
22543     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22544                        N->getValueType(0),
22545                        InputVector.getNode()->getOperand(0));
22546
22547   // Only operate on vectors of 4 elements, where the alternative shuffling
22548   // gets to be more expensive.
22549   if (InputVector.getValueType() != MVT::v4i32)
22550     return SDValue();
22551
22552   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22553   // single use which is a sign-extend or zero-extend, and all elements are
22554   // used.
22555   SmallVector<SDNode *, 4> Uses;
22556   unsigned ExtractedElements = 0;
22557   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22558        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22559     if (UI.getUse().getResNo() != InputVector.getResNo())
22560       return SDValue();
22561
22562     SDNode *Extract = *UI;
22563     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22564       return SDValue();
22565
22566     if (Extract->getValueType(0) != MVT::i32)
22567       return SDValue();
22568     if (!Extract->hasOneUse())
22569       return SDValue();
22570     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22571         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22572       return SDValue();
22573     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22574       return SDValue();
22575
22576     // Record which element was extracted.
22577     ExtractedElements |=
22578       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22579
22580     Uses.push_back(Extract);
22581   }
22582
22583   // If not all the elements were used, this may not be worthwhile.
22584   if (ExtractedElements != 15)
22585     return SDValue();
22586
22587   // Ok, we've now decided to do the transformation.
22588   // If 64-bit shifts are legal, use the extract-shift sequence,
22589   // otherwise bounce the vector off the cache.
22590   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22591   SDValue Vals[4];
22592   SDLoc dl(InputVector);
22593   
22594   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22595     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
22596     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
22597     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22598       DAG.getConstant(0, VecIdxTy));
22599     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22600       DAG.getConstant(1, VecIdxTy));
22601
22602     SDValue ShAmt = DAG.getConstant(32, 
22603       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
22604     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22605     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22606       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22607     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22608     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22609       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22610   } else {
22611     // Store the value to a temporary stack slot.
22612     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22613     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22614       MachinePointerInfo(), false, false, 0);
22615
22616     EVT ElementType = InputVector.getValueType().getVectorElementType();
22617     unsigned EltSize = ElementType.getSizeInBits() / 8;
22618
22619     // Replace each use (extract) with a load of the appropriate element.
22620     for (unsigned i = 0; i < 4; ++i) {
22621       uint64_t Offset = EltSize * i;
22622       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
22623
22624       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
22625                                        StackPtr, OffsetVal);
22626
22627       // Load the scalar.
22628       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22629                             ScalarAddr, MachinePointerInfo(),
22630                             false, false, false, 0);
22631
22632     }
22633   }
22634
22635   // Replace the extracts
22636   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22637     UE = Uses.end(); UI != UE; ++UI) {
22638     SDNode *Extract = *UI;
22639
22640     SDValue Idx = Extract->getOperand(1);
22641     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22642     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22643   }
22644
22645   // The replacement was made in place; don't return anything.
22646   return SDValue();
22647 }
22648
22649 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22650 static std::pair<unsigned, bool>
22651 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22652                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22653   if (!VT.isVector())
22654     return std::make_pair(0, false);
22655
22656   bool NeedSplit = false;
22657   switch (VT.getSimpleVT().SimpleTy) {
22658   default: return std::make_pair(0, false);
22659   case MVT::v4i64:
22660   case MVT::v2i64:
22661     if (!Subtarget->hasVLX())
22662       return std::make_pair(0, false);
22663     break;
22664   case MVT::v64i8:
22665   case MVT::v32i16:
22666     if (!Subtarget->hasBWI())
22667       return std::make_pair(0, false);
22668     break;
22669   case MVT::v16i32:
22670   case MVT::v8i64:
22671     if (!Subtarget->hasAVX512())
22672       return std::make_pair(0, false);
22673     break;
22674   case MVT::v32i8:
22675   case MVT::v16i16:
22676   case MVT::v8i32:
22677     if (!Subtarget->hasAVX2())
22678       NeedSplit = true;
22679     if (!Subtarget->hasAVX())
22680       return std::make_pair(0, false);
22681     break;
22682   case MVT::v16i8:
22683   case MVT::v8i16:
22684   case MVT::v4i32:
22685     if (!Subtarget->hasSSE2())
22686       return std::make_pair(0, false);
22687   }
22688
22689   // SSE2 has only a small subset of the operations.
22690   bool hasUnsigned = Subtarget->hasSSE41() ||
22691                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22692   bool hasSigned = Subtarget->hasSSE41() ||
22693                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22694
22695   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22696
22697   unsigned Opc = 0;
22698   // Check for x CC y ? x : y.
22699   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22700       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22701     switch (CC) {
22702     default: break;
22703     case ISD::SETULT:
22704     case ISD::SETULE:
22705       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22706     case ISD::SETUGT:
22707     case ISD::SETUGE:
22708       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22709     case ISD::SETLT:
22710     case ISD::SETLE:
22711       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22712     case ISD::SETGT:
22713     case ISD::SETGE:
22714       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22715     }
22716   // Check for x CC y ? y : x -- a min/max with reversed arms.
22717   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22718              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22719     switch (CC) {
22720     default: break;
22721     case ISD::SETULT:
22722     case ISD::SETULE:
22723       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22724     case ISD::SETUGT:
22725     case ISD::SETUGE:
22726       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22727     case ISD::SETLT:
22728     case ISD::SETLE:
22729       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22730     case ISD::SETGT:
22731     case ISD::SETGE:
22732       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22733     }
22734   }
22735
22736   return std::make_pair(Opc, NeedSplit);
22737 }
22738
22739 static SDValue
22740 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22741                                       const X86Subtarget *Subtarget) {
22742   SDLoc dl(N);
22743   SDValue Cond = N->getOperand(0);
22744   SDValue LHS = N->getOperand(1);
22745   SDValue RHS = N->getOperand(2);
22746
22747   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22748     SDValue CondSrc = Cond->getOperand(0);
22749     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22750       Cond = CondSrc->getOperand(0);
22751   }
22752
22753   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22754     return SDValue();
22755
22756   // A vselect where all conditions and data are constants can be optimized into
22757   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22758   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22759       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22760     return SDValue();
22761
22762   unsigned MaskValue = 0;
22763   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22764     return SDValue();
22765
22766   MVT VT = N->getSimpleValueType(0);
22767   unsigned NumElems = VT.getVectorNumElements();
22768   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22769   for (unsigned i = 0; i < NumElems; ++i) {
22770     // Be sure we emit undef where we can.
22771     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22772       ShuffleMask[i] = -1;
22773     else
22774       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22775   }
22776
22777   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22778   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22779     return SDValue();
22780   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22781 }
22782
22783 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22784 /// nodes.
22785 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22786                                     TargetLowering::DAGCombinerInfo &DCI,
22787                                     const X86Subtarget *Subtarget) {
22788   SDLoc DL(N);
22789   SDValue Cond = N->getOperand(0);
22790   // Get the LHS/RHS of the select.
22791   SDValue LHS = N->getOperand(1);
22792   SDValue RHS = N->getOperand(2);
22793   EVT VT = LHS.getValueType();
22794   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22795
22796   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22797   // instructions match the semantics of the common C idiom x<y?x:y but not
22798   // x<=y?x:y, because of how they handle negative zero (which can be
22799   // ignored in unsafe-math mode).
22800   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22801       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
22802       (Subtarget->hasSSE2() ||
22803        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22804     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22805
22806     unsigned Opcode = 0;
22807     // Check for x CC y ? x : y.
22808     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22809         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22810       switch (CC) {
22811       default: break;
22812       case ISD::SETULT:
22813         // Converting this to a min would handle NaNs incorrectly, and swapping
22814         // the operands would cause it to handle comparisons between positive
22815         // and negative zero incorrectly.
22816         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22817           if (!DAG.getTarget().Options.UnsafeFPMath &&
22818               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22819             break;
22820           std::swap(LHS, RHS);
22821         }
22822         Opcode = X86ISD::FMIN;
22823         break;
22824       case ISD::SETOLE:
22825         // Converting this to a min would handle comparisons between positive
22826         // and negative zero incorrectly.
22827         if (!DAG.getTarget().Options.UnsafeFPMath &&
22828             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22829           break;
22830         Opcode = X86ISD::FMIN;
22831         break;
22832       case ISD::SETULE:
22833         // Converting this to a min would handle both negative zeros and NaNs
22834         // incorrectly, but we can swap the operands to fix both.
22835         std::swap(LHS, RHS);
22836       case ISD::SETOLT:
22837       case ISD::SETLT:
22838       case ISD::SETLE:
22839         Opcode = X86ISD::FMIN;
22840         break;
22841
22842       case ISD::SETOGE:
22843         // Converting this to a max would handle comparisons between positive
22844         // and negative zero incorrectly.
22845         if (!DAG.getTarget().Options.UnsafeFPMath &&
22846             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22847           break;
22848         Opcode = X86ISD::FMAX;
22849         break;
22850       case ISD::SETUGT:
22851         // Converting this to a max would handle NaNs incorrectly, and swapping
22852         // the operands would cause it to handle comparisons between positive
22853         // and negative zero incorrectly.
22854         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22855           if (!DAG.getTarget().Options.UnsafeFPMath &&
22856               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22857             break;
22858           std::swap(LHS, RHS);
22859         }
22860         Opcode = X86ISD::FMAX;
22861         break;
22862       case ISD::SETUGE:
22863         // Converting this to a max would handle both negative zeros and NaNs
22864         // incorrectly, but we can swap the operands to fix both.
22865         std::swap(LHS, RHS);
22866       case ISD::SETOGT:
22867       case ISD::SETGT:
22868       case ISD::SETGE:
22869         Opcode = X86ISD::FMAX;
22870         break;
22871       }
22872     // Check for x CC y ? y : x -- a min/max with reversed arms.
22873     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22874                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22875       switch (CC) {
22876       default: break;
22877       case ISD::SETOGE:
22878         // Converting this to a min would handle comparisons between positive
22879         // and negative zero incorrectly, and swapping the operands would
22880         // cause it to handle NaNs incorrectly.
22881         if (!DAG.getTarget().Options.UnsafeFPMath &&
22882             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22883           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22884             break;
22885           std::swap(LHS, RHS);
22886         }
22887         Opcode = X86ISD::FMIN;
22888         break;
22889       case ISD::SETUGT:
22890         // Converting this to a min would handle NaNs incorrectly.
22891         if (!DAG.getTarget().Options.UnsafeFPMath &&
22892             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22893           break;
22894         Opcode = X86ISD::FMIN;
22895         break;
22896       case ISD::SETUGE:
22897         // Converting this to a min would handle both negative zeros and NaNs
22898         // incorrectly, but we can swap the operands to fix both.
22899         std::swap(LHS, RHS);
22900       case ISD::SETOGT:
22901       case ISD::SETGT:
22902       case ISD::SETGE:
22903         Opcode = X86ISD::FMIN;
22904         break;
22905
22906       case ISD::SETULT:
22907         // Converting this to a max would handle NaNs incorrectly.
22908         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22909           break;
22910         Opcode = X86ISD::FMAX;
22911         break;
22912       case ISD::SETOLE:
22913         // Converting this to a max would handle comparisons between positive
22914         // and negative zero incorrectly, and swapping the operands would
22915         // cause it to handle NaNs incorrectly.
22916         if (!DAG.getTarget().Options.UnsafeFPMath &&
22917             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22918           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22919             break;
22920           std::swap(LHS, RHS);
22921         }
22922         Opcode = X86ISD::FMAX;
22923         break;
22924       case ISD::SETULE:
22925         // Converting this to a max would handle both negative zeros and NaNs
22926         // incorrectly, but we can swap the operands to fix both.
22927         std::swap(LHS, RHS);
22928       case ISD::SETOLT:
22929       case ISD::SETLT:
22930       case ISD::SETLE:
22931         Opcode = X86ISD::FMAX;
22932         break;
22933       }
22934     }
22935
22936     if (Opcode)
22937       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22938   }
22939
22940   EVT CondVT = Cond.getValueType();
22941   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22942       CondVT.getVectorElementType() == MVT::i1) {
22943     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22944     // lowering on KNL. In this case we convert it to
22945     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22946     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22947     // Since SKX these selects have a proper lowering.
22948     EVT OpVT = LHS.getValueType();
22949     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22950         (OpVT.getVectorElementType() == MVT::i8 ||
22951          OpVT.getVectorElementType() == MVT::i16) &&
22952         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22953       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22954       DCI.AddToWorklist(Cond.getNode());
22955       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22956     }
22957   }
22958   // If this is a select between two integer constants, try to do some
22959   // optimizations.
22960   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22961     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22962       // Don't do this for crazy integer types.
22963       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22964         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22965         // so that TrueC (the true value) is larger than FalseC.
22966         bool NeedsCondInvert = false;
22967
22968         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22969             // Efficiently invertible.
22970             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22971              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22972               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22973           NeedsCondInvert = true;
22974           std::swap(TrueC, FalseC);
22975         }
22976
22977         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22978         if (FalseC->getAPIntValue() == 0 &&
22979             TrueC->getAPIntValue().isPowerOf2()) {
22980           if (NeedsCondInvert) // Invert the condition if needed.
22981             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22982                                DAG.getConstant(1, Cond.getValueType()));
22983
22984           // Zero extend the condition if needed.
22985           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22986
22987           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22988           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22989                              DAG.getConstant(ShAmt, MVT::i8));
22990         }
22991
22992         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22993         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22994           if (NeedsCondInvert) // Invert the condition if needed.
22995             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22996                                DAG.getConstant(1, Cond.getValueType()));
22997
22998           // Zero extend the condition if needed.
22999           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23000                              FalseC->getValueType(0), Cond);
23001           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23002                              SDValue(FalseC, 0));
23003         }
23004
23005         // Optimize cases that will turn into an LEA instruction.  This requires
23006         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23007         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23008           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23009           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23010
23011           bool isFastMultiplier = false;
23012           if (Diff < 10) {
23013             switch ((unsigned char)Diff) {
23014               default: break;
23015               case 1:  // result = add base, cond
23016               case 2:  // result = lea base(    , cond*2)
23017               case 3:  // result = lea base(cond, cond*2)
23018               case 4:  // result = lea base(    , cond*4)
23019               case 5:  // result = lea base(cond, cond*4)
23020               case 8:  // result = lea base(    , cond*8)
23021               case 9:  // result = lea base(cond, cond*8)
23022                 isFastMultiplier = true;
23023                 break;
23024             }
23025           }
23026
23027           if (isFastMultiplier) {
23028             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23029             if (NeedsCondInvert) // Invert the condition if needed.
23030               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23031                                  DAG.getConstant(1, Cond.getValueType()));
23032
23033             // Zero extend the condition if needed.
23034             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23035                                Cond);
23036             // Scale the condition by the difference.
23037             if (Diff != 1)
23038               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23039                                  DAG.getConstant(Diff, Cond.getValueType()));
23040
23041             // Add the base if non-zero.
23042             if (FalseC->getAPIntValue() != 0)
23043               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23044                                  SDValue(FalseC, 0));
23045             return Cond;
23046           }
23047         }
23048       }
23049   }
23050
23051   // Canonicalize max and min:
23052   // (x > y) ? x : y -> (x >= y) ? x : y
23053   // (x < y) ? x : y -> (x <= y) ? x : y
23054   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23055   // the need for an extra compare
23056   // against zero. e.g.
23057   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23058   // subl   %esi, %edi
23059   // testl  %edi, %edi
23060   // movl   $0, %eax
23061   // cmovgl %edi, %eax
23062   // =>
23063   // xorl   %eax, %eax
23064   // subl   %esi, $edi
23065   // cmovsl %eax, %edi
23066   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23067       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23068       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23069     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23070     switch (CC) {
23071     default: break;
23072     case ISD::SETLT:
23073     case ISD::SETGT: {
23074       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23075       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23076                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23077       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23078     }
23079     }
23080   }
23081
23082   // Early exit check
23083   if (!TLI.isTypeLegal(VT))
23084     return SDValue();
23085
23086   // Match VSELECTs into subs with unsigned saturation.
23087   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23088       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23089       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23090        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23091     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23092
23093     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23094     // left side invert the predicate to simplify logic below.
23095     SDValue Other;
23096     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23097       Other = RHS;
23098       CC = ISD::getSetCCInverse(CC, true);
23099     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23100       Other = LHS;
23101     }
23102
23103     if (Other.getNode() && Other->getNumOperands() == 2 &&
23104         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23105       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23106       SDValue CondRHS = Cond->getOperand(1);
23107
23108       // Look for a general sub with unsigned saturation first.
23109       // x >= y ? x-y : 0 --> subus x, y
23110       // x >  y ? x-y : 0 --> subus x, y
23111       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23112           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23113         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23114
23115       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23116         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23117           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23118             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23119               // If the RHS is a constant we have to reverse the const
23120               // canonicalization.
23121               // x > C-1 ? x+-C : 0 --> subus x, C
23122               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23123                   CondRHSConst->getAPIntValue() ==
23124                       (-OpRHSConst->getAPIntValue() - 1))
23125                 return DAG.getNode(
23126                     X86ISD::SUBUS, DL, VT, OpLHS,
23127                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
23128
23129           // Another special case: If C was a sign bit, the sub has been
23130           // canonicalized into a xor.
23131           // FIXME: Would it be better to use computeKnownBits to determine
23132           //        whether it's safe to decanonicalize the xor?
23133           // x s< 0 ? x^C : 0 --> subus x, C
23134           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23135               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23136               OpRHSConst->getAPIntValue().isSignBit())
23137             // Note that we have to rebuild the RHS constant here to ensure we
23138             // don't rely on particular values of undef lanes.
23139             return DAG.getNode(
23140                 X86ISD::SUBUS, DL, VT, OpLHS,
23141                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
23142         }
23143     }
23144   }
23145
23146   // Try to match a min/max vector operation.
23147   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
23148     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
23149     unsigned Opc = ret.first;
23150     bool NeedSplit = ret.second;
23151
23152     if (Opc && NeedSplit) {
23153       unsigned NumElems = VT.getVectorNumElements();
23154       // Extract the LHS vectors
23155       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
23156       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
23157
23158       // Extract the RHS vectors
23159       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
23160       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
23161
23162       // Create min/max for each subvector
23163       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
23164       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
23165
23166       // Merge the result
23167       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
23168     } else if (Opc)
23169       return DAG.getNode(Opc, DL, VT, LHS, RHS);
23170   }
23171
23172   // Simplify vector selection if condition value type matches vselect
23173   // operand type
23174   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23175     assert(Cond.getValueType().isVector() &&
23176            "vector select expects a vector selector!");
23177
23178     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23179     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23180
23181     // Try invert the condition if true value is not all 1s and false value
23182     // is not all 0s.
23183     if (!TValIsAllOnes && !FValIsAllZeros &&
23184         // Check if the selector will be produced by CMPP*/PCMP*
23185         Cond.getOpcode() == ISD::SETCC &&
23186         // Check if SETCC has already been promoted
23187         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
23188       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23189       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23190
23191       if (TValIsAllZeros || FValIsAllOnes) {
23192         SDValue CC = Cond.getOperand(2);
23193         ISD::CondCode NewCC =
23194           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23195                                Cond.getOperand(0).getValueType().isInteger());
23196         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23197         std::swap(LHS, RHS);
23198         TValIsAllOnes = FValIsAllOnes;
23199         FValIsAllZeros = TValIsAllZeros;
23200       }
23201     }
23202
23203     if (TValIsAllOnes || FValIsAllZeros) {
23204       SDValue Ret;
23205
23206       if (TValIsAllOnes && FValIsAllZeros)
23207         Ret = Cond;
23208       else if (TValIsAllOnes)
23209         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
23210                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
23211       else if (FValIsAllZeros)
23212         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23213                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
23214
23215       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
23216     }
23217   }
23218
23219   // If we know that this node is legal then we know that it is going to be
23220   // matched by one of the SSE/AVX BLEND instructions. These instructions only
23221   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
23222   // to simplify previous instructions.
23223   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23224       !DCI.isBeforeLegalize() &&
23225       // We explicitly check against v8i16 and v16i16 because, although
23226       // they're marked as Custom, they might only be legal when Cond is a
23227       // build_vector of constants. This will be taken care in a later
23228       // condition.
23229       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
23230        VT != MVT::v8i16) &&
23231       // Don't optimize vector of constants. Those are handled by
23232       // the generic code and all the bits must be properly set for
23233       // the generic optimizer.
23234       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23235     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23236
23237     // Don't optimize vector selects that map to mask-registers.
23238     if (BitWidth == 1)
23239       return SDValue();
23240
23241     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23242     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23243
23244     APInt KnownZero, KnownOne;
23245     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23246                                           DCI.isBeforeLegalizeOps());
23247     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23248         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23249                                  TLO)) {
23250       // If we changed the computation somewhere in the DAG, this change
23251       // will affect all users of Cond.
23252       // Make sure it is fine and update all the nodes so that we do not
23253       // use the generic VSELECT anymore. Otherwise, we may perform
23254       // wrong optimizations as we messed up with the actual expectation
23255       // for the vector boolean values.
23256       if (Cond != TLO.Old) {
23257         // Check all uses of that condition operand to check whether it will be
23258         // consumed by non-BLEND instructions, which may depend on all bits are
23259         // set properly.
23260         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23261              I != E; ++I)
23262           if (I->getOpcode() != ISD::VSELECT)
23263             // TODO: Add other opcodes eventually lowered into BLEND.
23264             return SDValue();
23265
23266         // Update all the users of the condition, before committing the change,
23267         // so that the VSELECT optimizations that expect the correct vector
23268         // boolean value will not be triggered.
23269         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23270              I != E; ++I)
23271           DAG.ReplaceAllUsesOfValueWith(
23272               SDValue(*I, 0),
23273               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23274                           Cond, I->getOperand(1), I->getOperand(2)));
23275         DCI.CommitTargetLoweringOpt(TLO);
23276         return SDValue();
23277       }
23278       // At this point, only Cond is changed. Change the condition
23279       // just for N to keep the opportunity to optimize all other
23280       // users their own way.
23281       DAG.ReplaceAllUsesOfValueWith(
23282           SDValue(N, 0),
23283           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23284                       TLO.New, N->getOperand(1), N->getOperand(2)));
23285       return SDValue();
23286     }
23287   }
23288
23289   // We should generate an X86ISD::BLENDI from a vselect if its argument
23290   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23291   // constants. This specific pattern gets generated when we split a
23292   // selector for a 512 bit vector in a machine without AVX512 (but with
23293   // 256-bit vectors), during legalization:
23294   //
23295   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23296   //
23297   // Iff we find this pattern and the build_vectors are built from
23298   // constants, we translate the vselect into a shuffle_vector that we
23299   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23300   if ((N->getOpcode() == ISD::VSELECT ||
23301        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23302       !DCI.isBeforeLegalize()) {
23303     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23304     if (Shuffle.getNode())
23305       return Shuffle;
23306   }
23307
23308   return SDValue();
23309 }
23310
23311 // Check whether a boolean test is testing a boolean value generated by
23312 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23313 // code.
23314 //
23315 // Simplify the following patterns:
23316 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23317 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23318 // to (Op EFLAGS Cond)
23319 //
23320 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23321 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23322 // to (Op EFLAGS !Cond)
23323 //
23324 // where Op could be BRCOND or CMOV.
23325 //
23326 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23327   // Quit if not CMP and SUB with its value result used.
23328   if (Cmp.getOpcode() != X86ISD::CMP &&
23329       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23330       return SDValue();
23331
23332   // Quit if not used as a boolean value.
23333   if (CC != X86::COND_E && CC != X86::COND_NE)
23334     return SDValue();
23335
23336   // Check CMP operands. One of them should be 0 or 1 and the other should be
23337   // an SetCC or extended from it.
23338   SDValue Op1 = Cmp.getOperand(0);
23339   SDValue Op2 = Cmp.getOperand(1);
23340
23341   SDValue SetCC;
23342   const ConstantSDNode* C = nullptr;
23343   bool needOppositeCond = (CC == X86::COND_E);
23344   bool checkAgainstTrue = false; // Is it a comparison against 1?
23345
23346   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23347     SetCC = Op2;
23348   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23349     SetCC = Op1;
23350   else // Quit if all operands are not constants.
23351     return SDValue();
23352
23353   if (C->getZExtValue() == 1) {
23354     needOppositeCond = !needOppositeCond;
23355     checkAgainstTrue = true;
23356   } else if (C->getZExtValue() != 0)
23357     // Quit if the constant is neither 0 or 1.
23358     return SDValue();
23359
23360   bool truncatedToBoolWithAnd = false;
23361   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23362   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23363          SetCC.getOpcode() == ISD::TRUNCATE ||
23364          SetCC.getOpcode() == ISD::AND) {
23365     if (SetCC.getOpcode() == ISD::AND) {
23366       int OpIdx = -1;
23367       ConstantSDNode *CS;
23368       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23369           CS->getZExtValue() == 1)
23370         OpIdx = 1;
23371       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23372           CS->getZExtValue() == 1)
23373         OpIdx = 0;
23374       if (OpIdx == -1)
23375         break;
23376       SetCC = SetCC.getOperand(OpIdx);
23377       truncatedToBoolWithAnd = true;
23378     } else
23379       SetCC = SetCC.getOperand(0);
23380   }
23381
23382   switch (SetCC.getOpcode()) {
23383   case X86ISD::SETCC_CARRY:
23384     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23385     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23386     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23387     // truncated to i1 using 'and'.
23388     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23389       break;
23390     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23391            "Invalid use of SETCC_CARRY!");
23392     // FALL THROUGH
23393   case X86ISD::SETCC:
23394     // Set the condition code or opposite one if necessary.
23395     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23396     if (needOppositeCond)
23397       CC = X86::GetOppositeBranchCondition(CC);
23398     return SetCC.getOperand(1);
23399   case X86ISD::CMOV: {
23400     // Check whether false/true value has canonical one, i.e. 0 or 1.
23401     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23402     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23403     // Quit if true value is not a constant.
23404     if (!TVal)
23405       return SDValue();
23406     // Quit if false value is not a constant.
23407     if (!FVal) {
23408       SDValue Op = SetCC.getOperand(0);
23409       // Skip 'zext' or 'trunc' node.
23410       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23411           Op.getOpcode() == ISD::TRUNCATE)
23412         Op = Op.getOperand(0);
23413       // A special case for rdrand/rdseed, where 0 is set if false cond is
23414       // found.
23415       if ((Op.getOpcode() != X86ISD::RDRAND &&
23416            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23417         return SDValue();
23418     }
23419     // Quit if false value is not the constant 0 or 1.
23420     bool FValIsFalse = true;
23421     if (FVal && FVal->getZExtValue() != 0) {
23422       if (FVal->getZExtValue() != 1)
23423         return SDValue();
23424       // If FVal is 1, opposite cond is needed.
23425       needOppositeCond = !needOppositeCond;
23426       FValIsFalse = false;
23427     }
23428     // Quit if TVal is not the constant opposite of FVal.
23429     if (FValIsFalse && TVal->getZExtValue() != 1)
23430       return SDValue();
23431     if (!FValIsFalse && TVal->getZExtValue() != 0)
23432       return SDValue();
23433     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23434     if (needOppositeCond)
23435       CC = X86::GetOppositeBranchCondition(CC);
23436     return SetCC.getOperand(3);
23437   }
23438   }
23439
23440   return SDValue();
23441 }
23442
23443 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23444 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23445                                   TargetLowering::DAGCombinerInfo &DCI,
23446                                   const X86Subtarget *Subtarget) {
23447   SDLoc DL(N);
23448
23449   // If the flag operand isn't dead, don't touch this CMOV.
23450   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23451     return SDValue();
23452
23453   SDValue FalseOp = N->getOperand(0);
23454   SDValue TrueOp = N->getOperand(1);
23455   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23456   SDValue Cond = N->getOperand(3);
23457
23458   if (CC == X86::COND_E || CC == X86::COND_NE) {
23459     switch (Cond.getOpcode()) {
23460     default: break;
23461     case X86ISD::BSR:
23462     case X86ISD::BSF:
23463       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23464       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23465         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23466     }
23467   }
23468
23469   SDValue Flags;
23470
23471   Flags = checkBoolTestSetCCCombine(Cond, CC);
23472   if (Flags.getNode() &&
23473       // Extra check as FCMOV only supports a subset of X86 cond.
23474       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23475     SDValue Ops[] = { FalseOp, TrueOp,
23476                       DAG.getConstant(CC, MVT::i8), Flags };
23477     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23478   }
23479
23480   // If this is a select between two integer constants, try to do some
23481   // optimizations.  Note that the operands are ordered the opposite of SELECT
23482   // operands.
23483   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23484     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23485       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23486       // larger than FalseC (the false value).
23487       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23488         CC = X86::GetOppositeBranchCondition(CC);
23489         std::swap(TrueC, FalseC);
23490         std::swap(TrueOp, FalseOp);
23491       }
23492
23493       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23494       // This is efficient for any integer data type (including i8/i16) and
23495       // shift amount.
23496       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23497         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23498                            DAG.getConstant(CC, MVT::i8), Cond);
23499
23500         // Zero extend the condition if needed.
23501         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23502
23503         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23504         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23505                            DAG.getConstant(ShAmt, MVT::i8));
23506         if (N->getNumValues() == 2)  // Dead flag value?
23507           return DCI.CombineTo(N, Cond, SDValue());
23508         return Cond;
23509       }
23510
23511       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23512       // for any integer data type, including i8/i16.
23513       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23514         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23515                            DAG.getConstant(CC, MVT::i8), Cond);
23516
23517         // Zero extend the condition if needed.
23518         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23519                            FalseC->getValueType(0), Cond);
23520         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23521                            SDValue(FalseC, 0));
23522
23523         if (N->getNumValues() == 2)  // Dead flag value?
23524           return DCI.CombineTo(N, Cond, SDValue());
23525         return Cond;
23526       }
23527
23528       // Optimize cases that will turn into an LEA instruction.  This requires
23529       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23530       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23531         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23532         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23533
23534         bool isFastMultiplier = false;
23535         if (Diff < 10) {
23536           switch ((unsigned char)Diff) {
23537           default: break;
23538           case 1:  // result = add base, cond
23539           case 2:  // result = lea base(    , cond*2)
23540           case 3:  // result = lea base(cond, cond*2)
23541           case 4:  // result = lea base(    , cond*4)
23542           case 5:  // result = lea base(cond, cond*4)
23543           case 8:  // result = lea base(    , cond*8)
23544           case 9:  // result = lea base(cond, cond*8)
23545             isFastMultiplier = true;
23546             break;
23547           }
23548         }
23549
23550         if (isFastMultiplier) {
23551           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23552           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23553                              DAG.getConstant(CC, MVT::i8), Cond);
23554           // Zero extend the condition if needed.
23555           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23556                              Cond);
23557           // Scale the condition by the difference.
23558           if (Diff != 1)
23559             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23560                                DAG.getConstant(Diff, Cond.getValueType()));
23561
23562           // Add the base if non-zero.
23563           if (FalseC->getAPIntValue() != 0)
23564             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23565                                SDValue(FalseC, 0));
23566           if (N->getNumValues() == 2)  // Dead flag value?
23567             return DCI.CombineTo(N, Cond, SDValue());
23568           return Cond;
23569         }
23570       }
23571     }
23572   }
23573
23574   // Handle these cases:
23575   //   (select (x != c), e, c) -> select (x != c), e, x),
23576   //   (select (x == c), c, e) -> select (x == c), x, e)
23577   // where the c is an integer constant, and the "select" is the combination
23578   // of CMOV and CMP.
23579   //
23580   // The rationale for this change is that the conditional-move from a constant
23581   // needs two instructions, however, conditional-move from a register needs
23582   // only one instruction.
23583   //
23584   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23585   //  some instruction-combining opportunities. This opt needs to be
23586   //  postponed as late as possible.
23587   //
23588   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23589     // the DCI.xxxx conditions are provided to postpone the optimization as
23590     // late as possible.
23591
23592     ConstantSDNode *CmpAgainst = nullptr;
23593     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23594         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23595         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23596
23597       if (CC == X86::COND_NE &&
23598           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23599         CC = X86::GetOppositeBranchCondition(CC);
23600         std::swap(TrueOp, FalseOp);
23601       }
23602
23603       if (CC == X86::COND_E &&
23604           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23605         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23606                           DAG.getConstant(CC, MVT::i8), Cond };
23607         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23608       }
23609     }
23610   }
23611
23612   return SDValue();
23613 }
23614
23615 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23616                                                 const X86Subtarget *Subtarget) {
23617   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23618   switch (IntNo) {
23619   default: return SDValue();
23620   // SSE/AVX/AVX2 blend intrinsics.
23621   case Intrinsic::x86_avx2_pblendvb:
23622   case Intrinsic::x86_avx2_pblendw:
23623   case Intrinsic::x86_avx2_pblendd_128:
23624   case Intrinsic::x86_avx2_pblendd_256:
23625     // Don't try to simplify this intrinsic if we don't have AVX2.
23626     if (!Subtarget->hasAVX2())
23627       return SDValue();
23628     // FALL-THROUGH
23629   case Intrinsic::x86_avx_blend_pd_256:
23630   case Intrinsic::x86_avx_blend_ps_256:
23631   case Intrinsic::x86_avx_blendv_pd_256:
23632   case Intrinsic::x86_avx_blendv_ps_256:
23633     // Don't try to simplify this intrinsic if we don't have AVX.
23634     if (!Subtarget->hasAVX())
23635       return SDValue();
23636     // FALL-THROUGH
23637   case Intrinsic::x86_sse41_pblendw:
23638   case Intrinsic::x86_sse41_blendpd:
23639   case Intrinsic::x86_sse41_blendps:
23640   case Intrinsic::x86_sse41_blendvps:
23641   case Intrinsic::x86_sse41_blendvpd:
23642   case Intrinsic::x86_sse41_pblendvb: {
23643     SDValue Op0 = N->getOperand(1);
23644     SDValue Op1 = N->getOperand(2);
23645     SDValue Mask = N->getOperand(3);
23646
23647     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23648     if (!Subtarget->hasSSE41())
23649       return SDValue();
23650
23651     // fold (blend A, A, Mask) -> A
23652     if (Op0 == Op1)
23653       return Op0;
23654     // fold (blend A, B, allZeros) -> A
23655     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23656       return Op0;
23657     // fold (blend A, B, allOnes) -> B
23658     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23659       return Op1;
23660
23661     // Simplify the case where the mask is a constant i32 value.
23662     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23663       if (C->isNullValue())
23664         return Op0;
23665       if (C->isAllOnesValue())
23666         return Op1;
23667     }
23668
23669     return SDValue();
23670   }
23671
23672   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23673   case Intrinsic::x86_sse2_psrai_w:
23674   case Intrinsic::x86_sse2_psrai_d:
23675   case Intrinsic::x86_avx2_psrai_w:
23676   case Intrinsic::x86_avx2_psrai_d:
23677   case Intrinsic::x86_sse2_psra_w:
23678   case Intrinsic::x86_sse2_psra_d:
23679   case Intrinsic::x86_avx2_psra_w:
23680   case Intrinsic::x86_avx2_psra_d: {
23681     SDValue Op0 = N->getOperand(1);
23682     SDValue Op1 = N->getOperand(2);
23683     EVT VT = Op0.getValueType();
23684     assert(VT.isVector() && "Expected a vector type!");
23685
23686     if (isa<BuildVectorSDNode>(Op1))
23687       Op1 = Op1.getOperand(0);
23688
23689     if (!isa<ConstantSDNode>(Op1))
23690       return SDValue();
23691
23692     EVT SVT = VT.getVectorElementType();
23693     unsigned SVTBits = SVT.getSizeInBits();
23694
23695     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23696     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23697     uint64_t ShAmt = C.getZExtValue();
23698
23699     // Don't try to convert this shift into a ISD::SRA if the shift
23700     // count is bigger than or equal to the element size.
23701     if (ShAmt >= SVTBits)
23702       return SDValue();
23703
23704     // Trivial case: if the shift count is zero, then fold this
23705     // into the first operand.
23706     if (ShAmt == 0)
23707       return Op0;
23708
23709     // Replace this packed shift intrinsic with a target independent
23710     // shift dag node.
23711     SDValue Splat = DAG.getConstant(C, VT);
23712     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
23713   }
23714   }
23715 }
23716
23717 /// PerformMulCombine - Optimize a single multiply with constant into two
23718 /// in order to implement it with two cheaper instructions, e.g.
23719 /// LEA + SHL, LEA + LEA.
23720 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23721                                  TargetLowering::DAGCombinerInfo &DCI) {
23722   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23723     return SDValue();
23724
23725   EVT VT = N->getValueType(0);
23726   if (VT != MVT::i64)
23727     return SDValue();
23728
23729   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23730   if (!C)
23731     return SDValue();
23732   uint64_t MulAmt = C->getZExtValue();
23733   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23734     return SDValue();
23735
23736   uint64_t MulAmt1 = 0;
23737   uint64_t MulAmt2 = 0;
23738   if ((MulAmt % 9) == 0) {
23739     MulAmt1 = 9;
23740     MulAmt2 = MulAmt / 9;
23741   } else if ((MulAmt % 5) == 0) {
23742     MulAmt1 = 5;
23743     MulAmt2 = MulAmt / 5;
23744   } else if ((MulAmt % 3) == 0) {
23745     MulAmt1 = 3;
23746     MulAmt2 = MulAmt / 3;
23747   }
23748   if (MulAmt2 &&
23749       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23750     SDLoc DL(N);
23751
23752     if (isPowerOf2_64(MulAmt2) &&
23753         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23754       // If second multiplifer is pow2, issue it first. We want the multiply by
23755       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23756       // is an add.
23757       std::swap(MulAmt1, MulAmt2);
23758
23759     SDValue NewMul;
23760     if (isPowerOf2_64(MulAmt1))
23761       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23762                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
23763     else
23764       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23765                            DAG.getConstant(MulAmt1, VT));
23766
23767     if (isPowerOf2_64(MulAmt2))
23768       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23769                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
23770     else
23771       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23772                            DAG.getConstant(MulAmt2, VT));
23773
23774     // Do not add new nodes to DAG combiner worklist.
23775     DCI.CombineTo(N, NewMul, false);
23776   }
23777   return SDValue();
23778 }
23779
23780 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23781   SDValue N0 = N->getOperand(0);
23782   SDValue N1 = N->getOperand(1);
23783   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23784   EVT VT = N0.getValueType();
23785
23786   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23787   // since the result of setcc_c is all zero's or all ones.
23788   if (VT.isInteger() && !VT.isVector() &&
23789       N1C && N0.getOpcode() == ISD::AND &&
23790       N0.getOperand(1).getOpcode() == ISD::Constant) {
23791     SDValue N00 = N0.getOperand(0);
23792     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23793         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23794           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23795          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23796       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23797       APInt ShAmt = N1C->getAPIntValue();
23798       Mask = Mask.shl(ShAmt);
23799       if (Mask != 0)
23800         return DAG.getNode(ISD::AND, SDLoc(N), VT,
23801                            N00, DAG.getConstant(Mask, VT));
23802     }
23803   }
23804
23805   // Hardware support for vector shifts is sparse which makes us scalarize the
23806   // vector operations in many cases. Also, on sandybridge ADD is faster than
23807   // shl.
23808   // (shl V, 1) -> add V,V
23809   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23810     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23811       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23812       // We shift all of the values by one. In many cases we do not have
23813       // hardware support for this operation. This is better expressed as an ADD
23814       // of two values.
23815       if (N1SplatC->getZExtValue() == 1)
23816         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23817     }
23818
23819   return SDValue();
23820 }
23821
23822 /// \brief Returns a vector of 0s if the node in input is a vector logical
23823 /// shift by a constant amount which is known to be bigger than or equal
23824 /// to the vector element size in bits.
23825 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23826                                       const X86Subtarget *Subtarget) {
23827   EVT VT = N->getValueType(0);
23828
23829   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23830       (!Subtarget->hasInt256() ||
23831        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23832     return SDValue();
23833
23834   SDValue Amt = N->getOperand(1);
23835   SDLoc DL(N);
23836   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23837     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23838       APInt ShiftAmt = AmtSplat->getAPIntValue();
23839       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23840
23841       // SSE2/AVX2 logical shifts always return a vector of 0s
23842       // if the shift amount is bigger than or equal to
23843       // the element size. The constant shift amount will be
23844       // encoded as a 8-bit immediate.
23845       if (ShiftAmt.trunc(8).uge(MaxAmount))
23846         return getZeroVector(VT, Subtarget, DAG, DL);
23847     }
23848
23849   return SDValue();
23850 }
23851
23852 /// PerformShiftCombine - Combine shifts.
23853 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23854                                    TargetLowering::DAGCombinerInfo &DCI,
23855                                    const X86Subtarget *Subtarget) {
23856   if (N->getOpcode() == ISD::SHL) {
23857     SDValue V = PerformSHLCombine(N, DAG);
23858     if (V.getNode()) return V;
23859   }
23860
23861   if (N->getOpcode() != ISD::SRA) {
23862     // Try to fold this logical shift into a zero vector.
23863     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
23864     if (V.getNode()) return V;
23865   }
23866
23867   return SDValue();
23868 }
23869
23870 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23871 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23872 // and friends.  Likewise for OR -> CMPNEQSS.
23873 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23874                             TargetLowering::DAGCombinerInfo &DCI,
23875                             const X86Subtarget *Subtarget) {
23876   unsigned opcode;
23877
23878   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23879   // we're requiring SSE2 for both.
23880   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23881     SDValue N0 = N->getOperand(0);
23882     SDValue N1 = N->getOperand(1);
23883     SDValue CMP0 = N0->getOperand(1);
23884     SDValue CMP1 = N1->getOperand(1);
23885     SDLoc DL(N);
23886
23887     // The SETCCs should both refer to the same CMP.
23888     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23889       return SDValue();
23890
23891     SDValue CMP00 = CMP0->getOperand(0);
23892     SDValue CMP01 = CMP0->getOperand(1);
23893     EVT     VT    = CMP00.getValueType();
23894
23895     if (VT == MVT::f32 || VT == MVT::f64) {
23896       bool ExpectingFlags = false;
23897       // Check for any users that want flags:
23898       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23899            !ExpectingFlags && UI != UE; ++UI)
23900         switch (UI->getOpcode()) {
23901         default:
23902         case ISD::BR_CC:
23903         case ISD::BRCOND:
23904         case ISD::SELECT:
23905           ExpectingFlags = true;
23906           break;
23907         case ISD::CopyToReg:
23908         case ISD::SIGN_EXTEND:
23909         case ISD::ZERO_EXTEND:
23910         case ISD::ANY_EXTEND:
23911           break;
23912         }
23913
23914       if (!ExpectingFlags) {
23915         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23916         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23917
23918         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23919           X86::CondCode tmp = cc0;
23920           cc0 = cc1;
23921           cc1 = tmp;
23922         }
23923
23924         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23925             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23926           // FIXME: need symbolic constants for these magic numbers.
23927           // See X86ATTInstPrinter.cpp:printSSECC().
23928           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23929           if (Subtarget->hasAVX512()) {
23930             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23931                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
23932             if (N->getValueType(0) != MVT::i1)
23933               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23934                                  FSetCC);
23935             return FSetCC;
23936           }
23937           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23938                                               CMP00.getValueType(), CMP00, CMP01,
23939                                               DAG.getConstant(x86cc, MVT::i8));
23940
23941           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23942           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23943
23944           if (is64BitFP && !Subtarget->is64Bit()) {
23945             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23946             // 64-bit integer, since that's not a legal type. Since
23947             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23948             // bits, but can do this little dance to extract the lowest 32 bits
23949             // and work with those going forward.
23950             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23951                                            OnesOrZeroesF);
23952             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
23953                                            Vector64);
23954             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23955                                         Vector32, DAG.getIntPtrConstant(0));
23956             IntVT = MVT::i32;
23957           }
23958
23959           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
23960           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23961                                       DAG.getConstant(1, IntVT));
23962           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
23963           return OneBitOfTruth;
23964         }
23965       }
23966     }
23967   }
23968   return SDValue();
23969 }
23970
23971 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23972 /// so it can be folded inside ANDNP.
23973 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23974   EVT VT = N->getValueType(0);
23975
23976   // Match direct AllOnes for 128 and 256-bit vectors
23977   if (ISD::isBuildVectorAllOnes(N))
23978     return true;
23979
23980   // Look through a bit convert.
23981   if (N->getOpcode() == ISD::BITCAST)
23982     N = N->getOperand(0).getNode();
23983
23984   // Sometimes the operand may come from a insert_subvector building a 256-bit
23985   // allones vector
23986   if (VT.is256BitVector() &&
23987       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23988     SDValue V1 = N->getOperand(0);
23989     SDValue V2 = N->getOperand(1);
23990
23991     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23992         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23993         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23994         ISD::isBuildVectorAllOnes(V2.getNode()))
23995       return true;
23996   }
23997
23998   return false;
23999 }
24000
24001 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24002 // register. In most cases we actually compare or select YMM-sized registers
24003 // and mixing the two types creates horrible code. This method optimizes
24004 // some of the transition sequences.
24005 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24006                                  TargetLowering::DAGCombinerInfo &DCI,
24007                                  const X86Subtarget *Subtarget) {
24008   EVT VT = N->getValueType(0);
24009   if (!VT.is256BitVector())
24010     return SDValue();
24011
24012   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24013           N->getOpcode() == ISD::ZERO_EXTEND ||
24014           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24015
24016   SDValue Narrow = N->getOperand(0);
24017   EVT NarrowVT = Narrow->getValueType(0);
24018   if (!NarrowVT.is128BitVector())
24019     return SDValue();
24020
24021   if (Narrow->getOpcode() != ISD::XOR &&
24022       Narrow->getOpcode() != ISD::AND &&
24023       Narrow->getOpcode() != ISD::OR)
24024     return SDValue();
24025
24026   SDValue N0  = Narrow->getOperand(0);
24027   SDValue N1  = Narrow->getOperand(1);
24028   SDLoc DL(Narrow);
24029
24030   // The Left side has to be a trunc.
24031   if (N0.getOpcode() != ISD::TRUNCATE)
24032     return SDValue();
24033
24034   // The type of the truncated inputs.
24035   EVT WideVT = N0->getOperand(0)->getValueType(0);
24036   if (WideVT != VT)
24037     return SDValue();
24038
24039   // The right side has to be a 'trunc' or a constant vector.
24040   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24041   ConstantSDNode *RHSConstSplat = nullptr;
24042   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24043     RHSConstSplat = RHSBV->getConstantSplatNode();
24044   if (!RHSTrunc && !RHSConstSplat)
24045     return SDValue();
24046
24047   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24048
24049   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24050     return SDValue();
24051
24052   // Set N0 and N1 to hold the inputs to the new wide operation.
24053   N0 = N0->getOperand(0);
24054   if (RHSConstSplat) {
24055     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24056                      SDValue(RHSConstSplat, 0));
24057     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24058     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24059   } else if (RHSTrunc) {
24060     N1 = N1->getOperand(0);
24061   }
24062
24063   // Generate the wide operation.
24064   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24065   unsigned Opcode = N->getOpcode();
24066   switch (Opcode) {
24067   case ISD::ANY_EXTEND:
24068     return Op;
24069   case ISD::ZERO_EXTEND: {
24070     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24071     APInt Mask = APInt::getAllOnesValue(InBits);
24072     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24073     return DAG.getNode(ISD::AND, DL, VT,
24074                        Op, DAG.getConstant(Mask, VT));
24075   }
24076   case ISD::SIGN_EXTEND:
24077     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24078                        Op, DAG.getValueType(NarrowVT));
24079   default:
24080     llvm_unreachable("Unexpected opcode");
24081   }
24082 }
24083
24084 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24085                                  TargetLowering::DAGCombinerInfo &DCI,
24086                                  const X86Subtarget *Subtarget) {
24087   EVT VT = N->getValueType(0);
24088   if (DCI.isBeforeLegalizeOps())
24089     return SDValue();
24090
24091   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24092   if (R.getNode())
24093     return R;
24094
24095   // Create BEXTR instructions
24096   // BEXTR is ((X >> imm) & (2**size-1))
24097   if (VT == MVT::i32 || VT == MVT::i64) {
24098     SDValue N0 = N->getOperand(0);
24099     SDValue N1 = N->getOperand(1);
24100     SDLoc DL(N);
24101
24102     // Check for BEXTR.
24103     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24104         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24105       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24106       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24107       if (MaskNode && ShiftNode) {
24108         uint64_t Mask = MaskNode->getZExtValue();
24109         uint64_t Shift = ShiftNode->getZExtValue();
24110         if (isMask_64(Mask)) {
24111           uint64_t MaskSize = CountPopulation_64(Mask);
24112           if (Shift + MaskSize <= VT.getSizeInBits())
24113             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24114                                DAG.getConstant(Shift | (MaskSize << 8), VT));
24115         }
24116       }
24117     } // BEXTR
24118
24119     return SDValue();
24120   }
24121
24122   // Want to form ANDNP nodes:
24123   // 1) In the hopes of then easily combining them with OR and AND nodes
24124   //    to form PBLEND/PSIGN.
24125   // 2) To match ANDN packed intrinsics
24126   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24127     return SDValue();
24128
24129   SDValue N0 = N->getOperand(0);
24130   SDValue N1 = N->getOperand(1);
24131   SDLoc DL(N);
24132
24133   // Check LHS for vnot
24134   if (N0.getOpcode() == ISD::XOR &&
24135       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24136       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24137     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24138
24139   // Check RHS for vnot
24140   if (N1.getOpcode() == ISD::XOR &&
24141       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24142       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24143     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24144
24145   return SDValue();
24146 }
24147
24148 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24149                                 TargetLowering::DAGCombinerInfo &DCI,
24150                                 const X86Subtarget *Subtarget) {
24151   if (DCI.isBeforeLegalizeOps())
24152     return SDValue();
24153
24154   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24155   if (R.getNode())
24156     return R;
24157
24158   SDValue N0 = N->getOperand(0);
24159   SDValue N1 = N->getOperand(1);
24160   EVT VT = N->getValueType(0);
24161
24162   // look for psign/blend
24163   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24164     if (!Subtarget->hasSSSE3() ||
24165         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24166       return SDValue();
24167
24168     // Canonicalize pandn to RHS
24169     if (N0.getOpcode() == X86ISD::ANDNP)
24170       std::swap(N0, N1);
24171     // or (and (m, y), (pandn m, x))
24172     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24173       SDValue Mask = N1.getOperand(0);
24174       SDValue X    = N1.getOperand(1);
24175       SDValue Y;
24176       if (N0.getOperand(0) == Mask)
24177         Y = N0.getOperand(1);
24178       if (N0.getOperand(1) == Mask)
24179         Y = N0.getOperand(0);
24180
24181       // Check to see if the mask appeared in both the AND and ANDNP and
24182       if (!Y.getNode())
24183         return SDValue();
24184
24185       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24186       // Look through mask bitcast.
24187       if (Mask.getOpcode() == ISD::BITCAST)
24188         Mask = Mask.getOperand(0);
24189       if (X.getOpcode() == ISD::BITCAST)
24190         X = X.getOperand(0);
24191       if (Y.getOpcode() == ISD::BITCAST)
24192         Y = Y.getOperand(0);
24193
24194       EVT MaskVT = Mask.getValueType();
24195
24196       // Validate that the Mask operand is a vector sra node.
24197       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24198       // there is no psrai.b
24199       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24200       unsigned SraAmt = ~0;
24201       if (Mask.getOpcode() == ISD::SRA) {
24202         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24203           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24204             SraAmt = AmtConst->getZExtValue();
24205       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24206         SDValue SraC = Mask.getOperand(1);
24207         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24208       }
24209       if ((SraAmt + 1) != EltBits)
24210         return SDValue();
24211
24212       SDLoc DL(N);
24213
24214       // Now we know we at least have a plendvb with the mask val.  See if
24215       // we can form a psignb/w/d.
24216       // psign = x.type == y.type == mask.type && y = sub(0, x);
24217       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24218           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24219           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24220         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24221                "Unsupported VT for PSIGN");
24222         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24223         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24224       }
24225       // PBLENDVB only available on SSE 4.1
24226       if (!Subtarget->hasSSE41())
24227         return SDValue();
24228
24229       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24230
24231       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
24232       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
24233       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
24234       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24235       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24236     }
24237   }
24238
24239   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24240     return SDValue();
24241
24242   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24243   MachineFunction &MF = DAG.getMachineFunction();
24244   bool OptForSize = MF.getFunction()->getAttributes().
24245     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
24246
24247   // SHLD/SHRD instructions have lower register pressure, but on some
24248   // platforms they have higher latency than the equivalent
24249   // series of shifts/or that would otherwise be generated.
24250   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24251   // have higher latencies and we are not optimizing for size.
24252   if (!OptForSize && Subtarget->isSHLDSlow())
24253     return SDValue();
24254
24255   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24256     std::swap(N0, N1);
24257   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24258     return SDValue();
24259   if (!N0.hasOneUse() || !N1.hasOneUse())
24260     return SDValue();
24261
24262   SDValue ShAmt0 = N0.getOperand(1);
24263   if (ShAmt0.getValueType() != MVT::i8)
24264     return SDValue();
24265   SDValue ShAmt1 = N1.getOperand(1);
24266   if (ShAmt1.getValueType() != MVT::i8)
24267     return SDValue();
24268   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24269     ShAmt0 = ShAmt0.getOperand(0);
24270   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24271     ShAmt1 = ShAmt1.getOperand(0);
24272
24273   SDLoc DL(N);
24274   unsigned Opc = X86ISD::SHLD;
24275   SDValue Op0 = N0.getOperand(0);
24276   SDValue Op1 = N1.getOperand(0);
24277   if (ShAmt0.getOpcode() == ISD::SUB) {
24278     Opc = X86ISD::SHRD;
24279     std::swap(Op0, Op1);
24280     std::swap(ShAmt0, ShAmt1);
24281   }
24282
24283   unsigned Bits = VT.getSizeInBits();
24284   if (ShAmt1.getOpcode() == ISD::SUB) {
24285     SDValue Sum = ShAmt1.getOperand(0);
24286     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24287       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24288       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24289         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24290       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24291         return DAG.getNode(Opc, DL, VT,
24292                            Op0, Op1,
24293                            DAG.getNode(ISD::TRUNCATE, DL,
24294                                        MVT::i8, ShAmt0));
24295     }
24296   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24297     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24298     if (ShAmt0C &&
24299         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24300       return DAG.getNode(Opc, DL, VT,
24301                          N0.getOperand(0), N1.getOperand(0),
24302                          DAG.getNode(ISD::TRUNCATE, DL,
24303                                        MVT::i8, ShAmt0));
24304   }
24305
24306   return SDValue();
24307 }
24308
24309 // Generate NEG and CMOV for integer abs.
24310 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24311   EVT VT = N->getValueType(0);
24312
24313   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24314   // 8-bit integer abs to NEG and CMOV.
24315   if (VT.isInteger() && VT.getSizeInBits() == 8)
24316     return SDValue();
24317
24318   SDValue N0 = N->getOperand(0);
24319   SDValue N1 = N->getOperand(1);
24320   SDLoc DL(N);
24321
24322   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24323   // and change it to SUB and CMOV.
24324   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24325       N0.getOpcode() == ISD::ADD &&
24326       N0.getOperand(1) == N1 &&
24327       N1.getOpcode() == ISD::SRA &&
24328       N1.getOperand(0) == N0.getOperand(0))
24329     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24330       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24331         // Generate SUB & CMOV.
24332         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24333                                   DAG.getConstant(0, VT), N0.getOperand(0));
24334
24335         SDValue Ops[] = { N0.getOperand(0), Neg,
24336                           DAG.getConstant(X86::COND_GE, MVT::i8),
24337                           SDValue(Neg.getNode(), 1) };
24338         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24339       }
24340   return SDValue();
24341 }
24342
24343 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24344 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24345                                  TargetLowering::DAGCombinerInfo &DCI,
24346                                  const X86Subtarget *Subtarget) {
24347   if (DCI.isBeforeLegalizeOps())
24348     return SDValue();
24349
24350   if (Subtarget->hasCMov()) {
24351     SDValue RV = performIntegerAbsCombine(N, DAG);
24352     if (RV.getNode())
24353       return RV;
24354   }
24355
24356   return SDValue();
24357 }
24358
24359 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24360 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24361                                   TargetLowering::DAGCombinerInfo &DCI,
24362                                   const X86Subtarget *Subtarget) {
24363   LoadSDNode *Ld = cast<LoadSDNode>(N);
24364   EVT RegVT = Ld->getValueType(0);
24365   EVT MemVT = Ld->getMemoryVT();
24366   SDLoc dl(Ld);
24367   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24368
24369   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24370   // into two 16-byte operations.
24371   ISD::LoadExtType Ext = Ld->getExtensionType();
24372   unsigned Alignment = Ld->getAlignment();
24373   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24374   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24375       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24376     unsigned NumElems = RegVT.getVectorNumElements();
24377     if (NumElems < 2)
24378       return SDValue();
24379
24380     SDValue Ptr = Ld->getBasePtr();
24381     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
24382
24383     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24384                                   NumElems/2);
24385     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24386                                 Ld->getPointerInfo(), Ld->isVolatile(),
24387                                 Ld->isNonTemporal(), Ld->isInvariant(),
24388                                 Alignment);
24389     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24390     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24391                                 Ld->getPointerInfo(), Ld->isVolatile(),
24392                                 Ld->isNonTemporal(), Ld->isInvariant(),
24393                                 std::min(16U, Alignment));
24394     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24395                              Load1.getValue(1),
24396                              Load2.getValue(1));
24397
24398     SDValue NewVec = DAG.getUNDEF(RegVT);
24399     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24400     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24401     return DCI.CombineTo(N, NewVec, TF, true);
24402   }
24403
24404   return SDValue();
24405 }
24406
24407 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24408 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24409                                    const X86Subtarget *Subtarget) {
24410   StoreSDNode *St = cast<StoreSDNode>(N);
24411   EVT VT = St->getValue().getValueType();
24412   EVT StVT = St->getMemoryVT();
24413   SDLoc dl(St);
24414   SDValue StoredVal = St->getOperand(1);
24415   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24416
24417   // If we are saving a concatenation of two XMM registers and 32-byte stores
24418   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24419   unsigned Alignment = St->getAlignment();
24420   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24421   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24422       StVT == VT && !IsAligned) {
24423     unsigned NumElems = VT.getVectorNumElements();
24424     if (NumElems < 2)
24425       return SDValue();
24426
24427     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24428     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24429
24430     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
24431     SDValue Ptr0 = St->getBasePtr();
24432     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24433
24434     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24435                                 St->getPointerInfo(), St->isVolatile(),
24436                                 St->isNonTemporal(), Alignment);
24437     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24438                                 St->getPointerInfo(), St->isVolatile(),
24439                                 St->isNonTemporal(),
24440                                 std::min(16U, Alignment));
24441     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24442   }
24443
24444   // Optimize trunc store (of multiple scalars) to shuffle and store.
24445   // First, pack all of the elements in one place. Next, store to memory
24446   // in fewer chunks.
24447   if (St->isTruncatingStore() && VT.isVector()) {
24448     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24449     unsigned NumElems = VT.getVectorNumElements();
24450     assert(StVT != VT && "Cannot truncate to the same type");
24451     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24452     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24453
24454     // From, To sizes and ElemCount must be pow of two
24455     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24456     // We are going to use the original vector elt for storing.
24457     // Accumulated smaller vector elements must be a multiple of the store size.
24458     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24459
24460     unsigned SizeRatio  = FromSz / ToSz;
24461
24462     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24463
24464     // Create a type on which we perform the shuffle
24465     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24466             StVT.getScalarType(), NumElems*SizeRatio);
24467
24468     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24469
24470     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
24471     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24472     for (unsigned i = 0; i != NumElems; ++i)
24473       ShuffleVec[i] = i * SizeRatio;
24474
24475     // Can't shuffle using an illegal type.
24476     if (!TLI.isTypeLegal(WideVecVT))
24477       return SDValue();
24478
24479     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24480                                          DAG.getUNDEF(WideVecVT),
24481                                          &ShuffleVec[0]);
24482     // At this point all of the data is stored at the bottom of the
24483     // register. We now need to save it to mem.
24484
24485     // Find the largest store unit
24486     MVT StoreType = MVT::i8;
24487     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
24488          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
24489       MVT Tp = (MVT::SimpleValueType)tp;
24490       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24491         StoreType = Tp;
24492     }
24493
24494     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24495     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24496         (64 <= NumElems * ToSz))
24497       StoreType = MVT::f64;
24498
24499     // Bitcast the original vector into a vector of store-size units
24500     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24501             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24502     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24503     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
24504     SmallVector<SDValue, 8> Chains;
24505     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
24506                                         TLI.getPointerTy());
24507     SDValue Ptr = St->getBasePtr();
24508
24509     // Perform one or more big stores into memory.
24510     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24511       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24512                                    StoreType, ShuffWide,
24513                                    DAG.getIntPtrConstant(i));
24514       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24515                                 St->getPointerInfo(), St->isVolatile(),
24516                                 St->isNonTemporal(), St->getAlignment());
24517       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24518       Chains.push_back(Ch);
24519     }
24520
24521     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24522   }
24523
24524   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24525   // the FP state in cases where an emms may be missing.
24526   // A preferable solution to the general problem is to figure out the right
24527   // places to insert EMMS.  This qualifies as a quick hack.
24528
24529   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24530   if (VT.getSizeInBits() != 64)
24531     return SDValue();
24532
24533   const Function *F = DAG.getMachineFunction().getFunction();
24534   bool NoImplicitFloatOps = F->getAttributes().
24535     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
24536   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
24537                      && Subtarget->hasSSE2();
24538   if ((VT.isVector() ||
24539        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24540       isa<LoadSDNode>(St->getValue()) &&
24541       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24542       St->getChain().hasOneUse() && !St->isVolatile()) {
24543     SDNode* LdVal = St->getValue().getNode();
24544     LoadSDNode *Ld = nullptr;
24545     int TokenFactorIndex = -1;
24546     SmallVector<SDValue, 8> Ops;
24547     SDNode* ChainVal = St->getChain().getNode();
24548     // Must be a store of a load.  We currently handle two cases:  the load
24549     // is a direct child, and it's under an intervening TokenFactor.  It is
24550     // possible to dig deeper under nested TokenFactors.
24551     if (ChainVal == LdVal)
24552       Ld = cast<LoadSDNode>(St->getChain());
24553     else if (St->getValue().hasOneUse() &&
24554              ChainVal->getOpcode() == ISD::TokenFactor) {
24555       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24556         if (ChainVal->getOperand(i).getNode() == LdVal) {
24557           TokenFactorIndex = i;
24558           Ld = cast<LoadSDNode>(St->getValue());
24559         } else
24560           Ops.push_back(ChainVal->getOperand(i));
24561       }
24562     }
24563
24564     if (!Ld || !ISD::isNormalLoad(Ld))
24565       return SDValue();
24566
24567     // If this is not the MMX case, i.e. we are just turning i64 load/store
24568     // into f64 load/store, avoid the transformation if there are multiple
24569     // uses of the loaded value.
24570     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24571       return SDValue();
24572
24573     SDLoc LdDL(Ld);
24574     SDLoc StDL(N);
24575     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24576     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24577     // pair instead.
24578     if (Subtarget->is64Bit() || F64IsLegal) {
24579       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24580       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24581                                   Ld->getPointerInfo(), Ld->isVolatile(),
24582                                   Ld->isNonTemporal(), Ld->isInvariant(),
24583                                   Ld->getAlignment());
24584       SDValue NewChain = NewLd.getValue(1);
24585       if (TokenFactorIndex != -1) {
24586         Ops.push_back(NewChain);
24587         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24588       }
24589       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24590                           St->getPointerInfo(),
24591                           St->isVolatile(), St->isNonTemporal(),
24592                           St->getAlignment());
24593     }
24594
24595     // Otherwise, lower to two pairs of 32-bit loads / stores.
24596     SDValue LoAddr = Ld->getBasePtr();
24597     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24598                                  DAG.getConstant(4, MVT::i32));
24599
24600     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24601                                Ld->getPointerInfo(),
24602                                Ld->isVolatile(), Ld->isNonTemporal(),
24603                                Ld->isInvariant(), Ld->getAlignment());
24604     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24605                                Ld->getPointerInfo().getWithOffset(4),
24606                                Ld->isVolatile(), Ld->isNonTemporal(),
24607                                Ld->isInvariant(),
24608                                MinAlign(Ld->getAlignment(), 4));
24609
24610     SDValue NewChain = LoLd.getValue(1);
24611     if (TokenFactorIndex != -1) {
24612       Ops.push_back(LoLd);
24613       Ops.push_back(HiLd);
24614       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24615     }
24616
24617     LoAddr = St->getBasePtr();
24618     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24619                          DAG.getConstant(4, MVT::i32));
24620
24621     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24622                                 St->getPointerInfo(),
24623                                 St->isVolatile(), St->isNonTemporal(),
24624                                 St->getAlignment());
24625     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24626                                 St->getPointerInfo().getWithOffset(4),
24627                                 St->isVolatile(),
24628                                 St->isNonTemporal(),
24629                                 MinAlign(St->getAlignment(), 4));
24630     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24631   }
24632   return SDValue();
24633 }
24634
24635 /// Return 'true' if this vector operation is "horizontal"
24636 /// and return the operands for the horizontal operation in LHS and RHS.  A
24637 /// horizontal operation performs the binary operation on successive elements
24638 /// of its first operand, then on successive elements of its second operand,
24639 /// returning the resulting values in a vector.  For example, if
24640 ///   A = < float a0, float a1, float a2, float a3 >
24641 /// and
24642 ///   B = < float b0, float b1, float b2, float b3 >
24643 /// then the result of doing a horizontal operation on A and B is
24644 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24645 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24646 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24647 /// set to A, RHS to B, and the routine returns 'true'.
24648 /// Note that the binary operation should have the property that if one of the
24649 /// operands is UNDEF then the result is UNDEF.
24650 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24651   // Look for the following pattern: if
24652   //   A = < float a0, float a1, float a2, float a3 >
24653   //   B = < float b0, float b1, float b2, float b3 >
24654   // and
24655   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24656   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24657   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24658   // which is A horizontal-op B.
24659
24660   // At least one of the operands should be a vector shuffle.
24661   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24662       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24663     return false;
24664
24665   MVT VT = LHS.getSimpleValueType();
24666
24667   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24668          "Unsupported vector type for horizontal add/sub");
24669
24670   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24671   // operate independently on 128-bit lanes.
24672   unsigned NumElts = VT.getVectorNumElements();
24673   unsigned NumLanes = VT.getSizeInBits()/128;
24674   unsigned NumLaneElts = NumElts / NumLanes;
24675   assert((NumLaneElts % 2 == 0) &&
24676          "Vector type should have an even number of elements in each lane");
24677   unsigned HalfLaneElts = NumLaneElts/2;
24678
24679   // View LHS in the form
24680   //   LHS = VECTOR_SHUFFLE A, B, LMask
24681   // If LHS is not a shuffle then pretend it is the shuffle
24682   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24683   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24684   // type VT.
24685   SDValue A, B;
24686   SmallVector<int, 16> LMask(NumElts);
24687   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24688     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24689       A = LHS.getOperand(0);
24690     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24691       B = LHS.getOperand(1);
24692     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24693     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24694   } else {
24695     if (LHS.getOpcode() != ISD::UNDEF)
24696       A = LHS;
24697     for (unsigned i = 0; i != NumElts; ++i)
24698       LMask[i] = i;
24699   }
24700
24701   // Likewise, view RHS in the form
24702   //   RHS = VECTOR_SHUFFLE C, D, RMask
24703   SDValue C, D;
24704   SmallVector<int, 16> RMask(NumElts);
24705   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24706     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24707       C = RHS.getOperand(0);
24708     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24709       D = RHS.getOperand(1);
24710     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24711     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24712   } else {
24713     if (RHS.getOpcode() != ISD::UNDEF)
24714       C = RHS;
24715     for (unsigned i = 0; i != NumElts; ++i)
24716       RMask[i] = i;
24717   }
24718
24719   // Check that the shuffles are both shuffling the same vectors.
24720   if (!(A == C && B == D) && !(A == D && B == C))
24721     return false;
24722
24723   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24724   if (!A.getNode() && !B.getNode())
24725     return false;
24726
24727   // If A and B occur in reverse order in RHS, then "swap" them (which means
24728   // rewriting the mask).
24729   if (A != C)
24730     CommuteVectorShuffleMask(RMask, NumElts);
24731
24732   // At this point LHS and RHS are equivalent to
24733   //   LHS = VECTOR_SHUFFLE A, B, LMask
24734   //   RHS = VECTOR_SHUFFLE A, B, RMask
24735   // Check that the masks correspond to performing a horizontal operation.
24736   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24737     for (unsigned i = 0; i != NumLaneElts; ++i) {
24738       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24739
24740       // Ignore any UNDEF components.
24741       if (LIdx < 0 || RIdx < 0 ||
24742           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24743           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24744         continue;
24745
24746       // Check that successive elements are being operated on.  If not, this is
24747       // not a horizontal operation.
24748       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24749       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24750       if (!(LIdx == Index && RIdx == Index + 1) &&
24751           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24752         return false;
24753     }
24754   }
24755
24756   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24757   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24758   return true;
24759 }
24760
24761 /// Do target-specific dag combines on floating point adds.
24762 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24763                                   const X86Subtarget *Subtarget) {
24764   EVT VT = N->getValueType(0);
24765   SDValue LHS = N->getOperand(0);
24766   SDValue RHS = N->getOperand(1);
24767
24768   // Try to synthesize horizontal adds from adds of shuffles.
24769   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24770        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24771       isHorizontalBinOp(LHS, RHS, true))
24772     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24773   return SDValue();
24774 }
24775
24776 /// Do target-specific dag combines on floating point subs.
24777 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24778                                   const X86Subtarget *Subtarget) {
24779   EVT VT = N->getValueType(0);
24780   SDValue LHS = N->getOperand(0);
24781   SDValue RHS = N->getOperand(1);
24782
24783   // Try to synthesize horizontal subs from subs of shuffles.
24784   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24785        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24786       isHorizontalBinOp(LHS, RHS, false))
24787     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24788   return SDValue();
24789 }
24790
24791 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24792 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24793   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24794   // F[X]OR(0.0, x) -> x
24795   // F[X]OR(x, 0.0) -> x
24796   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24797     if (C->getValueAPF().isPosZero())
24798       return N->getOperand(1);
24799   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24800     if (C->getValueAPF().isPosZero())
24801       return N->getOperand(0);
24802   return SDValue();
24803 }
24804
24805 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24806 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24807   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24808
24809   // Only perform optimizations if UnsafeMath is used.
24810   if (!DAG.getTarget().Options.UnsafeFPMath)
24811     return SDValue();
24812
24813   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24814   // into FMINC and FMAXC, which are Commutative operations.
24815   unsigned NewOp = 0;
24816   switch (N->getOpcode()) {
24817     default: llvm_unreachable("unknown opcode");
24818     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24819     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24820   }
24821
24822   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24823                      N->getOperand(0), N->getOperand(1));
24824 }
24825
24826 /// Do target-specific dag combines on X86ISD::FAND nodes.
24827 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24828   // FAND(0.0, x) -> 0.0
24829   // FAND(x, 0.0) -> 0.0
24830   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24831     if (C->getValueAPF().isPosZero())
24832       return N->getOperand(0);
24833   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24834     if (C->getValueAPF().isPosZero())
24835       return N->getOperand(1);
24836   return SDValue();
24837 }
24838
24839 /// Do target-specific dag combines on X86ISD::FANDN nodes
24840 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24841   // FANDN(x, 0.0) -> 0.0
24842   // FANDN(0.0, x) -> x
24843   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24844     if (C->getValueAPF().isPosZero())
24845       return N->getOperand(1);
24846   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24847     if (C->getValueAPF().isPosZero())
24848       return N->getOperand(1);
24849   return SDValue();
24850 }
24851
24852 static SDValue PerformBTCombine(SDNode *N,
24853                                 SelectionDAG &DAG,
24854                                 TargetLowering::DAGCombinerInfo &DCI) {
24855   // BT ignores high bits in the bit index operand.
24856   SDValue Op1 = N->getOperand(1);
24857   if (Op1.hasOneUse()) {
24858     unsigned BitWidth = Op1.getValueSizeInBits();
24859     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24860     APInt KnownZero, KnownOne;
24861     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24862                                           !DCI.isBeforeLegalizeOps());
24863     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24864     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24865         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24866       DCI.CommitTargetLoweringOpt(TLO);
24867   }
24868   return SDValue();
24869 }
24870
24871 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24872   SDValue Op = N->getOperand(0);
24873   if (Op.getOpcode() == ISD::BITCAST)
24874     Op = Op.getOperand(0);
24875   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24876   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24877       VT.getVectorElementType().getSizeInBits() ==
24878       OpVT.getVectorElementType().getSizeInBits()) {
24879     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24880   }
24881   return SDValue();
24882 }
24883
24884 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24885                                                const X86Subtarget *Subtarget) {
24886   EVT VT = N->getValueType(0);
24887   if (!VT.isVector())
24888     return SDValue();
24889
24890   SDValue N0 = N->getOperand(0);
24891   SDValue N1 = N->getOperand(1);
24892   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24893   SDLoc dl(N);
24894
24895   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24896   // both SSE and AVX2 since there is no sign-extended shift right
24897   // operation on a vector with 64-bit elements.
24898   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24899   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24900   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24901       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24902     SDValue N00 = N0.getOperand(0);
24903
24904     // EXTLOAD has a better solution on AVX2,
24905     // it may be replaced with X86ISD::VSEXT node.
24906     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24907       if (!ISD::isNormalLoad(N00.getNode()))
24908         return SDValue();
24909
24910     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24911         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24912                                   N00, N1);
24913       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24914     }
24915   }
24916   return SDValue();
24917 }
24918
24919 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24920                                   TargetLowering::DAGCombinerInfo &DCI,
24921                                   const X86Subtarget *Subtarget) {
24922   SDValue N0 = N->getOperand(0);
24923   EVT VT = N->getValueType(0);
24924
24925   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24926   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24927   // This exposes the sext to the sdivrem lowering, so that it directly extends
24928   // from AH (which we otherwise need to do contortions to access).
24929   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24930       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
24931     SDLoc dl(N);
24932     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24933     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
24934                             N0.getOperand(0), N0.getOperand(1));
24935     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24936     return R.getValue(1);
24937   }
24938
24939   if (!DCI.isBeforeLegalizeOps())
24940     return SDValue();
24941
24942   if (!Subtarget->hasFp256())
24943     return SDValue();
24944
24945   if (VT.isVector() && VT.getSizeInBits() == 256) {
24946     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
24947     if (R.getNode())
24948       return R;
24949   }
24950
24951   return SDValue();
24952 }
24953
24954 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24955                                  const X86Subtarget* Subtarget) {
24956   SDLoc dl(N);
24957   EVT VT = N->getValueType(0);
24958
24959   // Let legalize expand this if it isn't a legal type yet.
24960   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24961     return SDValue();
24962
24963   EVT ScalarVT = VT.getScalarType();
24964   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24965       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
24966     return SDValue();
24967
24968   SDValue A = N->getOperand(0);
24969   SDValue B = N->getOperand(1);
24970   SDValue C = N->getOperand(2);
24971
24972   bool NegA = (A.getOpcode() == ISD::FNEG);
24973   bool NegB = (B.getOpcode() == ISD::FNEG);
24974   bool NegC = (C.getOpcode() == ISD::FNEG);
24975
24976   // Negative multiplication when NegA xor NegB
24977   bool NegMul = (NegA != NegB);
24978   if (NegA)
24979     A = A.getOperand(0);
24980   if (NegB)
24981     B = B.getOperand(0);
24982   if (NegC)
24983     C = C.getOperand(0);
24984
24985   unsigned Opcode;
24986   if (!NegMul)
24987     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24988   else
24989     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24990
24991   return DAG.getNode(Opcode, dl, VT, A, B, C);
24992 }
24993
24994 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24995                                   TargetLowering::DAGCombinerInfo &DCI,
24996                                   const X86Subtarget *Subtarget) {
24997   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24998   //           (and (i32 x86isd::setcc_carry), 1)
24999   // This eliminates the zext. This transformation is necessary because
25000   // ISD::SETCC is always legalized to i8.
25001   SDLoc dl(N);
25002   SDValue N0 = N->getOperand(0);
25003   EVT VT = N->getValueType(0);
25004
25005   if (N0.getOpcode() == ISD::AND &&
25006       N0.hasOneUse() &&
25007       N0.getOperand(0).hasOneUse()) {
25008     SDValue N00 = N0.getOperand(0);
25009     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25010       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25011       if (!C || C->getZExtValue() != 1)
25012         return SDValue();
25013       return DAG.getNode(ISD::AND, dl, VT,
25014                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25015                                      N00.getOperand(0), N00.getOperand(1)),
25016                          DAG.getConstant(1, VT));
25017     }
25018   }
25019
25020   if (N0.getOpcode() == ISD::TRUNCATE &&
25021       N0.hasOneUse() &&
25022       N0.getOperand(0).hasOneUse()) {
25023     SDValue N00 = N0.getOperand(0);
25024     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25025       return DAG.getNode(ISD::AND, dl, VT,
25026                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25027                                      N00.getOperand(0), N00.getOperand(1)),
25028                          DAG.getConstant(1, VT));
25029     }
25030   }
25031   if (VT.is256BitVector()) {
25032     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
25033     if (R.getNode())
25034       return R;
25035   }
25036
25037   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25038   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25039   // This exposes the zext to the udivrem lowering, so that it directly extends
25040   // from AH (which we otherwise need to do contortions to access).
25041   if (N0.getOpcode() == ISD::UDIVREM &&
25042       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25043       (VT == MVT::i32 || VT == MVT::i64)) {
25044     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25045     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25046                             N0.getOperand(0), N0.getOperand(1));
25047     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25048     return R.getValue(1);
25049   }
25050
25051   return SDValue();
25052 }
25053
25054 // Optimize x == -y --> x+y == 0
25055 //          x != -y --> x+y != 0
25056 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25057                                       const X86Subtarget* Subtarget) {
25058   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25059   SDValue LHS = N->getOperand(0);
25060   SDValue RHS = N->getOperand(1);
25061   EVT VT = N->getValueType(0);
25062   SDLoc DL(N);
25063
25064   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25065     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25066       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25067         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25068                                    LHS.getValueType(), RHS, LHS.getOperand(1));
25069         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25070                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25071       }
25072   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25073     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25074       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25075         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25076                                    RHS.getValueType(), LHS, RHS.getOperand(1));
25077         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25078                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25079       }
25080
25081   if (VT.getScalarType() == MVT::i1) {
25082     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25083       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25084     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
25085     if (!IsSEXT0 && !IsVZero0)
25086       return SDValue();
25087     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
25088       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25089     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25090
25091     if (!IsSEXT1 && !IsVZero1)
25092       return SDValue();
25093
25094     if (IsSEXT0 && IsVZero1) {
25095       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
25096       if (CC == ISD::SETEQ)
25097         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25098       return LHS.getOperand(0);
25099     }
25100     if (IsSEXT1 && IsVZero0) {
25101       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
25102       if (CC == ISD::SETEQ)
25103         return DAG.getNOT(DL, RHS.getOperand(0), VT);
25104       return RHS.getOperand(0);
25105     }
25106   }
25107
25108   return SDValue();
25109 }
25110
25111 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25112                                       const X86Subtarget *Subtarget) {
25113   SDLoc dl(N);
25114   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25115   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25116          "X86insertps is only defined for v4x32");
25117
25118   SDValue Ld = N->getOperand(1);
25119   if (MayFoldLoad(Ld)) {
25120     // Extract the countS bits from the immediate so we can get the proper
25121     // address when narrowing the vector load to a specific element.
25122     // When the second source op is a memory address, interps doesn't use
25123     // countS and just gets an f32 from that address.
25124     unsigned DestIndex =
25125         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25126     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25127   } else
25128     return SDValue();
25129
25130   // Create this as a scalar to vector to match the instruction pattern.
25131   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25132   // countS bits are ignored when loading from memory on insertps, which
25133   // means we don't need to explicitly set them to 0.
25134   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25135                      LoadScalarToVector, N->getOperand(2));
25136 }
25137
25138 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25139 // as "sbb reg,reg", since it can be extended without zext and produces
25140 // an all-ones bit which is more useful than 0/1 in some cases.
25141 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25142                                MVT VT) {
25143   if (VT == MVT::i8)
25144     return DAG.getNode(ISD::AND, DL, VT,
25145                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25146                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
25147                        DAG.getConstant(1, VT));
25148   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25149   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25150                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25151                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
25152 }
25153
25154 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25155 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25156                                    TargetLowering::DAGCombinerInfo &DCI,
25157                                    const X86Subtarget *Subtarget) {
25158   SDLoc DL(N);
25159   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25160   SDValue EFLAGS = N->getOperand(1);
25161
25162   if (CC == X86::COND_A) {
25163     // Try to convert COND_A into COND_B in an attempt to facilitate
25164     // materializing "setb reg".
25165     //
25166     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25167     // cannot take an immediate as its first operand.
25168     //
25169     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25170         EFLAGS.getValueType().isInteger() &&
25171         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25172       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25173                                    EFLAGS.getNode()->getVTList(),
25174                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25175       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25176       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25177     }
25178   }
25179
25180   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25181   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25182   // cases.
25183   if (CC == X86::COND_B)
25184     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25185
25186   SDValue Flags;
25187
25188   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25189   if (Flags.getNode()) {
25190     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25191     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25192   }
25193
25194   return SDValue();
25195 }
25196
25197 // Optimize branch condition evaluation.
25198 //
25199 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25200                                     TargetLowering::DAGCombinerInfo &DCI,
25201                                     const X86Subtarget *Subtarget) {
25202   SDLoc DL(N);
25203   SDValue Chain = N->getOperand(0);
25204   SDValue Dest = N->getOperand(1);
25205   SDValue EFLAGS = N->getOperand(3);
25206   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25207
25208   SDValue Flags;
25209
25210   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25211   if (Flags.getNode()) {
25212     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25213     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25214                        Flags);
25215   }
25216
25217   return SDValue();
25218 }
25219
25220 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25221                                                          SelectionDAG &DAG) {
25222   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25223   // optimize away operation when it's from a constant.
25224   //
25225   // The general transformation is:
25226   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25227   //       AND(VECTOR_CMP(x,y), constant2)
25228   //    constant2 = UNARYOP(constant)
25229
25230   // Early exit if this isn't a vector operation, the operand of the
25231   // unary operation isn't a bitwise AND, or if the sizes of the operations
25232   // aren't the same.
25233   EVT VT = N->getValueType(0);
25234   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25235       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25236       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25237     return SDValue();
25238
25239   // Now check that the other operand of the AND is a constant. We could
25240   // make the transformation for non-constant splats as well, but it's unclear
25241   // that would be a benefit as it would not eliminate any operations, just
25242   // perform one more step in scalar code before moving to the vector unit.
25243   if (BuildVectorSDNode *BV =
25244           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25245     // Bail out if the vector isn't a constant.
25246     if (!BV->isConstant())
25247       return SDValue();
25248
25249     // Everything checks out. Build up the new and improved node.
25250     SDLoc DL(N);
25251     EVT IntVT = BV->getValueType(0);
25252     // Create a new constant of the appropriate type for the transformed
25253     // DAG.
25254     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25255     // The AND node needs bitcasts to/from an integer vector type around it.
25256     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
25257     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25258                                  N->getOperand(0)->getOperand(0), MaskConst);
25259     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
25260     return Res;
25261   }
25262
25263   return SDValue();
25264 }
25265
25266 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25267                                         const X86TargetLowering *XTLI) {
25268   // First try to optimize away the conversion entirely when it's
25269   // conditionally from a constant. Vectors only.
25270   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
25271   if (Res != SDValue())
25272     return Res;
25273
25274   // Now move on to more general possibilities.
25275   SDValue Op0 = N->getOperand(0);
25276   EVT InVT = Op0->getValueType(0);
25277
25278   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
25279   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
25280     SDLoc dl(N);
25281     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
25282     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25283     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
25284   }
25285
25286   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25287   // a 32-bit target where SSE doesn't support i64->FP operations.
25288   if (Op0.getOpcode() == ISD::LOAD) {
25289     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25290     EVT VT = Ld->getValueType(0);
25291     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
25292         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25293         !XTLI->getSubtarget()->is64Bit() &&
25294         VT == MVT::i64) {
25295       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
25296                                           Ld->getChain(), Op0, DAG);
25297       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25298       return FILDChain;
25299     }
25300   }
25301   return SDValue();
25302 }
25303
25304 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25305 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25306                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25307   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25308   // the result is either zero or one (depending on the input carry bit).
25309   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25310   if (X86::isZeroNode(N->getOperand(0)) &&
25311       X86::isZeroNode(N->getOperand(1)) &&
25312       // We don't have a good way to replace an EFLAGS use, so only do this when
25313       // dead right now.
25314       SDValue(N, 1).use_empty()) {
25315     SDLoc DL(N);
25316     EVT VT = N->getValueType(0);
25317     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
25318     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25319                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25320                                            DAG.getConstant(X86::COND_B,MVT::i8),
25321                                            N->getOperand(2)),
25322                                DAG.getConstant(1, VT));
25323     return DCI.CombineTo(N, Res1, CarryOut);
25324   }
25325
25326   return SDValue();
25327 }
25328
25329 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25330 //      (add Y, (setne X, 0)) -> sbb -1, Y
25331 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25332 //      (sub (setne X, 0), Y) -> adc -1, Y
25333 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25334   SDLoc DL(N);
25335
25336   // Look through ZExts.
25337   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25338   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25339     return SDValue();
25340
25341   SDValue SetCC = Ext.getOperand(0);
25342   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25343     return SDValue();
25344
25345   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25346   if (CC != X86::COND_E && CC != X86::COND_NE)
25347     return SDValue();
25348
25349   SDValue Cmp = SetCC.getOperand(1);
25350   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25351       !X86::isZeroNode(Cmp.getOperand(1)) ||
25352       !Cmp.getOperand(0).getValueType().isInteger())
25353     return SDValue();
25354
25355   SDValue CmpOp0 = Cmp.getOperand(0);
25356   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25357                                DAG.getConstant(1, CmpOp0.getValueType()));
25358
25359   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25360   if (CC == X86::COND_NE)
25361     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25362                        DL, OtherVal.getValueType(), OtherVal,
25363                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
25364   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25365                      DL, OtherVal.getValueType(), OtherVal,
25366                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
25367 }
25368
25369 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25370 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25371                                  const X86Subtarget *Subtarget) {
25372   EVT VT = N->getValueType(0);
25373   SDValue Op0 = N->getOperand(0);
25374   SDValue Op1 = N->getOperand(1);
25375
25376   // Try to synthesize horizontal adds from adds of shuffles.
25377   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25378        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25379       isHorizontalBinOp(Op0, Op1, true))
25380     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25381
25382   return OptimizeConditionalInDecrement(N, DAG);
25383 }
25384
25385 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25386                                  const X86Subtarget *Subtarget) {
25387   SDValue Op0 = N->getOperand(0);
25388   SDValue Op1 = N->getOperand(1);
25389
25390   // X86 can't encode an immediate LHS of a sub. See if we can push the
25391   // negation into a preceding instruction.
25392   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25393     // If the RHS of the sub is a XOR with one use and a constant, invert the
25394     // immediate. Then add one to the LHS of the sub so we can turn
25395     // X-Y -> X+~Y+1, saving one register.
25396     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25397         isa<ConstantSDNode>(Op1.getOperand(1))) {
25398       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25399       EVT VT = Op0.getValueType();
25400       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25401                                    Op1.getOperand(0),
25402                                    DAG.getConstant(~XorC, VT));
25403       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25404                          DAG.getConstant(C->getAPIntValue()+1, VT));
25405     }
25406   }
25407
25408   // Try to synthesize horizontal adds from adds of shuffles.
25409   EVT VT = N->getValueType(0);
25410   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25411        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25412       isHorizontalBinOp(Op0, Op1, true))
25413     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25414
25415   return OptimizeConditionalInDecrement(N, DAG);
25416 }
25417
25418 /// performVZEXTCombine - Performs build vector combines
25419 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25420                                    TargetLowering::DAGCombinerInfo &DCI,
25421                                    const X86Subtarget *Subtarget) {
25422   SDLoc DL(N);
25423   MVT VT = N->getSimpleValueType(0);
25424   SDValue Op = N->getOperand(0);
25425   MVT OpVT = Op.getSimpleValueType();
25426   MVT OpEltVT = OpVT.getVectorElementType();
25427   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25428
25429   // (vzext (bitcast (vzext (x)) -> (vzext x)
25430   SDValue V = Op;
25431   while (V.getOpcode() == ISD::BITCAST)
25432     V = V.getOperand(0);
25433
25434   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25435     MVT InnerVT = V.getSimpleValueType();
25436     MVT InnerEltVT = InnerVT.getVectorElementType();
25437
25438     // If the element sizes match exactly, we can just do one larger vzext. This
25439     // is always an exact type match as vzext operates on integer types.
25440     if (OpEltVT == InnerEltVT) {
25441       assert(OpVT == InnerVT && "Types must match for vzext!");
25442       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25443     }
25444
25445     // The only other way we can combine them is if only a single element of the
25446     // inner vzext is used in the input to the outer vzext.
25447     if (InnerEltVT.getSizeInBits() < InputBits)
25448       return SDValue();
25449
25450     // In this case, the inner vzext is completely dead because we're going to
25451     // only look at bits inside of the low element. Just do the outer vzext on
25452     // a bitcast of the input to the inner.
25453     return DAG.getNode(X86ISD::VZEXT, DL, VT,
25454                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
25455   }
25456
25457   // Check if we can bypass extracting and re-inserting an element of an input
25458   // vector. Essentialy:
25459   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25460   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25461       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25462       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25463     SDValue ExtractedV = V.getOperand(0);
25464     SDValue OrigV = ExtractedV.getOperand(0);
25465     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25466       if (ExtractIdx->getZExtValue() == 0) {
25467         MVT OrigVT = OrigV.getSimpleValueType();
25468         // Extract a subvector if necessary...
25469         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25470           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25471           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25472                                     OrigVT.getVectorNumElements() / Ratio);
25473           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25474                               DAG.getIntPtrConstant(0));
25475         }
25476         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
25477         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25478       }
25479   }
25480
25481   return SDValue();
25482 }
25483
25484 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25485                                              DAGCombinerInfo &DCI) const {
25486   SelectionDAG &DAG = DCI.DAG;
25487   switch (N->getOpcode()) {
25488   default: break;
25489   case ISD::EXTRACT_VECTOR_ELT:
25490     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25491   case ISD::VSELECT:
25492   case ISD::SELECT:
25493   case X86ISD::SHRUNKBLEND:
25494     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25495   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25496   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25497   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25498   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25499   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25500   case ISD::SHL:
25501   case ISD::SRA:
25502   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25503   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25504   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25505   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25506   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25507   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25508   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
25509   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25510   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25511   case X86ISD::FXOR:
25512   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25513   case X86ISD::FMIN:
25514   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25515   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25516   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25517   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25518   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25519   case ISD::ANY_EXTEND:
25520   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25521   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25522   case ISD::SIGN_EXTEND_INREG:
25523     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25524   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
25525   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25526   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25527   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25528   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25529   case X86ISD::SHUFP:       // Handle all target specific shuffles
25530   case X86ISD::PALIGNR:
25531   case X86ISD::UNPCKH:
25532   case X86ISD::UNPCKL:
25533   case X86ISD::MOVHLPS:
25534   case X86ISD::MOVLHPS:
25535   case X86ISD::PSHUFB:
25536   case X86ISD::PSHUFD:
25537   case X86ISD::PSHUFHW:
25538   case X86ISD::PSHUFLW:
25539   case X86ISD::MOVSS:
25540   case X86ISD::MOVSD:
25541   case X86ISD::VPERMILPI:
25542   case X86ISD::VPERM2X128:
25543   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25544   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25545   case ISD::INTRINSIC_WO_CHAIN:
25546     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25547   case X86ISD::INSERTPS:
25548     return PerformINSERTPSCombine(N, DAG, Subtarget);
25549   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
25550   }
25551
25552   return SDValue();
25553 }
25554
25555 /// isTypeDesirableForOp - Return true if the target has native support for
25556 /// the specified value type and it is 'desirable' to use the type for the
25557 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25558 /// instruction encodings are longer and some i16 instructions are slow.
25559 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25560   if (!isTypeLegal(VT))
25561     return false;
25562   if (VT != MVT::i16)
25563     return true;
25564
25565   switch (Opc) {
25566   default:
25567     return true;
25568   case ISD::LOAD:
25569   case ISD::SIGN_EXTEND:
25570   case ISD::ZERO_EXTEND:
25571   case ISD::ANY_EXTEND:
25572   case ISD::SHL:
25573   case ISD::SRL:
25574   case ISD::SUB:
25575   case ISD::ADD:
25576   case ISD::MUL:
25577   case ISD::AND:
25578   case ISD::OR:
25579   case ISD::XOR:
25580     return false;
25581   }
25582 }
25583
25584 /// IsDesirableToPromoteOp - This method query the target whether it is
25585 /// beneficial for dag combiner to promote the specified node. If true, it
25586 /// should return the desired promotion type by reference.
25587 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25588   EVT VT = Op.getValueType();
25589   if (VT != MVT::i16)
25590     return false;
25591
25592   bool Promote = false;
25593   bool Commute = false;
25594   switch (Op.getOpcode()) {
25595   default: break;
25596   case ISD::LOAD: {
25597     LoadSDNode *LD = cast<LoadSDNode>(Op);
25598     // If the non-extending load has a single use and it's not live out, then it
25599     // might be folded.
25600     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25601                                                      Op.hasOneUse()*/) {
25602       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25603              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25604         // The only case where we'd want to promote LOAD (rather then it being
25605         // promoted as an operand is when it's only use is liveout.
25606         if (UI->getOpcode() != ISD::CopyToReg)
25607           return false;
25608       }
25609     }
25610     Promote = true;
25611     break;
25612   }
25613   case ISD::SIGN_EXTEND:
25614   case ISD::ZERO_EXTEND:
25615   case ISD::ANY_EXTEND:
25616     Promote = true;
25617     break;
25618   case ISD::SHL:
25619   case ISD::SRL: {
25620     SDValue N0 = Op.getOperand(0);
25621     // Look out for (store (shl (load), x)).
25622     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25623       return false;
25624     Promote = true;
25625     break;
25626   }
25627   case ISD::ADD:
25628   case ISD::MUL:
25629   case ISD::AND:
25630   case ISD::OR:
25631   case ISD::XOR:
25632     Commute = true;
25633     // fallthrough
25634   case ISD::SUB: {
25635     SDValue N0 = Op.getOperand(0);
25636     SDValue N1 = Op.getOperand(1);
25637     if (!Commute && MayFoldLoad(N1))
25638       return false;
25639     // Avoid disabling potential load folding opportunities.
25640     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25641       return false;
25642     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25643       return false;
25644     Promote = true;
25645   }
25646   }
25647
25648   PVT = MVT::i32;
25649   return Promote;
25650 }
25651
25652 //===----------------------------------------------------------------------===//
25653 //                           X86 Inline Assembly Support
25654 //===----------------------------------------------------------------------===//
25655
25656 namespace {
25657   // Helper to match a string separated by whitespace.
25658   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
25659     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
25660
25661     for (unsigned i = 0, e = args.size(); i != e; ++i) {
25662       StringRef piece(*args[i]);
25663       if (!s.startswith(piece)) // Check if the piece matches.
25664         return false;
25665
25666       s = s.substr(piece.size());
25667       StringRef::size_type pos = s.find_first_not_of(" \t");
25668       if (pos == 0) // We matched a prefix.
25669         return false;
25670
25671       s = s.substr(pos);
25672     }
25673
25674     return s.empty();
25675   }
25676   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
25677 }
25678
25679 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25680
25681   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25682     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25683         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25684         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25685
25686       if (AsmPieces.size() == 3)
25687         return true;
25688       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25689         return true;
25690     }
25691   }
25692   return false;
25693 }
25694
25695 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25696   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25697
25698   std::string AsmStr = IA->getAsmString();
25699
25700   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25701   if (!Ty || Ty->getBitWidth() % 16 != 0)
25702     return false;
25703
25704   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25705   SmallVector<StringRef, 4> AsmPieces;
25706   SplitString(AsmStr, AsmPieces, ";\n");
25707
25708   switch (AsmPieces.size()) {
25709   default: return false;
25710   case 1:
25711     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25712     // we will turn this bswap into something that will be lowered to logical
25713     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25714     // lower so don't worry about this.
25715     // bswap $0
25716     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
25717         matchAsm(AsmPieces[0], "bswapl", "$0") ||
25718         matchAsm(AsmPieces[0], "bswapq", "$0") ||
25719         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
25720         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
25721         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
25722       // No need to check constraints, nothing other than the equivalent of
25723       // "=r,0" would be valid here.
25724       return IntrinsicLowering::LowerToByteSwap(CI);
25725     }
25726
25727     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25728     if (CI->getType()->isIntegerTy(16) &&
25729         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25730         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
25731          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
25732       AsmPieces.clear();
25733       const std::string &ConstraintsStr = IA->getConstraintString();
25734       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25735       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25736       if (clobbersFlagRegisters(AsmPieces))
25737         return IntrinsicLowering::LowerToByteSwap(CI);
25738     }
25739     break;
25740   case 3:
25741     if (CI->getType()->isIntegerTy(32) &&
25742         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25743         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
25744         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
25745         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
25746       AsmPieces.clear();
25747       const std::string &ConstraintsStr = IA->getConstraintString();
25748       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25749       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25750       if (clobbersFlagRegisters(AsmPieces))
25751         return IntrinsicLowering::LowerToByteSwap(CI);
25752     }
25753
25754     if (CI->getType()->isIntegerTy(64)) {
25755       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25756       if (Constraints.size() >= 2 &&
25757           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25758           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25759         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25760         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
25761             matchAsm(AsmPieces[1], "bswap", "%edx") &&
25762             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
25763           return IntrinsicLowering::LowerToByteSwap(CI);
25764       }
25765     }
25766     break;
25767   }
25768   return false;
25769 }
25770
25771 /// getConstraintType - Given a constraint letter, return the type of
25772 /// constraint it is for this target.
25773 X86TargetLowering::ConstraintType
25774 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
25775   if (Constraint.size() == 1) {
25776     switch (Constraint[0]) {
25777     case 'R':
25778     case 'q':
25779     case 'Q':
25780     case 'f':
25781     case 't':
25782     case 'u':
25783     case 'y':
25784     case 'x':
25785     case 'Y':
25786     case 'l':
25787       return C_RegisterClass;
25788     case 'a':
25789     case 'b':
25790     case 'c':
25791     case 'd':
25792     case 'S':
25793     case 'D':
25794     case 'A':
25795       return C_Register;
25796     case 'I':
25797     case 'J':
25798     case 'K':
25799     case 'L':
25800     case 'M':
25801     case 'N':
25802     case 'G':
25803     case 'C':
25804     case 'e':
25805     case 'Z':
25806       return C_Other;
25807     default:
25808       break;
25809     }
25810   }
25811   return TargetLowering::getConstraintType(Constraint);
25812 }
25813
25814 /// Examine constraint type and operand type and determine a weight value.
25815 /// This object must already have been set up with the operand type
25816 /// and the current alternative constraint selected.
25817 TargetLowering::ConstraintWeight
25818   X86TargetLowering::getSingleConstraintMatchWeight(
25819     AsmOperandInfo &info, const char *constraint) const {
25820   ConstraintWeight weight = CW_Invalid;
25821   Value *CallOperandVal = info.CallOperandVal;
25822     // If we don't have a value, we can't do a match,
25823     // but allow it at the lowest weight.
25824   if (!CallOperandVal)
25825     return CW_Default;
25826   Type *type = CallOperandVal->getType();
25827   // Look at the constraint type.
25828   switch (*constraint) {
25829   default:
25830     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25831   case 'R':
25832   case 'q':
25833   case 'Q':
25834   case 'a':
25835   case 'b':
25836   case 'c':
25837   case 'd':
25838   case 'S':
25839   case 'D':
25840   case 'A':
25841     if (CallOperandVal->getType()->isIntegerTy())
25842       weight = CW_SpecificReg;
25843     break;
25844   case 'f':
25845   case 't':
25846   case 'u':
25847     if (type->isFloatingPointTy())
25848       weight = CW_SpecificReg;
25849     break;
25850   case 'y':
25851     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25852       weight = CW_SpecificReg;
25853     break;
25854   case 'x':
25855   case 'Y':
25856     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25857         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25858       weight = CW_Register;
25859     break;
25860   case 'I':
25861     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25862       if (C->getZExtValue() <= 31)
25863         weight = CW_Constant;
25864     }
25865     break;
25866   case 'J':
25867     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25868       if (C->getZExtValue() <= 63)
25869         weight = CW_Constant;
25870     }
25871     break;
25872   case 'K':
25873     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25874       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25875         weight = CW_Constant;
25876     }
25877     break;
25878   case 'L':
25879     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25880       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25881         weight = CW_Constant;
25882     }
25883     break;
25884   case 'M':
25885     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25886       if (C->getZExtValue() <= 3)
25887         weight = CW_Constant;
25888     }
25889     break;
25890   case 'N':
25891     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25892       if (C->getZExtValue() <= 0xff)
25893         weight = CW_Constant;
25894     }
25895     break;
25896   case 'G':
25897   case 'C':
25898     if (dyn_cast<ConstantFP>(CallOperandVal)) {
25899       weight = CW_Constant;
25900     }
25901     break;
25902   case 'e':
25903     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25904       if ((C->getSExtValue() >= -0x80000000LL) &&
25905           (C->getSExtValue() <= 0x7fffffffLL))
25906         weight = CW_Constant;
25907     }
25908     break;
25909   case 'Z':
25910     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25911       if (C->getZExtValue() <= 0xffffffff)
25912         weight = CW_Constant;
25913     }
25914     break;
25915   }
25916   return weight;
25917 }
25918
25919 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25920 /// with another that has more specific requirements based on the type of the
25921 /// corresponding operand.
25922 const char *X86TargetLowering::
25923 LowerXConstraint(EVT ConstraintVT) const {
25924   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25925   // 'f' like normal targets.
25926   if (ConstraintVT.isFloatingPoint()) {
25927     if (Subtarget->hasSSE2())
25928       return "Y";
25929     if (Subtarget->hasSSE1())
25930       return "x";
25931   }
25932
25933   return TargetLowering::LowerXConstraint(ConstraintVT);
25934 }
25935
25936 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25937 /// vector.  If it is invalid, don't add anything to Ops.
25938 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25939                                                      std::string &Constraint,
25940                                                      std::vector<SDValue>&Ops,
25941                                                      SelectionDAG &DAG) const {
25942   SDValue Result;
25943
25944   // Only support length 1 constraints for now.
25945   if (Constraint.length() > 1) return;
25946
25947   char ConstraintLetter = Constraint[0];
25948   switch (ConstraintLetter) {
25949   default: break;
25950   case 'I':
25951     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25952       if (C->getZExtValue() <= 31) {
25953         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25954         break;
25955       }
25956     }
25957     return;
25958   case 'J':
25959     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25960       if (C->getZExtValue() <= 63) {
25961         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25962         break;
25963       }
25964     }
25965     return;
25966   case 'K':
25967     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25968       if (isInt<8>(C->getSExtValue())) {
25969         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25970         break;
25971       }
25972     }
25973     return;
25974   case 'N':
25975     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25976       if (C->getZExtValue() <= 255) {
25977         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25978         break;
25979       }
25980     }
25981     return;
25982   case 'e': {
25983     // 32-bit signed value
25984     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25985       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25986                                            C->getSExtValue())) {
25987         // Widen to 64 bits here to get it sign extended.
25988         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
25989         break;
25990       }
25991     // FIXME gcc accepts some relocatable values here too, but only in certain
25992     // memory models; it's complicated.
25993     }
25994     return;
25995   }
25996   case 'Z': {
25997     // 32-bit unsigned value
25998     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25999       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26000                                            C->getZExtValue())) {
26001         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26002         break;
26003       }
26004     }
26005     // FIXME gcc accepts some relocatable values here too, but only in certain
26006     // memory models; it's complicated.
26007     return;
26008   }
26009   case 'i': {
26010     // Literal immediates are always ok.
26011     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26012       // Widen to 64 bits here to get it sign extended.
26013       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
26014       break;
26015     }
26016
26017     // In any sort of PIC mode addresses need to be computed at runtime by
26018     // adding in a register or some sort of table lookup.  These can't
26019     // be used as immediates.
26020     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26021       return;
26022
26023     // If we are in non-pic codegen mode, we allow the address of a global (with
26024     // an optional displacement) to be used with 'i'.
26025     GlobalAddressSDNode *GA = nullptr;
26026     int64_t Offset = 0;
26027
26028     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26029     while (1) {
26030       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26031         Offset += GA->getOffset();
26032         break;
26033       } else if (Op.getOpcode() == ISD::ADD) {
26034         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26035           Offset += C->getZExtValue();
26036           Op = Op.getOperand(0);
26037           continue;
26038         }
26039       } else if (Op.getOpcode() == ISD::SUB) {
26040         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26041           Offset += -C->getZExtValue();
26042           Op = Op.getOperand(0);
26043           continue;
26044         }
26045       }
26046
26047       // Otherwise, this isn't something we can handle, reject it.
26048       return;
26049     }
26050
26051     const GlobalValue *GV = GA->getGlobal();
26052     // If we require an extra load to get this address, as in PIC mode, we
26053     // can't accept it.
26054     if (isGlobalStubReference(
26055             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26056       return;
26057
26058     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26059                                         GA->getValueType(0), Offset);
26060     break;
26061   }
26062   }
26063
26064   if (Result.getNode()) {
26065     Ops.push_back(Result);
26066     return;
26067   }
26068   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26069 }
26070
26071 std::pair<unsigned, const TargetRegisterClass*>
26072 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
26073                                                 MVT VT) const {
26074   // First, see if this is a constraint that directly corresponds to an LLVM
26075   // register class.
26076   if (Constraint.size() == 1) {
26077     // GCC Constraint Letters
26078     switch (Constraint[0]) {
26079     default: break;
26080       // TODO: Slight differences here in allocation order and leaving
26081       // RIP in the class. Do they matter any more here than they do
26082       // in the normal allocation?
26083     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26084       if (Subtarget->is64Bit()) {
26085         if (VT == MVT::i32 || VT == MVT::f32)
26086           return std::make_pair(0U, &X86::GR32RegClass);
26087         if (VT == MVT::i16)
26088           return std::make_pair(0U, &X86::GR16RegClass);
26089         if (VT == MVT::i8 || VT == MVT::i1)
26090           return std::make_pair(0U, &X86::GR8RegClass);
26091         if (VT == MVT::i64 || VT == MVT::f64)
26092           return std::make_pair(0U, &X86::GR64RegClass);
26093         break;
26094       }
26095       // 32-bit fallthrough
26096     case 'Q':   // Q_REGS
26097       if (VT == MVT::i32 || VT == MVT::f32)
26098         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26099       if (VT == MVT::i16)
26100         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26101       if (VT == MVT::i8 || VT == MVT::i1)
26102         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26103       if (VT == MVT::i64)
26104         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26105       break;
26106     case 'r':   // GENERAL_REGS
26107     case 'l':   // INDEX_REGS
26108       if (VT == MVT::i8 || VT == MVT::i1)
26109         return std::make_pair(0U, &X86::GR8RegClass);
26110       if (VT == MVT::i16)
26111         return std::make_pair(0U, &X86::GR16RegClass);
26112       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26113         return std::make_pair(0U, &X86::GR32RegClass);
26114       return std::make_pair(0U, &X86::GR64RegClass);
26115     case 'R':   // LEGACY_REGS
26116       if (VT == MVT::i8 || VT == MVT::i1)
26117         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26118       if (VT == MVT::i16)
26119         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26120       if (VT == MVT::i32 || !Subtarget->is64Bit())
26121         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26122       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26123     case 'f':  // FP Stack registers.
26124       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26125       // value to the correct fpstack register class.
26126       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26127         return std::make_pair(0U, &X86::RFP32RegClass);
26128       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26129         return std::make_pair(0U, &X86::RFP64RegClass);
26130       return std::make_pair(0U, &X86::RFP80RegClass);
26131     case 'y':   // MMX_REGS if MMX allowed.
26132       if (!Subtarget->hasMMX()) break;
26133       return std::make_pair(0U, &X86::VR64RegClass);
26134     case 'Y':   // SSE_REGS if SSE2 allowed
26135       if (!Subtarget->hasSSE2()) break;
26136       // FALL THROUGH.
26137     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26138       if (!Subtarget->hasSSE1()) break;
26139
26140       switch (VT.SimpleTy) {
26141       default: break;
26142       // Scalar SSE types.
26143       case MVT::f32:
26144       case MVT::i32:
26145         return std::make_pair(0U, &X86::FR32RegClass);
26146       case MVT::f64:
26147       case MVT::i64:
26148         return std::make_pair(0U, &X86::FR64RegClass);
26149       // Vector types.
26150       case MVT::v16i8:
26151       case MVT::v8i16:
26152       case MVT::v4i32:
26153       case MVT::v2i64:
26154       case MVT::v4f32:
26155       case MVT::v2f64:
26156         return std::make_pair(0U, &X86::VR128RegClass);
26157       // AVX types.
26158       case MVT::v32i8:
26159       case MVT::v16i16:
26160       case MVT::v8i32:
26161       case MVT::v4i64:
26162       case MVT::v8f32:
26163       case MVT::v4f64:
26164         return std::make_pair(0U, &X86::VR256RegClass);
26165       case MVT::v8f64:
26166       case MVT::v16f32:
26167       case MVT::v16i32:
26168       case MVT::v8i64:
26169         return std::make_pair(0U, &X86::VR512RegClass);
26170       }
26171       break;
26172     }
26173   }
26174
26175   // Use the default implementation in TargetLowering to convert the register
26176   // constraint into a member of a register class.
26177   std::pair<unsigned, const TargetRegisterClass*> Res;
26178   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
26179
26180   // Not found as a standard register?
26181   if (!Res.second) {
26182     // Map st(0) -> st(7) -> ST0
26183     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26184         tolower(Constraint[1]) == 's' &&
26185         tolower(Constraint[2]) == 't' &&
26186         Constraint[3] == '(' &&
26187         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26188         Constraint[5] == ')' &&
26189         Constraint[6] == '}') {
26190
26191       Res.first = X86::FP0+Constraint[4]-'0';
26192       Res.second = &X86::RFP80RegClass;
26193       return Res;
26194     }
26195
26196     // GCC allows "st(0)" to be called just plain "st".
26197     if (StringRef("{st}").equals_lower(Constraint)) {
26198       Res.first = X86::FP0;
26199       Res.second = &X86::RFP80RegClass;
26200       return Res;
26201     }
26202
26203     // flags -> EFLAGS
26204     if (StringRef("{flags}").equals_lower(Constraint)) {
26205       Res.first = X86::EFLAGS;
26206       Res.second = &X86::CCRRegClass;
26207       return Res;
26208     }
26209
26210     // 'A' means EAX + EDX.
26211     if (Constraint == "A") {
26212       Res.first = X86::EAX;
26213       Res.second = &X86::GR32_ADRegClass;
26214       return Res;
26215     }
26216     return Res;
26217   }
26218
26219   // Otherwise, check to see if this is a register class of the wrong value
26220   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26221   // turn into {ax},{dx}.
26222   if (Res.second->hasType(VT))
26223     return Res;   // Correct type already, nothing to do.
26224
26225   // All of the single-register GCC register classes map their values onto
26226   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
26227   // really want an 8-bit or 32-bit register, map to the appropriate register
26228   // class and return the appropriate register.
26229   if (Res.second == &X86::GR16RegClass) {
26230     if (VT == MVT::i8 || VT == MVT::i1) {
26231       unsigned DestReg = 0;
26232       switch (Res.first) {
26233       default: break;
26234       case X86::AX: DestReg = X86::AL; break;
26235       case X86::DX: DestReg = X86::DL; break;
26236       case X86::CX: DestReg = X86::CL; break;
26237       case X86::BX: DestReg = X86::BL; break;
26238       }
26239       if (DestReg) {
26240         Res.first = DestReg;
26241         Res.second = &X86::GR8RegClass;
26242       }
26243     } else if (VT == MVT::i32 || VT == MVT::f32) {
26244       unsigned DestReg = 0;
26245       switch (Res.first) {
26246       default: break;
26247       case X86::AX: DestReg = X86::EAX; break;
26248       case X86::DX: DestReg = X86::EDX; break;
26249       case X86::CX: DestReg = X86::ECX; break;
26250       case X86::BX: DestReg = X86::EBX; break;
26251       case X86::SI: DestReg = X86::ESI; break;
26252       case X86::DI: DestReg = X86::EDI; break;
26253       case X86::BP: DestReg = X86::EBP; break;
26254       case X86::SP: DestReg = X86::ESP; break;
26255       }
26256       if (DestReg) {
26257         Res.first = DestReg;
26258         Res.second = &X86::GR32RegClass;
26259       }
26260     } else if (VT == MVT::i64 || VT == MVT::f64) {
26261       unsigned DestReg = 0;
26262       switch (Res.first) {
26263       default: break;
26264       case X86::AX: DestReg = X86::RAX; break;
26265       case X86::DX: DestReg = X86::RDX; break;
26266       case X86::CX: DestReg = X86::RCX; break;
26267       case X86::BX: DestReg = X86::RBX; break;
26268       case X86::SI: DestReg = X86::RSI; break;
26269       case X86::DI: DestReg = X86::RDI; break;
26270       case X86::BP: DestReg = X86::RBP; break;
26271       case X86::SP: DestReg = X86::RSP; break;
26272       }
26273       if (DestReg) {
26274         Res.first = DestReg;
26275         Res.second = &X86::GR64RegClass;
26276       }
26277     }
26278   } else if (Res.second == &X86::FR32RegClass ||
26279              Res.second == &X86::FR64RegClass ||
26280              Res.second == &X86::VR128RegClass ||
26281              Res.second == &X86::VR256RegClass ||
26282              Res.second == &X86::FR32XRegClass ||
26283              Res.second == &X86::FR64XRegClass ||
26284              Res.second == &X86::VR128XRegClass ||
26285              Res.second == &X86::VR256XRegClass ||
26286              Res.second == &X86::VR512RegClass) {
26287     // Handle references to XMM physical registers that got mapped into the
26288     // wrong class.  This can happen with constraints like {xmm0} where the
26289     // target independent register mapper will just pick the first match it can
26290     // find, ignoring the required type.
26291
26292     if (VT == MVT::f32 || VT == MVT::i32)
26293       Res.second = &X86::FR32RegClass;
26294     else if (VT == MVT::f64 || VT == MVT::i64)
26295       Res.second = &X86::FR64RegClass;
26296     else if (X86::VR128RegClass.hasType(VT))
26297       Res.second = &X86::VR128RegClass;
26298     else if (X86::VR256RegClass.hasType(VT))
26299       Res.second = &X86::VR256RegClass;
26300     else if (X86::VR512RegClass.hasType(VT))
26301       Res.second = &X86::VR512RegClass;
26302   }
26303
26304   return Res;
26305 }
26306
26307 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
26308                                             Type *Ty) const {
26309   // Scaling factors are not free at all.
26310   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26311   // will take 2 allocations in the out of order engine instead of 1
26312   // for plain addressing mode, i.e. inst (reg1).
26313   // E.g.,
26314   // vaddps (%rsi,%drx), %ymm0, %ymm1
26315   // Requires two allocations (one for the load, one for the computation)
26316   // whereas:
26317   // vaddps (%rsi), %ymm0, %ymm1
26318   // Requires just 1 allocation, i.e., freeing allocations for other operations
26319   // and having less micro operations to execute.
26320   //
26321   // For some X86 architectures, this is even worse because for instance for
26322   // stores, the complex addressing mode forces the instruction to use the
26323   // "load" ports instead of the dedicated "store" port.
26324   // E.g., on Haswell:
26325   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26326   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26327   if (isLegalAddressingMode(AM, Ty))
26328     // Scale represents reg2 * scale, thus account for 1
26329     // as soon as we use a second register.
26330     return AM.Scale != 0;
26331   return -1;
26332 }
26333
26334 bool X86TargetLowering::isTargetFTOL() const {
26335   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26336 }