CodeGen: convert CCState interface to using ArrayRefs
[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 "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/VariadicFunction.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71     "x86-recip-refinement-steps", cl::init(1),
72     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73              "result of the hardware reciprocal estimate instruction."),
74     cl::NotHidden);
75
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
78                        SDValue V2);
79
80 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
81                                 SelectionDAG &DAG, SDLoc dl,
82                                 unsigned vectorWidth) {
83   assert((vectorWidth == 128 || vectorWidth == 256) &&
84          "Unsupported vector width");
85   EVT VT = Vec.getValueType();
86   EVT ElVT = VT.getVectorElementType();
87   unsigned Factor = VT.getSizeInBits()/vectorWidth;
88   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89                                   VT.getVectorNumElements()/Factor);
90
91   // Extract from UNDEF is UNDEF.
92   if (Vec.getOpcode() == ISD::UNDEF)
93     return DAG.getUNDEF(ResultVT);
94
95   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
96   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
97
98   // This is the index of the first element of the vectorWidth-bit chunk
99   // we want.
100   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
101                                * ElemsPerChunk);
102
103   // If the input is a buildvector just emit a smaller one.
104   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
105     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
106                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
107                                     ElemsPerChunk));
108
109   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
110   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
111 }
112
113 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
114 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
115 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
116 /// instructions or a simple subregister reference. Idx is an index in the
117 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
118 /// lowering EXTRACT_VECTOR_ELT operations easier.
119 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
120                                    SelectionDAG &DAG, SDLoc dl) {
121   assert((Vec.getValueType().is256BitVector() ||
122           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
123   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
124 }
125
126 /// Generate a DAG to grab 256-bits from a 512-bit vector.
127 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
128                                    SelectionDAG &DAG, SDLoc dl) {
129   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
130   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
131 }
132
133 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
134                                unsigned IdxVal, SelectionDAG &DAG,
135                                SDLoc dl, unsigned vectorWidth) {
136   assert((vectorWidth == 128 || vectorWidth == 256) &&
137          "Unsupported vector width");
138   // Inserting UNDEF is Result
139   if (Vec.getOpcode() == ISD::UNDEF)
140     return Result;
141   EVT VT = Vec.getValueType();
142   EVT ElVT = VT.getVectorElementType();
143   EVT ResultVT = Result.getValueType();
144
145   // Insert the relevant vectorWidth bits.
146   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147
148   // This is the index of the first element of the vectorWidth-bit chunk
149   // we want.
150   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
151                                * ElemsPerChunk);
152
153   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
154   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
155 }
156
157 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
158 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
159 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
160 /// simple superregister reference.  Idx is an index in the 128 bits
161 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
162 /// lowering INSERT_VECTOR_ELT operations easier.
163 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
164                                   SelectionDAG &DAG,SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
170                                   SelectionDAG &DAG, SDLoc dl) {
171   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
172   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
173 }
174
175 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
176 /// instructions. This is used because creating CONCAT_VECTOR nodes of
177 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
178 /// large BUILD_VECTORS.
179 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
180                                    unsigned NumElems, SelectionDAG &DAG,
181                                    SDLoc dl) {
182   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
183   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
184 }
185
186 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
187                                    unsigned NumElems, SelectionDAG &DAG,
188                                    SDLoc dl) {
189   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
190   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
191 }
192
193 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
194                                      const X86Subtarget &STI)
195     : TargetLowering(TM), Subtarget(&STI) {
196   X86ScalarSSEf64 = Subtarget->hasSSE2();
197   X86ScalarSSEf32 = Subtarget->hasSSE1();
198   TD = getDataLayout();
199
200   // Set up the TargetLowering object.
201   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
202
203   // X86 is weird. It always uses i8 for shift amounts and setcc results.
204   setBooleanContents(ZeroOrOneBooleanContent);
205   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
206   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
207
208   // For 64-bit, since we have so many registers, use the ILP scheduler.
209   // For 32-bit, use the register pressure specific scheduling.
210   // For Atom, always use ILP scheduling.
211   if (Subtarget->isAtom())
212     setSchedulingPreference(Sched::ILP);
213   else if (Subtarget->is64Bit())
214     setSchedulingPreference(Sched::ILP);
215   else
216     setSchedulingPreference(Sched::RegPressure);
217   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
218   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
219
220   // Bypass expensive divides on Atom when compiling with O2.
221   if (TM.getOptLevel() >= CodeGenOpt::Default) {
222     if (Subtarget->hasSlowDivide32())
223       addBypassSlowDiv(32, 8);
224     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
225       addBypassSlowDiv(64, 16);
226   }
227
228   if (Subtarget->isTargetKnownWindowsMSVC()) {
229     // Setup Windows compiler runtime calls.
230     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
231     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
232     setLibcallName(RTLIB::SREM_I64, "_allrem");
233     setLibcallName(RTLIB::UREM_I64, "_aullrem");
234     setLibcallName(RTLIB::MUL_I64, "_allmul");
235     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
236     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
237     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
238     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
239     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
240
241     // The _ftol2 runtime function has an unusual calling conv, which
242     // is modeled by a special pseudo-instruction.
243     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
244     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
245     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
246     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
247   }
248
249   if (Subtarget->isTargetDarwin()) {
250     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
251     setUseUnderscoreSetJmp(false);
252     setUseUnderscoreLongJmp(false);
253   } else if (Subtarget->isTargetWindowsGNU()) {
254     // MS runtime is weird: it exports _setjmp, but longjmp!
255     setUseUnderscoreSetJmp(true);
256     setUseUnderscoreLongJmp(false);
257   } else {
258     setUseUnderscoreSetJmp(true);
259     setUseUnderscoreLongJmp(true);
260   }
261
262   // Set up the register classes.
263   addRegisterClass(MVT::i8, &X86::GR8RegClass);
264   addRegisterClass(MVT::i16, &X86::GR16RegClass);
265   addRegisterClass(MVT::i32, &X86::GR32RegClass);
266   if (Subtarget->is64Bit())
267     addRegisterClass(MVT::i64, &X86::GR64RegClass);
268
269   for (MVT VT : MVT::integer_valuetypes())
270     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
271
272   // We don't accept any truncstore of integer registers.
273   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
274   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
275   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
276   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
277   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
278   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
279
280   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
281
282   // SETOEQ and SETUNE require checking two conditions.
283   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
284   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
285   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
286   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
287   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
288   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
289
290   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
291   // operation.
292   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
293   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
294   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
295
296   if (Subtarget->is64Bit()) {
297     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
298     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
299   } else if (!TM.Options.UseSoftFloat) {
300     // We have an algorithm for SSE2->double, and we turn this into a
301     // 64-bit FILD followed by conditional FADD for other targets.
302     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
303     // We have an algorithm for SSE2, and we turn this into a 64-bit
304     // FILD for other targets.
305     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
306   }
307
308   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
309   // this operation.
310   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
311   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
312
313   if (!TM.Options.UseSoftFloat) {
314     // SSE has no i16 to fp conversion, only i32
315     if (X86ScalarSSEf32) {
316       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
317       // f32 and f64 cases are Legal, f80 case is not
318       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
319     } else {
320       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
321       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
322     }
323   } else {
324     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
325     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
326   }
327
328   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
329   // are Legal, f80 is custom lowered.
330   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
331   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
332
333   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
334   // this operation.
335   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
336   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
337
338   if (X86ScalarSSEf32) {
339     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
340     // f32 and f64 cases are Legal, f80 case is not
341     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
342   } else {
343     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
344     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
345   }
346
347   // Handle FP_TO_UINT by promoting the destination to a larger signed
348   // conversion.
349   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
350   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
351   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
352
353   if (Subtarget->is64Bit()) {
354     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
355     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
356   } else if (!TM.Options.UseSoftFloat) {
357     // Since AVX is a superset of SSE3, only check for SSE here.
358     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
359       // Expand FP_TO_UINT into a select.
360       // FIXME: We would like to use a Custom expander here eventually to do
361       // the optimal thing for SSE vs. the default expansion in the legalizer.
362       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
363     else
364       // With SSE3 we can use fisttpll to convert to a signed i64; without
365       // SSE, we're stuck with a fistpll.
366       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
367   }
368
369   if (isTargetFTOL()) {
370     // Use the _ftol2 runtime function, which has a pseudo-instruction
371     // to handle its weird calling convention.
372     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
373   }
374
375   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
376   if (!X86ScalarSSEf64) {
377     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
378     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
379     if (Subtarget->is64Bit()) {
380       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
381       // Without SSE, i64->f64 goes through memory.
382       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
383     }
384   }
385
386   // Scalar integer divide and remainder are lowered to use operations that
387   // produce two results, to match the available instructions. This exposes
388   // the two-result form to trivial CSE, which is able to combine x/y and x%y
389   // into a single instruction.
390   //
391   // Scalar integer multiply-high is also lowered to use two-result
392   // operations, to match the available instructions. However, plain multiply
393   // (low) operations are left as Legal, as there are single-result
394   // instructions for this in x86. Using the two-result multiply instructions
395   // when both high and low results are needed must be arranged by dagcombine.
396   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
397     MVT VT = IntVTs[i];
398     setOperationAction(ISD::MULHS, VT, Expand);
399     setOperationAction(ISD::MULHU, VT, Expand);
400     setOperationAction(ISD::SDIV, VT, Expand);
401     setOperationAction(ISD::UDIV, VT, Expand);
402     setOperationAction(ISD::SREM, VT, Expand);
403     setOperationAction(ISD::UREM, VT, Expand);
404
405     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
406     setOperationAction(ISD::ADDC, VT, Custom);
407     setOperationAction(ISD::ADDE, VT, Custom);
408     setOperationAction(ISD::SUBC, VT, Custom);
409     setOperationAction(ISD::SUBE, VT, Custom);
410   }
411
412   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
413   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
414   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
415   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
416   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
417   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
418   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
419   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
420   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
421   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
422   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
423   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
424   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
425   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
426   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
427   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
428   if (Subtarget->is64Bit())
429     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
430   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
431   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
432   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
433   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
434   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
435   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
436   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
437   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
438
439   // Promote the i8 variants and force them on up to i32 which has a shorter
440   // encoding.
441   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
442   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
443   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
444   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
445   if (Subtarget->hasBMI()) {
446     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
447     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
448     if (Subtarget->is64Bit())
449       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
450   } else {
451     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
452     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
453     if (Subtarget->is64Bit())
454       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
455   }
456
457   if (Subtarget->hasLZCNT()) {
458     // When promoting the i8 variants, force them to i32 for a shorter
459     // encoding.
460     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
461     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
462     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
463     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
464     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
465     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
466     if (Subtarget->is64Bit())
467       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
468   } else {
469     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
470     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
471     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
472     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
473     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
474     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
475     if (Subtarget->is64Bit()) {
476       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
477       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
478     }
479   }
480
481   // Special handling for half-precision floating point conversions.
482   // If we don't have F16C support, then lower half float conversions
483   // into library calls.
484   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
485     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
486     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
487   }
488
489   // There's never any support for operations beyond MVT::f32.
490   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
491   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
492   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
493   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
494
495   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
496   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
497   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
498   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
499   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
500   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
501
502   if (Subtarget->hasPOPCNT()) {
503     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
504   } else {
505     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
506     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
507     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
508     if (Subtarget->is64Bit())
509       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
510   }
511
512   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
513
514   if (!Subtarget->hasMOVBE())
515     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
516
517   // These should be promoted to a larger select which is supported.
518   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
519   // X86 wants to expand cmov itself.
520   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
521   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
522   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
523   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
524   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
525   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
527   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
528   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
529   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
530   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
531   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
532   if (Subtarget->is64Bit()) {
533     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
534     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
535   }
536   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
537   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
538   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
539   // support continuation, user-level threading, and etc.. As a result, no
540   // other SjLj exception interfaces are implemented and please don't build
541   // your own exception handling based on them.
542   // LLVM/Clang supports zero-cost DWARF exception handling.
543   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
544   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
545
546   // Darwin ABI issue.
547   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
548   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
549   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
550   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
551   if (Subtarget->is64Bit())
552     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
553   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
554   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
555   if (Subtarget->is64Bit()) {
556     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
557     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
558     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
559     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
560     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
561   }
562   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
563   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
564   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
565   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
566   if (Subtarget->is64Bit()) {
567     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
568     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
569     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
570   }
571
572   if (Subtarget->hasSSE1())
573     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
574
575   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
576
577   // Expand certain atomics
578   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
579     MVT VT = IntVTs[i];
580     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
581     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
582     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
583   }
584
585   if (Subtarget->hasCmpxchg16b()) {
586     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
587   }
588
589   // FIXME - use subtarget debug flags
590   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
591       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
592     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
593   }
594
595   if (Subtarget->is64Bit()) {
596     setExceptionPointerRegister(X86::RAX);
597     setExceptionSelectorRegister(X86::RDX);
598   } else {
599     setExceptionPointerRegister(X86::EAX);
600     setExceptionSelectorRegister(X86::EDX);
601   }
602   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
603   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
604
605   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
606   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
607
608   setOperationAction(ISD::TRAP, MVT::Other, Legal);
609   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
610
611   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
612   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
613   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
614   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
615     // TargetInfo::X86_64ABIBuiltinVaList
616     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
617     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
618   } else {
619     // TargetInfo::CharPtrBuiltinVaList
620     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
621     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
622   }
623
624   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
625   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
626
627   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
628
629   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
630     // f32 and f64 use SSE.
631     // Set up the FP register classes.
632     addRegisterClass(MVT::f32, &X86::FR32RegClass);
633     addRegisterClass(MVT::f64, &X86::FR64RegClass);
634
635     // Use ANDPD to simulate FABS.
636     setOperationAction(ISD::FABS , MVT::f64, Custom);
637     setOperationAction(ISD::FABS , MVT::f32, Custom);
638
639     // Use XORP to simulate FNEG.
640     setOperationAction(ISD::FNEG , MVT::f64, Custom);
641     setOperationAction(ISD::FNEG , MVT::f32, Custom);
642
643     // Use ANDPD and ORPD to simulate FCOPYSIGN.
644     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
645     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
646
647     // Lower this to FGETSIGNx86 plus an AND.
648     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
649     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
650
651     // We don't support sin/cos/fmod
652     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
653     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
654     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
655     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
656     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
657     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
658
659     // Expand FP immediates into loads from the stack, except for the special
660     // cases we handle.
661     addLegalFPImmediate(APFloat(+0.0)); // xorpd
662     addLegalFPImmediate(APFloat(+0.0f)); // xorps
663   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
664     // Use SSE for f32, x87 for f64.
665     // Set up the FP register classes.
666     addRegisterClass(MVT::f32, &X86::FR32RegClass);
667     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
668
669     // Use ANDPS to simulate FABS.
670     setOperationAction(ISD::FABS , MVT::f32, Custom);
671
672     // Use XORP to simulate FNEG.
673     setOperationAction(ISD::FNEG , MVT::f32, Custom);
674
675     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
676
677     // Use ANDPS and ORPS to simulate FCOPYSIGN.
678     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
679     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
680
681     // We don't support sin/cos/fmod
682     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
683     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
684     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
685
686     // Special cases we handle for FP constants.
687     addLegalFPImmediate(APFloat(+0.0f)); // xorps
688     addLegalFPImmediate(APFloat(+0.0)); // FLD0
689     addLegalFPImmediate(APFloat(+1.0)); // FLD1
690     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
691     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
692
693     if (!TM.Options.UnsafeFPMath) {
694       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
695       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
696       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
697     }
698   } else if (!TM.Options.UseSoftFloat) {
699     // f32 and f64 in x87.
700     // Set up the FP register classes.
701     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
702     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
703
704     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
705     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
706     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
707     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
708
709     if (!TM.Options.UnsafeFPMath) {
710       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
711       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
712       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
713       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
714       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
715       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
716     }
717     addLegalFPImmediate(APFloat(+0.0)); // FLD0
718     addLegalFPImmediate(APFloat(+1.0)); // FLD1
719     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
720     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
721     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
722     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
723     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
724     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
725   }
726
727   // We don't support FMA.
728   setOperationAction(ISD::FMA, MVT::f64, Expand);
729   setOperationAction(ISD::FMA, MVT::f32, Expand);
730
731   // Long double always uses X87.
732   if (!TM.Options.UseSoftFloat) {
733     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
734     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
735     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
736     {
737       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
738       addLegalFPImmediate(TmpFlt);  // FLD0
739       TmpFlt.changeSign();
740       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
741
742       bool ignored;
743       APFloat TmpFlt2(+1.0);
744       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
745                       &ignored);
746       addLegalFPImmediate(TmpFlt2);  // FLD1
747       TmpFlt2.changeSign();
748       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
749     }
750
751     if (!TM.Options.UnsafeFPMath) {
752       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
753       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
754       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
755     }
756
757     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
758     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
759     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
760     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
761     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
762     setOperationAction(ISD::FMA, MVT::f80, Expand);
763   }
764
765   // Always use a library call for pow.
766   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
767   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
768   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
769
770   setOperationAction(ISD::FLOG, MVT::f80, Expand);
771   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
772   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
773   setOperationAction(ISD::FEXP, MVT::f80, Expand);
774   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
775   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
776   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
777
778   // First set operation action for all vector types to either promote
779   // (for widening) or expand (for scalarization). Then we will selectively
780   // turn on ones that can be effectively codegen'd.
781   for (MVT VT : MVT::vector_valuetypes()) {
782     setOperationAction(ISD::ADD , VT, Expand);
783     setOperationAction(ISD::SUB , VT, Expand);
784     setOperationAction(ISD::FADD, VT, Expand);
785     setOperationAction(ISD::FNEG, VT, Expand);
786     setOperationAction(ISD::FSUB, VT, Expand);
787     setOperationAction(ISD::MUL , VT, Expand);
788     setOperationAction(ISD::FMUL, VT, Expand);
789     setOperationAction(ISD::SDIV, VT, Expand);
790     setOperationAction(ISD::UDIV, VT, Expand);
791     setOperationAction(ISD::FDIV, VT, Expand);
792     setOperationAction(ISD::SREM, VT, Expand);
793     setOperationAction(ISD::UREM, VT, Expand);
794     setOperationAction(ISD::LOAD, VT, Expand);
795     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
796     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
797     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
798     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
799     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
800     setOperationAction(ISD::FABS, VT, Expand);
801     setOperationAction(ISD::FSIN, VT, Expand);
802     setOperationAction(ISD::FSINCOS, VT, Expand);
803     setOperationAction(ISD::FCOS, VT, Expand);
804     setOperationAction(ISD::FSINCOS, VT, Expand);
805     setOperationAction(ISD::FREM, VT, Expand);
806     setOperationAction(ISD::FMA,  VT, Expand);
807     setOperationAction(ISD::FPOWI, VT, Expand);
808     setOperationAction(ISD::FSQRT, VT, Expand);
809     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
810     setOperationAction(ISD::FFLOOR, VT, Expand);
811     setOperationAction(ISD::FCEIL, VT, Expand);
812     setOperationAction(ISD::FTRUNC, VT, Expand);
813     setOperationAction(ISD::FRINT, VT, Expand);
814     setOperationAction(ISD::FNEARBYINT, VT, Expand);
815     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
816     setOperationAction(ISD::MULHS, VT, Expand);
817     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
818     setOperationAction(ISD::MULHU, VT, Expand);
819     setOperationAction(ISD::SDIVREM, VT, Expand);
820     setOperationAction(ISD::UDIVREM, VT, Expand);
821     setOperationAction(ISD::FPOW, VT, Expand);
822     setOperationAction(ISD::CTPOP, VT, Expand);
823     setOperationAction(ISD::CTTZ, VT, Expand);
824     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
825     setOperationAction(ISD::CTLZ, VT, Expand);
826     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
827     setOperationAction(ISD::SHL, VT, Expand);
828     setOperationAction(ISD::SRA, VT, Expand);
829     setOperationAction(ISD::SRL, VT, Expand);
830     setOperationAction(ISD::ROTL, VT, Expand);
831     setOperationAction(ISD::ROTR, VT, Expand);
832     setOperationAction(ISD::BSWAP, VT, Expand);
833     setOperationAction(ISD::SETCC, VT, Expand);
834     setOperationAction(ISD::FLOG, VT, Expand);
835     setOperationAction(ISD::FLOG2, VT, Expand);
836     setOperationAction(ISD::FLOG10, VT, Expand);
837     setOperationAction(ISD::FEXP, VT, Expand);
838     setOperationAction(ISD::FEXP2, VT, Expand);
839     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
840     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
841     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
842     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
843     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
844     setOperationAction(ISD::TRUNCATE, VT, Expand);
845     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
846     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
847     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
848     setOperationAction(ISD::VSELECT, VT, Expand);
849     setOperationAction(ISD::SELECT_CC, VT, Expand);
850     for (MVT InnerVT : MVT::vector_valuetypes()) {
851       setTruncStoreAction(InnerVT, VT, Expand);
852
853       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
854       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
855
856       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
857       // types, we have to deal with them whether we ask for Expansion or not.
858       // Setting Expand causes its own optimisation problems though, so leave
859       // them legal.
860       if (VT.getVectorElementType() == MVT::i1)
861         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
862     }
863   }
864
865   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
866   // with -msoft-float, disable use of MMX as well.
867   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
868     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
869     // No operations on x86mmx supported, everything uses intrinsics.
870   }
871
872   // MMX-sized vectors (other than x86mmx) are expected to be expanded
873   // into smaller operations.
874   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
875   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
876   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
877   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
878   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
879   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
880   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
881   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
882   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
883   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
884   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
885   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
886   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
887   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
888   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
889   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
890   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
891   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
892   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
893   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
894   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
895   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
896   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
897   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
898   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
899   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
900   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
901   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
902   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
903
904   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
905     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
906
907     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
908     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
909     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
910     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
911     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
912     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
913     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
914     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
915     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
916     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
917     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
918     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
919     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
920     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
921   }
922
923   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
924     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
925
926     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
927     // registers cannot be used even for integer operations.
928     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
929     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
930     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
931     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
932
933     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
934     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
935     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
936     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
937     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
938     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
939     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
940     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
941     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
942     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
943     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
944     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
945     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
946     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
947     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
948     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
953     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
954     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
955
956     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
960
961     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
962     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
966
967     // Only provide customized ctpop vector bit twiddling for vector types we
968     // know to perform better than using the popcnt instructions on each vector
969     // element. If popcnt isn't supported, always provide the custom version.
970     if (!Subtarget->hasPOPCNT()) {
971       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
972       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
973     }
974
975     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
976     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
977       MVT VT = (MVT::SimpleValueType)i;
978       // Do not attempt to custom lower non-power-of-2 vectors
979       if (!isPowerOf2_32(VT.getVectorNumElements()))
980         continue;
981       // Do not attempt to custom lower non-128-bit vectors
982       if (!VT.is128BitVector())
983         continue;
984       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
985       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
986       setOperationAction(ISD::VSELECT,            VT, Custom);
987       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
988     }
989
990     // We support custom legalizing of sext and anyext loads for specific
991     // memory vector types which we can load as a scalar (or sequence of
992     // scalars) and extend in-register to a legal 128-bit vector type. For sext
993     // loads these must work with a single scalar load.
994     for (MVT VT : MVT::integer_vector_valuetypes()) {
995       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
996       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
997       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
998       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
999       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
1000       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
1001       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
1002       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
1003       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
1004     }
1005
1006     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1007     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1008     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1009     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1010     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1011     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1012     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1013     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1014
1015     if (Subtarget->is64Bit()) {
1016       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1017       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1018     }
1019
1020     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1021     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1022       MVT VT = (MVT::SimpleValueType)i;
1023
1024       // Do not attempt to promote non-128-bit vectors
1025       if (!VT.is128BitVector())
1026         continue;
1027
1028       setOperationAction(ISD::AND,    VT, Promote);
1029       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1030       setOperationAction(ISD::OR,     VT, Promote);
1031       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1032       setOperationAction(ISD::XOR,    VT, Promote);
1033       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1034       setOperationAction(ISD::LOAD,   VT, Promote);
1035       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1036       setOperationAction(ISD::SELECT, VT, Promote);
1037       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1038     }
1039
1040     // Custom lower v2i64 and v2f64 selects.
1041     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1042     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1043     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1044     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1045
1046     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1047     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1048
1049     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1050     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1051     // As there is no 64-bit GPR available, we need build a special custom
1052     // sequence to convert from v2i32 to v2f32.
1053     if (!Subtarget->is64Bit())
1054       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1055
1056     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1057     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1058
1059     for (MVT VT : MVT::fp_vector_valuetypes())
1060       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
1061
1062     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1063     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1064     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1065   }
1066
1067   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1068     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1069     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1070     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1071     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1072     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1073     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1074     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1075     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1076     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1077     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1078
1079     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1080     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1081     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1082     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1083     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1084     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1085     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1086     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1087     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1088     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1089
1090     // FIXME: Do we need to handle scalar-to-vector here?
1091     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1092
1093     // We directly match byte blends in the backend as they match the VSELECT
1094     // condition form.
1095     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1096
1097     // SSE41 brings specific instructions for doing vector sign extend even in
1098     // cases where we don't have SRA.
1099     for (MVT VT : MVT::integer_vector_valuetypes()) {
1100       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1101       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1102       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1103     }
1104
1105     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1106     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1107     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1108     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1109     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1110     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1111     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1112
1113     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
1114     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1115     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1116     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1117     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1118     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1119
1120     // i8 and i16 vectors are custom because the source register and source
1121     // source memory operand types are not the same width.  f32 vectors are
1122     // custom since the immediate controlling the insert encodes additional
1123     // information.
1124     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1125     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1126     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1127     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1128
1129     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1130     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1131     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1132     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1133
1134     // FIXME: these should be Legal, but that's only for the case where
1135     // the index is constant.  For now custom expand to deal with that.
1136     if (Subtarget->is64Bit()) {
1137       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1138       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1139     }
1140   }
1141
1142   if (Subtarget->hasSSE2()) {
1143     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1144     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1145
1146     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1147     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1148
1149     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1150     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1151
1152     // In the customized shift lowering, the legal cases in AVX2 will be
1153     // recognized.
1154     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1155     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1156
1157     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1158     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1159
1160     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1161   }
1162
1163   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1164     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1165     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1166     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1167     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1168     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1169     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1170
1171     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1172     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1173     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1174
1175     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1176     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1177     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1178     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1179     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1180     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1181     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1182     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1183     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1184     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1185     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1186     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1187
1188     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1189     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1190     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1191     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1192     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1193     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1194     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1195     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1196     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1197     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1198     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1199     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1200
1201     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1202     // even though v8i16 is a legal type.
1203     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1204     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1205     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1206
1207     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1208     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1209     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1210
1211     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1212     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1213
1214     for (MVT VT : MVT::fp_vector_valuetypes())
1215       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1216
1217     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1218     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1219
1220     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1221     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1222
1223     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1224     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1225
1226     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1227     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1228     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1229     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1230
1231     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1232     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1233     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1234
1235     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1236     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1237     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1238     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1239     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1240     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1241     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1242     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1243     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1244     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1245     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1246     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1247
1248     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1249       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1250       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1251       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1252       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1253       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1254       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1255     }
1256
1257     if (Subtarget->hasInt256()) {
1258       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1259       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1260       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1261       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1262
1263       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1264       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1265       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1266       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1267
1268       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1269       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1270       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1271       // Don't lower v32i8 because there is no 128-bit byte mul
1272
1273       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1274       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1275       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1276       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1277
1278       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1279       // when we have a 256bit-wide blend with immediate.
1280       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1281
1282       // Only provide customized ctpop vector bit twiddling for vector types we
1283       // know to perform better than using the popcnt instructions on each
1284       // vector element. If popcnt isn't supported, always provide the custom
1285       // version.
1286       if (!Subtarget->hasPOPCNT())
1287         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1288
1289       // Custom CTPOP always performs better on natively supported v8i32
1290       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1291
1292       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1293       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1294       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1295       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1296       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1297       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1298       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1299
1300       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1301       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1302       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1303       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1304       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1305       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1306     } else {
1307       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1308       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1309       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1310       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1311
1312       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1313       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1314       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1315       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1316
1317       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1318       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1319       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1320       // Don't lower v32i8 because there is no 128-bit byte mul
1321     }
1322
1323     // In the customized shift lowering, the legal cases in AVX2 will be
1324     // recognized.
1325     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1326     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1327
1328     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1329     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1330
1331     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1332
1333     // Custom lower several nodes for 256-bit types.
1334     for (MVT VT : MVT::vector_valuetypes()) {
1335       if (VT.getScalarSizeInBits() >= 32) {
1336         setOperationAction(ISD::MLOAD,  VT, Legal);
1337         setOperationAction(ISD::MSTORE, VT, Legal);
1338       }
1339       // Extract subvector is special because the value type
1340       // (result) is 128-bit but the source is 256-bit wide.
1341       if (VT.is128BitVector()) {
1342         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1343       }
1344       // Do not attempt to custom lower other non-256-bit vectors
1345       if (!VT.is256BitVector())
1346         continue;
1347
1348       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1349       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1350       setOperationAction(ISD::VSELECT,            VT, Custom);
1351       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1352       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1353       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1354       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1355       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1356     }
1357
1358     if (Subtarget->hasInt256())
1359       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1360
1361
1362     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1363     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1364       MVT VT = (MVT::SimpleValueType)i;
1365
1366       // Do not attempt to promote non-256-bit vectors
1367       if (!VT.is256BitVector())
1368         continue;
1369
1370       setOperationAction(ISD::AND,    VT, Promote);
1371       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1372       setOperationAction(ISD::OR,     VT, Promote);
1373       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1374       setOperationAction(ISD::XOR,    VT, Promote);
1375       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1376       setOperationAction(ISD::LOAD,   VT, Promote);
1377       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1378       setOperationAction(ISD::SELECT, VT, Promote);
1379       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1380     }
1381   }
1382
1383   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1384     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1385     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1386     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1387     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1388
1389     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1390     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1391     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1392
1393     for (MVT VT : MVT::fp_vector_valuetypes())
1394       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1395
1396     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1397     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1398     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1399     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1400     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1401     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1402     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1403     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1404     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1405     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1406
1407     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1408     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1409     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1410     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1411     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1412     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1413
1414     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1415     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1416     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1417     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1418     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1419     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1420     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1421     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1422
1423     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1424     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1425     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1426     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1427     if (Subtarget->is64Bit()) {
1428       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1429       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1430       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1431       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1432     }
1433     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1434     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1435     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1436     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1437     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1438     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1439     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1440     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1441     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1442     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1443     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1444     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1445     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1446     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1447
1448     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1449     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1450     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1451     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1452     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1453     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1454     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1455     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1456     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1457     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1458     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1459     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1460     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1461
1462     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1463     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1464     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1465     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1466     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1467     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1468     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1469     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1470     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1471     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1472
1473     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1474     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1475     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1476     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1477     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1478     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1479
1480     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1481     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1482
1483     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1484
1485     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1486     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1487     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1488     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1489     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1490     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1491     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1492     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1493     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1494
1495     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1496     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1497
1498     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1499     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1500
1501     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1502
1503     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1504     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1505
1506     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1507     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1508
1509     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1510     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1511
1512     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1513     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1514     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1515     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1516     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1517     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1518
1519     if (Subtarget->hasCDI()) {
1520       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1521       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1522     }
1523
1524     // Custom lower several nodes.
1525     for (MVT VT : MVT::vector_valuetypes()) {
1526       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1527       // Extract subvector is special because the value type
1528       // (result) is 256/128-bit but the source is 512-bit wide.
1529       if (VT.is128BitVector() || VT.is256BitVector()) {
1530         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1531       }
1532       if (VT.getVectorElementType() == MVT::i1)
1533         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1534
1535       // Do not attempt to custom lower other non-512-bit vectors
1536       if (!VT.is512BitVector())
1537         continue;
1538
1539       if ( EltSize >= 32) {
1540         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1541         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1542         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1543         setOperationAction(ISD::VSELECT,             VT, Legal);
1544         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1545         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1546         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1547         setOperationAction(ISD::MLOAD,               VT, Legal);
1548         setOperationAction(ISD::MSTORE,              VT, Legal);
1549       }
1550     }
1551     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1552       MVT VT = (MVT::SimpleValueType)i;
1553
1554       // Do not attempt to promote non-512-bit vectors.
1555       if (!VT.is512BitVector())
1556         continue;
1557
1558       setOperationAction(ISD::SELECT, VT, Promote);
1559       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1560     }
1561   }// has  AVX-512
1562
1563   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1564     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1565     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1566
1567     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1568     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1569
1570     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1571     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1572     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1573     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1574     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1575     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1576     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1577     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1578     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1579
1580     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1581       const MVT VT = (MVT::SimpleValueType)i;
1582
1583       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1584
1585       // Do not attempt to promote non-512-bit vectors.
1586       if (!VT.is512BitVector())
1587         continue;
1588
1589       if (EltSize < 32) {
1590         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1591         setOperationAction(ISD::VSELECT,             VT, Legal);
1592       }
1593     }
1594   }
1595
1596   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1597     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1598     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1599
1600     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1601     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1602     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Legal);
1603
1604     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1605     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1606     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1607     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1608     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1609     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1610   }
1611
1612   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1613   // of this type with custom code.
1614   for (MVT VT : MVT::vector_valuetypes())
1615     setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1616
1617   // We want to custom lower some of our intrinsics.
1618   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1619   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1620   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1621   if (!Subtarget->is64Bit())
1622     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1623
1624   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1625   // handle type legalization for these operations here.
1626   //
1627   // FIXME: We really should do custom legalization for addition and
1628   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1629   // than generic legalization for 64-bit multiplication-with-overflow, though.
1630   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1631     // Add/Sub/Mul with overflow operations are custom lowered.
1632     MVT VT = IntVTs[i];
1633     setOperationAction(ISD::SADDO, VT, Custom);
1634     setOperationAction(ISD::UADDO, VT, Custom);
1635     setOperationAction(ISD::SSUBO, VT, Custom);
1636     setOperationAction(ISD::USUBO, VT, Custom);
1637     setOperationAction(ISD::SMULO, VT, Custom);
1638     setOperationAction(ISD::UMULO, VT, Custom);
1639   }
1640
1641
1642   if (!Subtarget->is64Bit()) {
1643     // These libcalls are not available in 32-bit.
1644     setLibcallName(RTLIB::SHL_I128, nullptr);
1645     setLibcallName(RTLIB::SRL_I128, nullptr);
1646     setLibcallName(RTLIB::SRA_I128, nullptr);
1647   }
1648
1649   // Combine sin / cos into one node or libcall if possible.
1650   if (Subtarget->hasSinCos()) {
1651     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1652     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1653     if (Subtarget->isTargetDarwin()) {
1654       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1655       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1656       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1657       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1658     }
1659   }
1660
1661   if (Subtarget->isTargetWin64()) {
1662     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1663     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1664     setOperationAction(ISD::SREM, MVT::i128, Custom);
1665     setOperationAction(ISD::UREM, MVT::i128, Custom);
1666     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1667     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1668   }
1669
1670   // We have target-specific dag combine patterns for the following nodes:
1671   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1672   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1673   setTargetDAGCombine(ISD::BITCAST);
1674   setTargetDAGCombine(ISD::VSELECT);
1675   setTargetDAGCombine(ISD::SELECT);
1676   setTargetDAGCombine(ISD::SHL);
1677   setTargetDAGCombine(ISD::SRA);
1678   setTargetDAGCombine(ISD::SRL);
1679   setTargetDAGCombine(ISD::OR);
1680   setTargetDAGCombine(ISD::AND);
1681   setTargetDAGCombine(ISD::ADD);
1682   setTargetDAGCombine(ISD::FADD);
1683   setTargetDAGCombine(ISD::FSUB);
1684   setTargetDAGCombine(ISD::FMA);
1685   setTargetDAGCombine(ISD::SUB);
1686   setTargetDAGCombine(ISD::LOAD);
1687   setTargetDAGCombine(ISD::MLOAD);
1688   setTargetDAGCombine(ISD::STORE);
1689   setTargetDAGCombine(ISD::MSTORE);
1690   setTargetDAGCombine(ISD::ZERO_EXTEND);
1691   setTargetDAGCombine(ISD::ANY_EXTEND);
1692   setTargetDAGCombine(ISD::SIGN_EXTEND);
1693   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1694   setTargetDAGCombine(ISD::TRUNCATE);
1695   setTargetDAGCombine(ISD::SINT_TO_FP);
1696   setTargetDAGCombine(ISD::SETCC);
1697   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1698   setTargetDAGCombine(ISD::BUILD_VECTOR);
1699   setTargetDAGCombine(ISD::MUL);
1700   setTargetDAGCombine(ISD::XOR);
1701
1702   computeRegisterProperties();
1703
1704   // On Darwin, -Os means optimize for size without hurting performance,
1705   // do not reduce the limit.
1706   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1707   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1708   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1709   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1710   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1711   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1712   setPrefLoopAlignment(4); // 2^4 bytes.
1713
1714   // Predictable cmov don't hurt on atom because it's in-order.
1715   PredictableSelectIsExpensive = !Subtarget->isAtom();
1716   EnableExtLdPromotion = true;
1717   setPrefFunctionAlignment(4); // 2^4 bytes.
1718
1719   verifyIntrinsicTables();
1720 }
1721
1722 // This has so far only been implemented for 64-bit MachO.
1723 bool X86TargetLowering::useLoadStackGuardNode() const {
1724   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1725 }
1726
1727 TargetLoweringBase::LegalizeTypeAction
1728 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1729   if (ExperimentalVectorWideningLegalization &&
1730       VT.getVectorNumElements() != 1 &&
1731       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1732     return TypeWidenVector;
1733
1734   return TargetLoweringBase::getPreferredVectorAction(VT);
1735 }
1736
1737 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1738   if (!VT.isVector())
1739     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1740
1741   const unsigned NumElts = VT.getVectorNumElements();
1742   const EVT EltVT = VT.getVectorElementType();
1743   if (VT.is512BitVector()) {
1744     if (Subtarget->hasAVX512())
1745       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1746           EltVT == MVT::f32 || EltVT == MVT::f64)
1747         switch(NumElts) {
1748         case  8: return MVT::v8i1;
1749         case 16: return MVT::v16i1;
1750       }
1751     if (Subtarget->hasBWI())
1752       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1753         switch(NumElts) {
1754         case 32: return MVT::v32i1;
1755         case 64: return MVT::v64i1;
1756       }
1757   }
1758
1759   if (VT.is256BitVector() || VT.is128BitVector()) {
1760     if (Subtarget->hasVLX())
1761       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1762           EltVT == MVT::f32 || EltVT == MVT::f64)
1763         switch(NumElts) {
1764         case 2: return MVT::v2i1;
1765         case 4: return MVT::v4i1;
1766         case 8: return MVT::v8i1;
1767       }
1768     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1769       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1770         switch(NumElts) {
1771         case  8: return MVT::v8i1;
1772         case 16: return MVT::v16i1;
1773         case 32: return MVT::v32i1;
1774       }
1775   }
1776
1777   return VT.changeVectorElementTypeToInteger();
1778 }
1779
1780 /// Helper for getByValTypeAlignment to determine
1781 /// the desired ByVal argument alignment.
1782 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1783   if (MaxAlign == 16)
1784     return;
1785   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1786     if (VTy->getBitWidth() == 128)
1787       MaxAlign = 16;
1788   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1789     unsigned EltAlign = 0;
1790     getMaxByValAlign(ATy->getElementType(), EltAlign);
1791     if (EltAlign > MaxAlign)
1792       MaxAlign = EltAlign;
1793   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1794     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1795       unsigned EltAlign = 0;
1796       getMaxByValAlign(STy->getElementType(i), EltAlign);
1797       if (EltAlign > MaxAlign)
1798         MaxAlign = EltAlign;
1799       if (MaxAlign == 16)
1800         break;
1801     }
1802   }
1803 }
1804
1805 /// Return the desired alignment for ByVal aggregate
1806 /// function arguments in the caller parameter area. For X86, aggregates
1807 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1808 /// are at 4-byte boundaries.
1809 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1810   if (Subtarget->is64Bit()) {
1811     // Max of 8 and alignment of type.
1812     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1813     if (TyAlign > 8)
1814       return TyAlign;
1815     return 8;
1816   }
1817
1818   unsigned Align = 4;
1819   if (Subtarget->hasSSE1())
1820     getMaxByValAlign(Ty, Align);
1821   return Align;
1822 }
1823
1824 /// Returns the target specific optimal type for load
1825 /// and store operations as a result of memset, memcpy, and memmove
1826 /// lowering. If DstAlign is zero that means it's safe to destination
1827 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1828 /// means there isn't a need to check it against alignment requirement,
1829 /// probably because the source does not need to be loaded. If 'IsMemset' is
1830 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1831 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1832 /// source is constant so it does not need to be loaded.
1833 /// It returns EVT::Other if the type should be determined using generic
1834 /// target-independent logic.
1835 EVT
1836 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1837                                        unsigned DstAlign, unsigned SrcAlign,
1838                                        bool IsMemset, bool ZeroMemset,
1839                                        bool MemcpyStrSrc,
1840                                        MachineFunction &MF) const {
1841   const Function *F = MF.getFunction();
1842   if ((!IsMemset || ZeroMemset) &&
1843       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1844     if (Size >= 16 &&
1845         (Subtarget->isUnalignedMemAccessFast() ||
1846          ((DstAlign == 0 || DstAlign >= 16) &&
1847           (SrcAlign == 0 || SrcAlign >= 16)))) {
1848       if (Size >= 32) {
1849         if (Subtarget->hasInt256())
1850           return MVT::v8i32;
1851         if (Subtarget->hasFp256())
1852           return MVT::v8f32;
1853       }
1854       if (Subtarget->hasSSE2())
1855         return MVT::v4i32;
1856       if (Subtarget->hasSSE1())
1857         return MVT::v4f32;
1858     } else if (!MemcpyStrSrc && Size >= 8 &&
1859                !Subtarget->is64Bit() &&
1860                Subtarget->hasSSE2()) {
1861       // Do not use f64 to lower memcpy if source is string constant. It's
1862       // better to use i32 to avoid the loads.
1863       return MVT::f64;
1864     }
1865   }
1866   if (Subtarget->is64Bit() && Size >= 8)
1867     return MVT::i64;
1868   return MVT::i32;
1869 }
1870
1871 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1872   if (VT == MVT::f32)
1873     return X86ScalarSSEf32;
1874   else if (VT == MVT::f64)
1875     return X86ScalarSSEf64;
1876   return true;
1877 }
1878
1879 bool
1880 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1881                                                   unsigned,
1882                                                   unsigned,
1883                                                   bool *Fast) const {
1884   if (Fast)
1885     *Fast = Subtarget->isUnalignedMemAccessFast();
1886   return true;
1887 }
1888
1889 /// Return the entry encoding for a jump table in the
1890 /// current function.  The returned value is a member of the
1891 /// MachineJumpTableInfo::JTEntryKind enum.
1892 unsigned X86TargetLowering::getJumpTableEncoding() const {
1893   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1894   // symbol.
1895   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1896       Subtarget->isPICStyleGOT())
1897     return MachineJumpTableInfo::EK_Custom32;
1898
1899   // Otherwise, use the normal jump table encoding heuristics.
1900   return TargetLowering::getJumpTableEncoding();
1901 }
1902
1903 const MCExpr *
1904 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1905                                              const MachineBasicBlock *MBB,
1906                                              unsigned uid,MCContext &Ctx) const{
1907   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1908          Subtarget->isPICStyleGOT());
1909   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1910   // entries.
1911   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1912                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1913 }
1914
1915 /// Returns relocation base for the given PIC jumptable.
1916 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1917                                                     SelectionDAG &DAG) const {
1918   if (!Subtarget->is64Bit())
1919     // This doesn't have SDLoc associated with it, but is not really the
1920     // same as a Register.
1921     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1922   return Table;
1923 }
1924
1925 /// This returns the relocation base for the given PIC jumptable,
1926 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1927 const MCExpr *X86TargetLowering::
1928 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1929                              MCContext &Ctx) const {
1930   // X86-64 uses RIP relative addressing based on the jump table label.
1931   if (Subtarget->isPICStyleRIPRel())
1932     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1933
1934   // Otherwise, the reference is relative to the PIC base.
1935   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1936 }
1937
1938 // FIXME: Why this routine is here? Move to RegInfo!
1939 std::pair<const TargetRegisterClass*, uint8_t>
1940 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1941   const TargetRegisterClass *RRC = nullptr;
1942   uint8_t Cost = 1;
1943   switch (VT.SimpleTy) {
1944   default:
1945     return TargetLowering::findRepresentativeClass(VT);
1946   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1947     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1948     break;
1949   case MVT::x86mmx:
1950     RRC = &X86::VR64RegClass;
1951     break;
1952   case MVT::f32: case MVT::f64:
1953   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1954   case MVT::v4f32: case MVT::v2f64:
1955   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1956   case MVT::v4f64:
1957     RRC = &X86::VR128RegClass;
1958     break;
1959   }
1960   return std::make_pair(RRC, Cost);
1961 }
1962
1963 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1964                                                unsigned &Offset) const {
1965   if (!Subtarget->isTargetLinux())
1966     return false;
1967
1968   if (Subtarget->is64Bit()) {
1969     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1970     Offset = 0x28;
1971     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1972       AddressSpace = 256;
1973     else
1974       AddressSpace = 257;
1975   } else {
1976     // %gs:0x14 on i386
1977     Offset = 0x14;
1978     AddressSpace = 256;
1979   }
1980   return true;
1981 }
1982
1983 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1984                                             unsigned DestAS) const {
1985   assert(SrcAS != DestAS && "Expected different address spaces!");
1986
1987   return SrcAS < 256 && DestAS < 256;
1988 }
1989
1990 //===----------------------------------------------------------------------===//
1991 //               Return Value Calling Convention Implementation
1992 //===----------------------------------------------------------------------===//
1993
1994 #include "X86GenCallingConv.inc"
1995
1996 bool
1997 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1998                                   MachineFunction &MF, bool isVarArg,
1999                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2000                         LLVMContext &Context) const {
2001   SmallVector<CCValAssign, 16> RVLocs;
2002   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2003   return CCInfo.CheckReturn(Outs, RetCC_X86);
2004 }
2005
2006 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2007   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2008   return ScratchRegs;
2009 }
2010
2011 SDValue
2012 X86TargetLowering::LowerReturn(SDValue Chain,
2013                                CallingConv::ID CallConv, bool isVarArg,
2014                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2015                                const SmallVectorImpl<SDValue> &OutVals,
2016                                SDLoc dl, SelectionDAG &DAG) const {
2017   MachineFunction &MF = DAG.getMachineFunction();
2018   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2019
2020   SmallVector<CCValAssign, 16> RVLocs;
2021   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2022   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2023
2024   SDValue Flag;
2025   SmallVector<SDValue, 6> RetOps;
2026   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2027   // Operand #1 = Bytes To Pop
2028   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2029                    MVT::i16));
2030
2031   // Copy the result values into the output registers.
2032   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2033     CCValAssign &VA = RVLocs[i];
2034     assert(VA.isRegLoc() && "Can only return in registers!");
2035     SDValue ValToCopy = OutVals[i];
2036     EVT ValVT = ValToCopy.getValueType();
2037
2038     // Promote values to the appropriate types.
2039     if (VA.getLocInfo() == CCValAssign::SExt)
2040       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2041     else if (VA.getLocInfo() == CCValAssign::ZExt)
2042       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2043     else if (VA.getLocInfo() == CCValAssign::AExt)
2044       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2045     else if (VA.getLocInfo() == CCValAssign::BCvt)
2046       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2047
2048     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2049            "Unexpected FP-extend for return value.");
2050
2051     // If this is x86-64, and we disabled SSE, we can't return FP values,
2052     // or SSE or MMX vectors.
2053     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2054          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2055           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2056       report_fatal_error("SSE register return with SSE disabled");
2057     }
2058     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2059     // llvm-gcc has never done it right and no one has noticed, so this
2060     // should be OK for now.
2061     if (ValVT == MVT::f64 &&
2062         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2063       report_fatal_error("SSE2 register return with SSE2 disabled");
2064
2065     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2066     // the RET instruction and handled by the FP Stackifier.
2067     if (VA.getLocReg() == X86::FP0 ||
2068         VA.getLocReg() == X86::FP1) {
2069       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2070       // change the value to the FP stack register class.
2071       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2072         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2073       RetOps.push_back(ValToCopy);
2074       // Don't emit a copytoreg.
2075       continue;
2076     }
2077
2078     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2079     // which is returned in RAX / RDX.
2080     if (Subtarget->is64Bit()) {
2081       if (ValVT == MVT::x86mmx) {
2082         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2083           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2084           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2085                                   ValToCopy);
2086           // If we don't have SSE2 available, convert to v4f32 so the generated
2087           // register is legal.
2088           if (!Subtarget->hasSSE2())
2089             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2090         }
2091       }
2092     }
2093
2094     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2095     Flag = Chain.getValue(1);
2096     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2097   }
2098
2099   // The x86-64 ABIs require that for returning structs by value we copy
2100   // the sret argument into %rax/%eax (depending on ABI) for the return.
2101   // Win32 requires us to put the sret argument to %eax as well.
2102   // We saved the argument into a virtual register in the entry block,
2103   // so now we copy the value out and into %rax/%eax.
2104   //
2105   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2106   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2107   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2108   // either case FuncInfo->setSRetReturnReg() will have been called.
2109   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2110     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2111            "No need for an sret register");
2112     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2113
2114     unsigned RetValReg
2115         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2116           X86::RAX : X86::EAX;
2117     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2118     Flag = Chain.getValue(1);
2119
2120     // RAX/EAX now acts like a return value.
2121     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2122   }
2123
2124   RetOps[0] = Chain;  // Update chain.
2125
2126   // Add the flag if we have it.
2127   if (Flag.getNode())
2128     RetOps.push_back(Flag);
2129
2130   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2131 }
2132
2133 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2134   if (N->getNumValues() != 1)
2135     return false;
2136   if (!N->hasNUsesOfValue(1, 0))
2137     return false;
2138
2139   SDValue TCChain = Chain;
2140   SDNode *Copy = *N->use_begin();
2141   if (Copy->getOpcode() == ISD::CopyToReg) {
2142     // If the copy has a glue operand, we conservatively assume it isn't safe to
2143     // perform a tail call.
2144     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2145       return false;
2146     TCChain = Copy->getOperand(0);
2147   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2148     return false;
2149
2150   bool HasRet = false;
2151   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2152        UI != UE; ++UI) {
2153     if (UI->getOpcode() != X86ISD::RET_FLAG)
2154       return false;
2155     // If we are returning more than one value, we can definitely
2156     // not make a tail call see PR19530
2157     if (UI->getNumOperands() > 4)
2158       return false;
2159     if (UI->getNumOperands() == 4 &&
2160         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2161       return false;
2162     HasRet = true;
2163   }
2164
2165   if (!HasRet)
2166     return false;
2167
2168   Chain = TCChain;
2169   return true;
2170 }
2171
2172 EVT
2173 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2174                                             ISD::NodeType ExtendKind) const {
2175   MVT ReturnMVT;
2176   // TODO: Is this also valid on 32-bit?
2177   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2178     ReturnMVT = MVT::i8;
2179   else
2180     ReturnMVT = MVT::i32;
2181
2182   EVT MinVT = getRegisterType(Context, ReturnMVT);
2183   return VT.bitsLT(MinVT) ? MinVT : VT;
2184 }
2185
2186 /// Lower the result values of a call into the
2187 /// appropriate copies out of appropriate physical registers.
2188 ///
2189 SDValue
2190 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2191                                    CallingConv::ID CallConv, bool isVarArg,
2192                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2193                                    SDLoc dl, SelectionDAG &DAG,
2194                                    SmallVectorImpl<SDValue> &InVals) const {
2195
2196   // Assign locations to each value returned by this call.
2197   SmallVector<CCValAssign, 16> RVLocs;
2198   bool Is64Bit = Subtarget->is64Bit();
2199   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2200                  *DAG.getContext());
2201   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2202
2203   // Copy all of the result registers out of their specified physreg.
2204   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2205     CCValAssign &VA = RVLocs[i];
2206     EVT CopyVT = VA.getValVT();
2207
2208     // If this is x86-64, and we disabled SSE, we can't return FP values
2209     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2210         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2211       report_fatal_error("SSE register return with SSE disabled");
2212     }
2213
2214     // If we prefer to use the value in xmm registers, copy it out as f80 and
2215     // use a truncate to move it from fp stack reg to xmm reg.
2216     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2217         isScalarFPTypeInSSEReg(VA.getValVT()))
2218       CopyVT = MVT::f80;
2219
2220     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2221                                CopyVT, InFlag).getValue(1);
2222     SDValue Val = Chain.getValue(0);
2223
2224     if (CopyVT != VA.getValVT())
2225       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2226                         // This truncation won't change the value.
2227                         DAG.getIntPtrConstant(1));
2228
2229     InFlag = Chain.getValue(2);
2230     InVals.push_back(Val);
2231   }
2232
2233   return Chain;
2234 }
2235
2236 //===----------------------------------------------------------------------===//
2237 //                C & StdCall & Fast Calling Convention implementation
2238 //===----------------------------------------------------------------------===//
2239 //  StdCall calling convention seems to be standard for many Windows' API
2240 //  routines and around. It differs from C calling convention just a little:
2241 //  callee should clean up the stack, not caller. Symbols should be also
2242 //  decorated in some fancy way :) It doesn't support any vector arguments.
2243 //  For info on fast calling convention see Fast Calling Convention (tail call)
2244 //  implementation LowerX86_32FastCCCallTo.
2245
2246 /// CallIsStructReturn - Determines whether a call uses struct return
2247 /// semantics.
2248 enum StructReturnType {
2249   NotStructReturn,
2250   RegStructReturn,
2251   StackStructReturn
2252 };
2253 static StructReturnType
2254 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2255   if (Outs.empty())
2256     return NotStructReturn;
2257
2258   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2259   if (!Flags.isSRet())
2260     return NotStructReturn;
2261   if (Flags.isInReg())
2262     return RegStructReturn;
2263   return StackStructReturn;
2264 }
2265
2266 /// Determines whether a function uses struct return semantics.
2267 static StructReturnType
2268 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2269   if (Ins.empty())
2270     return NotStructReturn;
2271
2272   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2273   if (!Flags.isSRet())
2274     return NotStructReturn;
2275   if (Flags.isInReg())
2276     return RegStructReturn;
2277   return StackStructReturn;
2278 }
2279
2280 /// Make a copy of an aggregate at address specified by "Src" to address
2281 /// "Dst" with size and alignment information specified by the specific
2282 /// parameter attribute. The copy will be passed as a byval function parameter.
2283 static SDValue
2284 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2285                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2286                           SDLoc dl) {
2287   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2288
2289   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2290                        /*isVolatile*/false, /*AlwaysInline=*/true,
2291                        MachinePointerInfo(), MachinePointerInfo());
2292 }
2293
2294 /// Return true if the calling convention is one that
2295 /// supports tail call optimization.
2296 static bool IsTailCallConvention(CallingConv::ID CC) {
2297   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2298           CC == CallingConv::HiPE);
2299 }
2300
2301 /// \brief Return true if the calling convention is a C calling convention.
2302 static bool IsCCallConvention(CallingConv::ID CC) {
2303   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2304           CC == CallingConv::X86_64_SysV);
2305 }
2306
2307 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2308   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2309     return false;
2310
2311   CallSite CS(CI);
2312   CallingConv::ID CalleeCC = CS.getCallingConv();
2313   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2314     return false;
2315
2316   return true;
2317 }
2318
2319 /// Return true if the function is being made into
2320 /// a tailcall target by changing its ABI.
2321 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2322                                    bool GuaranteedTailCallOpt) {
2323   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2324 }
2325
2326 SDValue
2327 X86TargetLowering::LowerMemArgument(SDValue Chain,
2328                                     CallingConv::ID CallConv,
2329                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2330                                     SDLoc dl, SelectionDAG &DAG,
2331                                     const CCValAssign &VA,
2332                                     MachineFrameInfo *MFI,
2333                                     unsigned i) const {
2334   // Create the nodes corresponding to a load from this parameter slot.
2335   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2336   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2337       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2338   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2339   EVT ValVT;
2340
2341   // If value is passed by pointer we have address passed instead of the value
2342   // itself.
2343   if (VA.getLocInfo() == CCValAssign::Indirect)
2344     ValVT = VA.getLocVT();
2345   else
2346     ValVT = VA.getValVT();
2347
2348   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2349   // changed with more analysis.
2350   // In case of tail call optimization mark all arguments mutable. Since they
2351   // could be overwritten by lowering of arguments in case of a tail call.
2352   if (Flags.isByVal()) {
2353     unsigned Bytes = Flags.getByValSize();
2354     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2355     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2356     return DAG.getFrameIndex(FI, getPointerTy());
2357   } else {
2358     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2359                                     VA.getLocMemOffset(), isImmutable);
2360     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2361     return DAG.getLoad(ValVT, dl, Chain, FIN,
2362                        MachinePointerInfo::getFixedStack(FI),
2363                        false, false, false, 0);
2364   }
2365 }
2366
2367 // FIXME: Get this from tablegen.
2368 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2369                                                 const X86Subtarget *Subtarget) {
2370   assert(Subtarget->is64Bit());
2371
2372   if (Subtarget->isCallingConvWin64(CallConv)) {
2373     static const MCPhysReg GPR64ArgRegsWin64[] = {
2374       X86::RCX, X86::RDX, X86::R8,  X86::R9
2375     };
2376     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2377   }
2378
2379   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2380     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2381   };
2382   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2383 }
2384
2385 // FIXME: Get this from tablegen.
2386 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2387                                                 CallingConv::ID CallConv,
2388                                                 const X86Subtarget *Subtarget) {
2389   assert(Subtarget->is64Bit());
2390   if (Subtarget->isCallingConvWin64(CallConv)) {
2391     // The XMM registers which might contain var arg parameters are shadowed
2392     // in their paired GPR.  So we only need to save the GPR to their home
2393     // slots.
2394     // TODO: __vectorcall will change this.
2395     return None;
2396   }
2397
2398   const Function *Fn = MF.getFunction();
2399   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2400   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2401          "SSE register cannot be used when SSE is disabled!");
2402   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2403       !Subtarget->hasSSE1())
2404     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2405     // registers.
2406     return None;
2407
2408   static const MCPhysReg XMMArgRegs64Bit[] = {
2409     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2410     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2411   };
2412   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2413 }
2414
2415 SDValue
2416 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2417                                         CallingConv::ID CallConv,
2418                                         bool isVarArg,
2419                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2420                                         SDLoc dl,
2421                                         SelectionDAG &DAG,
2422                                         SmallVectorImpl<SDValue> &InVals)
2423                                           const {
2424   MachineFunction &MF = DAG.getMachineFunction();
2425   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2426
2427   const Function* Fn = MF.getFunction();
2428   if (Fn->hasExternalLinkage() &&
2429       Subtarget->isTargetCygMing() &&
2430       Fn->getName() == "main")
2431     FuncInfo->setForceFramePointer(true);
2432
2433   MachineFrameInfo *MFI = MF.getFrameInfo();
2434   bool Is64Bit = Subtarget->is64Bit();
2435   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2436
2437   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2438          "Var args not supported with calling convention fastcc, ghc or hipe");
2439
2440   // Assign locations to all of the incoming arguments.
2441   SmallVector<CCValAssign, 16> ArgLocs;
2442   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2443
2444   // Allocate shadow area for Win64
2445   if (IsWin64)
2446     CCInfo.AllocateStack(32, 8);
2447
2448   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2449
2450   unsigned LastVal = ~0U;
2451   SDValue ArgValue;
2452   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2453     CCValAssign &VA = ArgLocs[i];
2454     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2455     // places.
2456     assert(VA.getValNo() != LastVal &&
2457            "Don't support value assigned to multiple locs yet");
2458     (void)LastVal;
2459     LastVal = VA.getValNo();
2460
2461     if (VA.isRegLoc()) {
2462       EVT RegVT = VA.getLocVT();
2463       const TargetRegisterClass *RC;
2464       if (RegVT == MVT::i32)
2465         RC = &X86::GR32RegClass;
2466       else if (Is64Bit && RegVT == MVT::i64)
2467         RC = &X86::GR64RegClass;
2468       else if (RegVT == MVT::f32)
2469         RC = &X86::FR32RegClass;
2470       else if (RegVT == MVT::f64)
2471         RC = &X86::FR64RegClass;
2472       else if (RegVT.is512BitVector())
2473         RC = &X86::VR512RegClass;
2474       else if (RegVT.is256BitVector())
2475         RC = &X86::VR256RegClass;
2476       else if (RegVT.is128BitVector())
2477         RC = &X86::VR128RegClass;
2478       else if (RegVT == MVT::x86mmx)
2479         RC = &X86::VR64RegClass;
2480       else if (RegVT == MVT::i1)
2481         RC = &X86::VK1RegClass;
2482       else if (RegVT == MVT::v8i1)
2483         RC = &X86::VK8RegClass;
2484       else if (RegVT == MVT::v16i1)
2485         RC = &X86::VK16RegClass;
2486       else if (RegVT == MVT::v32i1)
2487         RC = &X86::VK32RegClass;
2488       else if (RegVT == MVT::v64i1)
2489         RC = &X86::VK64RegClass;
2490       else
2491         llvm_unreachable("Unknown argument type!");
2492
2493       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2494       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2495
2496       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2497       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2498       // right size.
2499       if (VA.getLocInfo() == CCValAssign::SExt)
2500         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2501                                DAG.getValueType(VA.getValVT()));
2502       else if (VA.getLocInfo() == CCValAssign::ZExt)
2503         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2504                                DAG.getValueType(VA.getValVT()));
2505       else if (VA.getLocInfo() == CCValAssign::BCvt)
2506         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2507
2508       if (VA.isExtInLoc()) {
2509         // Handle MMX values passed in XMM regs.
2510         if (RegVT.isVector())
2511           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2512         else
2513           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2514       }
2515     } else {
2516       assert(VA.isMemLoc());
2517       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2518     }
2519
2520     // If value is passed via pointer - do a load.
2521     if (VA.getLocInfo() == CCValAssign::Indirect)
2522       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2523                              MachinePointerInfo(), false, false, false, 0);
2524
2525     InVals.push_back(ArgValue);
2526   }
2527
2528   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2529     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2530       // The x86-64 ABIs require that for returning structs by value we copy
2531       // the sret argument into %rax/%eax (depending on ABI) for the return.
2532       // Win32 requires us to put the sret argument to %eax as well.
2533       // Save the argument into a virtual register so that we can access it
2534       // from the return points.
2535       if (Ins[i].Flags.isSRet()) {
2536         unsigned Reg = FuncInfo->getSRetReturnReg();
2537         if (!Reg) {
2538           MVT PtrTy = getPointerTy();
2539           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2540           FuncInfo->setSRetReturnReg(Reg);
2541         }
2542         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2543         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2544         break;
2545       }
2546     }
2547   }
2548
2549   unsigned StackSize = CCInfo.getNextStackOffset();
2550   // Align stack specially for tail calls.
2551   if (FuncIsMadeTailCallSafe(CallConv,
2552                              MF.getTarget().Options.GuaranteedTailCallOpt))
2553     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2554
2555   // If the function takes variable number of arguments, make a frame index for
2556   // the start of the first vararg value... for expansion of llvm.va_start. We
2557   // can skip this if there are no va_start calls.
2558   if (MFI->hasVAStart() &&
2559       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2560                    CallConv != CallingConv::X86_ThisCall))) {
2561     FuncInfo->setVarArgsFrameIndex(
2562         MFI->CreateFixedObject(1, StackSize, true));
2563   }
2564
2565   // Figure out if XMM registers are in use.
2566   assert(!(MF.getTarget().Options.UseSoftFloat &&
2567            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2568          "SSE register cannot be used when SSE is disabled!");
2569
2570   // 64-bit calling conventions support varargs and register parameters, so we
2571   // have to do extra work to spill them in the prologue.
2572   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2573     // Find the first unallocated argument registers.
2574     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2575     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2576     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2577     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2578     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2579            "SSE register cannot be used when SSE is disabled!");
2580
2581     // Gather all the live in physical registers.
2582     SmallVector<SDValue, 6> LiveGPRs;
2583     SmallVector<SDValue, 8> LiveXMMRegs;
2584     SDValue ALVal;
2585     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2586       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2587       LiveGPRs.push_back(
2588           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2589     }
2590     if (!ArgXMMs.empty()) {
2591       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2592       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2593       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2594         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2595         LiveXMMRegs.push_back(
2596             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2597       }
2598     }
2599
2600     if (IsWin64) {
2601       const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2602       // Get to the caller-allocated home save location.  Add 8 to account
2603       // for the return address.
2604       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2605       FuncInfo->setRegSaveFrameIndex(
2606           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2607       // Fixup to set vararg frame on shadow area (4 x i64).
2608       if (NumIntRegs < 4)
2609         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2610     } else {
2611       // For X86-64, if there are vararg parameters that are passed via
2612       // registers, then we must store them to their spots on the stack so
2613       // they may be loaded by deferencing the result of va_next.
2614       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2615       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2616       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2617           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2618     }
2619
2620     // Store the integer parameter registers.
2621     SmallVector<SDValue, 8> MemOps;
2622     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2623                                       getPointerTy());
2624     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2625     for (SDValue Val : LiveGPRs) {
2626       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2627                                 DAG.getIntPtrConstant(Offset));
2628       SDValue Store =
2629         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2630                      MachinePointerInfo::getFixedStack(
2631                        FuncInfo->getRegSaveFrameIndex(), Offset),
2632                      false, false, 0);
2633       MemOps.push_back(Store);
2634       Offset += 8;
2635     }
2636
2637     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2638       // Now store the XMM (fp + vector) parameter registers.
2639       SmallVector<SDValue, 12> SaveXMMOps;
2640       SaveXMMOps.push_back(Chain);
2641       SaveXMMOps.push_back(ALVal);
2642       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2643                              FuncInfo->getRegSaveFrameIndex()));
2644       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2645                              FuncInfo->getVarArgsFPOffset()));
2646       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2647                         LiveXMMRegs.end());
2648       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2649                                    MVT::Other, SaveXMMOps));
2650     }
2651
2652     if (!MemOps.empty())
2653       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2654   }
2655
2656   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2657     // Find the largest legal vector type.
2658     MVT VecVT = MVT::Other;
2659     // FIXME: Only some x86_32 calling conventions support AVX512.
2660     if (Subtarget->hasAVX512() &&
2661         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2662                      CallConv == CallingConv::Intel_OCL_BI)))
2663       VecVT = MVT::v16f32;
2664     else if (Subtarget->hasAVX())
2665       VecVT = MVT::v8f32;
2666     else if (Subtarget->hasSSE2())
2667       VecVT = MVT::v4f32;
2668
2669     // We forward some GPRs and some vector types.
2670     SmallVector<MVT, 2> RegParmTypes;
2671     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2672     RegParmTypes.push_back(IntVT);
2673     if (VecVT != MVT::Other)
2674       RegParmTypes.push_back(VecVT);
2675
2676     // Compute the set of forwarded registers. The rest are scratch.
2677     SmallVectorImpl<ForwardedRegister> &Forwards =
2678         FuncInfo->getForwardedMustTailRegParms();
2679     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2680
2681     // Conservatively forward AL on x86_64, since it might be used for varargs.
2682     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2683       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2684       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2685     }
2686
2687     // Copy all forwards from physical to virtual registers.
2688     for (ForwardedRegister &F : Forwards) {
2689       // FIXME: Can we use a less constrained schedule?
2690       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2691       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2692       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2693     }
2694   }
2695
2696   // Some CCs need callee pop.
2697   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2698                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2699     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2700   } else {
2701     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2702     // If this is an sret function, the return should pop the hidden pointer.
2703     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2704         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2705         argsAreStructReturn(Ins) == StackStructReturn)
2706       FuncInfo->setBytesToPopOnReturn(4);
2707   }
2708
2709   if (!Is64Bit) {
2710     // RegSaveFrameIndex is X86-64 only.
2711     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2712     if (CallConv == CallingConv::X86_FastCall ||
2713         CallConv == CallingConv::X86_ThisCall)
2714       // fastcc functions can't have varargs.
2715       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2716   }
2717
2718   FuncInfo->setArgumentStackSize(StackSize);
2719
2720   return Chain;
2721 }
2722
2723 SDValue
2724 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2725                                     SDValue StackPtr, SDValue Arg,
2726                                     SDLoc dl, SelectionDAG &DAG,
2727                                     const CCValAssign &VA,
2728                                     ISD::ArgFlagsTy Flags) const {
2729   unsigned LocMemOffset = VA.getLocMemOffset();
2730   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2731   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2732   if (Flags.isByVal())
2733     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2734
2735   return DAG.getStore(Chain, dl, Arg, PtrOff,
2736                       MachinePointerInfo::getStack(LocMemOffset),
2737                       false, false, 0);
2738 }
2739
2740 /// Emit a load of return address if tail call
2741 /// optimization is performed and it is required.
2742 SDValue
2743 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2744                                            SDValue &OutRetAddr, SDValue Chain,
2745                                            bool IsTailCall, bool Is64Bit,
2746                                            int FPDiff, SDLoc dl) const {
2747   // Adjust the Return address stack slot.
2748   EVT VT = getPointerTy();
2749   OutRetAddr = getReturnAddressFrameIndex(DAG);
2750
2751   // Load the "old" Return address.
2752   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2753                            false, false, false, 0);
2754   return SDValue(OutRetAddr.getNode(), 1);
2755 }
2756
2757 /// Emit a store of the return address if tail call
2758 /// optimization is performed and it is required (FPDiff!=0).
2759 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2760                                         SDValue Chain, SDValue RetAddrFrIdx,
2761                                         EVT PtrVT, unsigned SlotSize,
2762                                         int FPDiff, SDLoc dl) {
2763   // Store the return address to the appropriate stack slot.
2764   if (!FPDiff) return Chain;
2765   // Calculate the new stack slot for the return address.
2766   int NewReturnAddrFI =
2767     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2768                                          false);
2769   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2770   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2771                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2772                        false, false, 0);
2773   return Chain;
2774 }
2775
2776 SDValue
2777 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2778                              SmallVectorImpl<SDValue> &InVals) const {
2779   SelectionDAG &DAG                     = CLI.DAG;
2780   SDLoc &dl                             = CLI.DL;
2781   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2782   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2783   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2784   SDValue Chain                         = CLI.Chain;
2785   SDValue Callee                        = CLI.Callee;
2786   CallingConv::ID CallConv              = CLI.CallConv;
2787   bool &isTailCall                      = CLI.IsTailCall;
2788   bool isVarArg                         = CLI.IsVarArg;
2789
2790   MachineFunction &MF = DAG.getMachineFunction();
2791   bool Is64Bit        = Subtarget->is64Bit();
2792   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2793   StructReturnType SR = callIsStructReturn(Outs);
2794   bool IsSibcall      = false;
2795   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2796
2797   if (MF.getTarget().Options.DisableTailCalls)
2798     isTailCall = false;
2799
2800   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2801   if (IsMustTail) {
2802     // Force this to be a tail call.  The verifier rules are enough to ensure
2803     // that we can lower this successfully without moving the return address
2804     // around.
2805     isTailCall = true;
2806   } else if (isTailCall) {
2807     // Check if it's really possible to do a tail call.
2808     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2809                     isVarArg, SR != NotStructReturn,
2810                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2811                     Outs, OutVals, Ins, DAG);
2812
2813     // Sibcalls are automatically detected tailcalls which do not require
2814     // ABI changes.
2815     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2816       IsSibcall = true;
2817
2818     if (isTailCall)
2819       ++NumTailCalls;
2820   }
2821
2822   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2823          "Var args not supported with calling convention fastcc, ghc or hipe");
2824
2825   // Analyze operands of the call, assigning locations to each operand.
2826   SmallVector<CCValAssign, 16> ArgLocs;
2827   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2828
2829   // Allocate shadow area for Win64
2830   if (IsWin64)
2831     CCInfo.AllocateStack(32, 8);
2832
2833   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2834
2835   // Get a count of how many bytes are to be pushed on the stack.
2836   unsigned NumBytes = CCInfo.getNextStackOffset();
2837   if (IsSibcall)
2838     // This is a sibcall. The memory operands are available in caller's
2839     // own caller's stack.
2840     NumBytes = 0;
2841   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2842            IsTailCallConvention(CallConv))
2843     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2844
2845   int FPDiff = 0;
2846   if (isTailCall && !IsSibcall && !IsMustTail) {
2847     // Lower arguments at fp - stackoffset + fpdiff.
2848     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2849
2850     FPDiff = NumBytesCallerPushed - NumBytes;
2851
2852     // Set the delta of movement of the returnaddr stackslot.
2853     // But only set if delta is greater than previous delta.
2854     if (FPDiff < X86Info->getTCReturnAddrDelta())
2855       X86Info->setTCReturnAddrDelta(FPDiff);
2856   }
2857
2858   unsigned NumBytesToPush = NumBytes;
2859   unsigned NumBytesToPop = NumBytes;
2860
2861   // If we have an inalloca argument, all stack space has already been allocated
2862   // for us and be right at the top of the stack.  We don't support multiple
2863   // arguments passed in memory when using inalloca.
2864   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2865     NumBytesToPush = 0;
2866     if (!ArgLocs.back().isMemLoc())
2867       report_fatal_error("cannot use inalloca attribute on a register "
2868                          "parameter");
2869     if (ArgLocs.back().getLocMemOffset() != 0)
2870       report_fatal_error("any parameter with the inalloca attribute must be "
2871                          "the only memory argument");
2872   }
2873
2874   if (!IsSibcall)
2875     Chain = DAG.getCALLSEQ_START(
2876         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2877
2878   SDValue RetAddrFrIdx;
2879   // Load return address for tail calls.
2880   if (isTailCall && FPDiff)
2881     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2882                                     Is64Bit, FPDiff, dl);
2883
2884   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2885   SmallVector<SDValue, 8> MemOpChains;
2886   SDValue StackPtr;
2887
2888   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2889   // of tail call optimization arguments are handle later.
2890   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2891   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2892     // Skip inalloca arguments, they have already been written.
2893     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2894     if (Flags.isInAlloca())
2895       continue;
2896
2897     CCValAssign &VA = ArgLocs[i];
2898     EVT RegVT = VA.getLocVT();
2899     SDValue Arg = OutVals[i];
2900     bool isByVal = Flags.isByVal();
2901
2902     // Promote the value if needed.
2903     switch (VA.getLocInfo()) {
2904     default: llvm_unreachable("Unknown loc info!");
2905     case CCValAssign::Full: break;
2906     case CCValAssign::SExt:
2907       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2908       break;
2909     case CCValAssign::ZExt:
2910       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2911       break;
2912     case CCValAssign::AExt:
2913       if (RegVT.is128BitVector()) {
2914         // Special case: passing MMX values in XMM registers.
2915         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2916         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2917         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2918       } else
2919         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2920       break;
2921     case CCValAssign::BCvt:
2922       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2923       break;
2924     case CCValAssign::Indirect: {
2925       // Store the argument.
2926       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2927       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2928       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2929                            MachinePointerInfo::getFixedStack(FI),
2930                            false, false, 0);
2931       Arg = SpillSlot;
2932       break;
2933     }
2934     }
2935
2936     if (VA.isRegLoc()) {
2937       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2938       if (isVarArg && IsWin64) {
2939         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2940         // shadow reg if callee is a varargs function.
2941         unsigned ShadowReg = 0;
2942         switch (VA.getLocReg()) {
2943         case X86::XMM0: ShadowReg = X86::RCX; break;
2944         case X86::XMM1: ShadowReg = X86::RDX; break;
2945         case X86::XMM2: ShadowReg = X86::R8; break;
2946         case X86::XMM3: ShadowReg = X86::R9; break;
2947         }
2948         if (ShadowReg)
2949           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2950       }
2951     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2952       assert(VA.isMemLoc());
2953       if (!StackPtr.getNode())
2954         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2955                                       getPointerTy());
2956       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2957                                              dl, DAG, VA, Flags));
2958     }
2959   }
2960
2961   if (!MemOpChains.empty())
2962     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2963
2964   if (Subtarget->isPICStyleGOT()) {
2965     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2966     // GOT pointer.
2967     if (!isTailCall) {
2968       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2969                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2970     } else {
2971       // If we are tail calling and generating PIC/GOT style code load the
2972       // address of the callee into ECX. The value in ecx is used as target of
2973       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2974       // for tail calls on PIC/GOT architectures. Normally we would just put the
2975       // address of GOT into ebx and then call target@PLT. But for tail calls
2976       // ebx would be restored (since ebx is callee saved) before jumping to the
2977       // target@PLT.
2978
2979       // Note: The actual moving to ECX is done further down.
2980       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2981       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2982           !G->getGlobal()->hasProtectedVisibility())
2983         Callee = LowerGlobalAddress(Callee, DAG);
2984       else if (isa<ExternalSymbolSDNode>(Callee))
2985         Callee = LowerExternalSymbol(Callee, DAG);
2986     }
2987   }
2988
2989   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2990     // From AMD64 ABI document:
2991     // For calls that may call functions that use varargs or stdargs
2992     // (prototype-less calls or calls to functions containing ellipsis (...) in
2993     // the declaration) %al is used as hidden argument to specify the number
2994     // of SSE registers used. The contents of %al do not need to match exactly
2995     // the number of registers, but must be an ubound on the number of SSE
2996     // registers used and is in the range 0 - 8 inclusive.
2997
2998     // Count the number of XMM registers allocated.
2999     static const MCPhysReg XMMArgRegs[] = {
3000       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3001       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3002     };
3003     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3004     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3005            && "SSE registers cannot be used when SSE is disabled");
3006
3007     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3008                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
3009   }
3010
3011   if (isVarArg && IsMustTail) {
3012     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3013     for (const auto &F : Forwards) {
3014       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3015       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3016     }
3017   }
3018
3019   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3020   // don't need this because the eligibility check rejects calls that require
3021   // shuffling arguments passed in memory.
3022   if (!IsSibcall && isTailCall) {
3023     // Force all the incoming stack arguments to be loaded from the stack
3024     // before any new outgoing arguments are stored to the stack, because the
3025     // outgoing stack slots may alias the incoming argument stack slots, and
3026     // the alias isn't otherwise explicit. This is slightly more conservative
3027     // than necessary, because it means that each store effectively depends
3028     // on every argument instead of just those arguments it would clobber.
3029     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3030
3031     SmallVector<SDValue, 8> MemOpChains2;
3032     SDValue FIN;
3033     int FI = 0;
3034     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3035       CCValAssign &VA = ArgLocs[i];
3036       if (VA.isRegLoc())
3037         continue;
3038       assert(VA.isMemLoc());
3039       SDValue Arg = OutVals[i];
3040       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3041       // Skip inalloca arguments.  They don't require any work.
3042       if (Flags.isInAlloca())
3043         continue;
3044       // Create frame index.
3045       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3046       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3047       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3048       FIN = DAG.getFrameIndex(FI, getPointerTy());
3049
3050       if (Flags.isByVal()) {
3051         // Copy relative to framepointer.
3052         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3053         if (!StackPtr.getNode())
3054           StackPtr = DAG.getCopyFromReg(Chain, dl,
3055                                         RegInfo->getStackRegister(),
3056                                         getPointerTy());
3057         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3058
3059         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3060                                                          ArgChain,
3061                                                          Flags, DAG, dl));
3062       } else {
3063         // Store relative to framepointer.
3064         MemOpChains2.push_back(
3065           DAG.getStore(ArgChain, dl, Arg, FIN,
3066                        MachinePointerInfo::getFixedStack(FI),
3067                        false, false, 0));
3068       }
3069     }
3070
3071     if (!MemOpChains2.empty())
3072       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3073
3074     // Store the return address to the appropriate stack slot.
3075     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3076                                      getPointerTy(), RegInfo->getSlotSize(),
3077                                      FPDiff, dl);
3078   }
3079
3080   // Build a sequence of copy-to-reg nodes chained together with token chain
3081   // and flag operands which copy the outgoing args into registers.
3082   SDValue InFlag;
3083   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3084     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3085                              RegsToPass[i].second, InFlag);
3086     InFlag = Chain.getValue(1);
3087   }
3088
3089   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3090     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3091     // In the 64-bit large code model, we have to make all calls
3092     // through a register, since the call instruction's 32-bit
3093     // pc-relative offset may not be large enough to hold the whole
3094     // address.
3095   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3096     // If the callee is a GlobalAddress node (quite common, every direct call
3097     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3098     // it.
3099     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3100
3101     // We should use extra load for direct calls to dllimported functions in
3102     // non-JIT mode.
3103     const GlobalValue *GV = G->getGlobal();
3104     if (!GV->hasDLLImportStorageClass()) {
3105       unsigned char OpFlags = 0;
3106       bool ExtraLoad = false;
3107       unsigned WrapperKind = ISD::DELETED_NODE;
3108
3109       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3110       // external symbols most go through the PLT in PIC mode.  If the symbol
3111       // has hidden or protected visibility, or if it is static or local, then
3112       // we don't need to use the PLT - we can directly call it.
3113       if (Subtarget->isTargetELF() &&
3114           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3115           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3116         OpFlags = X86II::MO_PLT;
3117       } else if (Subtarget->isPICStyleStubAny() &&
3118                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3119                  (!Subtarget->getTargetTriple().isMacOSX() ||
3120                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3121         // PC-relative references to external symbols should go through $stub,
3122         // unless we're building with the leopard linker or later, which
3123         // automatically synthesizes these stubs.
3124         OpFlags = X86II::MO_DARWIN_STUB;
3125       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3126                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3127         // If the function is marked as non-lazy, generate an indirect call
3128         // which loads from the GOT directly. This avoids runtime overhead
3129         // at the cost of eager binding (and one extra byte of encoding).
3130         OpFlags = X86II::MO_GOTPCREL;
3131         WrapperKind = X86ISD::WrapperRIP;
3132         ExtraLoad = true;
3133       }
3134
3135       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3136                                           G->getOffset(), OpFlags);
3137
3138       // Add a wrapper if needed.
3139       if (WrapperKind != ISD::DELETED_NODE)
3140         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3141       // Add extra indirection if needed.
3142       if (ExtraLoad)
3143         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3144                              MachinePointerInfo::getGOT(),
3145                              false, false, false, 0);
3146     }
3147   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3148     unsigned char OpFlags = 0;
3149
3150     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3151     // external symbols should go through the PLT.
3152     if (Subtarget->isTargetELF() &&
3153         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3154       OpFlags = X86II::MO_PLT;
3155     } else if (Subtarget->isPICStyleStubAny() &&
3156                (!Subtarget->getTargetTriple().isMacOSX() ||
3157                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3158       // PC-relative references to external symbols should go through $stub,
3159       // unless we're building with the leopard linker or later, which
3160       // automatically synthesizes these stubs.
3161       OpFlags = X86II::MO_DARWIN_STUB;
3162     }
3163
3164     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3165                                          OpFlags);
3166   } else if (Subtarget->isTarget64BitILP32() &&
3167              Callee->getValueType(0) == MVT::i32) {
3168     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3169     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3170   }
3171
3172   // Returns a chain & a flag for retval copy to use.
3173   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3174   SmallVector<SDValue, 8> Ops;
3175
3176   if (!IsSibcall && isTailCall) {
3177     Chain = DAG.getCALLSEQ_END(Chain,
3178                                DAG.getIntPtrConstant(NumBytesToPop, true),
3179                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3180     InFlag = Chain.getValue(1);
3181   }
3182
3183   Ops.push_back(Chain);
3184   Ops.push_back(Callee);
3185
3186   if (isTailCall)
3187     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3188
3189   // Add argument registers to the end of the list so that they are known live
3190   // into the call.
3191   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3192     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3193                                   RegsToPass[i].second.getValueType()));
3194
3195   // Add a register mask operand representing the call-preserved registers.
3196   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3197   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3198   assert(Mask && "Missing call preserved mask for calling convention");
3199   Ops.push_back(DAG.getRegisterMask(Mask));
3200
3201   if (InFlag.getNode())
3202     Ops.push_back(InFlag);
3203
3204   if (isTailCall) {
3205     // We used to do:
3206     //// If this is the first return lowered for this function, add the regs
3207     //// to the liveout set for the function.
3208     // This isn't right, although it's probably harmless on x86; liveouts
3209     // should be computed from returns not tail calls.  Consider a void
3210     // function making a tail call to a function returning int.
3211     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3212   }
3213
3214   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3215   InFlag = Chain.getValue(1);
3216
3217   // Create the CALLSEQ_END node.
3218   unsigned NumBytesForCalleeToPop;
3219   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3220                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3221     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3222   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3223            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3224            SR == StackStructReturn)
3225     // If this is a call to a struct-return function, the callee
3226     // pops the hidden struct pointer, so we have to push it back.
3227     // This is common for Darwin/X86, Linux & Mingw32 targets.
3228     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3229     NumBytesForCalleeToPop = 4;
3230   else
3231     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3232
3233   // Returns a flag for retval copy to use.
3234   if (!IsSibcall) {
3235     Chain = DAG.getCALLSEQ_END(Chain,
3236                                DAG.getIntPtrConstant(NumBytesToPop, true),
3237                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3238                                                      true),
3239                                InFlag, dl);
3240     InFlag = Chain.getValue(1);
3241   }
3242
3243   // Handle result values, copying them out of physregs into vregs that we
3244   // return.
3245   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3246                          Ins, dl, DAG, InVals);
3247 }
3248
3249 //===----------------------------------------------------------------------===//
3250 //                Fast Calling Convention (tail call) implementation
3251 //===----------------------------------------------------------------------===//
3252
3253 //  Like std call, callee cleans arguments, convention except that ECX is
3254 //  reserved for storing the tail called function address. Only 2 registers are
3255 //  free for argument passing (inreg). Tail call optimization is performed
3256 //  provided:
3257 //                * tailcallopt is enabled
3258 //                * caller/callee are fastcc
3259 //  On X86_64 architecture with GOT-style position independent code only local
3260 //  (within module) calls are supported at the moment.
3261 //  To keep the stack aligned according to platform abi the function
3262 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3263 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3264 //  If a tail called function callee has more arguments than the caller the
3265 //  caller needs to make sure that there is room to move the RETADDR to. This is
3266 //  achieved by reserving an area the size of the argument delta right after the
3267 //  original RETADDR, but before the saved framepointer or the spilled registers
3268 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3269 //  stack layout:
3270 //    arg1
3271 //    arg2
3272 //    RETADDR
3273 //    [ new RETADDR
3274 //      move area ]
3275 //    (possible EBP)
3276 //    ESI
3277 //    EDI
3278 //    local1 ..
3279
3280 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3281 /// for a 16 byte align requirement.
3282 unsigned
3283 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3284                                                SelectionDAG& DAG) const {
3285   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3286   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3287   unsigned StackAlignment = TFI.getStackAlignment();
3288   uint64_t AlignMask = StackAlignment - 1;
3289   int64_t Offset = StackSize;
3290   unsigned SlotSize = RegInfo->getSlotSize();
3291   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3292     // Number smaller than 12 so just add the difference.
3293     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3294   } else {
3295     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3296     Offset = ((~AlignMask) & Offset) + StackAlignment +
3297       (StackAlignment-SlotSize);
3298   }
3299   return Offset;
3300 }
3301
3302 /// MatchingStackOffset - Return true if the given stack call argument is
3303 /// already available in the same position (relatively) of the caller's
3304 /// incoming argument stack.
3305 static
3306 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3307                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3308                          const X86InstrInfo *TII) {
3309   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3310   int FI = INT_MAX;
3311   if (Arg.getOpcode() == ISD::CopyFromReg) {
3312     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3313     if (!TargetRegisterInfo::isVirtualRegister(VR))
3314       return false;
3315     MachineInstr *Def = MRI->getVRegDef(VR);
3316     if (!Def)
3317       return false;
3318     if (!Flags.isByVal()) {
3319       if (!TII->isLoadFromStackSlot(Def, FI))
3320         return false;
3321     } else {
3322       unsigned Opcode = Def->getOpcode();
3323       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3324            Opcode == X86::LEA64_32r) &&
3325           Def->getOperand(1).isFI()) {
3326         FI = Def->getOperand(1).getIndex();
3327         Bytes = Flags.getByValSize();
3328       } else
3329         return false;
3330     }
3331   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3332     if (Flags.isByVal())
3333       // ByVal argument is passed in as a pointer but it's now being
3334       // dereferenced. e.g.
3335       // define @foo(%struct.X* %A) {
3336       //   tail call @bar(%struct.X* byval %A)
3337       // }
3338       return false;
3339     SDValue Ptr = Ld->getBasePtr();
3340     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3341     if (!FINode)
3342       return false;
3343     FI = FINode->getIndex();
3344   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3345     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3346     FI = FINode->getIndex();
3347     Bytes = Flags.getByValSize();
3348   } else
3349     return false;
3350
3351   assert(FI != INT_MAX);
3352   if (!MFI->isFixedObjectIndex(FI))
3353     return false;
3354   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3355 }
3356
3357 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3358 /// for tail call optimization. Targets which want to do tail call
3359 /// optimization should implement this function.
3360 bool
3361 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3362                                                      CallingConv::ID CalleeCC,
3363                                                      bool isVarArg,
3364                                                      bool isCalleeStructRet,
3365                                                      bool isCallerStructRet,
3366                                                      Type *RetTy,
3367                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3368                                     const SmallVectorImpl<SDValue> &OutVals,
3369                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3370                                                      SelectionDAG &DAG) const {
3371   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3372     return false;
3373
3374   // If -tailcallopt is specified, make fastcc functions tail-callable.
3375   const MachineFunction &MF = DAG.getMachineFunction();
3376   const Function *CallerF = MF.getFunction();
3377
3378   // If the function return type is x86_fp80 and the callee return type is not,
3379   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3380   // perform a tailcall optimization here.
3381   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3382     return false;
3383
3384   CallingConv::ID CallerCC = CallerF->getCallingConv();
3385   bool CCMatch = CallerCC == CalleeCC;
3386   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3387   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3388
3389   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3390     if (IsTailCallConvention(CalleeCC) && CCMatch)
3391       return true;
3392     return false;
3393   }
3394
3395   // Look for obvious safe cases to perform tail call optimization that do not
3396   // require ABI changes. This is what gcc calls sibcall.
3397
3398   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3399   // emit a special epilogue.
3400   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3401   if (RegInfo->needsStackRealignment(MF))
3402     return false;
3403
3404   // Also avoid sibcall optimization if either caller or callee uses struct
3405   // return semantics.
3406   if (isCalleeStructRet || isCallerStructRet)
3407     return false;
3408
3409   // An stdcall/thiscall caller is expected to clean up its arguments; the
3410   // callee isn't going to do that.
3411   // FIXME: this is more restrictive than needed. We could produce a tailcall
3412   // when the stack adjustment matches. For example, with a thiscall that takes
3413   // only one argument.
3414   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3415                    CallerCC == CallingConv::X86_ThisCall))
3416     return false;
3417
3418   // Do not sibcall optimize vararg calls unless all arguments are passed via
3419   // registers.
3420   if (isVarArg && !Outs.empty()) {
3421
3422     // Optimizing for varargs on Win64 is unlikely to be safe without
3423     // additional testing.
3424     if (IsCalleeWin64 || IsCallerWin64)
3425       return false;
3426
3427     SmallVector<CCValAssign, 16> ArgLocs;
3428     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3429                    *DAG.getContext());
3430
3431     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3432     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3433       if (!ArgLocs[i].isRegLoc())
3434         return false;
3435   }
3436
3437   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3438   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3439   // this into a sibcall.
3440   bool Unused = false;
3441   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3442     if (!Ins[i].Used) {
3443       Unused = true;
3444       break;
3445     }
3446   }
3447   if (Unused) {
3448     SmallVector<CCValAssign, 16> RVLocs;
3449     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3450                    *DAG.getContext());
3451     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3452     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3453       CCValAssign &VA = RVLocs[i];
3454       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3455         return false;
3456     }
3457   }
3458
3459   // If the calling conventions do not match, then we'd better make sure the
3460   // results are returned in the same way as what the caller expects.
3461   if (!CCMatch) {
3462     SmallVector<CCValAssign, 16> RVLocs1;
3463     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3464                     *DAG.getContext());
3465     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3466
3467     SmallVector<CCValAssign, 16> RVLocs2;
3468     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3469                     *DAG.getContext());
3470     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3471
3472     if (RVLocs1.size() != RVLocs2.size())
3473       return false;
3474     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3475       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3476         return false;
3477       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3478         return false;
3479       if (RVLocs1[i].isRegLoc()) {
3480         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3481           return false;
3482       } else {
3483         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3484           return false;
3485       }
3486     }
3487   }
3488
3489   // If the callee takes no arguments then go on to check the results of the
3490   // call.
3491   if (!Outs.empty()) {
3492     // Check if stack adjustment is needed. For now, do not do this if any
3493     // argument is passed on the stack.
3494     SmallVector<CCValAssign, 16> ArgLocs;
3495     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3496                    *DAG.getContext());
3497
3498     // Allocate shadow area for Win64
3499     if (IsCalleeWin64)
3500       CCInfo.AllocateStack(32, 8);
3501
3502     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3503     if (CCInfo.getNextStackOffset()) {
3504       MachineFunction &MF = DAG.getMachineFunction();
3505       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3506         return false;
3507
3508       // Check if the arguments are already laid out in the right way as
3509       // the caller's fixed stack objects.
3510       MachineFrameInfo *MFI = MF.getFrameInfo();
3511       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3512       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3513       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3514         CCValAssign &VA = ArgLocs[i];
3515         SDValue Arg = OutVals[i];
3516         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3517         if (VA.getLocInfo() == CCValAssign::Indirect)
3518           return false;
3519         if (!VA.isRegLoc()) {
3520           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3521                                    MFI, MRI, TII))
3522             return false;
3523         }
3524       }
3525     }
3526
3527     // If the tailcall address may be in a register, then make sure it's
3528     // possible to register allocate for it. In 32-bit, the call address can
3529     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3530     // callee-saved registers are restored. These happen to be the same
3531     // registers used to pass 'inreg' arguments so watch out for those.
3532     if (!Subtarget->is64Bit() &&
3533         ((!isa<GlobalAddressSDNode>(Callee) &&
3534           !isa<ExternalSymbolSDNode>(Callee)) ||
3535          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3536       unsigned NumInRegs = 0;
3537       // In PIC we need an extra register to formulate the address computation
3538       // for the callee.
3539       unsigned MaxInRegs =
3540         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3541
3542       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3543         CCValAssign &VA = ArgLocs[i];
3544         if (!VA.isRegLoc())
3545           continue;
3546         unsigned Reg = VA.getLocReg();
3547         switch (Reg) {
3548         default: break;
3549         case X86::EAX: case X86::EDX: case X86::ECX:
3550           if (++NumInRegs == MaxInRegs)
3551             return false;
3552           break;
3553         }
3554       }
3555     }
3556   }
3557
3558   return true;
3559 }
3560
3561 FastISel *
3562 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3563                                   const TargetLibraryInfo *libInfo) const {
3564   return X86::createFastISel(funcInfo, libInfo);
3565 }
3566
3567 //===----------------------------------------------------------------------===//
3568 //                           Other Lowering Hooks
3569 //===----------------------------------------------------------------------===//
3570
3571 static bool MayFoldLoad(SDValue Op) {
3572   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3573 }
3574
3575 static bool MayFoldIntoStore(SDValue Op) {
3576   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3577 }
3578
3579 static bool isTargetShuffle(unsigned Opcode) {
3580   switch(Opcode) {
3581   default: return false;
3582   case X86ISD::BLENDI:
3583   case X86ISD::PSHUFB:
3584   case X86ISD::PSHUFD:
3585   case X86ISD::PSHUFHW:
3586   case X86ISD::PSHUFLW:
3587   case X86ISD::SHUFP:
3588   case X86ISD::PALIGNR:
3589   case X86ISD::MOVLHPS:
3590   case X86ISD::MOVLHPD:
3591   case X86ISD::MOVHLPS:
3592   case X86ISD::MOVLPS:
3593   case X86ISD::MOVLPD:
3594   case X86ISD::MOVSHDUP:
3595   case X86ISD::MOVSLDUP:
3596   case X86ISD::MOVDDUP:
3597   case X86ISD::MOVSS:
3598   case X86ISD::MOVSD:
3599   case X86ISD::UNPCKL:
3600   case X86ISD::UNPCKH:
3601   case X86ISD::VPERMILPI:
3602   case X86ISD::VPERM2X128:
3603   case X86ISD::VPERMI:
3604     return true;
3605   }
3606 }
3607
3608 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3609                                     SDValue V1, unsigned TargetMask,
3610                                     SelectionDAG &DAG) {
3611   switch(Opc) {
3612   default: llvm_unreachable("Unknown x86 shuffle node");
3613   case X86ISD::PSHUFD:
3614   case X86ISD::PSHUFHW:
3615   case X86ISD::PSHUFLW:
3616   case X86ISD::VPERMILPI:
3617   case X86ISD::VPERMI:
3618     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3619   }
3620 }
3621
3622 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3623                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3624   switch(Opc) {
3625   default: llvm_unreachable("Unknown x86 shuffle node");
3626   case X86ISD::MOVLHPS:
3627   case X86ISD::MOVLHPD:
3628   case X86ISD::MOVHLPS:
3629   case X86ISD::MOVLPS:
3630   case X86ISD::MOVLPD:
3631   case X86ISD::MOVSS:
3632   case X86ISD::MOVSD:
3633   case X86ISD::UNPCKL:
3634   case X86ISD::UNPCKH:
3635     return DAG.getNode(Opc, dl, VT, V1, V2);
3636   }
3637 }
3638
3639 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3640   MachineFunction &MF = DAG.getMachineFunction();
3641   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3642   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3643   int ReturnAddrIndex = FuncInfo->getRAIndex();
3644
3645   if (ReturnAddrIndex == 0) {
3646     // Set up a frame object for the return address.
3647     unsigned SlotSize = RegInfo->getSlotSize();
3648     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3649                                                            -(int64_t)SlotSize,
3650                                                            false);
3651     FuncInfo->setRAIndex(ReturnAddrIndex);
3652   }
3653
3654   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3655 }
3656
3657 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3658                                        bool hasSymbolicDisplacement) {
3659   // Offset should fit into 32 bit immediate field.
3660   if (!isInt<32>(Offset))
3661     return false;
3662
3663   // If we don't have a symbolic displacement - we don't have any extra
3664   // restrictions.
3665   if (!hasSymbolicDisplacement)
3666     return true;
3667
3668   // FIXME: Some tweaks might be needed for medium code model.
3669   if (M != CodeModel::Small && M != CodeModel::Kernel)
3670     return false;
3671
3672   // For small code model we assume that latest object is 16MB before end of 31
3673   // bits boundary. We may also accept pretty large negative constants knowing
3674   // that all objects are in the positive half of address space.
3675   if (M == CodeModel::Small && Offset < 16*1024*1024)
3676     return true;
3677
3678   // For kernel code model we know that all object resist in the negative half
3679   // of 32bits address space. We may not accept negative offsets, since they may
3680   // be just off and we may accept pretty large positive ones.
3681   if (M == CodeModel::Kernel && Offset >= 0)
3682     return true;
3683
3684   return false;
3685 }
3686
3687 /// isCalleePop - Determines whether the callee is required to pop its
3688 /// own arguments. Callee pop is necessary to support tail calls.
3689 bool X86::isCalleePop(CallingConv::ID CallingConv,
3690                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3691   switch (CallingConv) {
3692   default:
3693     return false;
3694   case CallingConv::X86_StdCall:
3695   case CallingConv::X86_FastCall:
3696   case CallingConv::X86_ThisCall:
3697     return !is64Bit;
3698   case CallingConv::Fast:
3699   case CallingConv::GHC:
3700   case CallingConv::HiPE:
3701     if (IsVarArg)
3702       return false;
3703     return TailCallOpt;
3704   }
3705 }
3706
3707 /// \brief Return true if the condition is an unsigned comparison operation.
3708 static bool isX86CCUnsigned(unsigned X86CC) {
3709   switch (X86CC) {
3710   default: llvm_unreachable("Invalid integer condition!");
3711   case X86::COND_E:     return true;
3712   case X86::COND_G:     return false;
3713   case X86::COND_GE:    return false;
3714   case X86::COND_L:     return false;
3715   case X86::COND_LE:    return false;
3716   case X86::COND_NE:    return true;
3717   case X86::COND_B:     return true;
3718   case X86::COND_A:     return true;
3719   case X86::COND_BE:    return true;
3720   case X86::COND_AE:    return true;
3721   }
3722   llvm_unreachable("covered switch fell through?!");
3723 }
3724
3725 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3726 /// specific condition code, returning the condition code and the LHS/RHS of the
3727 /// comparison to make.
3728 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3729                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3730   if (!isFP) {
3731     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3732       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3733         // X > -1   -> X == 0, jump !sign.
3734         RHS = DAG.getConstant(0, RHS.getValueType());
3735         return X86::COND_NS;
3736       }
3737       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3738         // X < 0   -> X == 0, jump on sign.
3739         return X86::COND_S;
3740       }
3741       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3742         // X < 1   -> X <= 0
3743         RHS = DAG.getConstant(0, RHS.getValueType());
3744         return X86::COND_LE;
3745       }
3746     }
3747
3748     switch (SetCCOpcode) {
3749     default: llvm_unreachable("Invalid integer condition!");
3750     case ISD::SETEQ:  return X86::COND_E;
3751     case ISD::SETGT:  return X86::COND_G;
3752     case ISD::SETGE:  return X86::COND_GE;
3753     case ISD::SETLT:  return X86::COND_L;
3754     case ISD::SETLE:  return X86::COND_LE;
3755     case ISD::SETNE:  return X86::COND_NE;
3756     case ISD::SETULT: return X86::COND_B;
3757     case ISD::SETUGT: return X86::COND_A;
3758     case ISD::SETULE: return X86::COND_BE;
3759     case ISD::SETUGE: return X86::COND_AE;
3760     }
3761   }
3762
3763   // First determine if it is required or is profitable to flip the operands.
3764
3765   // If LHS is a foldable load, but RHS is not, flip the condition.
3766   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3767       !ISD::isNON_EXTLoad(RHS.getNode())) {
3768     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3769     std::swap(LHS, RHS);
3770   }
3771
3772   switch (SetCCOpcode) {
3773   default: break;
3774   case ISD::SETOLT:
3775   case ISD::SETOLE:
3776   case ISD::SETUGT:
3777   case ISD::SETUGE:
3778     std::swap(LHS, RHS);
3779     break;
3780   }
3781
3782   // On a floating point condition, the flags are set as follows:
3783   // ZF  PF  CF   op
3784   //  0 | 0 | 0 | X > Y
3785   //  0 | 0 | 1 | X < Y
3786   //  1 | 0 | 0 | X == Y
3787   //  1 | 1 | 1 | unordered
3788   switch (SetCCOpcode) {
3789   default: llvm_unreachable("Condcode should be pre-legalized away");
3790   case ISD::SETUEQ:
3791   case ISD::SETEQ:   return X86::COND_E;
3792   case ISD::SETOLT:              // flipped
3793   case ISD::SETOGT:
3794   case ISD::SETGT:   return X86::COND_A;
3795   case ISD::SETOLE:              // flipped
3796   case ISD::SETOGE:
3797   case ISD::SETGE:   return X86::COND_AE;
3798   case ISD::SETUGT:              // flipped
3799   case ISD::SETULT:
3800   case ISD::SETLT:   return X86::COND_B;
3801   case ISD::SETUGE:              // flipped
3802   case ISD::SETULE:
3803   case ISD::SETLE:   return X86::COND_BE;
3804   case ISD::SETONE:
3805   case ISD::SETNE:   return X86::COND_NE;
3806   case ISD::SETUO:   return X86::COND_P;
3807   case ISD::SETO:    return X86::COND_NP;
3808   case ISD::SETOEQ:
3809   case ISD::SETUNE:  return X86::COND_INVALID;
3810   }
3811 }
3812
3813 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3814 /// code. Current x86 isa includes the following FP cmov instructions:
3815 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3816 static bool hasFPCMov(unsigned X86CC) {
3817   switch (X86CC) {
3818   default:
3819     return false;
3820   case X86::COND_B:
3821   case X86::COND_BE:
3822   case X86::COND_E:
3823   case X86::COND_P:
3824   case X86::COND_A:
3825   case X86::COND_AE:
3826   case X86::COND_NE:
3827   case X86::COND_NP:
3828     return true;
3829   }
3830 }
3831
3832 /// isFPImmLegal - Returns true if the target can instruction select the
3833 /// specified FP immediate natively. If false, the legalizer will
3834 /// materialize the FP immediate as a load from a constant pool.
3835 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3836   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3837     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3838       return true;
3839   }
3840   return false;
3841 }
3842
3843 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3844                                               ISD::LoadExtType ExtTy,
3845                                               EVT NewVT) const {
3846   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3847   // relocation target a movq or addq instruction: don't let the load shrink.
3848   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3849   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3850     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3851       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3852   return true;
3853 }
3854
3855 /// \brief Returns true if it is beneficial to convert a load of a constant
3856 /// to just the constant itself.
3857 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3858                                                           Type *Ty) const {
3859   assert(Ty->isIntegerTy());
3860
3861   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3862   if (BitSize == 0 || BitSize > 64)
3863     return false;
3864   return true;
3865 }
3866
3867 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3868                                                 unsigned Index) const {
3869   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3870     return false;
3871
3872   return (Index == 0 || Index == ResVT.getVectorNumElements());
3873 }
3874
3875 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3876   // Speculate cttz only if we can directly use TZCNT.
3877   return Subtarget->hasBMI();
3878 }
3879
3880 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3881   // Speculate ctlz only if we can directly use LZCNT.
3882   return Subtarget->hasLZCNT();
3883 }
3884
3885 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3886 /// the specified range (L, H].
3887 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3888   return (Val < 0) || (Val >= Low && Val < Hi);
3889 }
3890
3891 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3892 /// specified value.
3893 static bool isUndefOrEqual(int Val, int CmpVal) {
3894   return (Val < 0 || Val == CmpVal);
3895 }
3896
3897 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3898 /// from position Pos and ending in Pos+Size, falls within the specified
3899 /// sequential range (Low, Low+Size]. or is undef.
3900 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3901                                        unsigned Pos, unsigned Size, int Low) {
3902   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3903     if (!isUndefOrEqual(Mask[i], Low))
3904       return false;
3905   return true;
3906 }
3907
3908 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3909 /// the two vector operands have swapped position.
3910 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3911                                      unsigned NumElems) {
3912   for (unsigned i = 0; i != NumElems; ++i) {
3913     int idx = Mask[i];
3914     if (idx < 0)
3915       continue;
3916     else if (idx < (int)NumElems)
3917       Mask[i] = idx + NumElems;
3918     else
3919       Mask[i] = idx - NumElems;
3920   }
3921 }
3922
3923 /// isVEXTRACTIndex - Return true if the specified
3924 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3925 /// suitable for instruction that extract 128 or 256 bit vectors
3926 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3927   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3928   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3929     return false;
3930
3931   // The index should be aligned on a vecWidth-bit boundary.
3932   uint64_t Index =
3933     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3934
3935   MVT VT = N->getSimpleValueType(0);
3936   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3937   bool Result = (Index * ElSize) % vecWidth == 0;
3938
3939   return Result;
3940 }
3941
3942 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3943 /// operand specifies a subvector insert that is suitable for input to
3944 /// insertion of 128 or 256-bit subvectors
3945 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3946   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3947   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3948     return false;
3949   // The index should be aligned on a vecWidth-bit boundary.
3950   uint64_t Index =
3951     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3952
3953   MVT VT = N->getSimpleValueType(0);
3954   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3955   bool Result = (Index * ElSize) % vecWidth == 0;
3956
3957   return Result;
3958 }
3959
3960 bool X86::isVINSERT128Index(SDNode *N) {
3961   return isVINSERTIndex(N, 128);
3962 }
3963
3964 bool X86::isVINSERT256Index(SDNode *N) {
3965   return isVINSERTIndex(N, 256);
3966 }
3967
3968 bool X86::isVEXTRACT128Index(SDNode *N) {
3969   return isVEXTRACTIndex(N, 128);
3970 }
3971
3972 bool X86::isVEXTRACT256Index(SDNode *N) {
3973   return isVEXTRACTIndex(N, 256);
3974 }
3975
3976 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3977   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3978   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3979     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3980
3981   uint64_t Index =
3982     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3983
3984   MVT VecVT = N->getOperand(0).getSimpleValueType();
3985   MVT ElVT = VecVT.getVectorElementType();
3986
3987   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3988   return Index / NumElemsPerChunk;
3989 }
3990
3991 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3992   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3993   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3994     llvm_unreachable("Illegal insert subvector for VINSERT");
3995
3996   uint64_t Index =
3997     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3998
3999   MVT VecVT = N->getSimpleValueType(0);
4000   MVT ElVT = VecVT.getVectorElementType();
4001
4002   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4003   return Index / NumElemsPerChunk;
4004 }
4005
4006 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4007 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4008 /// and VINSERTI128 instructions.
4009 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4010   return getExtractVEXTRACTImmediate(N, 128);
4011 }
4012
4013 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4014 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4015 /// and VINSERTI64x4 instructions.
4016 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4017   return getExtractVEXTRACTImmediate(N, 256);
4018 }
4019
4020 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4021 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4022 /// and VINSERTI128 instructions.
4023 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4024   return getInsertVINSERTImmediate(N, 128);
4025 }
4026
4027 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4028 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4029 /// and VINSERTI64x4 instructions.
4030 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4031   return getInsertVINSERTImmediate(N, 256);
4032 }
4033
4034 /// isZero - Returns true if Elt is a constant integer zero
4035 static bool isZero(SDValue V) {
4036   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4037   return C && C->isNullValue();
4038 }
4039
4040 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4041 /// constant +0.0.
4042 bool X86::isZeroNode(SDValue Elt) {
4043   if (isZero(Elt))
4044     return true;
4045   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4046     return CFP->getValueAPF().isPosZero();
4047   return false;
4048 }
4049
4050 /// getZeroVector - Returns a vector of specified type with all zero elements.
4051 ///
4052 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4053                              SelectionDAG &DAG, SDLoc dl) {
4054   assert(VT.isVector() && "Expected a vector type");
4055
4056   // Always build SSE zero vectors as <4 x i32> bitcasted
4057   // to their dest type. This ensures they get CSE'd.
4058   SDValue Vec;
4059   if (VT.is128BitVector()) {  // SSE
4060     if (Subtarget->hasSSE2()) {  // SSE2
4061       SDValue Cst = DAG.getConstant(0, MVT::i32);
4062       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4063     } else { // SSE1
4064       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4065       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4066     }
4067   } else if (VT.is256BitVector()) { // AVX
4068     if (Subtarget->hasInt256()) { // AVX2
4069       SDValue Cst = DAG.getConstant(0, MVT::i32);
4070       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4071       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4072     } else {
4073       // 256-bit logic and arithmetic instructions in AVX are all
4074       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4075       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4076       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4077       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4078     }
4079   } else if (VT.is512BitVector()) { // AVX-512
4080       SDValue Cst = DAG.getConstant(0, MVT::i32);
4081       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4082                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4083       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4084   } else if (VT.getScalarType() == MVT::i1) {
4085     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4086     SDValue Cst = DAG.getConstant(0, MVT::i1);
4087     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4088     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4089   } else
4090     llvm_unreachable("Unexpected vector type");
4091
4092   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4093 }
4094
4095 /// getOnesVector - Returns a vector of specified type with all bits set.
4096 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4097 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4098 /// Then bitcast to their original type, ensuring they get CSE'd.
4099 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4100                              SDLoc dl) {
4101   assert(VT.isVector() && "Expected a vector type");
4102
4103   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4104   SDValue Vec;
4105   if (VT.is256BitVector()) {
4106     if (HasInt256) { // AVX2
4107       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4108       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4109     } else { // AVX
4110       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4111       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4112     }
4113   } else if (VT.is128BitVector()) {
4114     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4115   } else
4116     llvm_unreachable("Unexpected vector type");
4117
4118   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4119 }
4120
4121 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4122 /// operation of specified width.
4123 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4124                        SDValue V2) {
4125   unsigned NumElems = VT.getVectorNumElements();
4126   SmallVector<int, 8> Mask;
4127   Mask.push_back(NumElems);
4128   for (unsigned i = 1; i != NumElems; ++i)
4129     Mask.push_back(i);
4130   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4131 }
4132
4133 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4134 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4135                           SDValue V2) {
4136   unsigned NumElems = VT.getVectorNumElements();
4137   SmallVector<int, 8> Mask;
4138   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4139     Mask.push_back(i);
4140     Mask.push_back(i + NumElems);
4141   }
4142   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4143 }
4144
4145 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4146 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4147                           SDValue V2) {
4148   unsigned NumElems = VT.getVectorNumElements();
4149   SmallVector<int, 8> Mask;
4150   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4151     Mask.push_back(i + Half);
4152     Mask.push_back(i + NumElems + Half);
4153   }
4154   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4155 }
4156
4157 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4158 /// vector of zero or undef vector.  This produces a shuffle where the low
4159 /// element of V2 is swizzled into the zero/undef vector, landing at element
4160 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4161 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4162                                            bool IsZero,
4163                                            const X86Subtarget *Subtarget,
4164                                            SelectionDAG &DAG) {
4165   MVT VT = V2.getSimpleValueType();
4166   SDValue V1 = IsZero
4167     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4168   unsigned NumElems = VT.getVectorNumElements();
4169   SmallVector<int, 16> MaskVec;
4170   for (unsigned i = 0; i != NumElems; ++i)
4171     // If this is the insertion idx, put the low elt of V2 here.
4172     MaskVec.push_back(i == Idx ? NumElems : i);
4173   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4174 }
4175
4176 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4177 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4178 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4179 /// shuffles which use a single input multiple times, and in those cases it will
4180 /// adjust the mask to only have indices within that single input.
4181 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4182                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4183   unsigned NumElems = VT.getVectorNumElements();
4184   SDValue ImmN;
4185
4186   IsUnary = false;
4187   bool IsFakeUnary = false;
4188   switch(N->getOpcode()) {
4189   case X86ISD::BLENDI:
4190     ImmN = N->getOperand(N->getNumOperands()-1);
4191     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4192     break;
4193   case X86ISD::SHUFP:
4194     ImmN = N->getOperand(N->getNumOperands()-1);
4195     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4196     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4197     break;
4198   case X86ISD::UNPCKH:
4199     DecodeUNPCKHMask(VT, Mask);
4200     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4201     break;
4202   case X86ISD::UNPCKL:
4203     DecodeUNPCKLMask(VT, Mask);
4204     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4205     break;
4206   case X86ISD::MOVHLPS:
4207     DecodeMOVHLPSMask(NumElems, Mask);
4208     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4209     break;
4210   case X86ISD::MOVLHPS:
4211     DecodeMOVLHPSMask(NumElems, Mask);
4212     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4213     break;
4214   case X86ISD::PALIGNR:
4215     ImmN = N->getOperand(N->getNumOperands()-1);
4216     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4217     break;
4218   case X86ISD::PSHUFD:
4219   case X86ISD::VPERMILPI:
4220     ImmN = N->getOperand(N->getNumOperands()-1);
4221     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4222     IsUnary = true;
4223     break;
4224   case X86ISD::PSHUFHW:
4225     ImmN = N->getOperand(N->getNumOperands()-1);
4226     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4227     IsUnary = true;
4228     break;
4229   case X86ISD::PSHUFLW:
4230     ImmN = N->getOperand(N->getNumOperands()-1);
4231     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4232     IsUnary = true;
4233     break;
4234   case X86ISD::PSHUFB: {
4235     IsUnary = true;
4236     SDValue MaskNode = N->getOperand(1);
4237     while (MaskNode->getOpcode() == ISD::BITCAST)
4238       MaskNode = MaskNode->getOperand(0);
4239
4240     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4241       // If we have a build-vector, then things are easy.
4242       EVT VT = MaskNode.getValueType();
4243       assert(VT.isVector() &&
4244              "Can't produce a non-vector with a build_vector!");
4245       if (!VT.isInteger())
4246         return false;
4247
4248       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4249
4250       SmallVector<uint64_t, 32> RawMask;
4251       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4252         SDValue Op = MaskNode->getOperand(i);
4253         if (Op->getOpcode() == ISD::UNDEF) {
4254           RawMask.push_back((uint64_t)SM_SentinelUndef);
4255           continue;
4256         }
4257         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4258         if (!CN)
4259           return false;
4260         APInt MaskElement = CN->getAPIntValue();
4261
4262         // We now have to decode the element which could be any integer size and
4263         // extract each byte of it.
4264         for (int j = 0; j < NumBytesPerElement; ++j) {
4265           // Note that this is x86 and so always little endian: the low byte is
4266           // the first byte of the mask.
4267           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4268           MaskElement = MaskElement.lshr(8);
4269         }
4270       }
4271       DecodePSHUFBMask(RawMask, Mask);
4272       break;
4273     }
4274
4275     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4276     if (!MaskLoad)
4277       return false;
4278
4279     SDValue Ptr = MaskLoad->getBasePtr();
4280     if (Ptr->getOpcode() == X86ISD::Wrapper)
4281       Ptr = Ptr->getOperand(0);
4282
4283     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4284     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4285       return false;
4286
4287     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4288       DecodePSHUFBMask(C, Mask);
4289       if (Mask.empty())
4290         return false;
4291       break;
4292     }
4293
4294     return false;
4295   }
4296   case X86ISD::VPERMI:
4297     ImmN = N->getOperand(N->getNumOperands()-1);
4298     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4299     IsUnary = true;
4300     break;
4301   case X86ISD::MOVSS:
4302   case X86ISD::MOVSD:
4303     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4304     break;
4305   case X86ISD::VPERM2X128:
4306     ImmN = N->getOperand(N->getNumOperands()-1);
4307     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4308     if (Mask.empty()) return false;
4309     break;
4310   case X86ISD::MOVSLDUP:
4311     DecodeMOVSLDUPMask(VT, Mask);
4312     IsUnary = true;
4313     break;
4314   case X86ISD::MOVSHDUP:
4315     DecodeMOVSHDUPMask(VT, Mask);
4316     IsUnary = true;
4317     break;
4318   case X86ISD::MOVDDUP:
4319     DecodeMOVDDUPMask(VT, Mask);
4320     IsUnary = true;
4321     break;
4322   case X86ISD::MOVLHPD:
4323   case X86ISD::MOVLPD:
4324   case X86ISD::MOVLPS:
4325     // Not yet implemented
4326     return false;
4327   default: llvm_unreachable("unknown target shuffle node");
4328   }
4329
4330   // If we have a fake unary shuffle, the shuffle mask is spread across two
4331   // inputs that are actually the same node. Re-map the mask to always point
4332   // into the first input.
4333   if (IsFakeUnary)
4334     for (int &M : Mask)
4335       if (M >= (int)Mask.size())
4336         M -= Mask.size();
4337
4338   return true;
4339 }
4340
4341 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4342 /// element of the result of the vector shuffle.
4343 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4344                                    unsigned Depth) {
4345   if (Depth == 6)
4346     return SDValue();  // Limit search depth.
4347
4348   SDValue V = SDValue(N, 0);
4349   EVT VT = V.getValueType();
4350   unsigned Opcode = V.getOpcode();
4351
4352   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4353   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4354     int Elt = SV->getMaskElt(Index);
4355
4356     if (Elt < 0)
4357       return DAG.getUNDEF(VT.getVectorElementType());
4358
4359     unsigned NumElems = VT.getVectorNumElements();
4360     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4361                                          : SV->getOperand(1);
4362     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4363   }
4364
4365   // Recurse into target specific vector shuffles to find scalars.
4366   if (isTargetShuffle(Opcode)) {
4367     MVT ShufVT = V.getSimpleValueType();
4368     unsigned NumElems = ShufVT.getVectorNumElements();
4369     SmallVector<int, 16> ShuffleMask;
4370     bool IsUnary;
4371
4372     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4373       return SDValue();
4374
4375     int Elt = ShuffleMask[Index];
4376     if (Elt < 0)
4377       return DAG.getUNDEF(ShufVT.getVectorElementType());
4378
4379     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4380                                          : N->getOperand(1);
4381     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4382                                Depth+1);
4383   }
4384
4385   // Actual nodes that may contain scalar elements
4386   if (Opcode == ISD::BITCAST) {
4387     V = V.getOperand(0);
4388     EVT SrcVT = V.getValueType();
4389     unsigned NumElems = VT.getVectorNumElements();
4390
4391     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4392       return SDValue();
4393   }
4394
4395   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4396     return (Index == 0) ? V.getOperand(0)
4397                         : DAG.getUNDEF(VT.getVectorElementType());
4398
4399   if (V.getOpcode() == ISD::BUILD_VECTOR)
4400     return V.getOperand(Index);
4401
4402   return SDValue();
4403 }
4404
4405 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4406 ///
4407 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4408                                        unsigned NumNonZero, unsigned NumZero,
4409                                        SelectionDAG &DAG,
4410                                        const X86Subtarget* Subtarget,
4411                                        const TargetLowering &TLI) {
4412   if (NumNonZero > 8)
4413     return SDValue();
4414
4415   SDLoc dl(Op);
4416   SDValue V;
4417   bool First = true;
4418   for (unsigned i = 0; i < 16; ++i) {
4419     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4420     if (ThisIsNonZero && First) {
4421       if (NumZero)
4422         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4423       else
4424         V = DAG.getUNDEF(MVT::v8i16);
4425       First = false;
4426     }
4427
4428     if ((i & 1) != 0) {
4429       SDValue ThisElt, LastElt;
4430       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4431       if (LastIsNonZero) {
4432         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4433                               MVT::i16, Op.getOperand(i-1));
4434       }
4435       if (ThisIsNonZero) {
4436         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4437         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4438                               ThisElt, DAG.getConstant(8, MVT::i8));
4439         if (LastIsNonZero)
4440           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4441       } else
4442         ThisElt = LastElt;
4443
4444       if (ThisElt.getNode())
4445         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4446                         DAG.getIntPtrConstant(i/2));
4447     }
4448   }
4449
4450   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4451 }
4452
4453 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4454 ///
4455 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4456                                      unsigned NumNonZero, unsigned NumZero,
4457                                      SelectionDAG &DAG,
4458                                      const X86Subtarget* Subtarget,
4459                                      const TargetLowering &TLI) {
4460   if (NumNonZero > 4)
4461     return SDValue();
4462
4463   SDLoc dl(Op);
4464   SDValue V;
4465   bool First = true;
4466   for (unsigned i = 0; i < 8; ++i) {
4467     bool isNonZero = (NonZeros & (1 << i)) != 0;
4468     if (isNonZero) {
4469       if (First) {
4470         if (NumZero)
4471           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4472         else
4473           V = DAG.getUNDEF(MVT::v8i16);
4474         First = false;
4475       }
4476       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4477                       MVT::v8i16, V, Op.getOperand(i),
4478                       DAG.getIntPtrConstant(i));
4479     }
4480   }
4481
4482   return V;
4483 }
4484
4485 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4486 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4487                                      const X86Subtarget *Subtarget,
4488                                      const TargetLowering &TLI) {
4489   // Find all zeroable elements.
4490   std::bitset<4> Zeroable;
4491   for (int i=0; i < 4; ++i) {
4492     SDValue Elt = Op->getOperand(i);
4493     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4494   }
4495   assert(Zeroable.size() - Zeroable.count() > 1 &&
4496          "We expect at least two non-zero elements!");
4497
4498   // We only know how to deal with build_vector nodes where elements are either
4499   // zeroable or extract_vector_elt with constant index.
4500   SDValue FirstNonZero;
4501   unsigned FirstNonZeroIdx;
4502   for (unsigned i=0; i < 4; ++i) {
4503     if (Zeroable[i])
4504       continue;
4505     SDValue Elt = Op->getOperand(i);
4506     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4507         !isa<ConstantSDNode>(Elt.getOperand(1)))
4508       return SDValue();
4509     // Make sure that this node is extracting from a 128-bit vector.
4510     MVT VT = Elt.getOperand(0).getSimpleValueType();
4511     if (!VT.is128BitVector())
4512       return SDValue();
4513     if (!FirstNonZero.getNode()) {
4514       FirstNonZero = Elt;
4515       FirstNonZeroIdx = i;
4516     }
4517   }
4518
4519   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4520   SDValue V1 = FirstNonZero.getOperand(0);
4521   MVT VT = V1.getSimpleValueType();
4522
4523   // See if this build_vector can be lowered as a blend with zero.
4524   SDValue Elt;
4525   unsigned EltMaskIdx, EltIdx;
4526   int Mask[4];
4527   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4528     if (Zeroable[EltIdx]) {
4529       // The zero vector will be on the right hand side.
4530       Mask[EltIdx] = EltIdx+4;
4531       continue;
4532     }
4533
4534     Elt = Op->getOperand(EltIdx);
4535     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4536     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4537     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4538       break;
4539     Mask[EltIdx] = EltIdx;
4540   }
4541
4542   if (EltIdx == 4) {
4543     // Let the shuffle legalizer deal with blend operations.
4544     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4545     if (V1.getSimpleValueType() != VT)
4546       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4547     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4548   }
4549
4550   // See if we can lower this build_vector to a INSERTPS.
4551   if (!Subtarget->hasSSE41())
4552     return SDValue();
4553
4554   SDValue V2 = Elt.getOperand(0);
4555   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4556     V1 = SDValue();
4557
4558   bool CanFold = true;
4559   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4560     if (Zeroable[i])
4561       continue;
4562
4563     SDValue Current = Op->getOperand(i);
4564     SDValue SrcVector = Current->getOperand(0);
4565     if (!V1.getNode())
4566       V1 = SrcVector;
4567     CanFold = SrcVector == V1 &&
4568       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4569   }
4570
4571   if (!CanFold)
4572     return SDValue();
4573
4574   assert(V1.getNode() && "Expected at least two non-zero elements!");
4575   if (V1.getSimpleValueType() != MVT::v4f32)
4576     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4577   if (V2.getSimpleValueType() != MVT::v4f32)
4578     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4579
4580   // Ok, we can emit an INSERTPS instruction.
4581   unsigned ZMask = Zeroable.to_ulong();
4582
4583   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4584   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4585   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4586                                DAG.getIntPtrConstant(InsertPSMask));
4587   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4588 }
4589
4590 /// Return a vector logical shift node.
4591 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4592                          unsigned NumBits, SelectionDAG &DAG,
4593                          const TargetLowering &TLI, SDLoc dl) {
4594   assert(VT.is128BitVector() && "Unknown type for VShift");
4595   MVT ShVT = MVT::v2i64;
4596   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4597   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4598   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4599   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4600   SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4601   return DAG.getNode(ISD::BITCAST, dl, VT,
4602                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4603 }
4604
4605 static SDValue
4606 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4607
4608   // Check if the scalar load can be widened into a vector load. And if
4609   // the address is "base + cst" see if the cst can be "absorbed" into
4610   // the shuffle mask.
4611   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4612     SDValue Ptr = LD->getBasePtr();
4613     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4614       return SDValue();
4615     EVT PVT = LD->getValueType(0);
4616     if (PVT != MVT::i32 && PVT != MVT::f32)
4617       return SDValue();
4618
4619     int FI = -1;
4620     int64_t Offset = 0;
4621     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4622       FI = FINode->getIndex();
4623       Offset = 0;
4624     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4625                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4626       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4627       Offset = Ptr.getConstantOperandVal(1);
4628       Ptr = Ptr.getOperand(0);
4629     } else {
4630       return SDValue();
4631     }
4632
4633     // FIXME: 256-bit vector instructions don't require a strict alignment,
4634     // improve this code to support it better.
4635     unsigned RequiredAlign = VT.getSizeInBits()/8;
4636     SDValue Chain = LD->getChain();
4637     // Make sure the stack object alignment is at least 16 or 32.
4638     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4639     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4640       if (MFI->isFixedObjectIndex(FI)) {
4641         // Can't change the alignment. FIXME: It's possible to compute
4642         // the exact stack offset and reference FI + adjust offset instead.
4643         // If someone *really* cares about this. That's the way to implement it.
4644         return SDValue();
4645       } else {
4646         MFI->setObjectAlignment(FI, RequiredAlign);
4647       }
4648     }
4649
4650     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4651     // Ptr + (Offset & ~15).
4652     if (Offset < 0)
4653       return SDValue();
4654     if ((Offset % RequiredAlign) & 3)
4655       return SDValue();
4656     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4657     if (StartOffset)
4658       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4659                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4660
4661     int EltNo = (Offset - StartOffset) >> 2;
4662     unsigned NumElems = VT.getVectorNumElements();
4663
4664     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4665     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4666                              LD->getPointerInfo().getWithOffset(StartOffset),
4667                              false, false, false, 0);
4668
4669     SmallVector<int, 8> Mask(NumElems, EltNo);
4670
4671     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4672   }
4673
4674   return SDValue();
4675 }
4676
4677 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4678 /// elements can be replaced by a single large load which has the same value as
4679 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4680 ///
4681 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4682 ///
4683 /// FIXME: we'd also like to handle the case where the last elements are zero
4684 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4685 /// There's even a handy isZeroNode for that purpose.
4686 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4687                                         SDLoc &DL, SelectionDAG &DAG,
4688                                         bool isAfterLegalize) {
4689   unsigned NumElems = Elts.size();
4690
4691   LoadSDNode *LDBase = nullptr;
4692   unsigned LastLoadedElt = -1U;
4693
4694   // For each element in the initializer, see if we've found a load or an undef.
4695   // If we don't find an initial load element, or later load elements are
4696   // non-consecutive, bail out.
4697   for (unsigned i = 0; i < NumElems; ++i) {
4698     SDValue Elt = Elts[i];
4699     // Look through a bitcast.
4700     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4701       Elt = Elt.getOperand(0);
4702     if (!Elt.getNode() ||
4703         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4704       return SDValue();
4705     if (!LDBase) {
4706       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4707         return SDValue();
4708       LDBase = cast<LoadSDNode>(Elt.getNode());
4709       LastLoadedElt = i;
4710       continue;
4711     }
4712     if (Elt.getOpcode() == ISD::UNDEF)
4713       continue;
4714
4715     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4716     EVT LdVT = Elt.getValueType();
4717     // Each loaded element must be the correct fractional portion of the
4718     // requested vector load.
4719     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4720       return SDValue();
4721     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4722       return SDValue();
4723     LastLoadedElt = i;
4724   }
4725
4726   // If we have found an entire vector of loads and undefs, then return a large
4727   // load of the entire vector width starting at the base pointer.  If we found
4728   // consecutive loads for the low half, generate a vzext_load node.
4729   if (LastLoadedElt == NumElems - 1) {
4730     assert(LDBase && "Did not find base load for merging consecutive loads");
4731     EVT EltVT = LDBase->getValueType(0);
4732     // Ensure that the input vector size for the merged loads matches the
4733     // cumulative size of the input elements.
4734     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4735       return SDValue();
4736
4737     if (isAfterLegalize &&
4738         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4739       return SDValue();
4740
4741     SDValue NewLd = SDValue();
4742
4743     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4744                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4745                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4746                         LDBase->getAlignment());
4747
4748     if (LDBase->hasAnyUseOfValue(1)) {
4749       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4750                                      SDValue(LDBase, 1),
4751                                      SDValue(NewLd.getNode(), 1));
4752       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4753       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4754                              SDValue(NewLd.getNode(), 1));
4755     }
4756
4757     return NewLd;
4758   }
4759
4760   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4761   //of a v4i32 / v4f32. It's probably worth generalizing.
4762   EVT EltVT = VT.getVectorElementType();
4763   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4764       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4765     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4766     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4767     SDValue ResNode =
4768         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4769                                 LDBase->getPointerInfo(),
4770                                 LDBase->getAlignment(),
4771                                 false/*isVolatile*/, true/*ReadMem*/,
4772                                 false/*WriteMem*/);
4773
4774     // Make sure the newly-created LOAD is in the same position as LDBase in
4775     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4776     // update uses of LDBase's output chain to use the TokenFactor.
4777     if (LDBase->hasAnyUseOfValue(1)) {
4778       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4779                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4780       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4781       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4782                              SDValue(ResNode.getNode(), 1));
4783     }
4784
4785     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4786   }
4787   return SDValue();
4788 }
4789
4790 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4791 /// to generate a splat value for the following cases:
4792 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4793 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4794 /// a scalar load, or a constant.
4795 /// The VBROADCAST node is returned when a pattern is found,
4796 /// or SDValue() otherwise.
4797 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4798                                     SelectionDAG &DAG) {
4799   // VBROADCAST requires AVX.
4800   // TODO: Splats could be generated for non-AVX CPUs using SSE
4801   // instructions, but there's less potential gain for only 128-bit vectors.
4802   if (!Subtarget->hasAVX())
4803     return SDValue();
4804
4805   MVT VT = Op.getSimpleValueType();
4806   SDLoc dl(Op);
4807
4808   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4809          "Unsupported vector type for broadcast.");
4810
4811   SDValue Ld;
4812   bool ConstSplatVal;
4813
4814   switch (Op.getOpcode()) {
4815     default:
4816       // Unknown pattern found.
4817       return SDValue();
4818
4819     case ISD::BUILD_VECTOR: {
4820       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4821       BitVector UndefElements;
4822       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4823
4824       // We need a splat of a single value to use broadcast, and it doesn't
4825       // make any sense if the value is only in one element of the vector.
4826       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4827         return SDValue();
4828
4829       Ld = Splat;
4830       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4831                        Ld.getOpcode() == ISD::ConstantFP);
4832
4833       // Make sure that all of the users of a non-constant load are from the
4834       // BUILD_VECTOR node.
4835       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4836         return SDValue();
4837       break;
4838     }
4839
4840     case ISD::VECTOR_SHUFFLE: {
4841       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4842
4843       // Shuffles must have a splat mask where the first element is
4844       // broadcasted.
4845       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4846         return SDValue();
4847
4848       SDValue Sc = Op.getOperand(0);
4849       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4850           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4851
4852         if (!Subtarget->hasInt256())
4853           return SDValue();
4854
4855         // Use the register form of the broadcast instruction available on AVX2.
4856         if (VT.getSizeInBits() >= 256)
4857           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4858         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4859       }
4860
4861       Ld = Sc.getOperand(0);
4862       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4863                        Ld.getOpcode() == ISD::ConstantFP);
4864
4865       // The scalar_to_vector node and the suspected
4866       // load node must have exactly one user.
4867       // Constants may have multiple users.
4868
4869       // AVX-512 has register version of the broadcast
4870       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4871         Ld.getValueType().getSizeInBits() >= 32;
4872       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4873           !hasRegVer))
4874         return SDValue();
4875       break;
4876     }
4877   }
4878
4879   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4880   bool IsGE256 = (VT.getSizeInBits() >= 256);
4881
4882   // When optimizing for size, generate up to 5 extra bytes for a broadcast
4883   // instruction to save 8 or more bytes of constant pool data.
4884   // TODO: If multiple splats are generated to load the same constant,
4885   // it may be detrimental to overall size. There needs to be a way to detect
4886   // that condition to know if this is truly a size win.
4887   const Function *F = DAG.getMachineFunction().getFunction();
4888   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4889
4890   // Handle broadcasting a single constant scalar from the constant pool
4891   // into a vector.
4892   // On Sandybridge (no AVX2), it is still better to load a constant vector
4893   // from the constant pool and not to broadcast it from a scalar.
4894   // But override that restriction when optimizing for size.
4895   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4896   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4897     EVT CVT = Ld.getValueType();
4898     assert(!CVT.isVector() && "Must not broadcast a vector type");
4899
4900     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4901     // For size optimization, also splat v2f64 and v2i64, and for size opt
4902     // with AVX2, also splat i8 and i16.
4903     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4904     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4905         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4906       const Constant *C = nullptr;
4907       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4908         C = CI->getConstantIntValue();
4909       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4910         C = CF->getConstantFPValue();
4911
4912       assert(C && "Invalid constant type");
4913
4914       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4915       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4916       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4917       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4918                        MachinePointerInfo::getConstantPool(),
4919                        false, false, false, Alignment);
4920
4921       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4922     }
4923   }
4924
4925   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4926
4927   // Handle AVX2 in-register broadcasts.
4928   if (!IsLoad && Subtarget->hasInt256() &&
4929       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4930     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4931
4932   // The scalar source must be a normal load.
4933   if (!IsLoad)
4934     return SDValue();
4935
4936   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4937       (Subtarget->hasVLX() && ScalarSize == 64))
4938     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4939
4940   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4941   // double since there is no vbroadcastsd xmm
4942   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4943     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4944       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4945   }
4946
4947   // Unsupported broadcast.
4948   return SDValue();
4949 }
4950
4951 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4952 /// underlying vector and index.
4953 ///
4954 /// Modifies \p ExtractedFromVec to the real vector and returns the real
4955 /// index.
4956 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
4957                                          SDValue ExtIdx) {
4958   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
4959   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
4960     return Idx;
4961
4962   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
4963   // lowered this:
4964   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
4965   // to:
4966   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
4967   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
4968   //                           undef)
4969   //                       Constant<0>)
4970   // In this case the vector is the extract_subvector expression and the index
4971   // is 2, as specified by the shuffle.
4972   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
4973   SDValue ShuffleVec = SVOp->getOperand(0);
4974   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
4975   assert(ShuffleVecVT.getVectorElementType() ==
4976          ExtractedFromVec.getSimpleValueType().getVectorElementType());
4977
4978   int ShuffleIdx = SVOp->getMaskElt(Idx);
4979   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
4980     ExtractedFromVec = ShuffleVec;
4981     return ShuffleIdx;
4982   }
4983   return Idx;
4984 }
4985
4986 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
4987   MVT VT = Op.getSimpleValueType();
4988
4989   // Skip if insert_vec_elt is not supported.
4990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4991   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
4992     return SDValue();
4993
4994   SDLoc DL(Op);
4995   unsigned NumElems = Op.getNumOperands();
4996
4997   SDValue VecIn1;
4998   SDValue VecIn2;
4999   SmallVector<unsigned, 4> InsertIndices;
5000   SmallVector<int, 8> Mask(NumElems, -1);
5001
5002   for (unsigned i = 0; i != NumElems; ++i) {
5003     unsigned Opc = Op.getOperand(i).getOpcode();
5004
5005     if (Opc == ISD::UNDEF)
5006       continue;
5007
5008     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5009       // Quit if more than 1 elements need inserting.
5010       if (InsertIndices.size() > 1)
5011         return SDValue();
5012
5013       InsertIndices.push_back(i);
5014       continue;
5015     }
5016
5017     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5018     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5019     // Quit if non-constant index.
5020     if (!isa<ConstantSDNode>(ExtIdx))
5021       return SDValue();
5022     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5023
5024     // Quit if extracted from vector of different type.
5025     if (ExtractedFromVec.getValueType() != VT)
5026       return SDValue();
5027
5028     if (!VecIn1.getNode())
5029       VecIn1 = ExtractedFromVec;
5030     else if (VecIn1 != ExtractedFromVec) {
5031       if (!VecIn2.getNode())
5032         VecIn2 = ExtractedFromVec;
5033       else if (VecIn2 != ExtractedFromVec)
5034         // Quit if more than 2 vectors to shuffle
5035         return SDValue();
5036     }
5037
5038     if (ExtractedFromVec == VecIn1)
5039       Mask[i] = Idx;
5040     else if (ExtractedFromVec == VecIn2)
5041       Mask[i] = Idx + NumElems;
5042   }
5043
5044   if (!VecIn1.getNode())
5045     return SDValue();
5046
5047   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5048   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5049   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5050     unsigned Idx = InsertIndices[i];
5051     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5052                      DAG.getIntPtrConstant(Idx));
5053   }
5054
5055   return NV;
5056 }
5057
5058 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5059 SDValue
5060 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5061
5062   MVT VT = Op.getSimpleValueType();
5063   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5064          "Unexpected type in LowerBUILD_VECTORvXi1!");
5065
5066   SDLoc dl(Op);
5067   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5068     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5069     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5070     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5071   }
5072
5073   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5074     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5075     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5076     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5077   }
5078
5079   bool AllContants = true;
5080   uint64_t Immediate = 0;
5081   int NonConstIdx = -1;
5082   bool IsSplat = true;
5083   unsigned NumNonConsts = 0;
5084   unsigned NumConsts = 0;
5085   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5086     SDValue In = Op.getOperand(idx);
5087     if (In.getOpcode() == ISD::UNDEF)
5088       continue;
5089     if (!isa<ConstantSDNode>(In)) {
5090       AllContants = false;
5091       NonConstIdx = idx;
5092       NumNonConsts++;
5093     } else {
5094       NumConsts++;
5095       if (cast<ConstantSDNode>(In)->getZExtValue())
5096       Immediate |= (1ULL << idx);
5097     }
5098     if (In != Op.getOperand(0))
5099       IsSplat = false;
5100   }
5101
5102   if (AllContants) {
5103     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5104       DAG.getConstant(Immediate, MVT::i16));
5105     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5106                        DAG.getIntPtrConstant(0));
5107   }
5108
5109   if (NumNonConsts == 1 && NonConstIdx != 0) {
5110     SDValue DstVec;
5111     if (NumConsts) {
5112       SDValue VecAsImm = DAG.getConstant(Immediate,
5113                                          MVT::getIntegerVT(VT.getSizeInBits()));
5114       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5115     }
5116     else
5117       DstVec = DAG.getUNDEF(VT);
5118     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5119                        Op.getOperand(NonConstIdx),
5120                        DAG.getIntPtrConstant(NonConstIdx));
5121   }
5122   if (!IsSplat && (NonConstIdx != 0))
5123     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5124   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5125   SDValue Select;
5126   if (IsSplat)
5127     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5128                           DAG.getConstant(-1, SelectVT),
5129                           DAG.getConstant(0, SelectVT));
5130   else
5131     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5132                          DAG.getConstant((Immediate | 1), SelectVT),
5133                          DAG.getConstant(Immediate, SelectVT));
5134   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5135 }
5136
5137 /// \brief Return true if \p N implements a horizontal binop and return the
5138 /// operands for the horizontal binop into V0 and V1.
5139 ///
5140 /// This is a helper function of PerformBUILD_VECTORCombine.
5141 /// This function checks that the build_vector \p N in input implements a
5142 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5143 /// operation to match.
5144 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5145 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5146 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5147 /// arithmetic sub.
5148 ///
5149 /// This function only analyzes elements of \p N whose indices are
5150 /// in range [BaseIdx, LastIdx).
5151 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5152                               SelectionDAG &DAG,
5153                               unsigned BaseIdx, unsigned LastIdx,
5154                               SDValue &V0, SDValue &V1) {
5155   EVT VT = N->getValueType(0);
5156
5157   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5158   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5159          "Invalid Vector in input!");
5160
5161   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5162   bool CanFold = true;
5163   unsigned ExpectedVExtractIdx = BaseIdx;
5164   unsigned NumElts = LastIdx - BaseIdx;
5165   V0 = DAG.getUNDEF(VT);
5166   V1 = DAG.getUNDEF(VT);
5167
5168   // Check if N implements a horizontal binop.
5169   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5170     SDValue Op = N->getOperand(i + BaseIdx);
5171
5172     // Skip UNDEFs.
5173     if (Op->getOpcode() == ISD::UNDEF) {
5174       // Update the expected vector extract index.
5175       if (i * 2 == NumElts)
5176         ExpectedVExtractIdx = BaseIdx;
5177       ExpectedVExtractIdx += 2;
5178       continue;
5179     }
5180
5181     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5182
5183     if (!CanFold)
5184       break;
5185
5186     SDValue Op0 = Op.getOperand(0);
5187     SDValue Op1 = Op.getOperand(1);
5188
5189     // Try to match the following pattern:
5190     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5191     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5192         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5193         Op0.getOperand(0) == Op1.getOperand(0) &&
5194         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5195         isa<ConstantSDNode>(Op1.getOperand(1)));
5196     if (!CanFold)
5197       break;
5198
5199     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5200     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5201
5202     if (i * 2 < NumElts) {
5203       if (V0.getOpcode() == ISD::UNDEF)
5204         V0 = Op0.getOperand(0);
5205     } else {
5206       if (V1.getOpcode() == ISD::UNDEF)
5207         V1 = Op0.getOperand(0);
5208       if (i * 2 == NumElts)
5209         ExpectedVExtractIdx = BaseIdx;
5210     }
5211
5212     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5213     if (I0 == ExpectedVExtractIdx)
5214       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5215     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5216       // Try to match the following dag sequence:
5217       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5218       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5219     } else
5220       CanFold = false;
5221
5222     ExpectedVExtractIdx += 2;
5223   }
5224
5225   return CanFold;
5226 }
5227
5228 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5229 /// a concat_vector.
5230 ///
5231 /// This is a helper function of PerformBUILD_VECTORCombine.
5232 /// This function expects two 256-bit vectors called V0 and V1.
5233 /// At first, each vector is split into two separate 128-bit vectors.
5234 /// Then, the resulting 128-bit vectors are used to implement two
5235 /// horizontal binary operations.
5236 ///
5237 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5238 ///
5239 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5240 /// the two new horizontal binop.
5241 /// When Mode is set, the first horizontal binop dag node would take as input
5242 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5243 /// horizontal binop dag node would take as input the lower 128-bit of V1
5244 /// and the upper 128-bit of V1.
5245 ///   Example:
5246 ///     HADD V0_LO, V0_HI
5247 ///     HADD V1_LO, V1_HI
5248 ///
5249 /// Otherwise, the first horizontal binop dag node takes as input the lower
5250 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5251 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5252 ///   Example:
5253 ///     HADD V0_LO, V1_LO
5254 ///     HADD V0_HI, V1_HI
5255 ///
5256 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5257 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5258 /// the upper 128-bits of the result.
5259 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5260                                      SDLoc DL, SelectionDAG &DAG,
5261                                      unsigned X86Opcode, bool Mode,
5262                                      bool isUndefLO, bool isUndefHI) {
5263   EVT VT = V0.getValueType();
5264   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5265          "Invalid nodes in input!");
5266
5267   unsigned NumElts = VT.getVectorNumElements();
5268   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5269   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5270   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5271   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5272   EVT NewVT = V0_LO.getValueType();
5273
5274   SDValue LO = DAG.getUNDEF(NewVT);
5275   SDValue HI = DAG.getUNDEF(NewVT);
5276
5277   if (Mode) {
5278     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5279     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5280       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5281     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5282       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5283   } else {
5284     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5285     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5286                        V1_LO->getOpcode() != ISD::UNDEF))
5287       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5288
5289     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5290                        V1_HI->getOpcode() != ISD::UNDEF))
5291       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5292   }
5293
5294   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5295 }
5296
5297 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5298 /// sequence of 'vadd + vsub + blendi'.
5299 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5300                            const X86Subtarget *Subtarget) {
5301   SDLoc DL(BV);
5302   EVT VT = BV->getValueType(0);
5303   unsigned NumElts = VT.getVectorNumElements();
5304   SDValue InVec0 = DAG.getUNDEF(VT);
5305   SDValue InVec1 = DAG.getUNDEF(VT);
5306
5307   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5308           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5309
5310   // Odd-numbered elements in the input build vector are obtained from
5311   // adding two integer/float elements.
5312   // Even-numbered elements in the input build vector are obtained from
5313   // subtracting two integer/float elements.
5314   unsigned ExpectedOpcode = ISD::FSUB;
5315   unsigned NextExpectedOpcode = ISD::FADD;
5316   bool AddFound = false;
5317   bool SubFound = false;
5318
5319   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5320     SDValue Op = BV->getOperand(i);
5321
5322     // Skip 'undef' values.
5323     unsigned Opcode = Op.getOpcode();
5324     if (Opcode == ISD::UNDEF) {
5325       std::swap(ExpectedOpcode, NextExpectedOpcode);
5326       continue;
5327     }
5328
5329     // Early exit if we found an unexpected opcode.
5330     if (Opcode != ExpectedOpcode)
5331       return SDValue();
5332
5333     SDValue Op0 = Op.getOperand(0);
5334     SDValue Op1 = Op.getOperand(1);
5335
5336     // Try to match the following pattern:
5337     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5338     // Early exit if we cannot match that sequence.
5339     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5340         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5341         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5342         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5343         Op0.getOperand(1) != Op1.getOperand(1))
5344       return SDValue();
5345
5346     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5347     if (I0 != i)
5348       return SDValue();
5349
5350     // We found a valid add/sub node. Update the information accordingly.
5351     if (i & 1)
5352       AddFound = true;
5353     else
5354       SubFound = true;
5355
5356     // Update InVec0 and InVec1.
5357     if (InVec0.getOpcode() == ISD::UNDEF)
5358       InVec0 = Op0.getOperand(0);
5359     if (InVec1.getOpcode() == ISD::UNDEF)
5360       InVec1 = Op1.getOperand(0);
5361
5362     // Make sure that operands in input to each add/sub node always
5363     // come from a same pair of vectors.
5364     if (InVec0 != Op0.getOperand(0)) {
5365       if (ExpectedOpcode == ISD::FSUB)
5366         return SDValue();
5367
5368       // FADD is commutable. Try to commute the operands
5369       // and then test again.
5370       std::swap(Op0, Op1);
5371       if (InVec0 != Op0.getOperand(0))
5372         return SDValue();
5373     }
5374
5375     if (InVec1 != Op1.getOperand(0))
5376       return SDValue();
5377
5378     // Update the pair of expected opcodes.
5379     std::swap(ExpectedOpcode, NextExpectedOpcode);
5380   }
5381
5382   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5383   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5384       InVec1.getOpcode() != ISD::UNDEF)
5385     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5386
5387   return SDValue();
5388 }
5389
5390 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5391                                           const X86Subtarget *Subtarget) {
5392   SDLoc DL(N);
5393   EVT VT = N->getValueType(0);
5394   unsigned NumElts = VT.getVectorNumElements();
5395   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5396   SDValue InVec0, InVec1;
5397
5398   // Try to match an ADDSUB.
5399   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5400       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5401     SDValue Value = matchAddSub(BV, DAG, Subtarget);
5402     if (Value.getNode())
5403       return Value;
5404   }
5405
5406   // Try to match horizontal ADD/SUB.
5407   unsigned NumUndefsLO = 0;
5408   unsigned NumUndefsHI = 0;
5409   unsigned Half = NumElts/2;
5410
5411   // Count the number of UNDEF operands in the build_vector in input.
5412   for (unsigned i = 0, e = Half; i != e; ++i)
5413     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5414       NumUndefsLO++;
5415
5416   for (unsigned i = Half, e = NumElts; i != e; ++i)
5417     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5418       NumUndefsHI++;
5419
5420   // Early exit if this is either a build_vector of all UNDEFs or all the
5421   // operands but one are UNDEF.
5422   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5423     return SDValue();
5424
5425   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5426     // Try to match an SSE3 float HADD/HSUB.
5427     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5428       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5429
5430     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5431       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5432   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5433     // Try to match an SSSE3 integer HADD/HSUB.
5434     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5435       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5436
5437     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5438       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5439   }
5440
5441   if (!Subtarget->hasAVX())
5442     return SDValue();
5443
5444   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5445     // Try to match an AVX horizontal add/sub of packed single/double
5446     // precision floating point values from 256-bit vectors.
5447     SDValue InVec2, InVec3;
5448     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5449         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5450         ((InVec0.getOpcode() == ISD::UNDEF ||
5451           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5452         ((InVec1.getOpcode() == ISD::UNDEF ||
5453           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5454       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5455
5456     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5457         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5458         ((InVec0.getOpcode() == ISD::UNDEF ||
5459           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5460         ((InVec1.getOpcode() == ISD::UNDEF ||
5461           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5462       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5463   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5464     // Try to match an AVX2 horizontal add/sub of signed integers.
5465     SDValue InVec2, InVec3;
5466     unsigned X86Opcode;
5467     bool CanFold = true;
5468
5469     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5470         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5471         ((InVec0.getOpcode() == ISD::UNDEF ||
5472           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5473         ((InVec1.getOpcode() == ISD::UNDEF ||
5474           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5475       X86Opcode = X86ISD::HADD;
5476     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5477         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5478         ((InVec0.getOpcode() == ISD::UNDEF ||
5479           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5480         ((InVec1.getOpcode() == ISD::UNDEF ||
5481           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5482       X86Opcode = X86ISD::HSUB;
5483     else
5484       CanFold = false;
5485
5486     if (CanFold) {
5487       // Fold this build_vector into a single horizontal add/sub.
5488       // Do this only if the target has AVX2.
5489       if (Subtarget->hasAVX2())
5490         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5491
5492       // Do not try to expand this build_vector into a pair of horizontal
5493       // add/sub if we can emit a pair of scalar add/sub.
5494       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5495         return SDValue();
5496
5497       // Convert this build_vector into a pair of horizontal binop followed by
5498       // a concat vector.
5499       bool isUndefLO = NumUndefsLO == Half;
5500       bool isUndefHI = NumUndefsHI == Half;
5501       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5502                                    isUndefLO, isUndefHI);
5503     }
5504   }
5505
5506   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5507        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5508     unsigned X86Opcode;
5509     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5510       X86Opcode = X86ISD::HADD;
5511     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5512       X86Opcode = X86ISD::HSUB;
5513     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5514       X86Opcode = X86ISD::FHADD;
5515     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5516       X86Opcode = X86ISD::FHSUB;
5517     else
5518       return SDValue();
5519
5520     // Don't try to expand this build_vector into a pair of horizontal add/sub
5521     // if we can simply emit a pair of scalar add/sub.
5522     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5523       return SDValue();
5524
5525     // Convert this build_vector into two horizontal add/sub followed by
5526     // a concat vector.
5527     bool isUndefLO = NumUndefsLO == Half;
5528     bool isUndefHI = NumUndefsHI == Half;
5529     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5530                                  isUndefLO, isUndefHI);
5531   }
5532
5533   return SDValue();
5534 }
5535
5536 SDValue
5537 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5538   SDLoc dl(Op);
5539
5540   MVT VT = Op.getSimpleValueType();
5541   MVT ExtVT = VT.getVectorElementType();
5542   unsigned NumElems = Op.getNumOperands();
5543
5544   // Generate vectors for predicate vectors.
5545   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5546     return LowerBUILD_VECTORvXi1(Op, DAG);
5547
5548   // Vectors containing all zeros can be matched by pxor and xorps later
5549   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5550     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5551     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5552     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5553       return Op;
5554
5555     return getZeroVector(VT, Subtarget, DAG, dl);
5556   }
5557
5558   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5559   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5560   // vpcmpeqd on 256-bit vectors.
5561   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5562     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5563       return Op;
5564
5565     if (!VT.is512BitVector())
5566       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5567   }
5568
5569   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5570   if (Broadcast.getNode())
5571     return Broadcast;
5572
5573   unsigned EVTBits = ExtVT.getSizeInBits();
5574
5575   unsigned NumZero  = 0;
5576   unsigned NumNonZero = 0;
5577   unsigned NonZeros = 0;
5578   bool IsAllConstants = true;
5579   SmallSet<SDValue, 8> Values;
5580   for (unsigned i = 0; i < NumElems; ++i) {
5581     SDValue Elt = Op.getOperand(i);
5582     if (Elt.getOpcode() == ISD::UNDEF)
5583       continue;
5584     Values.insert(Elt);
5585     if (Elt.getOpcode() != ISD::Constant &&
5586         Elt.getOpcode() != ISD::ConstantFP)
5587       IsAllConstants = false;
5588     if (X86::isZeroNode(Elt))
5589       NumZero++;
5590     else {
5591       NonZeros |= (1 << i);
5592       NumNonZero++;
5593     }
5594   }
5595
5596   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5597   if (NumNonZero == 0)
5598     return DAG.getUNDEF(VT);
5599
5600   // Special case for single non-zero, non-undef, element.
5601   if (NumNonZero == 1) {
5602     unsigned Idx = countTrailingZeros(NonZeros);
5603     SDValue Item = Op.getOperand(Idx);
5604
5605     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5606     // the value are obviously zero, truncate the value to i32 and do the
5607     // insertion that way.  Only do this if the value is non-constant or if the
5608     // value is a constant being inserted into element 0.  It is cheaper to do
5609     // a constant pool load than it is to do a movd + shuffle.
5610     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5611         (!IsAllConstants || Idx == 0)) {
5612       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5613         // Handle SSE only.
5614         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5615         EVT VecVT = MVT::v4i32;
5616
5617         // Truncate the value (which may itself be a constant) to i32, and
5618         // convert it to a vector with movd (S2V+shuffle to zero extend).
5619         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5620         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5621         return DAG.getNode(
5622             ISD::BITCAST, dl, VT,
5623             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5624       }
5625     }
5626
5627     // If we have a constant or non-constant insertion into the low element of
5628     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5629     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5630     // depending on what the source datatype is.
5631     if (Idx == 0) {
5632       if (NumZero == 0)
5633         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5634
5635       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5636           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5637         if (VT.is256BitVector() || VT.is512BitVector()) {
5638           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5639           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5640                              Item, DAG.getIntPtrConstant(0));
5641         }
5642         assert(VT.is128BitVector() && "Expected an SSE value type!");
5643         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5644         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5645         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5646       }
5647
5648       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5649         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5650         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5651         if (VT.is256BitVector()) {
5652           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5653           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5654         } else {
5655           assert(VT.is128BitVector() && "Expected an SSE value type!");
5656           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5657         }
5658         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5659       }
5660     }
5661
5662     // Is it a vector logical left shift?
5663     if (NumElems == 2 && Idx == 1 &&
5664         X86::isZeroNode(Op.getOperand(0)) &&
5665         !X86::isZeroNode(Op.getOperand(1))) {
5666       unsigned NumBits = VT.getSizeInBits();
5667       return getVShift(true, VT,
5668                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5669                                    VT, Op.getOperand(1)),
5670                        NumBits/2, DAG, *this, dl);
5671     }
5672
5673     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5674       return SDValue();
5675
5676     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5677     // is a non-constant being inserted into an element other than the low one,
5678     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5679     // movd/movss) to move this into the low element, then shuffle it into
5680     // place.
5681     if (EVTBits == 32) {
5682       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5683       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5684     }
5685   }
5686
5687   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5688   if (Values.size() == 1) {
5689     if (EVTBits == 32) {
5690       // Instead of a shuffle like this:
5691       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5692       // Check if it's possible to issue this instead.
5693       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5694       unsigned Idx = countTrailingZeros(NonZeros);
5695       SDValue Item = Op.getOperand(Idx);
5696       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5697         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5698     }
5699     return SDValue();
5700   }
5701
5702   // A vector full of immediates; various special cases are already
5703   // handled, so this is best done with a single constant-pool load.
5704   if (IsAllConstants)
5705     return SDValue();
5706
5707   // For AVX-length vectors, see if we can use a vector load to get all of the
5708   // elements, otherwise build the individual 128-bit pieces and use
5709   // shuffles to put them in place.
5710   if (VT.is256BitVector() || VT.is512BitVector()) {
5711     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5712
5713     // Check for a build vector of consecutive loads.
5714     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5715       return LD;
5716
5717     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5718
5719     // Build both the lower and upper subvector.
5720     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5721                                 makeArrayRef(&V[0], NumElems/2));
5722     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5723                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5724
5725     // Recreate the wider vector with the lower and upper part.
5726     if (VT.is256BitVector())
5727       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5728     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5729   }
5730
5731   // Let legalizer expand 2-wide build_vectors.
5732   if (EVTBits == 64) {
5733     if (NumNonZero == 1) {
5734       // One half is zero or undef.
5735       unsigned Idx = countTrailingZeros(NonZeros);
5736       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5737                                  Op.getOperand(Idx));
5738       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5739     }
5740     return SDValue();
5741   }
5742
5743   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5744   if (EVTBits == 8 && NumElems == 16) {
5745     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5746                                         Subtarget, *this);
5747     if (V.getNode()) return V;
5748   }
5749
5750   if (EVTBits == 16 && NumElems == 8) {
5751     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5752                                       Subtarget, *this);
5753     if (V.getNode()) return V;
5754   }
5755
5756   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5757   if (EVTBits == 32 && NumElems == 4) {
5758     SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
5759     if (V.getNode())
5760       return V;
5761   }
5762
5763   // If element VT is == 32 bits, turn it into a number of shuffles.
5764   SmallVector<SDValue, 8> V(NumElems);
5765   if (NumElems == 4 && NumZero > 0) {
5766     for (unsigned i = 0; i < 4; ++i) {
5767       bool isZero = !(NonZeros & (1 << i));
5768       if (isZero)
5769         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5770       else
5771         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5772     }
5773
5774     for (unsigned i = 0; i < 2; ++i) {
5775       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5776         default: break;
5777         case 0:
5778           V[i] = V[i*2];  // Must be a zero vector.
5779           break;
5780         case 1:
5781           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5782           break;
5783         case 2:
5784           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5785           break;
5786         case 3:
5787           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5788           break;
5789       }
5790     }
5791
5792     bool Reverse1 = (NonZeros & 0x3) == 2;
5793     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5794     int MaskVec[] = {
5795       Reverse1 ? 1 : 0,
5796       Reverse1 ? 0 : 1,
5797       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5798       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5799     };
5800     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5801   }
5802
5803   if (Values.size() > 1 && VT.is128BitVector()) {
5804     // Check for a build vector of consecutive loads.
5805     for (unsigned i = 0; i < NumElems; ++i)
5806       V[i] = Op.getOperand(i);
5807
5808     // Check for elements which are consecutive loads.
5809     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
5810     if (LD.getNode())
5811       return LD;
5812
5813     // Check for a build vector from mostly shuffle plus few inserting.
5814     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5815     if (Sh.getNode())
5816       return Sh;
5817
5818     // For SSE 4.1, use insertps to put the high elements into the low element.
5819     if (Subtarget->hasSSE41()) {
5820       SDValue Result;
5821       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5822         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5823       else
5824         Result = DAG.getUNDEF(VT);
5825
5826       for (unsigned i = 1; i < NumElems; ++i) {
5827         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5828         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5829                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5830       }
5831       return Result;
5832     }
5833
5834     // Otherwise, expand into a number of unpckl*, start by extending each of
5835     // our (non-undef) elements to the full vector width with the element in the
5836     // bottom slot of the vector (which generates no code for SSE).
5837     for (unsigned i = 0; i < NumElems; ++i) {
5838       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5839         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5840       else
5841         V[i] = DAG.getUNDEF(VT);
5842     }
5843
5844     // Next, we iteratively mix elements, e.g. for v4f32:
5845     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5846     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5847     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5848     unsigned EltStride = NumElems >> 1;
5849     while (EltStride != 0) {
5850       for (unsigned i = 0; i < EltStride; ++i) {
5851         // If V[i+EltStride] is undef and this is the first round of mixing,
5852         // then it is safe to just drop this shuffle: V[i] is already in the
5853         // right place, the one element (since it's the first round) being
5854         // inserted as undef can be dropped.  This isn't safe for successive
5855         // rounds because they will permute elements within both vectors.
5856         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5857             EltStride == NumElems/2)
5858           continue;
5859
5860         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5861       }
5862       EltStride >>= 1;
5863     }
5864     return V[0];
5865   }
5866   return SDValue();
5867 }
5868
5869 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5870 // to create 256-bit vectors from two other 128-bit ones.
5871 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5872   SDLoc dl(Op);
5873   MVT ResVT = Op.getSimpleValueType();
5874
5875   assert((ResVT.is256BitVector() ||
5876           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5877
5878   SDValue V1 = Op.getOperand(0);
5879   SDValue V2 = Op.getOperand(1);
5880   unsigned NumElems = ResVT.getVectorNumElements();
5881   if(ResVT.is256BitVector())
5882     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5883
5884   if (Op.getNumOperands() == 4) {
5885     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5886                                 ResVT.getVectorNumElements()/2);
5887     SDValue V3 = Op.getOperand(2);
5888     SDValue V4 = Op.getOperand(3);
5889     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5890       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5891   }
5892   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5893 }
5894
5895 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5896   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
5897   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
5898          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
5899           Op.getNumOperands() == 4)));
5900
5901   // AVX can use the vinsertf128 instruction to create 256-bit vectors
5902   // from two other 128-bit ones.
5903
5904   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
5905   return LowerAVXCONCAT_VECTORS(Op, DAG);
5906 }
5907
5908
5909 //===----------------------------------------------------------------------===//
5910 // Vector shuffle lowering
5911 //
5912 // This is an experimental code path for lowering vector shuffles on x86. It is
5913 // designed to handle arbitrary vector shuffles and blends, gracefully
5914 // degrading performance as necessary. It works hard to recognize idiomatic
5915 // shuffles and lower them to optimal instruction patterns without leaving
5916 // a framework that allows reasonably efficient handling of all vector shuffle
5917 // patterns.
5918 //===----------------------------------------------------------------------===//
5919
5920 /// \brief Tiny helper function to identify a no-op mask.
5921 ///
5922 /// This is a somewhat boring predicate function. It checks whether the mask
5923 /// array input, which is assumed to be a single-input shuffle mask of the kind
5924 /// used by the X86 shuffle instructions (not a fully general
5925 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
5926 /// in-place shuffle are 'no-op's.
5927 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
5928   for (int i = 0, Size = Mask.size(); i < Size; ++i)
5929     if (Mask[i] != -1 && Mask[i] != i)
5930       return false;
5931   return true;
5932 }
5933
5934 /// \brief Helper function to classify a mask as a single-input mask.
5935 ///
5936 /// This isn't a generic single-input test because in the vector shuffle
5937 /// lowering we canonicalize single inputs to be the first input operand. This
5938 /// means we can more quickly test for a single input by only checking whether
5939 /// an input from the second operand exists. We also assume that the size of
5940 /// mask corresponds to the size of the input vectors which isn't true in the
5941 /// fully general case.
5942 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
5943   for (int M : Mask)
5944     if (M >= (int)Mask.size())
5945       return false;
5946   return true;
5947 }
5948
5949 /// \brief Test whether there are elements crossing 128-bit lanes in this
5950 /// shuffle mask.
5951 ///
5952 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
5953 /// and we routinely test for these.
5954 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
5955   int LaneSize = 128 / VT.getScalarSizeInBits();
5956   int Size = Mask.size();
5957   for (int i = 0; i < Size; ++i)
5958     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
5959       return true;
5960   return false;
5961 }
5962
5963 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
5964 ///
5965 /// This checks a shuffle mask to see if it is performing the same
5966 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
5967 /// that it is also not lane-crossing. It may however involve a blend from the
5968 /// same lane of a second vector.
5969 ///
5970 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
5971 /// non-trivial to compute in the face of undef lanes. The representation is
5972 /// *not* suitable for use with existing 128-bit shuffles as it will contain
5973 /// entries from both V1 and V2 inputs to the wider mask.
5974 static bool
5975 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
5976                                 SmallVectorImpl<int> &RepeatedMask) {
5977   int LaneSize = 128 / VT.getScalarSizeInBits();
5978   RepeatedMask.resize(LaneSize, -1);
5979   int Size = Mask.size();
5980   for (int i = 0; i < Size; ++i) {
5981     if (Mask[i] < 0)
5982       continue;
5983     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
5984       // This entry crosses lanes, so there is no way to model this shuffle.
5985       return false;
5986
5987     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
5988     if (RepeatedMask[i % LaneSize] == -1)
5989       // This is the first non-undef entry in this slot of a 128-bit lane.
5990       RepeatedMask[i % LaneSize] =
5991           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
5992     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
5993       // Found a mismatch with the repeated mask.
5994       return false;
5995   }
5996   return true;
5997 }
5998
5999 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6000 /// arguments.
6001 ///
6002 /// This is a fast way to test a shuffle mask against a fixed pattern:
6003 ///
6004 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6005 ///
6006 /// It returns true if the mask is exactly as wide as the argument list, and
6007 /// each element of the mask is either -1 (signifying undef) or the value given
6008 /// in the argument.
6009 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6010                                 ArrayRef<int> ExpectedMask) {
6011   if (Mask.size() != ExpectedMask.size())
6012     return false;
6013
6014   int Size = Mask.size();
6015
6016   // If the values are build vectors, we can look through them to find
6017   // equivalent inputs that make the shuffles equivalent.
6018   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6019   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6020
6021   for (int i = 0; i < Size; ++i)
6022     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6023       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6024       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6025       if (!MaskBV || !ExpectedBV ||
6026           MaskBV->getOperand(Mask[i] % Size) !=
6027               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6028         return false;
6029     }
6030
6031   return true;
6032 }
6033
6034 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6035 ///
6036 /// This helper function produces an 8-bit shuffle immediate corresponding to
6037 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6038 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6039 /// example.
6040 ///
6041 /// NB: We rely heavily on "undef" masks preserving the input lane.
6042 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6043                                           SelectionDAG &DAG) {
6044   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6045   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6046   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6047   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6048   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6049
6050   unsigned Imm = 0;
6051   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6052   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6053   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6054   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6055   return DAG.getConstant(Imm, MVT::i8);
6056 }
6057
6058 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6059 ///
6060 /// This is used as a fallback approach when first class blend instructions are
6061 /// unavailable. Currently it is only suitable for integer vectors, but could
6062 /// be generalized for floating point vectors if desirable.
6063 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6064                                             SDValue V2, ArrayRef<int> Mask,
6065                                             SelectionDAG &DAG) {
6066   assert(VT.isInteger() && "Only supports integer vector types!");
6067   MVT EltVT = VT.getScalarType();
6068   int NumEltBits = EltVT.getSizeInBits();
6069   SDValue Zero = DAG.getConstant(0, EltVT);
6070   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6071   SmallVector<SDValue, 16> MaskOps;
6072   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6073     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6074       return SDValue(); // Shuffled input!
6075     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6076   }
6077
6078   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6079   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6080   // We have to cast V2 around.
6081   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6082   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6083                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6084                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6085                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6086   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6087 }
6088
6089 /// \brief Try to emit a blend instruction for a shuffle.
6090 ///
6091 /// This doesn't do any checks for the availability of instructions for blending
6092 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6093 /// be matched in the backend with the type given. What it does check for is
6094 /// that the shuffle mask is in fact a blend.
6095 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6096                                          SDValue V2, ArrayRef<int> Mask,
6097                                          const X86Subtarget *Subtarget,
6098                                          SelectionDAG &DAG) {
6099   unsigned BlendMask = 0;
6100   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6101     if (Mask[i] >= Size) {
6102       if (Mask[i] != i + Size)
6103         return SDValue(); // Shuffled V2 input!
6104       BlendMask |= 1u << i;
6105       continue;
6106     }
6107     if (Mask[i] >= 0 && Mask[i] != i)
6108       return SDValue(); // Shuffled V1 input!
6109   }
6110   switch (VT.SimpleTy) {
6111   case MVT::v2f64:
6112   case MVT::v4f32:
6113   case MVT::v4f64:
6114   case MVT::v8f32:
6115     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6116                        DAG.getConstant(BlendMask, MVT::i8));
6117
6118   case MVT::v4i64:
6119   case MVT::v8i32:
6120     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6121     // FALLTHROUGH
6122   case MVT::v2i64:
6123   case MVT::v4i32:
6124     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6125     // that instruction.
6126     if (Subtarget->hasAVX2()) {
6127       // Scale the blend by the number of 32-bit dwords per element.
6128       int Scale =  VT.getScalarSizeInBits() / 32;
6129       BlendMask = 0;
6130       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6131         if (Mask[i] >= Size)
6132           for (int j = 0; j < Scale; ++j)
6133             BlendMask |= 1u << (i * Scale + j);
6134
6135       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6136       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6137       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6138       return DAG.getNode(ISD::BITCAST, DL, VT,
6139                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6140                                      DAG.getConstant(BlendMask, MVT::i8)));
6141     }
6142     // FALLTHROUGH
6143   case MVT::v8i16: {
6144     // For integer shuffles we need to expand the mask and cast the inputs to
6145     // v8i16s prior to blending.
6146     int Scale = 8 / VT.getVectorNumElements();
6147     BlendMask = 0;
6148     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6149       if (Mask[i] >= Size)
6150         for (int j = 0; j < Scale; ++j)
6151           BlendMask |= 1u << (i * Scale + j);
6152
6153     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6154     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6155     return DAG.getNode(ISD::BITCAST, DL, VT,
6156                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6157                                    DAG.getConstant(BlendMask, MVT::i8)));
6158   }
6159
6160   case MVT::v16i16: {
6161     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6162     SmallVector<int, 8> RepeatedMask;
6163     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6164       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6165       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6166       BlendMask = 0;
6167       for (int i = 0; i < 8; ++i)
6168         if (RepeatedMask[i] >= 16)
6169           BlendMask |= 1u << i;
6170       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6171                          DAG.getConstant(BlendMask, MVT::i8));
6172     }
6173   }
6174     // FALLTHROUGH
6175   case MVT::v16i8:
6176   case MVT::v32i8: {
6177     // Scale the blend by the number of bytes per element.
6178     int Scale = VT.getScalarSizeInBits() / 8;
6179
6180     // This form of blend is always done on bytes. Compute the byte vector
6181     // type.
6182     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6183
6184     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6185     // mix of LLVM's code generator and the x86 backend. We tell the code
6186     // generator that boolean values in the elements of an x86 vector register
6187     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6188     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6189     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6190     // of the element (the remaining are ignored) and 0 in that high bit would
6191     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6192     // the LLVM model for boolean values in vector elements gets the relevant
6193     // bit set, it is set backwards and over constrained relative to x86's
6194     // actual model.
6195     SmallVector<SDValue, 32> VSELECTMask;
6196     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6197       for (int j = 0; j < Scale; ++j)
6198         VSELECTMask.push_back(
6199             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6200                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6201
6202     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6203     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6204     return DAG.getNode(
6205         ISD::BITCAST, DL, VT,
6206         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6207                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6208                     V1, V2));
6209   }
6210
6211   default:
6212     llvm_unreachable("Not a supported integer vector type!");
6213   }
6214 }
6215
6216 /// \brief Try to lower as a blend of elements from two inputs followed by
6217 /// a single-input permutation.
6218 ///
6219 /// This matches the pattern where we can blend elements from two inputs and
6220 /// then reduce the shuffle to a single-input permutation.
6221 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6222                                                    SDValue V2,
6223                                                    ArrayRef<int> Mask,
6224                                                    SelectionDAG &DAG) {
6225   // We build up the blend mask while checking whether a blend is a viable way
6226   // to reduce the shuffle.
6227   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6228   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6229
6230   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6231     if (Mask[i] < 0)
6232       continue;
6233
6234     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6235
6236     if (BlendMask[Mask[i] % Size] == -1)
6237       BlendMask[Mask[i] % Size] = Mask[i];
6238     else if (BlendMask[Mask[i] % Size] != Mask[i])
6239       return SDValue(); // Can't blend in the needed input!
6240
6241     PermuteMask[i] = Mask[i] % Size;
6242   }
6243
6244   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6245   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6246 }
6247
6248 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6249 /// blends and permutes.
6250 ///
6251 /// This matches the extremely common pattern for handling combined
6252 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6253 /// operations. It will try to pick the best arrangement of shuffles and
6254 /// blends.
6255 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6256                                                           SDValue V1,
6257                                                           SDValue V2,
6258                                                           ArrayRef<int> Mask,
6259                                                           SelectionDAG &DAG) {
6260   // Shuffle the input elements into the desired positions in V1 and V2 and
6261   // blend them together.
6262   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6263   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6264   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6265   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6266     if (Mask[i] >= 0 && Mask[i] < Size) {
6267       V1Mask[i] = Mask[i];
6268       BlendMask[i] = i;
6269     } else if (Mask[i] >= Size) {
6270       V2Mask[i] = Mask[i] - Size;
6271       BlendMask[i] = i + Size;
6272     }
6273
6274   // Try to lower with the simpler initial blend strategy unless one of the
6275   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6276   // shuffle may be able to fold with a load or other benefit. However, when
6277   // we'll have to do 2x as many shuffles in order to achieve this, blending
6278   // first is a better strategy.
6279   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6280     if (SDValue BlendPerm =
6281             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6282       return BlendPerm;
6283
6284   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6285   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6286   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6287 }
6288
6289 /// \brief Try to lower a vector shuffle as a byte rotation.
6290 ///
6291 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6292 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6293 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6294 /// try to generically lower a vector shuffle through such an pattern. It
6295 /// does not check for the profitability of lowering either as PALIGNR or
6296 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6297 /// This matches shuffle vectors that look like:
6298 ///
6299 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6300 ///
6301 /// Essentially it concatenates V1 and V2, shifts right by some number of
6302 /// elements, and takes the low elements as the result. Note that while this is
6303 /// specified as a *right shift* because x86 is little-endian, it is a *left
6304 /// rotate* of the vector lanes.
6305 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6306                                               SDValue V2,
6307                                               ArrayRef<int> Mask,
6308                                               const X86Subtarget *Subtarget,
6309                                               SelectionDAG &DAG) {
6310   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6311
6312   int NumElts = Mask.size();
6313   int NumLanes = VT.getSizeInBits() / 128;
6314   int NumLaneElts = NumElts / NumLanes;
6315
6316   // We need to detect various ways of spelling a rotation:
6317   //   [11, 12, 13, 14, 15,  0,  1,  2]
6318   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6319   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6320   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6321   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6322   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6323   int Rotation = 0;
6324   SDValue Lo, Hi;
6325   for (int l = 0; l < NumElts; l += NumLaneElts) {
6326     for (int i = 0; i < NumLaneElts; ++i) {
6327       if (Mask[l + i] == -1)
6328         continue;
6329       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6330
6331       // Get the mod-Size index and lane correct it.
6332       int LaneIdx = (Mask[l + i] % NumElts) - l;
6333       // Make sure it was in this lane.
6334       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6335         return SDValue();
6336
6337       // Determine where a rotated vector would have started.
6338       int StartIdx = i - LaneIdx;
6339       if (StartIdx == 0)
6340         // The identity rotation isn't interesting, stop.
6341         return SDValue();
6342
6343       // If we found the tail of a vector the rotation must be the missing
6344       // front. If we found the head of a vector, it must be how much of the
6345       // head.
6346       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6347
6348       if (Rotation == 0)
6349         Rotation = CandidateRotation;
6350       else if (Rotation != CandidateRotation)
6351         // The rotations don't match, so we can't match this mask.
6352         return SDValue();
6353
6354       // Compute which value this mask is pointing at.
6355       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6356
6357       // Compute which of the two target values this index should be assigned
6358       // to. This reflects whether the high elements are remaining or the low
6359       // elements are remaining.
6360       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6361
6362       // Either set up this value if we've not encountered it before, or check
6363       // that it remains consistent.
6364       if (!TargetV)
6365         TargetV = MaskV;
6366       else if (TargetV != MaskV)
6367         // This may be a rotation, but it pulls from the inputs in some
6368         // unsupported interleaving.
6369         return SDValue();
6370     }
6371   }
6372
6373   // Check that we successfully analyzed the mask, and normalize the results.
6374   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6375   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6376   if (!Lo)
6377     Lo = Hi;
6378   else if (!Hi)
6379     Hi = Lo;
6380
6381   // The actual rotate instruction rotates bytes, so we need to scale the
6382   // rotation based on how many bytes are in the vector lane.
6383   int Scale = 16 / NumLaneElts;
6384
6385   // SSSE3 targets can use the palignr instruction.
6386   if (Subtarget->hasSSSE3()) {
6387     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6388     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6389     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6390     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6391
6392     return DAG.getNode(ISD::BITCAST, DL, VT,
6393                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6394                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
6395   }
6396
6397   assert(VT.getSizeInBits() == 128 &&
6398          "Rotate-based lowering only supports 128-bit lowering!");
6399   assert(Mask.size() <= 16 &&
6400          "Can shuffle at most 16 bytes in a 128-bit vector!");
6401
6402   // Default SSE2 implementation
6403   int LoByteShift = 16 - Rotation * Scale;
6404   int HiByteShift = Rotation * Scale;
6405
6406   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6407   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6408   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6409
6410   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6411                                 DAG.getConstant(LoByteShift, MVT::i8));
6412   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6413                                 DAG.getConstant(HiByteShift, MVT::i8));
6414   return DAG.getNode(ISD::BITCAST, DL, VT,
6415                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6416 }
6417
6418 /// \brief Compute whether each element of a shuffle is zeroable.
6419 ///
6420 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6421 /// Either it is an undef element in the shuffle mask, the element of the input
6422 /// referenced is undef, or the element of the input referenced is known to be
6423 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6424 /// as many lanes with this technique as possible to simplify the remaining
6425 /// shuffle.
6426 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6427                                                      SDValue V1, SDValue V2) {
6428   SmallBitVector Zeroable(Mask.size(), false);
6429
6430   while (V1.getOpcode() == ISD::BITCAST)
6431     V1 = V1->getOperand(0);
6432   while (V2.getOpcode() == ISD::BITCAST)
6433     V2 = V2->getOperand(0);
6434
6435   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6436   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6437
6438   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6439     int M = Mask[i];
6440     // Handle the easy cases.
6441     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6442       Zeroable[i] = true;
6443       continue;
6444     }
6445
6446     // If this is an index into a build_vector node (which has the same number
6447     // of elements), dig out the input value and use it.
6448     SDValue V = M < Size ? V1 : V2;
6449     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6450       continue;
6451
6452     SDValue Input = V.getOperand(M % Size);
6453     // The UNDEF opcode check really should be dead code here, but not quite
6454     // worth asserting on (it isn't invalid, just unexpected).
6455     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6456       Zeroable[i] = true;
6457   }
6458
6459   return Zeroable;
6460 }
6461
6462 /// \brief Try to emit a bitmask instruction for a shuffle.
6463 ///
6464 /// This handles cases where we can model a blend exactly as a bitmask due to
6465 /// one of the inputs being zeroable.
6466 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6467                                            SDValue V2, ArrayRef<int> Mask,
6468                                            SelectionDAG &DAG) {
6469   MVT EltVT = VT.getScalarType();
6470   int NumEltBits = EltVT.getSizeInBits();
6471   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6472   SDValue Zero = DAG.getConstant(0, IntEltVT);
6473   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6474   if (EltVT.isFloatingPoint()) {
6475     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6476     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6477   }
6478   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6479   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6480   SDValue V;
6481   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6482     if (Zeroable[i])
6483       continue;
6484     if (Mask[i] % Size != i)
6485       return SDValue(); // Not a blend.
6486     if (!V)
6487       V = Mask[i] < Size ? V1 : V2;
6488     else if (V != (Mask[i] < Size ? V1 : V2))
6489       return SDValue(); // Can only let one input through the mask.
6490
6491     VMaskOps[i] = AllOnes;
6492   }
6493   if (!V)
6494     return SDValue(); // No non-zeroable elements!
6495
6496   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6497   V = DAG.getNode(VT.isFloatingPoint()
6498                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6499                   DL, VT, V, VMask);
6500   return V;
6501 }
6502
6503 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6504 ///
6505 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6506 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6507 /// matches elements from one of the input vectors shuffled to the left or
6508 /// right with zeroable elements 'shifted in'. It handles both the strictly
6509 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6510 /// quad word lane.
6511 ///
6512 /// PSHL : (little-endian) left bit shift.
6513 /// [ zz, 0, zz,  2 ]
6514 /// [ -1, 4, zz, -1 ]
6515 /// PSRL : (little-endian) right bit shift.
6516 /// [  1, zz,  3, zz]
6517 /// [ -1, -1,  7, zz]
6518 /// PSLLDQ : (little-endian) left byte shift
6519 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6520 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6521 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6522 /// PSRLDQ : (little-endian) right byte shift
6523 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6524 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6525 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6526 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6527                                          SDValue V2, ArrayRef<int> Mask,
6528                                          SelectionDAG &DAG) {
6529   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6530
6531   int Size = Mask.size();
6532   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6533
6534   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6535     for (int i = 0; i < Size; i += Scale)
6536       for (int j = 0; j < Shift; ++j)
6537         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6538           return false;
6539
6540     return true;
6541   };
6542
6543   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6544     for (int i = 0; i != Size; i += Scale) {
6545       unsigned Pos = Left ? i + Shift : i;
6546       unsigned Low = Left ? i : i + Shift;
6547       unsigned Len = Scale - Shift;
6548       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6549                                       Low + (V == V1 ? 0 : Size)))
6550         return SDValue();
6551     }
6552
6553     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6554     bool ByteShift = ShiftEltBits > 64;
6555     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6556                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6557     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6558
6559     // Normalize the scale for byte shifts to still produce an i64 element
6560     // type.
6561     Scale = ByteShift ? Scale / 2 : Scale;
6562
6563     // We need to round trip through the appropriate type for the shift.
6564     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6565     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6566     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6567            "Illegal integer vector type");
6568     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6569
6570     V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6571     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6572   };
6573
6574   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6575   // keep doubling the size of the integer elements up to that. We can
6576   // then shift the elements of the integer vector by whole multiples of
6577   // their width within the elements of the larger integer vector. Test each
6578   // multiple to see if we can find a match with the moved element indices
6579   // and that the shifted in elements are all zeroable.
6580   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6581     for (int Shift = 1; Shift != Scale; ++Shift)
6582       for (bool Left : {true, false})
6583         if (CheckZeros(Shift, Scale, Left))
6584           for (SDValue V : {V1, V2})
6585             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6586               return Match;
6587
6588   // no match
6589   return SDValue();
6590 }
6591
6592 /// \brief Lower a vector shuffle as a zero or any extension.
6593 ///
6594 /// Given a specific number of elements, element bit width, and extension
6595 /// stride, produce either a zero or any extension based on the available
6596 /// features of the subtarget.
6597 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6598     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6599     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6600   assert(Scale > 1 && "Need a scale to extend.");
6601   int NumElements = VT.getVectorNumElements();
6602   int EltBits = VT.getScalarSizeInBits();
6603   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6604          "Only 8, 16, and 32 bit elements can be extended.");
6605   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6606
6607   // Found a valid zext mask! Try various lowering strategies based on the
6608   // input type and available ISA extensions.
6609   if (Subtarget->hasSSE41()) {
6610     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6611                                  NumElements / Scale);
6612     return DAG.getNode(ISD::BITCAST, DL, VT,
6613                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6614   }
6615
6616   // For any extends we can cheat for larger element sizes and use shuffle
6617   // instructions that can fold with a load and/or copy.
6618   if (AnyExt && EltBits == 32) {
6619     int PSHUFDMask[4] = {0, -1, 1, -1};
6620     return DAG.getNode(
6621         ISD::BITCAST, DL, VT,
6622         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6623                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6624                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6625   }
6626   if (AnyExt && EltBits == 16 && Scale > 2) {
6627     int PSHUFDMask[4] = {0, -1, 0, -1};
6628     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6629                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6630                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6631     int PSHUFHWMask[4] = {1, -1, -1, -1};
6632     return DAG.getNode(
6633         ISD::BITCAST, DL, VT,
6634         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6635                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6636                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6637   }
6638
6639   // If this would require more than 2 unpack instructions to expand, use
6640   // pshufb when available. We can only use more than 2 unpack instructions
6641   // when zero extending i8 elements which also makes it easier to use pshufb.
6642   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6643     assert(NumElements == 16 && "Unexpected byte vector width!");
6644     SDValue PSHUFBMask[16];
6645     for (int i = 0; i < 16; ++i)
6646       PSHUFBMask[i] =
6647           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6648     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6649     return DAG.getNode(ISD::BITCAST, DL, VT,
6650                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6651                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6652                                                MVT::v16i8, PSHUFBMask)));
6653   }
6654
6655   // Otherwise emit a sequence of unpacks.
6656   do {
6657     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6658     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6659                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6660     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6661     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6662     Scale /= 2;
6663     EltBits *= 2;
6664     NumElements /= 2;
6665   } while (Scale > 1);
6666   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6667 }
6668
6669 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6670 ///
6671 /// This routine will try to do everything in its power to cleverly lower
6672 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6673 /// check for the profitability of this lowering,  it tries to aggressively
6674 /// match this pattern. It will use all of the micro-architectural details it
6675 /// can to emit an efficient lowering. It handles both blends with all-zero
6676 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6677 /// masking out later).
6678 ///
6679 /// The reason we have dedicated lowering for zext-style shuffles is that they
6680 /// are both incredibly common and often quite performance sensitive.
6681 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6682     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6683     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6684   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6685
6686   int Bits = VT.getSizeInBits();
6687   int NumElements = VT.getVectorNumElements();
6688   assert(VT.getScalarSizeInBits() <= 32 &&
6689          "Exceeds 32-bit integer zero extension limit");
6690   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6691
6692   // Define a helper function to check a particular ext-scale and lower to it if
6693   // valid.
6694   auto Lower = [&](int Scale) -> SDValue {
6695     SDValue InputV;
6696     bool AnyExt = true;
6697     for (int i = 0; i < NumElements; ++i) {
6698       if (Mask[i] == -1)
6699         continue; // Valid anywhere but doesn't tell us anything.
6700       if (i % Scale != 0) {
6701         // Each of the extended elements need to be zeroable.
6702         if (!Zeroable[i])
6703           return SDValue();
6704
6705         // We no longer are in the anyext case.
6706         AnyExt = false;
6707         continue;
6708       }
6709
6710       // Each of the base elements needs to be consecutive indices into the
6711       // same input vector.
6712       SDValue V = Mask[i] < NumElements ? V1 : V2;
6713       if (!InputV)
6714         InputV = V;
6715       else if (InputV != V)
6716         return SDValue(); // Flip-flopping inputs.
6717
6718       if (Mask[i] % NumElements != i / Scale)
6719         return SDValue(); // Non-consecutive strided elements.
6720     }
6721
6722     // If we fail to find an input, we have a zero-shuffle which should always
6723     // have already been handled.
6724     // FIXME: Maybe handle this here in case during blending we end up with one?
6725     if (!InputV)
6726       return SDValue();
6727
6728     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6729         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6730   };
6731
6732   // The widest scale possible for extending is to a 64-bit integer.
6733   assert(Bits % 64 == 0 &&
6734          "The number of bits in a vector must be divisible by 64 on x86!");
6735   int NumExtElements = Bits / 64;
6736
6737   // Each iteration, try extending the elements half as much, but into twice as
6738   // many elements.
6739   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6740     assert(NumElements % NumExtElements == 0 &&
6741            "The input vector size must be divisible by the extended size.");
6742     if (SDValue V = Lower(NumElements / NumExtElements))
6743       return V;
6744   }
6745
6746   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6747   if (Bits != 128)
6748     return SDValue();
6749
6750   // Returns one of the source operands if the shuffle can be reduced to a
6751   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6752   auto CanZExtLowHalf = [&]() {
6753     for (int i = NumElements / 2; i != NumElements; ++i)
6754       if (!Zeroable[i])
6755         return SDValue();
6756     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6757       return V1;
6758     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6759       return V2;
6760     return SDValue();
6761   };
6762
6763   if (SDValue V = CanZExtLowHalf()) {
6764     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6765     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6766     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6767   }
6768
6769   // No viable ext lowering found.
6770   return SDValue();
6771 }
6772
6773 /// \brief Try to get a scalar value for a specific element of a vector.
6774 ///
6775 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6776 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6777                                               SelectionDAG &DAG) {
6778   MVT VT = V.getSimpleValueType();
6779   MVT EltVT = VT.getVectorElementType();
6780   while (V.getOpcode() == ISD::BITCAST)
6781     V = V.getOperand(0);
6782   // If the bitcasts shift the element size, we can't extract an equivalent
6783   // element from it.
6784   MVT NewVT = V.getSimpleValueType();
6785   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6786     return SDValue();
6787
6788   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6789       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6790     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6791
6792   return SDValue();
6793 }
6794
6795 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6796 ///
6797 /// This is particularly important because the set of instructions varies
6798 /// significantly based on whether the operand is a load or not.
6799 static bool isShuffleFoldableLoad(SDValue V) {
6800   while (V.getOpcode() == ISD::BITCAST)
6801     V = V.getOperand(0);
6802
6803   return ISD::isNON_EXTLoad(V.getNode());
6804 }
6805
6806 /// \brief Try to lower insertion of a single element into a zero vector.
6807 ///
6808 /// This is a common pattern that we have especially efficient patterns to lower
6809 /// across all subtarget feature sets.
6810 static SDValue lowerVectorShuffleAsElementInsertion(
6811     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6812     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6813   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6814   MVT ExtVT = VT;
6815   MVT EltVT = VT.getVectorElementType();
6816
6817   int V2Index = std::find_if(Mask.begin(), Mask.end(),
6818                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
6819                 Mask.begin();
6820   bool IsV1Zeroable = true;
6821   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6822     if (i != V2Index && !Zeroable[i]) {
6823       IsV1Zeroable = false;
6824       break;
6825     }
6826
6827   // Check for a single input from a SCALAR_TO_VECTOR node.
6828   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6829   // all the smarts here sunk into that routine. However, the current
6830   // lowering of BUILD_VECTOR makes that nearly impossible until the old
6831   // vector shuffle lowering is dead.
6832   if (SDValue V2S = getScalarValueForVectorElement(
6833           V2, Mask[V2Index] - Mask.size(), DAG)) {
6834     // We need to zext the scalar if it is smaller than an i32.
6835     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6836     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6837       // Using zext to expand a narrow element won't work for non-zero
6838       // insertions.
6839       if (!IsV1Zeroable)
6840         return SDValue();
6841
6842       // Zero-extend directly to i32.
6843       ExtVT = MVT::v4i32;
6844       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6845     }
6846     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6847   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6848              EltVT == MVT::i16) {
6849     // Either not inserting from the low element of the input or the input
6850     // element size is too small to use VZEXT_MOVL to clear the high bits.
6851     return SDValue();
6852   }
6853
6854   if (!IsV1Zeroable) {
6855     // If V1 can't be treated as a zero vector we have fewer options to lower
6856     // this. We can't support integer vectors or non-zero targets cheaply, and
6857     // the V1 elements can't be permuted in any way.
6858     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6859     if (!VT.isFloatingPoint() || V2Index != 0)
6860       return SDValue();
6861     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6862     V1Mask[V2Index] = -1;
6863     if (!isNoopShuffleMask(V1Mask))
6864       return SDValue();
6865     // This is essentially a special case blend operation, but if we have
6866     // general purpose blend operations, they are always faster. Bail and let
6867     // the rest of the lowering handle these as blends.
6868     if (Subtarget->hasSSE41())
6869       return SDValue();
6870
6871     // Otherwise, use MOVSD or MOVSS.
6872     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6873            "Only two types of floating point element types to handle!");
6874     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6875                        ExtVT, V1, V2);
6876   }
6877
6878   // This lowering only works for the low element with floating point vectors.
6879   if (VT.isFloatingPoint() && V2Index != 0)
6880     return SDValue();
6881
6882   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6883   if (ExtVT != VT)
6884     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6885
6886   if (V2Index != 0) {
6887     // If we have 4 or fewer lanes we can cheaply shuffle the element into
6888     // the desired position. Otherwise it is more efficient to do a vector
6889     // shift left. We know that we can do a vector shift left because all
6890     // the inputs are zero.
6891     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
6892       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
6893       V2Shuffle[V2Index] = 0;
6894       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
6895     } else {
6896       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
6897       V2 = DAG.getNode(
6898           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
6899           DAG.getConstant(
6900               V2Index * EltVT.getSizeInBits()/8,
6901               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
6902       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6903     }
6904   }
6905   return V2;
6906 }
6907
6908 /// \brief Try to lower broadcast of a single element.
6909 ///
6910 /// For convenience, this code also bundles all of the subtarget feature set
6911 /// filtering. While a little annoying to re-dispatch on type here, there isn't
6912 /// a convenient way to factor it out.
6913 static SDValue lowerVectorShuffleAsBroadcast(MVT VT, SDLoc DL, SDValue V,
6914                                              ArrayRef<int> Mask,
6915                                              const X86Subtarget *Subtarget,
6916                                              SelectionDAG &DAG) {
6917   if (!Subtarget->hasAVX())
6918     return SDValue();
6919   if (VT.isInteger() && !Subtarget->hasAVX2())
6920     return SDValue();
6921
6922   // Check that the mask is a broadcast.
6923   int BroadcastIdx = -1;
6924   for (int M : Mask)
6925     if (M >= 0 && BroadcastIdx == -1)
6926       BroadcastIdx = M;
6927     else if (M >= 0 && M != BroadcastIdx)
6928       return SDValue();
6929
6930   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
6931                                             "a sorted mask where the broadcast "
6932                                             "comes from V1.");
6933
6934   // Go up the chain of (vector) values to try and find a scalar load that
6935   // we can combine with the broadcast.
6936   for (;;) {
6937     switch (V.getOpcode()) {
6938     case ISD::CONCAT_VECTORS: {
6939       int OperandSize = Mask.size() / V.getNumOperands();
6940       V = V.getOperand(BroadcastIdx / OperandSize);
6941       BroadcastIdx %= OperandSize;
6942       continue;
6943     }
6944
6945     case ISD::INSERT_SUBVECTOR: {
6946       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
6947       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
6948       if (!ConstantIdx)
6949         break;
6950
6951       int BeginIdx = (int)ConstantIdx->getZExtValue();
6952       int EndIdx =
6953           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
6954       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
6955         BroadcastIdx -= BeginIdx;
6956         V = VInner;
6957       } else {
6958         V = VOuter;
6959       }
6960       continue;
6961     }
6962     }
6963     break;
6964   }
6965
6966   // Check if this is a broadcast of a scalar. We special case lowering
6967   // for scalars so that we can more effectively fold with loads.
6968   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6969       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
6970     V = V.getOperand(BroadcastIdx);
6971
6972     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
6973     // AVX2.
6974     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
6975       return SDValue();
6976   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
6977     // We can't broadcast from a vector register w/o AVX2, and we can only
6978     // broadcast from the zero-element of a vector register.
6979     return SDValue();
6980   }
6981
6982   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
6983 }
6984
6985 // Check for whether we can use INSERTPS to perform the shuffle. We only use
6986 // INSERTPS when the V1 elements are already in the correct locations
6987 // because otherwise we can just always use two SHUFPS instructions which
6988 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
6989 // perform INSERTPS if a single V1 element is out of place and all V2
6990 // elements are zeroable.
6991 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
6992                                             ArrayRef<int> Mask,
6993                                             SelectionDAG &DAG) {
6994   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
6995   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
6996   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
6997   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
6998
6999   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7000
7001   unsigned ZMask = 0;
7002   int V1DstIndex = -1;
7003   int V2DstIndex = -1;
7004   bool V1UsedInPlace = false;
7005
7006   for (int i = 0; i < 4; ++i) {
7007     // Synthesize a zero mask from the zeroable elements (includes undefs).
7008     if (Zeroable[i]) {
7009       ZMask |= 1 << i;
7010       continue;
7011     }
7012
7013     // Flag if we use any V1 inputs in place.
7014     if (i == Mask[i]) {
7015       V1UsedInPlace = true;
7016       continue;
7017     }
7018
7019     // We can only insert a single non-zeroable element.
7020     if (V1DstIndex != -1 || V2DstIndex != -1)
7021       return SDValue();
7022
7023     if (Mask[i] < 4) {
7024       // V1 input out of place for insertion.
7025       V1DstIndex = i;
7026     } else {
7027       // V2 input for insertion.
7028       V2DstIndex = i;
7029     }
7030   }
7031
7032   // Don't bother if we have no (non-zeroable) element for insertion.
7033   if (V1DstIndex == -1 && V2DstIndex == -1)
7034     return SDValue();
7035
7036   // Determine element insertion src/dst indices. The src index is from the
7037   // start of the inserted vector, not the start of the concatenated vector.
7038   unsigned V2SrcIndex = 0;
7039   if (V1DstIndex != -1) {
7040     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7041     // and don't use the original V2 at all.
7042     V2SrcIndex = Mask[V1DstIndex];
7043     V2DstIndex = V1DstIndex;
7044     V2 = V1;
7045   } else {
7046     V2SrcIndex = Mask[V2DstIndex] - 4;
7047   }
7048
7049   // If no V1 inputs are used in place, then the result is created only from
7050   // the zero mask and the V2 insertion - so remove V1 dependency.
7051   if (!V1UsedInPlace)
7052     V1 = DAG.getUNDEF(MVT::v4f32);
7053
7054   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7055   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7056
7057   // Insert the V2 element into the desired position.
7058   SDLoc DL(Op);
7059   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7060                      DAG.getConstant(InsertPSMask, MVT::i8));
7061 }
7062
7063 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7064 /// UNPCK instruction.
7065 ///
7066 /// This specifically targets cases where we end up with alternating between
7067 /// the two inputs, and so can permute them into something that feeds a single
7068 /// UNPCK instruction. Note that this routine only targets integer vectors
7069 /// because for floating point vectors we have a generalized SHUFPS lowering
7070 /// strategy that handles everything that doesn't *exactly* match an unpack,
7071 /// making this clever lowering unnecessary.
7072 static SDValue lowerVectorShuffleAsUnpack(MVT VT, SDLoc DL, SDValue V1,
7073                                           SDValue V2, ArrayRef<int> Mask,
7074                                           SelectionDAG &DAG) {
7075   assert(!VT.isFloatingPoint() &&
7076          "This routine only supports integer vectors.");
7077   assert(!isSingleInputShuffleMask(Mask) &&
7078          "This routine should only be used when blending two inputs.");
7079   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7080
7081   int Size = Mask.size();
7082
7083   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7084     return M >= 0 && M % Size < Size / 2;
7085   });
7086   int NumHiInputs = std::count_if(
7087       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7088
7089   bool UnpackLo = NumLoInputs >= NumHiInputs;
7090
7091   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7092     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7093     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7094
7095     for (int i = 0; i < Size; ++i) {
7096       if (Mask[i] < 0)
7097         continue;
7098
7099       // Each element of the unpack contains Scale elements from this mask.
7100       int UnpackIdx = i / Scale;
7101
7102       // We only handle the case where V1 feeds the first slots of the unpack.
7103       // We rely on canonicalization to ensure this is the case.
7104       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7105         return SDValue();
7106
7107       // Setup the mask for this input. The indexing is tricky as we have to
7108       // handle the unpack stride.
7109       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7110       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7111           Mask[i] % Size;
7112     }
7113
7114     // If we will have to shuffle both inputs to use the unpack, check whether
7115     // we can just unpack first and shuffle the result. If so, skip this unpack.
7116     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7117         !isNoopShuffleMask(V2Mask))
7118       return SDValue();
7119
7120     // Shuffle the inputs into place.
7121     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7122     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7123
7124     // Cast the inputs to the type we will use to unpack them.
7125     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7126     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7127
7128     // Unpack the inputs and cast the result back to the desired type.
7129     return DAG.getNode(ISD::BITCAST, DL, VT,
7130                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7131                                    DL, UnpackVT, V1, V2));
7132   };
7133
7134   // We try each unpack from the largest to the smallest to try and find one
7135   // that fits this mask.
7136   int OrigNumElements = VT.getVectorNumElements();
7137   int OrigScalarSize = VT.getScalarSizeInBits();
7138   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7139     int Scale = ScalarSize / OrigScalarSize;
7140     int NumElements = OrigNumElements / Scale;
7141     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7142     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7143       return Unpack;
7144   }
7145
7146   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7147   // initial unpack.
7148   if (NumLoInputs == 0 || NumHiInputs == 0) {
7149     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7150            "We have to have *some* inputs!");
7151     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7152
7153     // FIXME: We could consider the total complexity of the permute of each
7154     // possible unpacking. Or at the least we should consider how many
7155     // half-crossings are created.
7156     // FIXME: We could consider commuting the unpacks.
7157
7158     SmallVector<int, 32> PermMask;
7159     PermMask.assign(Size, -1);
7160     for (int i = 0; i < Size; ++i) {
7161       if (Mask[i] < 0)
7162         continue;
7163
7164       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7165
7166       PermMask[i] =
7167           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7168     }
7169     return DAG.getVectorShuffle(
7170         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7171                             DL, VT, V1, V2),
7172         DAG.getUNDEF(VT), PermMask);
7173   }
7174
7175   return SDValue();
7176 }
7177
7178 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7179 ///
7180 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7181 /// support for floating point shuffles but not integer shuffles. These
7182 /// instructions will incur a domain crossing penalty on some chips though so
7183 /// it is better to avoid lowering through this for integer vectors where
7184 /// possible.
7185 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7186                                        const X86Subtarget *Subtarget,
7187                                        SelectionDAG &DAG) {
7188   SDLoc DL(Op);
7189   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7190   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7191   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7192   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7193   ArrayRef<int> Mask = SVOp->getMask();
7194   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7195
7196   if (isSingleInputShuffleMask(Mask)) {
7197     // Use low duplicate instructions for masks that match their pattern.
7198     if (Subtarget->hasSSE3())
7199       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7200         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7201
7202     // Straight shuffle of a single input vector. Simulate this by using the
7203     // single input as both of the "inputs" to this instruction..
7204     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7205
7206     if (Subtarget->hasAVX()) {
7207       // If we have AVX, we can use VPERMILPS which will allow folding a load
7208       // into the shuffle.
7209       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7210                          DAG.getConstant(SHUFPDMask, MVT::i8));
7211     }
7212
7213     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7214                        DAG.getConstant(SHUFPDMask, MVT::i8));
7215   }
7216   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7217   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7218
7219   // If we have a single input, insert that into V1 if we can do so cheaply.
7220   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7221     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7222             MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
7223       return Insertion;
7224     // Try inverting the insertion since for v2 masks it is easy to do and we
7225     // can't reliably sort the mask one way or the other.
7226     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7227                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7228     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7229             MVT::v2f64, DL, V2, V1, InverseMask, Subtarget, DAG))
7230       return Insertion;
7231   }
7232
7233   // Try to use one of the special instruction patterns to handle two common
7234   // blend patterns if a zero-blend above didn't work.
7235   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7236       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7237     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7238       // We can either use a special instruction to load over the low double or
7239       // to move just the low double.
7240       return DAG.getNode(
7241           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7242           DL, MVT::v2f64, V2,
7243           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7244
7245   if (Subtarget->hasSSE41())
7246     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7247                                                   Subtarget, DAG))
7248       return Blend;
7249
7250   // Use dedicated unpack instructions for masks that match their pattern.
7251   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7252     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7253   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7254     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7255
7256   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7257   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7258                      DAG.getConstant(SHUFPDMask, MVT::i8));
7259 }
7260
7261 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7262 ///
7263 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7264 /// the integer unit to minimize domain crossing penalties. However, for blends
7265 /// it falls back to the floating point shuffle operation with appropriate bit
7266 /// casting.
7267 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7268                                        const X86Subtarget *Subtarget,
7269                                        SelectionDAG &DAG) {
7270   SDLoc DL(Op);
7271   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7272   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7273   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7274   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7275   ArrayRef<int> Mask = SVOp->getMask();
7276   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7277
7278   if (isSingleInputShuffleMask(Mask)) {
7279     // Check for being able to broadcast a single element.
7280     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v2i64, DL, V1,
7281                                                           Mask, Subtarget, DAG))
7282       return Broadcast;
7283
7284     // Straight shuffle of a single input vector. For everything from SSE2
7285     // onward this has a single fast instruction with no scary immediates.
7286     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7287     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7288     int WidenedMask[4] = {
7289         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7290         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7291     return DAG.getNode(
7292         ISD::BITCAST, DL, MVT::v2i64,
7293         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7294                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7295   }
7296   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7297   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7298   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7299   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7300
7301   // If we have a blend of two PACKUS operations an the blend aligns with the
7302   // low and half halves, we can just merge the PACKUS operations. This is
7303   // particularly important as it lets us merge shuffles that this routine itself
7304   // creates.
7305   auto GetPackNode = [](SDValue V) {
7306     while (V.getOpcode() == ISD::BITCAST)
7307       V = V.getOperand(0);
7308
7309     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7310   };
7311   if (SDValue V1Pack = GetPackNode(V1))
7312     if (SDValue V2Pack = GetPackNode(V2))
7313       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7314                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7315                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7316                                                   : V1Pack.getOperand(1),
7317                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7318                                                   : V2Pack.getOperand(1)));
7319
7320   // Try to use shift instructions.
7321   if (SDValue Shift =
7322           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7323     return Shift;
7324
7325   // When loading a scalar and then shuffling it into a vector we can often do
7326   // the insertion cheaply.
7327   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7328           MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
7329     return Insertion;
7330   // Try inverting the insertion since for v2 masks it is easy to do and we
7331   // can't reliably sort the mask one way or the other.
7332   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7333   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7334           MVT::v2i64, DL, V2, V1, InverseMask, Subtarget, DAG))
7335     return Insertion;
7336
7337   // We have different paths for blend lowering, but they all must use the
7338   // *exact* same predicate.
7339   bool IsBlendSupported = Subtarget->hasSSE41();
7340   if (IsBlendSupported)
7341     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7342                                                   Subtarget, DAG))
7343       return Blend;
7344
7345   // Use dedicated unpack instructions for masks that match their pattern.
7346   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7347     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7348   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7349     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7350
7351   // Try to use byte rotation instructions.
7352   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7353   if (Subtarget->hasSSSE3())
7354     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7355             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7356       return Rotate;
7357
7358   // If we have direct support for blends, we should lower by decomposing into
7359   // a permute. That will be faster than the domain cross.
7360   if (IsBlendSupported)
7361     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7362                                                       Mask, DAG);
7363
7364   // We implement this with SHUFPD which is pretty lame because it will likely
7365   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7366   // However, all the alternatives are still more cycles and newer chips don't
7367   // have this problem. It would be really nice if x86 had better shuffles here.
7368   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7369   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7370   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7371                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7372 }
7373
7374 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7375 ///
7376 /// This is used to disable more specialized lowerings when the shufps lowering
7377 /// will happen to be efficient.
7378 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7379   // This routine only handles 128-bit shufps.
7380   assert(Mask.size() == 4 && "Unsupported mask size!");
7381
7382   // To lower with a single SHUFPS we need to have the low half and high half
7383   // each requiring a single input.
7384   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7385     return false;
7386   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7387     return false;
7388
7389   return true;
7390 }
7391
7392 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7393 ///
7394 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7395 /// It makes no assumptions about whether this is the *best* lowering, it simply
7396 /// uses it.
7397 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7398                                             ArrayRef<int> Mask, SDValue V1,
7399                                             SDValue V2, SelectionDAG &DAG) {
7400   SDValue LowV = V1, HighV = V2;
7401   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7402
7403   int NumV2Elements =
7404       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7405
7406   if (NumV2Elements == 1) {
7407     int V2Index =
7408         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7409         Mask.begin();
7410
7411     // Compute the index adjacent to V2Index and in the same half by toggling
7412     // the low bit.
7413     int V2AdjIndex = V2Index ^ 1;
7414
7415     if (Mask[V2AdjIndex] == -1) {
7416       // Handles all the cases where we have a single V2 element and an undef.
7417       // This will only ever happen in the high lanes because we commute the
7418       // vector otherwise.
7419       if (V2Index < 2)
7420         std::swap(LowV, HighV);
7421       NewMask[V2Index] -= 4;
7422     } else {
7423       // Handle the case where the V2 element ends up adjacent to a V1 element.
7424       // To make this work, blend them together as the first step.
7425       int V1Index = V2AdjIndex;
7426       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7427       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7428                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7429
7430       // Now proceed to reconstruct the final blend as we have the necessary
7431       // high or low half formed.
7432       if (V2Index < 2) {
7433         LowV = V2;
7434         HighV = V1;
7435       } else {
7436         HighV = V2;
7437       }
7438       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7439       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7440     }
7441   } else if (NumV2Elements == 2) {
7442     if (Mask[0] < 4 && Mask[1] < 4) {
7443       // Handle the easy case where we have V1 in the low lanes and V2 in the
7444       // high lanes.
7445       NewMask[2] -= 4;
7446       NewMask[3] -= 4;
7447     } else if (Mask[2] < 4 && Mask[3] < 4) {
7448       // We also handle the reversed case because this utility may get called
7449       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7450       // arrange things in the right direction.
7451       NewMask[0] -= 4;
7452       NewMask[1] -= 4;
7453       HighV = V1;
7454       LowV = V2;
7455     } else {
7456       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7457       // trying to place elements directly, just blend them and set up the final
7458       // shuffle to place them.
7459
7460       // The first two blend mask elements are for V1, the second two are for
7461       // V2.
7462       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7463                           Mask[2] < 4 ? Mask[2] : Mask[3],
7464                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7465                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7466       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7467                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7468
7469       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7470       // a blend.
7471       LowV = HighV = V1;
7472       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7473       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7474       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7475       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7476     }
7477   }
7478   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7479                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7480 }
7481
7482 /// \brief Lower 4-lane 32-bit floating point shuffles.
7483 ///
7484 /// Uses instructions exclusively from the floating point unit to minimize
7485 /// domain crossing penalties, as these are sufficient to implement all v4f32
7486 /// shuffles.
7487 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7488                                        const X86Subtarget *Subtarget,
7489                                        SelectionDAG &DAG) {
7490   SDLoc DL(Op);
7491   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7492   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7493   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7494   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7495   ArrayRef<int> Mask = SVOp->getMask();
7496   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7497
7498   int NumV2Elements =
7499       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7500
7501   if (NumV2Elements == 0) {
7502     // Check for being able to broadcast a single element.
7503     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f32, DL, V1,
7504                                                           Mask, Subtarget, DAG))
7505       return Broadcast;
7506
7507     // Use even/odd duplicate instructions for masks that match their pattern.
7508     if (Subtarget->hasSSE3()) {
7509       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7510         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7511       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7512         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7513     }
7514
7515     if (Subtarget->hasAVX()) {
7516       // If we have AVX, we can use VPERMILPS which will allow folding a load
7517       // into the shuffle.
7518       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7519                          getV4X86ShuffleImm8ForMask(Mask, DAG));
7520     }
7521
7522     // Otherwise, use a straight shuffle of a single input vector. We pass the
7523     // input vector to both operands to simulate this with a SHUFPS.
7524     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7525                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7526   }
7527
7528   // There are special ways we can lower some single-element blends. However, we
7529   // have custom ways we can lower more complex single-element blends below that
7530   // we defer to if both this and BLENDPS fail to match, so restrict this to
7531   // when the V2 input is targeting element 0 of the mask -- that is the fast
7532   // case here.
7533   if (NumV2Elements == 1 && Mask[0] >= 4)
7534     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
7535                                                          Mask, Subtarget, DAG))
7536       return V;
7537
7538   if (Subtarget->hasSSE41()) {
7539     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7540                                                   Subtarget, DAG))
7541       return Blend;
7542
7543     // Use INSERTPS if we can complete the shuffle efficiently.
7544     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7545       return V;
7546
7547     if (!isSingleSHUFPSMask(Mask))
7548       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7549               DL, MVT::v4f32, V1, V2, Mask, DAG))
7550         return BlendPerm;
7551   }
7552
7553   // Use dedicated unpack instructions for masks that match their pattern.
7554   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7555     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7556   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7557     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7558   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7559     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7560   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7561     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7562
7563   // Otherwise fall back to a SHUFPS lowering strategy.
7564   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7565 }
7566
7567 /// \brief Lower 4-lane i32 vector shuffles.
7568 ///
7569 /// We try to handle these with integer-domain shuffles where we can, but for
7570 /// blends we use the floating point domain blend instructions.
7571 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7572                                        const X86Subtarget *Subtarget,
7573                                        SelectionDAG &DAG) {
7574   SDLoc DL(Op);
7575   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7576   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7577   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7578   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7579   ArrayRef<int> Mask = SVOp->getMask();
7580   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7581
7582   // Whenever we can lower this as a zext, that instruction is strictly faster
7583   // than any alternative. It also allows us to fold memory operands into the
7584   // shuffle in many cases.
7585   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7586                                                          Mask, Subtarget, DAG))
7587     return ZExt;
7588
7589   int NumV2Elements =
7590       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7591
7592   if (NumV2Elements == 0) {
7593     // Check for being able to broadcast a single element.
7594     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i32, DL, V1,
7595                                                           Mask, Subtarget, DAG))
7596       return Broadcast;
7597
7598     // Straight shuffle of a single input vector. For everything from SSE2
7599     // onward this has a single fast instruction with no scary immediates.
7600     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7601     // but we aren't actually going to use the UNPCK instruction because doing
7602     // so prevents folding a load into this instruction or making a copy.
7603     const int UnpackLoMask[] = {0, 0, 1, 1};
7604     const int UnpackHiMask[] = {2, 2, 3, 3};
7605     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7606       Mask = UnpackLoMask;
7607     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7608       Mask = UnpackHiMask;
7609
7610     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7611                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7612   }
7613
7614   // Try to use shift instructions.
7615   if (SDValue Shift =
7616           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7617     return Shift;
7618
7619   // There are special ways we can lower some single-element blends.
7620   if (NumV2Elements == 1)
7621     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
7622                                                          Mask, Subtarget, DAG))
7623       return V;
7624
7625   // We have different paths for blend lowering, but they all must use the
7626   // *exact* same predicate.
7627   bool IsBlendSupported = Subtarget->hasSSE41();
7628   if (IsBlendSupported)
7629     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7630                                                   Subtarget, DAG))
7631       return Blend;
7632
7633   if (SDValue Masked =
7634           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7635     return Masked;
7636
7637   // Use dedicated unpack instructions for masks that match their pattern.
7638   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7639     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7640   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7641     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7642   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7643     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7644   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7645     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7646
7647   // Try to use byte rotation instructions.
7648   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7649   if (Subtarget->hasSSSE3())
7650     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7651             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7652       return Rotate;
7653
7654   // If we have direct support for blends, we should lower by decomposing into
7655   // a permute. That will be faster than the domain cross.
7656   if (IsBlendSupported)
7657     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7658                                                       Mask, DAG);
7659
7660   // Try to lower by permuting the inputs into an unpack instruction.
7661   if (SDValue Unpack =
7662           lowerVectorShuffleAsUnpack(MVT::v4i32, DL, V1, V2, Mask, DAG))
7663     return Unpack;
7664
7665   // We implement this with SHUFPS because it can blend from two vectors.
7666   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7667   // up the inputs, bypassing domain shift penalties that we would encur if we
7668   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7669   // relevant.
7670   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7671                      DAG.getVectorShuffle(
7672                          MVT::v4f32, DL,
7673                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7674                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7675 }
7676
7677 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7678 /// shuffle lowering, and the most complex part.
7679 ///
7680 /// The lowering strategy is to try to form pairs of input lanes which are
7681 /// targeted at the same half of the final vector, and then use a dword shuffle
7682 /// to place them onto the right half, and finally unpack the paired lanes into
7683 /// their final position.
7684 ///
7685 /// The exact breakdown of how to form these dword pairs and align them on the
7686 /// correct sides is really tricky. See the comments within the function for
7687 /// more of the details.
7688 static SDValue lowerV8I16SingleInputVectorShuffle(
7689     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7690     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7691   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7692   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7693   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7694
7695   SmallVector<int, 4> LoInputs;
7696   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7697                [](int M) { return M >= 0; });
7698   std::sort(LoInputs.begin(), LoInputs.end());
7699   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7700   SmallVector<int, 4> HiInputs;
7701   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7702                [](int M) { return M >= 0; });
7703   std::sort(HiInputs.begin(), HiInputs.end());
7704   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7705   int NumLToL =
7706       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7707   int NumHToL = LoInputs.size() - NumLToL;
7708   int NumLToH =
7709       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7710   int NumHToH = HiInputs.size() - NumLToH;
7711   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7712   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7713   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7714   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7715
7716   // Check for being able to broadcast a single element.
7717   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i16, DL, V,
7718                                                         Mask, Subtarget, DAG))
7719     return Broadcast;
7720
7721   // Try to use shift instructions.
7722   if (SDValue Shift =
7723           lowerVectorShuffleAsShift(DL, MVT::v8i16, V, V, Mask, DAG))
7724     return Shift;
7725
7726   // Use dedicated unpack instructions for masks that match their pattern.
7727   if (isShuffleEquivalent(V, V, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
7728     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
7729   if (isShuffleEquivalent(V, V, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
7730     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
7731
7732   // Try to use byte rotation instructions.
7733   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7734           DL, MVT::v8i16, V, V, Mask, Subtarget, DAG))
7735     return Rotate;
7736
7737   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7738   // such inputs we can swap two of the dwords across the half mark and end up
7739   // with <=2 inputs to each half in each half. Once there, we can fall through
7740   // to the generic code below. For example:
7741   //
7742   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7743   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7744   //
7745   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7746   // and an existing 2-into-2 on the other half. In this case we may have to
7747   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7748   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7749   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7750   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7751   // half than the one we target for fixing) will be fixed when we re-enter this
7752   // path. We will also combine away any sequence of PSHUFD instructions that
7753   // result into a single instruction. Here is an example of the tricky case:
7754   //
7755   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7756   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7757   //
7758   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7759   //
7760   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7761   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7762   //
7763   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7764   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7765   //
7766   // The result is fine to be handled by the generic logic.
7767   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7768                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7769                           int AOffset, int BOffset) {
7770     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7771            "Must call this with A having 3 or 1 inputs from the A half.");
7772     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7773            "Must call this with B having 1 or 3 inputs from the B half.");
7774     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7775            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7776
7777     // Compute the index of dword with only one word among the three inputs in
7778     // a half by taking the sum of the half with three inputs and subtracting
7779     // the sum of the actual three inputs. The difference is the remaining
7780     // slot.
7781     int ADWord, BDWord;
7782     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7783     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7784     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7785     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7786     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7787     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7788     int TripleNonInputIdx =
7789         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7790     TripleDWord = TripleNonInputIdx / 2;
7791
7792     // We use xor with one to compute the adjacent DWord to whichever one the
7793     // OneInput is in.
7794     OneInputDWord = (OneInput / 2) ^ 1;
7795
7796     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7797     // and BToA inputs. If there is also such a problem with the BToB and AToB
7798     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7799     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7800     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7801     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7802       // Compute how many inputs will be flipped by swapping these DWords. We
7803       // need
7804       // to balance this to ensure we don't form a 3-1 shuffle in the other
7805       // half.
7806       int NumFlippedAToBInputs =
7807           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7808           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7809       int NumFlippedBToBInputs =
7810           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7811           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7812       if ((NumFlippedAToBInputs == 1 &&
7813            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7814           (NumFlippedBToBInputs == 1 &&
7815            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7816         // We choose whether to fix the A half or B half based on whether that
7817         // half has zero flipped inputs. At zero, we may not be able to fix it
7818         // with that half. We also bias towards fixing the B half because that
7819         // will more commonly be the high half, and we have to bias one way.
7820         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7821                                                        ArrayRef<int> Inputs) {
7822           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7823           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7824                                          PinnedIdx ^ 1) != Inputs.end();
7825           // Determine whether the free index is in the flipped dword or the
7826           // unflipped dword based on where the pinned index is. We use this bit
7827           // in an xor to conditionally select the adjacent dword.
7828           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7829           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7830                                              FixFreeIdx) != Inputs.end();
7831           if (IsFixIdxInput == IsFixFreeIdxInput)
7832             FixFreeIdx += 1;
7833           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7834                                         FixFreeIdx) != Inputs.end();
7835           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7836                  "We need to be changing the number of flipped inputs!");
7837           int PSHUFHalfMask[] = {0, 1, 2, 3};
7838           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7839           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7840                           MVT::v8i16, V,
7841                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7842
7843           for (int &M : Mask)
7844             if (M != -1 && M == FixIdx)
7845               M = FixFreeIdx;
7846             else if (M != -1 && M == FixFreeIdx)
7847               M = FixIdx;
7848         };
7849         if (NumFlippedBToBInputs != 0) {
7850           int BPinnedIdx =
7851               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7852           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7853         } else {
7854           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7855           int APinnedIdx =
7856               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7857           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7858         }
7859       }
7860     }
7861
7862     int PSHUFDMask[] = {0, 1, 2, 3};
7863     PSHUFDMask[ADWord] = BDWord;
7864     PSHUFDMask[BDWord] = ADWord;
7865     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7866                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7867                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7868                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7869
7870     // Adjust the mask to match the new locations of A and B.
7871     for (int &M : Mask)
7872       if (M != -1 && M/2 == ADWord)
7873         M = 2 * BDWord + M % 2;
7874       else if (M != -1 && M/2 == BDWord)
7875         M = 2 * ADWord + M % 2;
7876
7877     // Recurse back into this routine to re-compute state now that this isn't
7878     // a 3 and 1 problem.
7879     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7880                                 Mask);
7881   };
7882   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7883     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7884   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7885     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7886
7887   // At this point there are at most two inputs to the low and high halves from
7888   // each half. That means the inputs can always be grouped into dwords and
7889   // those dwords can then be moved to the correct half with a dword shuffle.
7890   // We use at most one low and one high word shuffle to collect these paired
7891   // inputs into dwords, and finally a dword shuffle to place them.
7892   int PSHUFLMask[4] = {-1, -1, -1, -1};
7893   int PSHUFHMask[4] = {-1, -1, -1, -1};
7894   int PSHUFDMask[4] = {-1, -1, -1, -1};
7895
7896   // First fix the masks for all the inputs that are staying in their
7897   // original halves. This will then dictate the targets of the cross-half
7898   // shuffles.
7899   auto fixInPlaceInputs =
7900       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7901                     MutableArrayRef<int> SourceHalfMask,
7902                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7903     if (InPlaceInputs.empty())
7904       return;
7905     if (InPlaceInputs.size() == 1) {
7906       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7907           InPlaceInputs[0] - HalfOffset;
7908       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7909       return;
7910     }
7911     if (IncomingInputs.empty()) {
7912       // Just fix all of the in place inputs.
7913       for (int Input : InPlaceInputs) {
7914         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7915         PSHUFDMask[Input / 2] = Input / 2;
7916       }
7917       return;
7918     }
7919
7920     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7921     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7922         InPlaceInputs[0] - HalfOffset;
7923     // Put the second input next to the first so that they are packed into
7924     // a dword. We find the adjacent index by toggling the low bit.
7925     int AdjIndex = InPlaceInputs[0] ^ 1;
7926     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7927     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7928     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7929   };
7930   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7931   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7932
7933   // Now gather the cross-half inputs and place them into a free dword of
7934   // their target half.
7935   // FIXME: This operation could almost certainly be simplified dramatically to
7936   // look more like the 3-1 fixing operation.
7937   auto moveInputsToRightHalf = [&PSHUFDMask](
7938       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7939       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7940       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7941       int DestOffset) {
7942     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7943       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7944     };
7945     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7946                                                int Word) {
7947       int LowWord = Word & ~1;
7948       int HighWord = Word | 1;
7949       return isWordClobbered(SourceHalfMask, LowWord) ||
7950              isWordClobbered(SourceHalfMask, HighWord);
7951     };
7952
7953     if (IncomingInputs.empty())
7954       return;
7955
7956     if (ExistingInputs.empty()) {
7957       // Map any dwords with inputs from them into the right half.
7958       for (int Input : IncomingInputs) {
7959         // If the source half mask maps over the inputs, turn those into
7960         // swaps and use the swapped lane.
7961         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7962           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7963             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7964                 Input - SourceOffset;
7965             // We have to swap the uses in our half mask in one sweep.
7966             for (int &M : HalfMask)
7967               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7968                 M = Input;
7969               else if (M == Input)
7970                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7971           } else {
7972             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7973                        Input - SourceOffset &&
7974                    "Previous placement doesn't match!");
7975           }
7976           // Note that this correctly re-maps both when we do a swap and when
7977           // we observe the other side of the swap above. We rely on that to
7978           // avoid swapping the members of the input list directly.
7979           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7980         }
7981
7982         // Map the input's dword into the correct half.
7983         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7984           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7985         else
7986           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7987                      Input / 2 &&
7988                  "Previous placement doesn't match!");
7989       }
7990
7991       // And just directly shift any other-half mask elements to be same-half
7992       // as we will have mirrored the dword containing the element into the
7993       // same position within that half.
7994       for (int &M : HalfMask)
7995         if (M >= SourceOffset && M < SourceOffset + 4) {
7996           M = M - SourceOffset + DestOffset;
7997           assert(M >= 0 && "This should never wrap below zero!");
7998         }
7999       return;
8000     }
8001
8002     // Ensure we have the input in a viable dword of its current half. This
8003     // is particularly tricky because the original position may be clobbered
8004     // by inputs being moved and *staying* in that half.
8005     if (IncomingInputs.size() == 1) {
8006       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8007         int InputFixed = std::find(std::begin(SourceHalfMask),
8008                                    std::end(SourceHalfMask), -1) -
8009                          std::begin(SourceHalfMask) + SourceOffset;
8010         SourceHalfMask[InputFixed - SourceOffset] =
8011             IncomingInputs[0] - SourceOffset;
8012         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8013                      InputFixed);
8014         IncomingInputs[0] = InputFixed;
8015       }
8016     } else if (IncomingInputs.size() == 2) {
8017       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8018           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8019         // We have two non-adjacent or clobbered inputs we need to extract from
8020         // the source half. To do this, we need to map them into some adjacent
8021         // dword slot in the source mask.
8022         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8023                               IncomingInputs[1] - SourceOffset};
8024
8025         // If there is a free slot in the source half mask adjacent to one of
8026         // the inputs, place the other input in it. We use (Index XOR 1) to
8027         // compute an adjacent index.
8028         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8029             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8030           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8031           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8032           InputsFixed[1] = InputsFixed[0] ^ 1;
8033         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8034                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8035           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8036           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8037           InputsFixed[0] = InputsFixed[1] ^ 1;
8038         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8039                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8040           // The two inputs are in the same DWord but it is clobbered and the
8041           // adjacent DWord isn't used at all. Move both inputs to the free
8042           // slot.
8043           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8044           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8045           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8046           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8047         } else {
8048           // The only way we hit this point is if there is no clobbering
8049           // (because there are no off-half inputs to this half) and there is no
8050           // free slot adjacent to one of the inputs. In this case, we have to
8051           // swap an input with a non-input.
8052           for (int i = 0; i < 4; ++i)
8053             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8054                    "We can't handle any clobbers here!");
8055           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8056                  "Cannot have adjacent inputs here!");
8057
8058           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8059           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8060
8061           // We also have to update the final source mask in this case because
8062           // it may need to undo the above swap.
8063           for (int &M : FinalSourceHalfMask)
8064             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8065               M = InputsFixed[1] + SourceOffset;
8066             else if (M == InputsFixed[1] + SourceOffset)
8067               M = (InputsFixed[0] ^ 1) + SourceOffset;
8068
8069           InputsFixed[1] = InputsFixed[0] ^ 1;
8070         }
8071
8072         // Point everything at the fixed inputs.
8073         for (int &M : HalfMask)
8074           if (M == IncomingInputs[0])
8075             M = InputsFixed[0] + SourceOffset;
8076           else if (M == IncomingInputs[1])
8077             M = InputsFixed[1] + SourceOffset;
8078
8079         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8080         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8081       }
8082     } else {
8083       llvm_unreachable("Unhandled input size!");
8084     }
8085
8086     // Now hoist the DWord down to the right half.
8087     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8088     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8089     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8090     for (int &M : HalfMask)
8091       for (int Input : IncomingInputs)
8092         if (M == Input)
8093           M = FreeDWord * 2 + Input % 2;
8094   };
8095   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8096                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8097   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8098                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8099
8100   // Now enact all the shuffles we've computed to move the inputs into their
8101   // target half.
8102   if (!isNoopShuffleMask(PSHUFLMask))
8103     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8104                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8105   if (!isNoopShuffleMask(PSHUFHMask))
8106     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8107                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8108   if (!isNoopShuffleMask(PSHUFDMask))
8109     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8110                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8111                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8112                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8113
8114   // At this point, each half should contain all its inputs, and we can then
8115   // just shuffle them into their final position.
8116   assert(std::count_if(LoMask.begin(), LoMask.end(),
8117                        [](int M) { return M >= 4; }) == 0 &&
8118          "Failed to lift all the high half inputs to the low mask!");
8119   assert(std::count_if(HiMask.begin(), HiMask.end(),
8120                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8121          "Failed to lift all the low half inputs to the high mask!");
8122
8123   // Do a half shuffle for the low mask.
8124   if (!isNoopShuffleMask(LoMask))
8125     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8126                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8127
8128   // Do a half shuffle with the high mask after shifting its values down.
8129   for (int &M : HiMask)
8130     if (M >= 0)
8131       M -= 4;
8132   if (!isNoopShuffleMask(HiMask))
8133     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8134                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8135
8136   return V;
8137 }
8138
8139 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8140 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8141                                           SDValue V2, ArrayRef<int> Mask,
8142                                           SelectionDAG &DAG, bool &V1InUse,
8143                                           bool &V2InUse) {
8144   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8145   SDValue V1Mask[16];
8146   SDValue V2Mask[16];
8147   V1InUse = false;
8148   V2InUse = false;
8149
8150   int Size = Mask.size();
8151   int Scale = 16 / Size;
8152   for (int i = 0; i < 16; ++i) {
8153     if (Mask[i / Scale] == -1) {
8154       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8155     } else {
8156       const int ZeroMask = 0x80;
8157       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8158                                           : ZeroMask;
8159       int V2Idx = Mask[i / Scale] < Size
8160                       ? ZeroMask
8161                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8162       if (Zeroable[i / Scale])
8163         V1Idx = V2Idx = ZeroMask;
8164       V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8165       V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8166       V1InUse |= (ZeroMask != V1Idx);
8167       V2InUse |= (ZeroMask != V2Idx);
8168     }
8169   }
8170
8171   if (V1InUse)
8172     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8173                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8174                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8175   if (V2InUse)
8176     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8177                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8178                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8179
8180   // If we need shuffled inputs from both, blend the two.
8181   SDValue V;
8182   if (V1InUse && V2InUse)
8183     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8184   else
8185     V = V1InUse ? V1 : V2;
8186
8187   // Cast the result back to the correct type.
8188   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8189 }
8190
8191 /// \brief Generic lowering of 8-lane i16 shuffles.
8192 ///
8193 /// This handles both single-input shuffles and combined shuffle/blends with
8194 /// two inputs. The single input shuffles are immediately delegated to
8195 /// a dedicated lowering routine.
8196 ///
8197 /// The blends are lowered in one of three fundamental ways. If there are few
8198 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8199 /// of the input is significantly cheaper when lowered as an interleaving of
8200 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8201 /// halves of the inputs separately (making them have relatively few inputs)
8202 /// and then concatenate them.
8203 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8204                                        const X86Subtarget *Subtarget,
8205                                        SelectionDAG &DAG) {
8206   SDLoc DL(Op);
8207   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8208   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8209   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8210   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8211   ArrayRef<int> OrigMask = SVOp->getMask();
8212   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8213                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8214   MutableArrayRef<int> Mask(MaskStorage);
8215
8216   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8217
8218   // Whenever we can lower this as a zext, that instruction is strictly faster
8219   // than any alternative.
8220   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8221           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8222     return ZExt;
8223
8224   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8225   (void)isV1;
8226   auto isV2 = [](int M) { return M >= 8; };
8227
8228   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8229
8230   if (NumV2Inputs == 0)
8231     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
8232
8233   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8234          "All single-input shuffles should be canonicalized to be V1-input "
8235          "shuffles.");
8236
8237   // Try to use shift instructions.
8238   if (SDValue Shift =
8239           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8240     return Shift;
8241
8242   // There are special ways we can lower some single-element blends.
8243   if (NumV2Inputs == 1)
8244     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
8245                                                          Mask, Subtarget, DAG))
8246       return V;
8247
8248   // We have different paths for blend lowering, but they all must use the
8249   // *exact* same predicate.
8250   bool IsBlendSupported = Subtarget->hasSSE41();
8251   if (IsBlendSupported)
8252     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8253                                                   Subtarget, DAG))
8254       return Blend;
8255
8256   if (SDValue Masked =
8257           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8258     return Masked;
8259
8260   // Use dedicated unpack instructions for masks that match their pattern.
8261   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8262     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8263   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8264     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8265
8266   // Try to use byte rotation instructions.
8267   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8268           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8269     return Rotate;
8270
8271   if (SDValue BitBlend =
8272           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8273     return BitBlend;
8274
8275   if (SDValue Unpack =
8276           lowerVectorShuffleAsUnpack(MVT::v8i16, DL, V1, V2, Mask, DAG))
8277     return Unpack;
8278
8279   // If we can't directly blend but can use PSHUFB, that will be better as it
8280   // can both shuffle and set up the inefficient blend.
8281   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8282     bool V1InUse, V2InUse;
8283     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8284                                       V1InUse, V2InUse);
8285   }
8286
8287   // We can always bit-blend if we have to so the fallback strategy is to
8288   // decompose into single-input permutes and blends.
8289   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8290                                                       Mask, DAG);
8291 }
8292
8293 /// \brief Check whether a compaction lowering can be done by dropping even
8294 /// elements and compute how many times even elements must be dropped.
8295 ///
8296 /// This handles shuffles which take every Nth element where N is a power of
8297 /// two. Example shuffle masks:
8298 ///
8299 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8300 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8301 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8302 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8303 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8304 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8305 ///
8306 /// Any of these lanes can of course be undef.
8307 ///
8308 /// This routine only supports N <= 3.
8309 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8310 /// for larger N.
8311 ///
8312 /// \returns N above, or the number of times even elements must be dropped if
8313 /// there is such a number. Otherwise returns zero.
8314 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8315   // Figure out whether we're looping over two inputs or just one.
8316   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8317
8318   // The modulus for the shuffle vector entries is based on whether this is
8319   // a single input or not.
8320   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8321   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8322          "We should only be called with masks with a power-of-2 size!");
8323
8324   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8325
8326   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8327   // and 2^3 simultaneously. This is because we may have ambiguity with
8328   // partially undef inputs.
8329   bool ViableForN[3] = {true, true, true};
8330
8331   for (int i = 0, e = Mask.size(); i < e; ++i) {
8332     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8333     // want.
8334     if (Mask[i] == -1)
8335       continue;
8336
8337     bool IsAnyViable = false;
8338     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8339       if (ViableForN[j]) {
8340         uint64_t N = j + 1;
8341
8342         // The shuffle mask must be equal to (i * 2^N) % M.
8343         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8344           IsAnyViable = true;
8345         else
8346           ViableForN[j] = false;
8347       }
8348     // Early exit if we exhaust the possible powers of two.
8349     if (!IsAnyViable)
8350       break;
8351   }
8352
8353   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8354     if (ViableForN[j])
8355       return j + 1;
8356
8357   // Return 0 as there is no viable power of two.
8358   return 0;
8359 }
8360
8361 /// \brief Generic lowering of v16i8 shuffles.
8362 ///
8363 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8364 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8365 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8366 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8367 /// back together.
8368 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8369                                        const X86Subtarget *Subtarget,
8370                                        SelectionDAG &DAG) {
8371   SDLoc DL(Op);
8372   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8373   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8374   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8375   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8376   ArrayRef<int> Mask = SVOp->getMask();
8377   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8378
8379   // Try to use shift instructions.
8380   if (SDValue Shift =
8381           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8382     return Shift;
8383
8384   // Try to use byte rotation instructions.
8385   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8386           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8387     return Rotate;
8388
8389   // Try to use a zext lowering.
8390   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8391           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8392     return ZExt;
8393
8394   int NumV2Elements =
8395       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8396
8397   // For single-input shuffles, there are some nicer lowering tricks we can use.
8398   if (NumV2Elements == 0) {
8399     // Check for being able to broadcast a single element.
8400     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i8, DL, V1,
8401                                                           Mask, Subtarget, DAG))
8402       return Broadcast;
8403
8404     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8405     // Notably, this handles splat and partial-splat shuffles more efficiently.
8406     // However, it only makes sense if the pre-duplication shuffle simplifies
8407     // things significantly. Currently, this means we need to be able to
8408     // express the pre-duplication shuffle as an i16 shuffle.
8409     //
8410     // FIXME: We should check for other patterns which can be widened into an
8411     // i16 shuffle as well.
8412     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8413       for (int i = 0; i < 16; i += 2)
8414         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8415           return false;
8416
8417       return true;
8418     };
8419     auto tryToWidenViaDuplication = [&]() -> SDValue {
8420       if (!canWidenViaDuplication(Mask))
8421         return SDValue();
8422       SmallVector<int, 4> LoInputs;
8423       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8424                    [](int M) { return M >= 0 && M < 8; });
8425       std::sort(LoInputs.begin(), LoInputs.end());
8426       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8427                      LoInputs.end());
8428       SmallVector<int, 4> HiInputs;
8429       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8430                    [](int M) { return M >= 8; });
8431       std::sort(HiInputs.begin(), HiInputs.end());
8432       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8433                      HiInputs.end());
8434
8435       bool TargetLo = LoInputs.size() >= HiInputs.size();
8436       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8437       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8438
8439       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8440       SmallDenseMap<int, int, 8> LaneMap;
8441       for (int I : InPlaceInputs) {
8442         PreDupI16Shuffle[I/2] = I/2;
8443         LaneMap[I] = I;
8444       }
8445       int j = TargetLo ? 0 : 4, je = j + 4;
8446       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8447         // Check if j is already a shuffle of this input. This happens when
8448         // there are two adjacent bytes after we move the low one.
8449         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8450           // If we haven't yet mapped the input, search for a slot into which
8451           // we can map it.
8452           while (j < je && PreDupI16Shuffle[j] != -1)
8453             ++j;
8454
8455           if (j == je)
8456             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8457             return SDValue();
8458
8459           // Map this input with the i16 shuffle.
8460           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8461         }
8462
8463         // Update the lane map based on the mapping we ended up with.
8464         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8465       }
8466       V1 = DAG.getNode(
8467           ISD::BITCAST, DL, MVT::v16i8,
8468           DAG.getVectorShuffle(MVT::v8i16, DL,
8469                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8470                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8471
8472       // Unpack the bytes to form the i16s that will be shuffled into place.
8473       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8474                        MVT::v16i8, V1, V1);
8475
8476       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8477       for (int i = 0; i < 16; ++i)
8478         if (Mask[i] != -1) {
8479           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8480           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8481           if (PostDupI16Shuffle[i / 2] == -1)
8482             PostDupI16Shuffle[i / 2] = MappedMask;
8483           else
8484             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8485                    "Conflicting entrties in the original shuffle!");
8486         }
8487       return DAG.getNode(
8488           ISD::BITCAST, DL, MVT::v16i8,
8489           DAG.getVectorShuffle(MVT::v8i16, DL,
8490                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8491                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8492     };
8493     if (SDValue V = tryToWidenViaDuplication())
8494       return V;
8495   }
8496
8497   // Use dedicated unpack instructions for masks that match their pattern.
8498   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8499                                          0, 16, 1, 17, 2, 18, 3, 19,
8500                                          // High half.
8501                                          4, 20, 5, 21, 6, 22, 7, 23}))
8502     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8503   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8504                                          8, 24, 9, 25, 10, 26, 11, 27,
8505                                          // High half.
8506                                          12, 28, 13, 29, 14, 30, 15, 31}))
8507     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8508
8509   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8510   // with PSHUFB. It is important to do this before we attempt to generate any
8511   // blends but after all of the single-input lowerings. If the single input
8512   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8513   // want to preserve that and we can DAG combine any longer sequences into
8514   // a PSHUFB in the end. But once we start blending from multiple inputs,
8515   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8516   // and there are *very* few patterns that would actually be faster than the
8517   // PSHUFB approach because of its ability to zero lanes.
8518   //
8519   // FIXME: The only exceptions to the above are blends which are exact
8520   // interleavings with direct instructions supporting them. We currently don't
8521   // handle those well here.
8522   if (Subtarget->hasSSSE3()) {
8523     bool V1InUse = false;
8524     bool V2InUse = false;
8525
8526     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8527                                                 DAG, V1InUse, V2InUse);
8528
8529     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8530     // do so. This avoids using them to handle blends-with-zero which is
8531     // important as a single pshufb is significantly faster for that.
8532     if (V1InUse && V2InUse) {
8533       if (Subtarget->hasSSE41())
8534         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8535                                                       Mask, Subtarget, DAG))
8536           return Blend;
8537
8538       // We can use an unpack to do the blending rather than an or in some
8539       // cases. Even though the or may be (very minorly) more efficient, we
8540       // preference this lowering because there are common cases where part of
8541       // the complexity of the shuffles goes away when we do the final blend as
8542       // an unpack.
8543       // FIXME: It might be worth trying to detect if the unpack-feeding
8544       // shuffles will both be pshufb, in which case we shouldn't bother with
8545       // this.
8546       if (SDValue Unpack =
8547               lowerVectorShuffleAsUnpack(MVT::v16i8, DL, V1, V2, Mask, DAG))
8548         return Unpack;
8549     }
8550
8551     return PSHUFB;
8552   }
8553
8554   // There are special ways we can lower some single-element blends.
8555   if (NumV2Elements == 1)
8556     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
8557                                                          Mask, Subtarget, DAG))
8558       return V;
8559
8560   if (SDValue BitBlend =
8561           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8562     return BitBlend;
8563
8564   // Check whether a compaction lowering can be done. This handles shuffles
8565   // which take every Nth element for some even N. See the helper function for
8566   // details.
8567   //
8568   // We special case these as they can be particularly efficiently handled with
8569   // the PACKUSB instruction on x86 and they show up in common patterns of
8570   // rearranging bytes to truncate wide elements.
8571   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8572     // NumEvenDrops is the power of two stride of the elements. Another way of
8573     // thinking about it is that we need to drop the even elements this many
8574     // times to get the original input.
8575     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8576
8577     // First we need to zero all the dropped bytes.
8578     assert(NumEvenDrops <= 3 &&
8579            "No support for dropping even elements more than 3 times.");
8580     // We use the mask type to pick which bytes are preserved based on how many
8581     // elements are dropped.
8582     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8583     SDValue ByteClearMask =
8584         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8585                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8586     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8587     if (!IsSingleInput)
8588       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8589
8590     // Now pack things back together.
8591     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8592     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8593     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8594     for (int i = 1; i < NumEvenDrops; ++i) {
8595       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8596       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8597     }
8598
8599     return Result;
8600   }
8601
8602   // Handle multi-input cases by blending single-input shuffles.
8603   if (NumV2Elements > 0)
8604     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8605                                                       Mask, DAG);
8606
8607   // The fallback path for single-input shuffles widens this into two v8i16
8608   // vectors with unpacks, shuffles those, and then pulls them back together
8609   // with a pack.
8610   SDValue V = V1;
8611
8612   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8613   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8614   for (int i = 0; i < 16; ++i)
8615     if (Mask[i] >= 0)
8616       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8617
8618   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8619
8620   SDValue VLoHalf, VHiHalf;
8621   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8622   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8623   // i16s.
8624   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8625                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8626       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8627                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8628     // Use a mask to drop the high bytes.
8629     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8630     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8631                      DAG.getConstant(0x00FF, MVT::v8i16));
8632
8633     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8634     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8635
8636     // Squash the masks to point directly into VLoHalf.
8637     for (int &M : LoBlendMask)
8638       if (M >= 0)
8639         M /= 2;
8640     for (int &M : HiBlendMask)
8641       if (M >= 0)
8642         M /= 2;
8643   } else {
8644     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8645     // VHiHalf so that we can blend them as i16s.
8646     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8647                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8648     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8649                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8650   }
8651
8652   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8653   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8654
8655   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8656 }
8657
8658 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8659 ///
8660 /// This routine breaks down the specific type of 128-bit shuffle and
8661 /// dispatches to the lowering routines accordingly.
8662 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8663                                         MVT VT, const X86Subtarget *Subtarget,
8664                                         SelectionDAG &DAG) {
8665   switch (VT.SimpleTy) {
8666   case MVT::v2i64:
8667     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8668   case MVT::v2f64:
8669     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8670   case MVT::v4i32:
8671     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8672   case MVT::v4f32:
8673     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8674   case MVT::v8i16:
8675     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8676   case MVT::v16i8:
8677     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8678
8679   default:
8680     llvm_unreachable("Unimplemented!");
8681   }
8682 }
8683
8684 /// \brief Helper function to test whether a shuffle mask could be
8685 /// simplified by widening the elements being shuffled.
8686 ///
8687 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8688 /// leaves it in an unspecified state.
8689 ///
8690 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8691 /// shuffle masks. The latter have the special property of a '-2' representing
8692 /// a zero-ed lane of a vector.
8693 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8694                                     SmallVectorImpl<int> &WidenedMask) {
8695   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8696     // If both elements are undef, its trivial.
8697     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8698       WidenedMask.push_back(SM_SentinelUndef);
8699       continue;
8700     }
8701
8702     // Check for an undef mask and a mask value properly aligned to fit with
8703     // a pair of values. If we find such a case, use the non-undef mask's value.
8704     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8705       WidenedMask.push_back(Mask[i + 1] / 2);
8706       continue;
8707     }
8708     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8709       WidenedMask.push_back(Mask[i] / 2);
8710       continue;
8711     }
8712
8713     // When zeroing, we need to spread the zeroing across both lanes to widen.
8714     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8715       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8716           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8717         WidenedMask.push_back(SM_SentinelZero);
8718         continue;
8719       }
8720       return false;
8721     }
8722
8723     // Finally check if the two mask values are adjacent and aligned with
8724     // a pair.
8725     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8726       WidenedMask.push_back(Mask[i] / 2);
8727       continue;
8728     }
8729
8730     // Otherwise we can't safely widen the elements used in this shuffle.
8731     return false;
8732   }
8733   assert(WidenedMask.size() == Mask.size() / 2 &&
8734          "Incorrect size of mask after widening the elements!");
8735
8736   return true;
8737 }
8738
8739 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8740 ///
8741 /// This routine just extracts two subvectors, shuffles them independently, and
8742 /// then concatenates them back together. This should work effectively with all
8743 /// AVX vector shuffle types.
8744 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8745                                           SDValue V2, ArrayRef<int> Mask,
8746                                           SelectionDAG &DAG) {
8747   assert(VT.getSizeInBits() >= 256 &&
8748          "Only for 256-bit or wider vector shuffles!");
8749   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8750   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8751
8752   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8753   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8754
8755   int NumElements = VT.getVectorNumElements();
8756   int SplitNumElements = NumElements / 2;
8757   MVT ScalarVT = VT.getScalarType();
8758   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8759
8760   // Rather than splitting build-vectors, just build two narrower build
8761   // vectors. This helps shuffling with splats and zeros.
8762   auto SplitVector = [&](SDValue V) {
8763     while (V.getOpcode() == ISD::BITCAST)
8764       V = V->getOperand(0);
8765
8766     MVT OrigVT = V.getSimpleValueType();
8767     int OrigNumElements = OrigVT.getVectorNumElements();
8768     int OrigSplitNumElements = OrigNumElements / 2;
8769     MVT OrigScalarVT = OrigVT.getScalarType();
8770     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8771
8772     SDValue LoV, HiV;
8773
8774     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8775     if (!BV) {
8776       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8777                         DAG.getIntPtrConstant(0));
8778       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8779                         DAG.getIntPtrConstant(OrigSplitNumElements));
8780     } else {
8781
8782       SmallVector<SDValue, 16> LoOps, HiOps;
8783       for (int i = 0; i < OrigSplitNumElements; ++i) {
8784         LoOps.push_back(BV->getOperand(i));
8785         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8786       }
8787       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8788       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8789     }
8790     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8791                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8792   };
8793
8794   SDValue LoV1, HiV1, LoV2, HiV2;
8795   std::tie(LoV1, HiV1) = SplitVector(V1);
8796   std::tie(LoV2, HiV2) = SplitVector(V2);
8797
8798   // Now create two 4-way blends of these half-width vectors.
8799   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8800     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8801     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8802     for (int i = 0; i < SplitNumElements; ++i) {
8803       int M = HalfMask[i];
8804       if (M >= NumElements) {
8805         if (M >= NumElements + SplitNumElements)
8806           UseHiV2 = true;
8807         else
8808           UseLoV2 = true;
8809         V2BlendMask.push_back(M - NumElements);
8810         V1BlendMask.push_back(-1);
8811         BlendMask.push_back(SplitNumElements + i);
8812       } else if (M >= 0) {
8813         if (M >= SplitNumElements)
8814           UseHiV1 = true;
8815         else
8816           UseLoV1 = true;
8817         V2BlendMask.push_back(-1);
8818         V1BlendMask.push_back(M);
8819         BlendMask.push_back(i);
8820       } else {
8821         V2BlendMask.push_back(-1);
8822         V1BlendMask.push_back(-1);
8823         BlendMask.push_back(-1);
8824       }
8825     }
8826
8827     // Because the lowering happens after all combining takes place, we need to
8828     // manually combine these blend masks as much as possible so that we create
8829     // a minimal number of high-level vector shuffle nodes.
8830
8831     // First try just blending the halves of V1 or V2.
8832     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8833       return DAG.getUNDEF(SplitVT);
8834     if (!UseLoV2 && !UseHiV2)
8835       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8836     if (!UseLoV1 && !UseHiV1)
8837       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8838
8839     SDValue V1Blend, V2Blend;
8840     if (UseLoV1 && UseHiV1) {
8841       V1Blend =
8842         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8843     } else {
8844       // We only use half of V1 so map the usage down into the final blend mask.
8845       V1Blend = UseLoV1 ? LoV1 : HiV1;
8846       for (int i = 0; i < SplitNumElements; ++i)
8847         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8848           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8849     }
8850     if (UseLoV2 && UseHiV2) {
8851       V2Blend =
8852         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8853     } else {
8854       // We only use half of V2 so map the usage down into the final blend mask.
8855       V2Blend = UseLoV2 ? LoV2 : HiV2;
8856       for (int i = 0; i < SplitNumElements; ++i)
8857         if (BlendMask[i] >= SplitNumElements)
8858           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8859     }
8860     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8861   };
8862   SDValue Lo = HalfBlend(LoMask);
8863   SDValue Hi = HalfBlend(HiMask);
8864   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8865 }
8866
8867 /// \brief Either split a vector in halves or decompose the shuffles and the
8868 /// blend.
8869 ///
8870 /// This is provided as a good fallback for many lowerings of non-single-input
8871 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8872 /// between splitting the shuffle into 128-bit components and stitching those
8873 /// back together vs. extracting the single-input shuffles and blending those
8874 /// results.
8875 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8876                                                 SDValue V2, ArrayRef<int> Mask,
8877                                                 SelectionDAG &DAG) {
8878   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8879                                             "lower single-input shuffles as it "
8880                                             "could then recurse on itself.");
8881   int Size = Mask.size();
8882
8883   // If this can be modeled as a broadcast of two elements followed by a blend,
8884   // prefer that lowering. This is especially important because broadcasts can
8885   // often fold with memory operands.
8886   auto DoBothBroadcast = [&] {
8887     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
8888     for (int M : Mask)
8889       if (M >= Size) {
8890         if (V2BroadcastIdx == -1)
8891           V2BroadcastIdx = M - Size;
8892         else if (M - Size != V2BroadcastIdx)
8893           return false;
8894       } else if (M >= 0) {
8895         if (V1BroadcastIdx == -1)
8896           V1BroadcastIdx = M;
8897         else if (M != V1BroadcastIdx)
8898           return false;
8899       }
8900     return true;
8901   };
8902   if (DoBothBroadcast())
8903     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
8904                                                       DAG);
8905
8906   // If the inputs all stem from a single 128-bit lane of each input, then we
8907   // split them rather than blending because the split will decompose to
8908   // unusually few instructions.
8909   int LaneCount = VT.getSizeInBits() / 128;
8910   int LaneSize = Size / LaneCount;
8911   SmallBitVector LaneInputs[2];
8912   LaneInputs[0].resize(LaneCount, false);
8913   LaneInputs[1].resize(LaneCount, false);
8914   for (int i = 0; i < Size; ++i)
8915     if (Mask[i] >= 0)
8916       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
8917   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
8918     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8919
8920   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
8921   // that the decomposed single-input shuffles don't end up here.
8922   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8923 }
8924
8925 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
8926 /// a permutation and blend of those lanes.
8927 ///
8928 /// This essentially blends the out-of-lane inputs to each lane into the lane
8929 /// from a permuted copy of the vector. This lowering strategy results in four
8930 /// instructions in the worst case for a single-input cross lane shuffle which
8931 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
8932 /// of. Special cases for each particular shuffle pattern should be handled
8933 /// prior to trying this lowering.
8934 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
8935                                                        SDValue V1, SDValue V2,
8936                                                        ArrayRef<int> Mask,
8937                                                        SelectionDAG &DAG) {
8938   // FIXME: This should probably be generalized for 512-bit vectors as well.
8939   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8940   int LaneSize = Mask.size() / 2;
8941
8942   // If there are only inputs from one 128-bit lane, splitting will in fact be
8943   // less expensive. The flags track wether the given lane contains an element
8944   // that crosses to another lane.
8945   bool LaneCrossing[2] = {false, false};
8946   for (int i = 0, Size = Mask.size(); i < Size; ++i)
8947     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
8948       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
8949   if (!LaneCrossing[0] || !LaneCrossing[1])
8950     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8951
8952   if (isSingleInputShuffleMask(Mask)) {
8953     SmallVector<int, 32> FlippedBlendMask;
8954     for (int i = 0, Size = Mask.size(); i < Size; ++i)
8955       FlippedBlendMask.push_back(
8956           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
8957                                   ? Mask[i]
8958                                   : Mask[i] % LaneSize +
8959                                         (i / LaneSize) * LaneSize + Size));
8960
8961     // Flip the vector, and blend the results which should now be in-lane. The
8962     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
8963     // 5 for the high source. The value 3 selects the high half of source 2 and
8964     // the value 2 selects the low half of source 2. We only use source 2 to
8965     // allow folding it into a memory operand.
8966     unsigned PERMMask = 3 | 2 << 4;
8967     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
8968                                   V1, DAG.getConstant(PERMMask, MVT::i8));
8969     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
8970   }
8971
8972   // This now reduces to two single-input shuffles of V1 and V2 which at worst
8973   // will be handled by the above logic and a blend of the results, much like
8974   // other patterns in AVX.
8975   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8976 }
8977
8978 /// \brief Handle lowering 2-lane 128-bit shuffles.
8979 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8980                                         SDValue V2, ArrayRef<int> Mask,
8981                                         const X86Subtarget *Subtarget,
8982                                         SelectionDAG &DAG) {
8983   // Blends are faster and handle all the non-lane-crossing cases.
8984   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
8985                                                 Subtarget, DAG))
8986     return Blend;
8987
8988   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
8989                                VT.getVectorNumElements() / 2);
8990   // Check for patterns which can be matched with a single insert of a 128-bit
8991   // subvector.
8992   if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1}) ||
8993       isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
8994     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
8995                               DAG.getIntPtrConstant(0));
8996     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
8997                               Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
8998     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
8999   }
9000   if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 6, 7})) {
9001     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9002                               DAG.getIntPtrConstant(0));
9003     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9004                               DAG.getIntPtrConstant(2));
9005     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9006   }
9007
9008   // Otherwise form a 128-bit permutation.
9009   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9010   unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
9011   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9012                      DAG.getConstant(PermMask, MVT::i8));
9013 }
9014
9015 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9016 /// shuffling each lane.
9017 ///
9018 /// This will only succeed when the result of fixing the 128-bit lanes results
9019 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9020 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9021 /// the lane crosses early and then use simpler shuffles within each lane.
9022 ///
9023 /// FIXME: It might be worthwhile at some point to support this without
9024 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9025 /// in x86 only floating point has interesting non-repeating shuffles, and even
9026 /// those are still *marginally* more expensive.
9027 static SDValue lowerVectorShuffleByMerging128BitLanes(
9028     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9029     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9030   assert(!isSingleInputShuffleMask(Mask) &&
9031          "This is only useful with multiple inputs.");
9032
9033   int Size = Mask.size();
9034   int LaneSize = 128 / VT.getScalarSizeInBits();
9035   int NumLanes = Size / LaneSize;
9036   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9037
9038   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9039   // check whether the in-128-bit lane shuffles share a repeating pattern.
9040   SmallVector<int, 4> Lanes;
9041   Lanes.resize(NumLanes, -1);
9042   SmallVector<int, 4> InLaneMask;
9043   InLaneMask.resize(LaneSize, -1);
9044   for (int i = 0; i < Size; ++i) {
9045     if (Mask[i] < 0)
9046       continue;
9047
9048     int j = i / LaneSize;
9049
9050     if (Lanes[j] < 0) {
9051       // First entry we've seen for this lane.
9052       Lanes[j] = Mask[i] / LaneSize;
9053     } else if (Lanes[j] != Mask[i] / LaneSize) {
9054       // This doesn't match the lane selected previously!
9055       return SDValue();
9056     }
9057
9058     // Check that within each lane we have a consistent shuffle mask.
9059     int k = i % LaneSize;
9060     if (InLaneMask[k] < 0) {
9061       InLaneMask[k] = Mask[i] % LaneSize;
9062     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9063       // This doesn't fit a repeating in-lane mask.
9064       return SDValue();
9065     }
9066   }
9067
9068   // First shuffle the lanes into place.
9069   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9070                                 VT.getSizeInBits() / 64);
9071   SmallVector<int, 8> LaneMask;
9072   LaneMask.resize(NumLanes * 2, -1);
9073   for (int i = 0; i < NumLanes; ++i)
9074     if (Lanes[i] >= 0) {
9075       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9076       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9077     }
9078
9079   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9080   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9081   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9082
9083   // Cast it back to the type we actually want.
9084   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9085
9086   // Now do a simple shuffle that isn't lane crossing.
9087   SmallVector<int, 8> NewMask;
9088   NewMask.resize(Size, -1);
9089   for (int i = 0; i < Size; ++i)
9090     if (Mask[i] >= 0)
9091       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9092   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9093          "Must not introduce lane crosses at this point!");
9094
9095   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9096 }
9097
9098 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9099 /// given mask.
9100 ///
9101 /// This returns true if the elements from a particular input are already in the
9102 /// slot required by the given mask and require no permutation.
9103 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9104   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9105   int Size = Mask.size();
9106   for (int i = 0; i < Size; ++i)
9107     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9108       return false;
9109
9110   return true;
9111 }
9112
9113 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9114 ///
9115 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9116 /// isn't available.
9117 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9118                                        const X86Subtarget *Subtarget,
9119                                        SelectionDAG &DAG) {
9120   SDLoc DL(Op);
9121   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9122   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9123   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9124   ArrayRef<int> Mask = SVOp->getMask();
9125   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9126
9127   SmallVector<int, 4> WidenedMask;
9128   if (canWidenShuffleElements(Mask, WidenedMask))
9129     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9130                                     DAG);
9131
9132   if (isSingleInputShuffleMask(Mask)) {
9133     // Check for being able to broadcast a single element.
9134     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f64, DL, V1,
9135                                                           Mask, Subtarget, DAG))
9136       return Broadcast;
9137
9138     // Use low duplicate instructions for masks that match their pattern.
9139     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9140       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9141
9142     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9143       // Non-half-crossing single input shuffles can be lowerid with an
9144       // interleaved permutation.
9145       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9146                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9147       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9148                          DAG.getConstant(VPERMILPMask, MVT::i8));
9149     }
9150
9151     // With AVX2 we have direct support for this permutation.
9152     if (Subtarget->hasAVX2())
9153       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9154                          getV4X86ShuffleImm8ForMask(Mask, DAG));
9155
9156     // Otherwise, fall back.
9157     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9158                                                    DAG);
9159   }
9160
9161   // X86 has dedicated unpack instructions that can handle specific blend
9162   // operations: UNPCKH and UNPCKL.
9163   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9164     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9165   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9166     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9167   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9168     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9169   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9170     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9171
9172   // If we have a single input to the zero element, insert that into V1 if we
9173   // can do so cheaply.
9174   int NumV2Elements =
9175       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9176   if (NumV2Elements == 1 && Mask[0] >= 4)
9177     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9178             MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
9179       return Insertion;
9180
9181   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9182                                                 Subtarget, DAG))
9183     return Blend;
9184
9185   // Check if the blend happens to exactly fit that of SHUFPD.
9186   if ((Mask[0] == -1 || Mask[0] < 2) &&
9187       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9188       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9189       (Mask[3] == -1 || Mask[3] >= 6)) {
9190     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9191                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9192     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9193                        DAG.getConstant(SHUFPDMask, MVT::i8));
9194   }
9195   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9196       (Mask[1] == -1 || Mask[1] < 2) &&
9197       (Mask[2] == -1 || Mask[2] >= 6) &&
9198       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9199     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9200                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9201     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9202                        DAG.getConstant(SHUFPDMask, MVT::i8));
9203   }
9204
9205   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9206   // shuffle. However, if we have AVX2 and either inputs are already in place,
9207   // we will be able to shuffle even across lanes the other input in a single
9208   // instruction so skip this pattern.
9209   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9210                                  isShuffleMaskInputInPlace(1, Mask))))
9211     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9212             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9213       return Result;
9214
9215   // If we have AVX2 then we always want to lower with a blend because an v4 we
9216   // can fully permute the elements.
9217   if (Subtarget->hasAVX2())
9218     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9219                                                       Mask, DAG);
9220
9221   // Otherwise fall back on generic lowering.
9222   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9223 }
9224
9225 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9226 ///
9227 /// This routine is only called when we have AVX2 and thus a reasonable
9228 /// instruction set for v4i64 shuffling..
9229 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9230                                        const X86Subtarget *Subtarget,
9231                                        SelectionDAG &DAG) {
9232   SDLoc DL(Op);
9233   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9234   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9235   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9236   ArrayRef<int> Mask = SVOp->getMask();
9237   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9238   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9239
9240   SmallVector<int, 4> WidenedMask;
9241   if (canWidenShuffleElements(Mask, WidenedMask))
9242     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9243                                     DAG);
9244
9245   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9246                                                 Subtarget, DAG))
9247     return Blend;
9248
9249   // Check for being able to broadcast a single element.
9250   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i64, DL, V1,
9251                                                         Mask, Subtarget, DAG))
9252     return Broadcast;
9253
9254   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9255   // use lower latency instructions that will operate on both 128-bit lanes.
9256   SmallVector<int, 2> RepeatedMask;
9257   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9258     if (isSingleInputShuffleMask(Mask)) {
9259       int PSHUFDMask[] = {-1, -1, -1, -1};
9260       for (int i = 0; i < 2; ++i)
9261         if (RepeatedMask[i] >= 0) {
9262           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9263           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9264         }
9265       return DAG.getNode(
9266           ISD::BITCAST, DL, MVT::v4i64,
9267           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9268                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9269                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9270     }
9271   }
9272
9273   // AVX2 provides a direct instruction for permuting a single input across
9274   // lanes.
9275   if (isSingleInputShuffleMask(Mask))
9276     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9277                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9278
9279   // Try to use shift instructions.
9280   if (SDValue Shift =
9281           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9282     return Shift;
9283
9284   // Use dedicated unpack instructions for masks that match their pattern.
9285   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9286     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9287   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9288     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9289   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9290     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9291   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9292     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9293
9294   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9295   // shuffle. However, if we have AVX2 and either inputs are already in place,
9296   // we will be able to shuffle even across lanes the other input in a single
9297   // instruction so skip this pattern.
9298   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9299                                  isShuffleMaskInputInPlace(1, Mask))))
9300     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9301             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9302       return Result;
9303
9304   // Otherwise fall back on generic blend lowering.
9305   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9306                                                     Mask, DAG);
9307 }
9308
9309 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9310 ///
9311 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9312 /// isn't available.
9313 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9314                                        const X86Subtarget *Subtarget,
9315                                        SelectionDAG &DAG) {
9316   SDLoc DL(Op);
9317   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9318   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9319   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9320   ArrayRef<int> Mask = SVOp->getMask();
9321   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9322
9323   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9324                                                 Subtarget, DAG))
9325     return Blend;
9326
9327   // Check for being able to broadcast a single element.
9328   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8f32, DL, V1,
9329                                                         Mask, Subtarget, DAG))
9330     return Broadcast;
9331
9332   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9333   // options to efficiently lower the shuffle.
9334   SmallVector<int, 4> RepeatedMask;
9335   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9336     assert(RepeatedMask.size() == 4 &&
9337            "Repeated masks must be half the mask width!");
9338
9339     // Use even/odd duplicate instructions for masks that match their pattern.
9340     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9341       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9342     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9343       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9344
9345     if (isSingleInputShuffleMask(Mask))
9346       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9347                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9348
9349     // Use dedicated unpack instructions for masks that match their pattern.
9350     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9351       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9352     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9353       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9354     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9355       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9356     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9357       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9358
9359     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9360     // have already handled any direct blends. We also need to squash the
9361     // repeated mask into a simulated v4f32 mask.
9362     for (int i = 0; i < 4; ++i)
9363       if (RepeatedMask[i] >= 8)
9364         RepeatedMask[i] -= 4;
9365     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9366   }
9367
9368   // If we have a single input shuffle with different shuffle patterns in the
9369   // two 128-bit lanes use the variable mask to VPERMILPS.
9370   if (isSingleInputShuffleMask(Mask)) {
9371     SDValue VPermMask[8];
9372     for (int i = 0; i < 8; ++i)
9373       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9374                                  : DAG.getConstant(Mask[i], MVT::i32);
9375     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9376       return DAG.getNode(
9377           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9378           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9379
9380     if (Subtarget->hasAVX2())
9381       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9382                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9383                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9384                                                  MVT::v8i32, VPermMask)),
9385                          V1);
9386
9387     // Otherwise, fall back.
9388     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9389                                                    DAG);
9390   }
9391
9392   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9393   // shuffle.
9394   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9395           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9396     return Result;
9397
9398   // If we have AVX2 then we always want to lower with a blend because at v8 we
9399   // can fully permute the elements.
9400   if (Subtarget->hasAVX2())
9401     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9402                                                       Mask, DAG);
9403
9404   // Otherwise fall back on generic lowering.
9405   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9406 }
9407
9408 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9409 ///
9410 /// This routine is only called when we have AVX2 and thus a reasonable
9411 /// instruction set for v8i32 shuffling..
9412 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9413                                        const X86Subtarget *Subtarget,
9414                                        SelectionDAG &DAG) {
9415   SDLoc DL(Op);
9416   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9417   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9418   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9419   ArrayRef<int> Mask = SVOp->getMask();
9420   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9421   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9422
9423   // Whenever we can lower this as a zext, that instruction is strictly faster
9424   // than any alternative. It also allows us to fold memory operands into the
9425   // shuffle in many cases.
9426   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9427                                                          Mask, Subtarget, DAG))
9428     return ZExt;
9429
9430   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9431                                                 Subtarget, DAG))
9432     return Blend;
9433
9434   // Check for being able to broadcast a single element.
9435   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i32, DL, V1,
9436                                                         Mask, Subtarget, DAG))
9437     return Broadcast;
9438
9439   // If the shuffle mask is repeated in each 128-bit lane we can use more
9440   // efficient instructions that mirror the shuffles across the two 128-bit
9441   // lanes.
9442   SmallVector<int, 4> RepeatedMask;
9443   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9444     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9445     if (isSingleInputShuffleMask(Mask))
9446       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9447                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9448
9449     // Use dedicated unpack instructions for masks that match their pattern.
9450     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9451       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9452     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9453       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9454     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9455       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9456     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9457       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9458   }
9459
9460   // Try to use shift instructions.
9461   if (SDValue Shift =
9462           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9463     return Shift;
9464
9465   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9466           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9467     return Rotate;
9468
9469   // If the shuffle patterns aren't repeated but it is a single input, directly
9470   // generate a cross-lane VPERMD instruction.
9471   if (isSingleInputShuffleMask(Mask)) {
9472     SDValue VPermMask[8];
9473     for (int i = 0; i < 8; ++i)
9474       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9475                                  : DAG.getConstant(Mask[i], MVT::i32);
9476     return DAG.getNode(
9477         X86ISD::VPERMV, DL, MVT::v8i32,
9478         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9479   }
9480
9481   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9482   // shuffle.
9483   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9484           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9485     return Result;
9486
9487   // Otherwise fall back on generic blend lowering.
9488   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9489                                                     Mask, DAG);
9490 }
9491
9492 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9493 ///
9494 /// This routine is only called when we have AVX2 and thus a reasonable
9495 /// instruction set for v16i16 shuffling..
9496 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9497                                         const X86Subtarget *Subtarget,
9498                                         SelectionDAG &DAG) {
9499   SDLoc DL(Op);
9500   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9501   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9502   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9503   ArrayRef<int> Mask = SVOp->getMask();
9504   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9505   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9506
9507   // Whenever we can lower this as a zext, that instruction is strictly faster
9508   // than any alternative. It also allows us to fold memory operands into the
9509   // shuffle in many cases.
9510   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9511                                                          Mask, Subtarget, DAG))
9512     return ZExt;
9513
9514   // Check for being able to broadcast a single element.
9515   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i16, DL, V1,
9516                                                         Mask, Subtarget, DAG))
9517     return Broadcast;
9518
9519   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9520                                                 Subtarget, DAG))
9521     return Blend;
9522
9523   // Use dedicated unpack instructions for masks that match their pattern.
9524   if (isShuffleEquivalent(V1, V2, Mask,
9525                           {// First 128-bit lane:
9526                            0, 16, 1, 17, 2, 18, 3, 19,
9527                            // Second 128-bit lane:
9528                            8, 24, 9, 25, 10, 26, 11, 27}))
9529     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9530   if (isShuffleEquivalent(V1, V2, Mask,
9531                           {// First 128-bit lane:
9532                            4, 20, 5, 21, 6, 22, 7, 23,
9533                            // Second 128-bit lane:
9534                            12, 28, 13, 29, 14, 30, 15, 31}))
9535     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9536
9537   // Try to use shift instructions.
9538   if (SDValue Shift =
9539           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9540     return Shift;
9541
9542   // Try to use byte rotation instructions.
9543   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9544           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9545     return Rotate;
9546
9547   if (isSingleInputShuffleMask(Mask)) {
9548     // There are no generalized cross-lane shuffle operations available on i16
9549     // element types.
9550     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9551       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9552                                                      Mask, DAG);
9553
9554     SDValue PSHUFBMask[32];
9555     for (int i = 0; i < 16; ++i) {
9556       if (Mask[i] == -1) {
9557         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9558         continue;
9559       }
9560
9561       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9562       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9563       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9564       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9565     }
9566     return DAG.getNode(
9567         ISD::BITCAST, DL, MVT::v16i16,
9568         DAG.getNode(
9569             X86ISD::PSHUFB, DL, MVT::v32i8,
9570             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9571             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9572   }
9573
9574   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9575   // shuffle.
9576   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9577           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9578     return Result;
9579
9580   // Otherwise fall back on generic lowering.
9581   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9582 }
9583
9584 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9585 ///
9586 /// This routine is only called when we have AVX2 and thus a reasonable
9587 /// instruction set for v32i8 shuffling..
9588 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9589                                        const X86Subtarget *Subtarget,
9590                                        SelectionDAG &DAG) {
9591   SDLoc DL(Op);
9592   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9593   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9594   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9595   ArrayRef<int> Mask = SVOp->getMask();
9596   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9597   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9598
9599   // Whenever we can lower this as a zext, that instruction is strictly faster
9600   // than any alternative. It also allows us to fold memory operands into the
9601   // shuffle in many cases.
9602   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9603                                                          Mask, Subtarget, DAG))
9604     return ZExt;
9605
9606   // Check for being able to broadcast a single element.
9607   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v32i8, DL, V1,
9608                                                         Mask, Subtarget, DAG))
9609     return Broadcast;
9610
9611   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9612                                                 Subtarget, DAG))
9613     return Blend;
9614
9615   // Use dedicated unpack instructions for masks that match their pattern.
9616   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9617   // 256-bit lanes.
9618   if (isShuffleEquivalent(
9619           V1, V2, Mask,
9620           {// First 128-bit lane:
9621            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9622            // Second 128-bit lane:
9623            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9624     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9625   if (isShuffleEquivalent(
9626           V1, V2, Mask,
9627           {// First 128-bit lane:
9628            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9629            // Second 128-bit lane:
9630            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9631     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9632
9633   // Try to use shift instructions.
9634   if (SDValue Shift =
9635           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9636     return Shift;
9637
9638   // Try to use byte rotation instructions.
9639   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9640           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9641     return Rotate;
9642
9643   if (isSingleInputShuffleMask(Mask)) {
9644     // There are no generalized cross-lane shuffle operations available on i8
9645     // element types.
9646     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9647       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9648                                                      Mask, DAG);
9649
9650     SDValue PSHUFBMask[32];
9651     for (int i = 0; i < 32; ++i)
9652       PSHUFBMask[i] =
9653           Mask[i] < 0
9654               ? DAG.getUNDEF(MVT::i8)
9655               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9656
9657     return DAG.getNode(
9658         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9659         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9660   }
9661
9662   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9663   // shuffle.
9664   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9665           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9666     return Result;
9667
9668   // Otherwise fall back on generic lowering.
9669   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9670 }
9671
9672 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9673 ///
9674 /// This routine either breaks down the specific type of a 256-bit x86 vector
9675 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9676 /// together based on the available instructions.
9677 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9678                                         MVT VT, const X86Subtarget *Subtarget,
9679                                         SelectionDAG &DAG) {
9680   SDLoc DL(Op);
9681   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9682   ArrayRef<int> Mask = SVOp->getMask();
9683
9684   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9685   // check for those subtargets here and avoid much of the subtarget querying in
9686   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9687   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9688   // floating point types there eventually, just immediately cast everything to
9689   // a float and operate entirely in that domain.
9690   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9691     int ElementBits = VT.getScalarSizeInBits();
9692     if (ElementBits < 32)
9693       // No floating point type available, decompose into 128-bit vectors.
9694       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9695
9696     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9697                                 VT.getVectorNumElements());
9698     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9699     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9700     return DAG.getNode(ISD::BITCAST, DL, VT,
9701                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9702   }
9703
9704   switch (VT.SimpleTy) {
9705   case MVT::v4f64:
9706     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9707   case MVT::v4i64:
9708     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9709   case MVT::v8f32:
9710     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9711   case MVT::v8i32:
9712     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9713   case MVT::v16i16:
9714     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9715   case MVT::v32i8:
9716     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9717
9718   default:
9719     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9720   }
9721 }
9722
9723 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9724 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9725                                        const X86Subtarget *Subtarget,
9726                                        SelectionDAG &DAG) {
9727   SDLoc DL(Op);
9728   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9729   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9730   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9731   ArrayRef<int> Mask = SVOp->getMask();
9732   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9733
9734   // X86 has dedicated unpack instructions that can handle specific blend
9735   // operations: UNPCKH and UNPCKL.
9736   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9737     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9738   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9739     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9740
9741   // FIXME: Implement direct support for this type!
9742   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9743 }
9744
9745 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9746 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9747                                        const X86Subtarget *Subtarget,
9748                                        SelectionDAG &DAG) {
9749   SDLoc DL(Op);
9750   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9751   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9752   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9753   ArrayRef<int> Mask = SVOp->getMask();
9754   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9755
9756   // Use dedicated unpack instructions for masks that match their pattern.
9757   if (isShuffleEquivalent(V1, V2, Mask,
9758                           {// First 128-bit lane.
9759                            0, 16, 1, 17, 4, 20, 5, 21,
9760                            // Second 128-bit lane.
9761                            8, 24, 9, 25, 12, 28, 13, 29}))
9762     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9763   if (isShuffleEquivalent(V1, V2, Mask,
9764                           {// First 128-bit lane.
9765                            2, 18, 3, 19, 6, 22, 7, 23,
9766                            // Second 128-bit lane.
9767                            10, 26, 11, 27, 14, 30, 15, 31}))
9768     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9769
9770   // FIXME: Implement direct support for this type!
9771   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9772 }
9773
9774 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9775 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9776                                        const X86Subtarget *Subtarget,
9777                                        SelectionDAG &DAG) {
9778   SDLoc DL(Op);
9779   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9780   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9781   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9782   ArrayRef<int> Mask = SVOp->getMask();
9783   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9784
9785   // X86 has dedicated unpack instructions that can handle specific blend
9786   // operations: UNPCKH and UNPCKL.
9787   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9788     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9789   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9790     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9791
9792   // FIXME: Implement direct support for this type!
9793   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9794 }
9795
9796 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9797 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9798                                        const X86Subtarget *Subtarget,
9799                                        SelectionDAG &DAG) {
9800   SDLoc DL(Op);
9801   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9802   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9803   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9804   ArrayRef<int> Mask = SVOp->getMask();
9805   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9806
9807   // Use dedicated unpack instructions for masks that match their pattern.
9808   if (isShuffleEquivalent(V1, V2, Mask,
9809                           {// First 128-bit lane.
9810                            0, 16, 1, 17, 4, 20, 5, 21,
9811                            // Second 128-bit lane.
9812                            8, 24, 9, 25, 12, 28, 13, 29}))
9813     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9814   if (isShuffleEquivalent(V1, V2, Mask,
9815                           {// First 128-bit lane.
9816                            2, 18, 3, 19, 6, 22, 7, 23,
9817                            // Second 128-bit lane.
9818                            10, 26, 11, 27, 14, 30, 15, 31}))
9819     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9820
9821   // FIXME: Implement direct support for this type!
9822   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9823 }
9824
9825 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
9826 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9827                                         const X86Subtarget *Subtarget,
9828                                         SelectionDAG &DAG) {
9829   SDLoc DL(Op);
9830   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9831   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9832   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9833   ArrayRef<int> Mask = SVOp->getMask();
9834   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9835   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
9836
9837   // FIXME: Implement direct support for this type!
9838   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
9839 }
9840
9841 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
9842 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9843                                        const X86Subtarget *Subtarget,
9844                                        SelectionDAG &DAG) {
9845   SDLoc DL(Op);
9846   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9847   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9848   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9849   ArrayRef<int> Mask = SVOp->getMask();
9850   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
9851   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
9852
9853   // FIXME: Implement direct support for this type!
9854   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
9855 }
9856
9857 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
9858 ///
9859 /// This routine either breaks down the specific type of a 512-bit x86 vector
9860 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
9861 /// together based on the available instructions.
9862 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9863                                         MVT VT, const X86Subtarget *Subtarget,
9864                                         SelectionDAG &DAG) {
9865   SDLoc DL(Op);
9866   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9867   ArrayRef<int> Mask = SVOp->getMask();
9868   assert(Subtarget->hasAVX512() &&
9869          "Cannot lower 512-bit vectors w/ basic ISA!");
9870
9871   // Check for being able to broadcast a single element.
9872   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(VT.SimpleTy, DL, V1,
9873                                                         Mask, Subtarget, DAG))
9874     return Broadcast;
9875
9876   // Dispatch to each element type for lowering. If we don't have supprot for
9877   // specific element type shuffles at 512 bits, immediately split them and
9878   // lower them. Each lowering routine of a given type is allowed to assume that
9879   // the requisite ISA extensions for that element type are available.
9880   switch (VT.SimpleTy) {
9881   case MVT::v8f64:
9882     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9883   case MVT::v16f32:
9884     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9885   case MVT::v8i64:
9886     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9887   case MVT::v16i32:
9888     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9889   case MVT::v32i16:
9890     if (Subtarget->hasBWI())
9891       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9892     break;
9893   case MVT::v64i8:
9894     if (Subtarget->hasBWI())
9895       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9896     break;
9897
9898   default:
9899     llvm_unreachable("Not a valid 512-bit x86 vector type!");
9900   }
9901
9902   // Otherwise fall back on splitting.
9903   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9904 }
9905
9906 /// \brief Top-level lowering for x86 vector shuffles.
9907 ///
9908 /// This handles decomposition, canonicalization, and lowering of all x86
9909 /// vector shuffles. Most of the specific lowering strategies are encapsulated
9910 /// above in helper routines. The canonicalization attempts to widen shuffles
9911 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
9912 /// s.t. only one of the two inputs needs to be tested, etc.
9913 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9914                                   SelectionDAG &DAG) {
9915   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9916   ArrayRef<int> Mask = SVOp->getMask();
9917   SDValue V1 = Op.getOperand(0);
9918   SDValue V2 = Op.getOperand(1);
9919   MVT VT = Op.getSimpleValueType();
9920   int NumElements = VT.getVectorNumElements();
9921   SDLoc dl(Op);
9922
9923   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9924
9925   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9926   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9927   if (V1IsUndef && V2IsUndef)
9928     return DAG.getUNDEF(VT);
9929
9930   // When we create a shuffle node we put the UNDEF node to second operand,
9931   // but in some cases the first operand may be transformed to UNDEF.
9932   // In this case we should just commute the node.
9933   if (V1IsUndef)
9934     return DAG.getCommutedVectorShuffle(*SVOp);
9935
9936   // Check for non-undef masks pointing at an undef vector and make the masks
9937   // undef as well. This makes it easier to match the shuffle based solely on
9938   // the mask.
9939   if (V2IsUndef)
9940     for (int M : Mask)
9941       if (M >= NumElements) {
9942         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
9943         for (int &M : NewMask)
9944           if (M >= NumElements)
9945             M = -1;
9946         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
9947       }
9948
9949   // We actually see shuffles that are entirely re-arrangements of a set of
9950   // zero inputs. This mostly happens while decomposing complex shuffles into
9951   // simple ones. Directly lower these as a buildvector of zeros.
9952   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9953   if (Zeroable.all())
9954     return getZeroVector(VT, Subtarget, DAG, dl);
9955
9956   // Try to collapse shuffles into using a vector type with fewer elements but
9957   // wider element types. We cap this to not form integers or floating point
9958   // elements wider than 64 bits, but it might be interesting to form i128
9959   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
9960   SmallVector<int, 16> WidenedMask;
9961   if (VT.getScalarSizeInBits() < 64 &&
9962       canWidenShuffleElements(Mask, WidenedMask)) {
9963     MVT NewEltVT = VT.isFloatingPoint()
9964                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
9965                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
9966     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
9967     // Make sure that the new vector type is legal. For example, v2f64 isn't
9968     // legal on SSE1.
9969     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
9970       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
9971       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
9972       return DAG.getNode(ISD::BITCAST, dl, VT,
9973                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
9974     }
9975   }
9976
9977   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
9978   for (int M : SVOp->getMask())
9979     if (M < 0)
9980       ++NumUndefElements;
9981     else if (M < NumElements)
9982       ++NumV1Elements;
9983     else
9984       ++NumV2Elements;
9985
9986   // Commute the shuffle as needed such that more elements come from V1 than
9987   // V2. This allows us to match the shuffle pattern strictly on how many
9988   // elements come from V1 without handling the symmetric cases.
9989   if (NumV2Elements > NumV1Elements)
9990     return DAG.getCommutedVectorShuffle(*SVOp);
9991
9992   // When the number of V1 and V2 elements are the same, try to minimize the
9993   // number of uses of V2 in the low half of the vector. When that is tied,
9994   // ensure that the sum of indices for V1 is equal to or lower than the sum
9995   // indices for V2. When those are equal, try to ensure that the number of odd
9996   // indices for V1 is lower than the number of odd indices for V2.
9997   if (NumV1Elements == NumV2Elements) {
9998     int LowV1Elements = 0, LowV2Elements = 0;
9999     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10000       if (M >= NumElements)
10001         ++LowV2Elements;
10002       else if (M >= 0)
10003         ++LowV1Elements;
10004     if (LowV2Elements > LowV1Elements) {
10005       return DAG.getCommutedVectorShuffle(*SVOp);
10006     } else if (LowV2Elements == LowV1Elements) {
10007       int SumV1Indices = 0, SumV2Indices = 0;
10008       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10009         if (SVOp->getMask()[i] >= NumElements)
10010           SumV2Indices += i;
10011         else if (SVOp->getMask()[i] >= 0)
10012           SumV1Indices += i;
10013       if (SumV2Indices < SumV1Indices) {
10014         return DAG.getCommutedVectorShuffle(*SVOp);
10015       } else if (SumV2Indices == SumV1Indices) {
10016         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10017         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10018           if (SVOp->getMask()[i] >= NumElements)
10019             NumV2OddIndices += i % 2;
10020           else if (SVOp->getMask()[i] >= 0)
10021             NumV1OddIndices += i % 2;
10022         if (NumV2OddIndices < NumV1OddIndices)
10023           return DAG.getCommutedVectorShuffle(*SVOp);
10024       }
10025     }
10026   }
10027
10028   // For each vector width, delegate to a specialized lowering routine.
10029   if (VT.getSizeInBits() == 128)
10030     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10031
10032   if (VT.getSizeInBits() == 256)
10033     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10034
10035   // Force AVX-512 vectors to be scalarized for now.
10036   // FIXME: Implement AVX-512 support!
10037   if (VT.getSizeInBits() == 512)
10038     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10039
10040   llvm_unreachable("Unimplemented!");
10041 }
10042
10043 // This function assumes its argument is a BUILD_VECTOR of constants or
10044 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10045 // true.
10046 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10047                                     unsigned &MaskValue) {
10048   MaskValue = 0;
10049   unsigned NumElems = BuildVector->getNumOperands();
10050   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10051   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10052   unsigned NumElemsInLane = NumElems / NumLanes;
10053
10054   // Blend for v16i16 should be symetric for the both lanes.
10055   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10056     SDValue EltCond = BuildVector->getOperand(i);
10057     SDValue SndLaneEltCond =
10058         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10059
10060     int Lane1Cond = -1, Lane2Cond = -1;
10061     if (isa<ConstantSDNode>(EltCond))
10062       Lane1Cond = !isZero(EltCond);
10063     if (isa<ConstantSDNode>(SndLaneEltCond))
10064       Lane2Cond = !isZero(SndLaneEltCond);
10065
10066     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10067       // Lane1Cond != 0, means we want the first argument.
10068       // Lane1Cond == 0, means we want the second argument.
10069       // The encoding of this argument is 0 for the first argument, 1
10070       // for the second. Therefore, invert the condition.
10071       MaskValue |= !Lane1Cond << i;
10072     else if (Lane1Cond < 0)
10073       MaskValue |= !Lane2Cond << i;
10074     else
10075       return false;
10076   }
10077   return true;
10078 }
10079
10080 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10081 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10082                                            const X86Subtarget *Subtarget,
10083                                            SelectionDAG &DAG) {
10084   SDValue Cond = Op.getOperand(0);
10085   SDValue LHS = Op.getOperand(1);
10086   SDValue RHS = Op.getOperand(2);
10087   SDLoc dl(Op);
10088   MVT VT = Op.getSimpleValueType();
10089
10090   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10091     return SDValue();
10092   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10093
10094   // Only non-legal VSELECTs reach this lowering, convert those into generic
10095   // shuffles and re-use the shuffle lowering path for blends.
10096   SmallVector<int, 32> Mask;
10097   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10098     SDValue CondElt = CondBV->getOperand(i);
10099     Mask.push_back(
10100         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10101   }
10102   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10103 }
10104
10105 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10106   // A vselect where all conditions and data are constants can be optimized into
10107   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10108   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10109       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10110       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10111     return SDValue();
10112
10113   // Try to lower this to a blend-style vector shuffle. This can handle all
10114   // constant condition cases.
10115   SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG);
10116   if (BlendOp.getNode())
10117     return BlendOp;
10118
10119   // Variable blends are only legal from SSE4.1 onward.
10120   if (!Subtarget->hasSSE41())
10121     return SDValue();
10122
10123   // Some types for vselect were previously set to Expand, not Legal or
10124   // Custom. Return an empty SDValue so we fall-through to Expand, after
10125   // the Custom lowering phase.
10126   MVT VT = Op.getSimpleValueType();
10127   switch (VT.SimpleTy) {
10128   default:
10129     break;
10130   case MVT::v8i16:
10131   case MVT::v16i16:
10132     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10133       break;
10134     return SDValue();
10135   }
10136
10137   // We couldn't create a "Blend with immediate" node.
10138   // This node should still be legal, but we'll have to emit a blendv*
10139   // instruction.
10140   return Op;
10141 }
10142
10143 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10144   MVT VT = Op.getSimpleValueType();
10145   SDLoc dl(Op);
10146
10147   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10148     return SDValue();
10149
10150   if (VT.getSizeInBits() == 8) {
10151     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10152                                   Op.getOperand(0), Op.getOperand(1));
10153     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10154                                   DAG.getValueType(VT));
10155     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10156   }
10157
10158   if (VT.getSizeInBits() == 16) {
10159     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10160     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10161     if (Idx == 0)
10162       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10163                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10164                                      DAG.getNode(ISD::BITCAST, dl,
10165                                                  MVT::v4i32,
10166                                                  Op.getOperand(0)),
10167                                      Op.getOperand(1)));
10168     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10169                                   Op.getOperand(0), Op.getOperand(1));
10170     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10171                                   DAG.getValueType(VT));
10172     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10173   }
10174
10175   if (VT == MVT::f32) {
10176     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10177     // the result back to FR32 register. It's only worth matching if the
10178     // result has a single use which is a store or a bitcast to i32.  And in
10179     // the case of a store, it's not worth it if the index is a constant 0,
10180     // because a MOVSSmr can be used instead, which is smaller and faster.
10181     if (!Op.hasOneUse())
10182       return SDValue();
10183     SDNode *User = *Op.getNode()->use_begin();
10184     if ((User->getOpcode() != ISD::STORE ||
10185          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10186           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10187         (User->getOpcode() != ISD::BITCAST ||
10188          User->getValueType(0) != MVT::i32))
10189       return SDValue();
10190     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10191                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10192                                               Op.getOperand(0)),
10193                                               Op.getOperand(1));
10194     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10195   }
10196
10197   if (VT == MVT::i32 || VT == MVT::i64) {
10198     // ExtractPS/pextrq works with constant index.
10199     if (isa<ConstantSDNode>(Op.getOperand(1)))
10200       return Op;
10201   }
10202   return SDValue();
10203 }
10204
10205 /// Extract one bit from mask vector, like v16i1 or v8i1.
10206 /// AVX-512 feature.
10207 SDValue
10208 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10209   SDValue Vec = Op.getOperand(0);
10210   SDLoc dl(Vec);
10211   MVT VecVT = Vec.getSimpleValueType();
10212   SDValue Idx = Op.getOperand(1);
10213   MVT EltVT = Op.getSimpleValueType();
10214
10215   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10216   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10217          "Unexpected vector type in ExtractBitFromMaskVector");
10218
10219   // variable index can't be handled in mask registers,
10220   // extend vector to VR512
10221   if (!isa<ConstantSDNode>(Idx)) {
10222     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10223     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10224     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10225                               ExtVT.getVectorElementType(), Ext, Idx);
10226     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10227   }
10228
10229   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10230   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10231   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10232     rc = getRegClassFor(MVT::v16i1);
10233   unsigned MaxSift = rc->getSize()*8 - 1;
10234   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10235                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10236   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10237                     DAG.getConstant(MaxSift, MVT::i8));
10238   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10239                        DAG.getIntPtrConstant(0));
10240 }
10241
10242 SDValue
10243 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10244                                            SelectionDAG &DAG) const {
10245   SDLoc dl(Op);
10246   SDValue Vec = Op.getOperand(0);
10247   MVT VecVT = Vec.getSimpleValueType();
10248   SDValue Idx = Op.getOperand(1);
10249
10250   if (Op.getSimpleValueType() == MVT::i1)
10251     return ExtractBitFromMaskVector(Op, DAG);
10252
10253   if (!isa<ConstantSDNode>(Idx)) {
10254     if (VecVT.is512BitVector() ||
10255         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10256          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10257
10258       MVT MaskEltVT =
10259         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10260       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10261                                     MaskEltVT.getSizeInBits());
10262
10263       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10264       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10265                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10266                                 Idx, DAG.getConstant(0, getPointerTy()));
10267       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10268       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10269                         Perm, DAG.getConstant(0, getPointerTy()));
10270     }
10271     return SDValue();
10272   }
10273
10274   // If this is a 256-bit vector result, first extract the 128-bit vector and
10275   // then extract the element from the 128-bit vector.
10276   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10277
10278     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10279     // Get the 128-bit vector.
10280     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10281     MVT EltVT = VecVT.getVectorElementType();
10282
10283     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10284
10285     //if (IdxVal >= NumElems/2)
10286     //  IdxVal -= NumElems/2;
10287     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10288     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10289                        DAG.getConstant(IdxVal, MVT::i32));
10290   }
10291
10292   assert(VecVT.is128BitVector() && "Unexpected vector length");
10293
10294   if (Subtarget->hasSSE41()) {
10295     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10296     if (Res.getNode())
10297       return Res;
10298   }
10299
10300   MVT VT = Op.getSimpleValueType();
10301   // TODO: handle v16i8.
10302   if (VT.getSizeInBits() == 16) {
10303     SDValue Vec = Op.getOperand(0);
10304     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10305     if (Idx == 0)
10306       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10307                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10308                                      DAG.getNode(ISD::BITCAST, dl,
10309                                                  MVT::v4i32, Vec),
10310                                      Op.getOperand(1)));
10311     // Transform it so it match pextrw which produces a 32-bit result.
10312     MVT EltVT = MVT::i32;
10313     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10314                                   Op.getOperand(0), Op.getOperand(1));
10315     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10316                                   DAG.getValueType(VT));
10317     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10318   }
10319
10320   if (VT.getSizeInBits() == 32) {
10321     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10322     if (Idx == 0)
10323       return Op;
10324
10325     // SHUFPS the element to the lowest double word, then movss.
10326     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10327     MVT VVT = Op.getOperand(0).getSimpleValueType();
10328     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10329                                        DAG.getUNDEF(VVT), Mask);
10330     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10331                        DAG.getIntPtrConstant(0));
10332   }
10333
10334   if (VT.getSizeInBits() == 64) {
10335     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10336     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10337     //        to match extract_elt for f64.
10338     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10339     if (Idx == 0)
10340       return Op;
10341
10342     // UNPCKHPD the element to the lowest double word, then movsd.
10343     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10344     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10345     int Mask[2] = { 1, -1 };
10346     MVT VVT = Op.getOperand(0).getSimpleValueType();
10347     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10348                                        DAG.getUNDEF(VVT), Mask);
10349     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10350                        DAG.getIntPtrConstant(0));
10351   }
10352
10353   return SDValue();
10354 }
10355
10356 /// Insert one bit to mask vector, like v16i1 or v8i1.
10357 /// AVX-512 feature.
10358 SDValue
10359 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10360   SDLoc dl(Op);
10361   SDValue Vec = Op.getOperand(0);
10362   SDValue Elt = Op.getOperand(1);
10363   SDValue Idx = Op.getOperand(2);
10364   MVT VecVT = Vec.getSimpleValueType();
10365
10366   if (!isa<ConstantSDNode>(Idx)) {
10367     // Non constant index. Extend source and destination,
10368     // insert element and then truncate the result.
10369     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10370     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10371     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10372       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10373       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10374     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10375   }
10376
10377   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10378   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10379   if (Vec.getOpcode() == ISD::UNDEF)
10380     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10381                        DAG.getConstant(IdxVal, MVT::i8));
10382   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10383   unsigned MaxSift = rc->getSize()*8 - 1;
10384   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10385                     DAG.getConstant(MaxSift, MVT::i8));
10386   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10387                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10388   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10389 }
10390
10391 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10392                                                   SelectionDAG &DAG) const {
10393   MVT VT = Op.getSimpleValueType();
10394   MVT EltVT = VT.getVectorElementType();
10395
10396   if (EltVT == MVT::i1)
10397     return InsertBitToMaskVector(Op, DAG);
10398
10399   SDLoc dl(Op);
10400   SDValue N0 = Op.getOperand(0);
10401   SDValue N1 = Op.getOperand(1);
10402   SDValue N2 = Op.getOperand(2);
10403   if (!isa<ConstantSDNode>(N2))
10404     return SDValue();
10405   auto *N2C = cast<ConstantSDNode>(N2);
10406   unsigned IdxVal = N2C->getZExtValue();
10407
10408   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10409   // into that, and then insert the subvector back into the result.
10410   if (VT.is256BitVector() || VT.is512BitVector()) {
10411     // Get the desired 128-bit vector half.
10412     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10413
10414     // Insert the element into the desired half.
10415     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10416     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10417
10418     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10419                     DAG.getConstant(IdxIn128, MVT::i32));
10420
10421     // Insert the changed part back to the 256-bit vector
10422     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10423   }
10424   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10425
10426   if (Subtarget->hasSSE41()) {
10427     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10428       unsigned Opc;
10429       if (VT == MVT::v8i16) {
10430         Opc = X86ISD::PINSRW;
10431       } else {
10432         assert(VT == MVT::v16i8);
10433         Opc = X86ISD::PINSRB;
10434       }
10435
10436       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10437       // argument.
10438       if (N1.getValueType() != MVT::i32)
10439         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10440       if (N2.getValueType() != MVT::i32)
10441         N2 = DAG.getIntPtrConstant(IdxVal);
10442       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10443     }
10444
10445     if (EltVT == MVT::f32) {
10446       // Bits [7:6] of the constant are the source select.  This will always be
10447       //  zero here.  The DAG Combiner may combine an extract_elt index into
10448       //  these
10449       //  bits.  For example (insert (extract, 3), 2) could be matched by
10450       //  putting
10451       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10452       // Bits [5:4] of the constant are the destination select.  This is the
10453       //  value of the incoming immediate.
10454       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10455       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10456       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10457       // Create this as a scalar to vector..
10458       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10459       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10460     }
10461
10462     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10463       // PINSR* works with constant index.
10464       return Op;
10465     }
10466   }
10467
10468   if (EltVT == MVT::i8)
10469     return SDValue();
10470
10471   if (EltVT.getSizeInBits() == 16) {
10472     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10473     // as its second argument.
10474     if (N1.getValueType() != MVT::i32)
10475       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10476     if (N2.getValueType() != MVT::i32)
10477       N2 = DAG.getIntPtrConstant(IdxVal);
10478     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10479   }
10480   return SDValue();
10481 }
10482
10483 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10484   SDLoc dl(Op);
10485   MVT OpVT = Op.getSimpleValueType();
10486
10487   // If this is a 256-bit vector result, first insert into a 128-bit
10488   // vector and then insert into the 256-bit vector.
10489   if (!OpVT.is128BitVector()) {
10490     // Insert into a 128-bit vector.
10491     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10492     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10493                                  OpVT.getVectorNumElements() / SizeFactor);
10494
10495     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10496
10497     // Insert the 128-bit vector.
10498     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10499   }
10500
10501   if (OpVT == MVT::v1i64 &&
10502       Op.getOperand(0).getValueType() == MVT::i64)
10503     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10504
10505   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10506   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10507   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10508                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10509 }
10510
10511 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10512 // a simple subregister reference or explicit instructions to grab
10513 // upper bits of a vector.
10514 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10515                                       SelectionDAG &DAG) {
10516   SDLoc dl(Op);
10517   SDValue In =  Op.getOperand(0);
10518   SDValue Idx = Op.getOperand(1);
10519   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10520   MVT ResVT   = Op.getSimpleValueType();
10521   MVT InVT    = In.getSimpleValueType();
10522
10523   if (Subtarget->hasFp256()) {
10524     if (ResVT.is128BitVector() &&
10525         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10526         isa<ConstantSDNode>(Idx)) {
10527       return Extract128BitVector(In, IdxVal, DAG, dl);
10528     }
10529     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10530         isa<ConstantSDNode>(Idx)) {
10531       return Extract256BitVector(In, IdxVal, DAG, dl);
10532     }
10533   }
10534   return SDValue();
10535 }
10536
10537 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10538 // simple superregister reference or explicit instructions to insert
10539 // the upper bits of a vector.
10540 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10541                                      SelectionDAG &DAG) {
10542   if (!Subtarget->hasAVX())
10543     return SDValue();
10544
10545   SDLoc dl(Op);
10546   SDValue Vec = Op.getOperand(0);
10547   SDValue SubVec = Op.getOperand(1);
10548   SDValue Idx = Op.getOperand(2);
10549
10550   if (!isa<ConstantSDNode>(Idx))
10551     return SDValue();
10552
10553   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10554   MVT OpVT = Op.getSimpleValueType();
10555   MVT SubVecVT = SubVec.getSimpleValueType();
10556
10557   // Fold two 16-byte subvector loads into one 32-byte load:
10558   // (insert_subvector (insert_subvector undef, (load addr), 0),
10559   //                   (load addr + 16), Elts/2)
10560   // --> load32 addr
10561   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10562       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10563       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10564       !Subtarget->isUnalignedMem32Slow()) {
10565     SDValue SubVec2 = Vec.getOperand(1);
10566     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10567       if (Idx2->getZExtValue() == 0) {
10568         SDValue Ops[] = { SubVec2, SubVec };
10569         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10570         if (LD.getNode())
10571           return LD;
10572       }
10573     }
10574   }
10575
10576   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10577       SubVecVT.is128BitVector())
10578     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10579
10580   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10581     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10582
10583   return SDValue();
10584 }
10585
10586 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10587 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10588 // one of the above mentioned nodes. It has to be wrapped because otherwise
10589 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10590 // be used to form addressing mode. These wrapped nodes will be selected
10591 // into MOV32ri.
10592 SDValue
10593 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10594   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10595
10596   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10597   // global base reg.
10598   unsigned char OpFlag = 0;
10599   unsigned WrapperKind = X86ISD::Wrapper;
10600   CodeModel::Model M = DAG.getTarget().getCodeModel();
10601
10602   if (Subtarget->isPICStyleRIPRel() &&
10603       (M == CodeModel::Small || M == CodeModel::Kernel))
10604     WrapperKind = X86ISD::WrapperRIP;
10605   else if (Subtarget->isPICStyleGOT())
10606     OpFlag = X86II::MO_GOTOFF;
10607   else if (Subtarget->isPICStyleStubPIC())
10608     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10609
10610   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10611                                              CP->getAlignment(),
10612                                              CP->getOffset(), OpFlag);
10613   SDLoc DL(CP);
10614   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10615   // With PIC, the address is actually $g + Offset.
10616   if (OpFlag) {
10617     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10618                          DAG.getNode(X86ISD::GlobalBaseReg,
10619                                      SDLoc(), getPointerTy()),
10620                          Result);
10621   }
10622
10623   return Result;
10624 }
10625
10626 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10627   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10628
10629   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10630   // global base reg.
10631   unsigned char OpFlag = 0;
10632   unsigned WrapperKind = X86ISD::Wrapper;
10633   CodeModel::Model M = DAG.getTarget().getCodeModel();
10634
10635   if (Subtarget->isPICStyleRIPRel() &&
10636       (M == CodeModel::Small || M == CodeModel::Kernel))
10637     WrapperKind = X86ISD::WrapperRIP;
10638   else if (Subtarget->isPICStyleGOT())
10639     OpFlag = X86II::MO_GOTOFF;
10640   else if (Subtarget->isPICStyleStubPIC())
10641     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10642
10643   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10644                                           OpFlag);
10645   SDLoc DL(JT);
10646   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10647
10648   // With PIC, the address is actually $g + Offset.
10649   if (OpFlag)
10650     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10651                          DAG.getNode(X86ISD::GlobalBaseReg,
10652                                      SDLoc(), getPointerTy()),
10653                          Result);
10654
10655   return Result;
10656 }
10657
10658 SDValue
10659 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10660   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10661
10662   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10663   // global base reg.
10664   unsigned char OpFlag = 0;
10665   unsigned WrapperKind = X86ISD::Wrapper;
10666   CodeModel::Model M = DAG.getTarget().getCodeModel();
10667
10668   if (Subtarget->isPICStyleRIPRel() &&
10669       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10670     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10671       OpFlag = X86II::MO_GOTPCREL;
10672     WrapperKind = X86ISD::WrapperRIP;
10673   } else if (Subtarget->isPICStyleGOT()) {
10674     OpFlag = X86II::MO_GOT;
10675   } else if (Subtarget->isPICStyleStubPIC()) {
10676     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10677   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10678     OpFlag = X86II::MO_DARWIN_NONLAZY;
10679   }
10680
10681   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10682
10683   SDLoc DL(Op);
10684   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10685
10686   // With PIC, the address is actually $g + Offset.
10687   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10688       !Subtarget->is64Bit()) {
10689     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10690                          DAG.getNode(X86ISD::GlobalBaseReg,
10691                                      SDLoc(), getPointerTy()),
10692                          Result);
10693   }
10694
10695   // For symbols that require a load from a stub to get the address, emit the
10696   // load.
10697   if (isGlobalStubReference(OpFlag))
10698     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10699                          MachinePointerInfo::getGOT(), false, false, false, 0);
10700
10701   return Result;
10702 }
10703
10704 SDValue
10705 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10706   // Create the TargetBlockAddressAddress node.
10707   unsigned char OpFlags =
10708     Subtarget->ClassifyBlockAddressReference();
10709   CodeModel::Model M = DAG.getTarget().getCodeModel();
10710   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10711   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10712   SDLoc dl(Op);
10713   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10714                                              OpFlags);
10715
10716   if (Subtarget->isPICStyleRIPRel() &&
10717       (M == CodeModel::Small || M == CodeModel::Kernel))
10718     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10719   else
10720     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10721
10722   // With PIC, the address is actually $g + Offset.
10723   if (isGlobalRelativeToPICBase(OpFlags)) {
10724     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10725                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10726                          Result);
10727   }
10728
10729   return Result;
10730 }
10731
10732 SDValue
10733 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10734                                       int64_t Offset, SelectionDAG &DAG) const {
10735   // Create the TargetGlobalAddress node, folding in the constant
10736   // offset if it is legal.
10737   unsigned char OpFlags =
10738       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10739   CodeModel::Model M = DAG.getTarget().getCodeModel();
10740   SDValue Result;
10741   if (OpFlags == X86II::MO_NO_FLAG &&
10742       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10743     // A direct static reference to a global.
10744     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10745     Offset = 0;
10746   } else {
10747     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10748   }
10749
10750   if (Subtarget->isPICStyleRIPRel() &&
10751       (M == CodeModel::Small || M == CodeModel::Kernel))
10752     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10753   else
10754     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10755
10756   // With PIC, the address is actually $g + Offset.
10757   if (isGlobalRelativeToPICBase(OpFlags)) {
10758     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10759                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10760                          Result);
10761   }
10762
10763   // For globals that require a load from a stub to get the address, emit the
10764   // load.
10765   if (isGlobalStubReference(OpFlags))
10766     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10767                          MachinePointerInfo::getGOT(), false, false, false, 0);
10768
10769   // If there was a non-zero offset that we didn't fold, create an explicit
10770   // addition for it.
10771   if (Offset != 0)
10772     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10773                          DAG.getConstant(Offset, getPointerTy()));
10774
10775   return Result;
10776 }
10777
10778 SDValue
10779 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10780   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10781   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10782   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10783 }
10784
10785 static SDValue
10786 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10787            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10788            unsigned char OperandFlags, bool LocalDynamic = false) {
10789   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10790   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10791   SDLoc dl(GA);
10792   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10793                                            GA->getValueType(0),
10794                                            GA->getOffset(),
10795                                            OperandFlags);
10796
10797   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10798                                            : X86ISD::TLSADDR;
10799
10800   if (InFlag) {
10801     SDValue Ops[] = { Chain,  TGA, *InFlag };
10802     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10803   } else {
10804     SDValue Ops[]  = { Chain, TGA };
10805     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10806   }
10807
10808   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10809   MFI->setAdjustsStack(true);
10810   MFI->setHasCalls(true);
10811
10812   SDValue Flag = Chain.getValue(1);
10813   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10814 }
10815
10816 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10817 static SDValue
10818 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10819                                 const EVT PtrVT) {
10820   SDValue InFlag;
10821   SDLoc dl(GA);  // ? function entry point might be better
10822   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10823                                    DAG.getNode(X86ISD::GlobalBaseReg,
10824                                                SDLoc(), PtrVT), InFlag);
10825   InFlag = Chain.getValue(1);
10826
10827   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10828 }
10829
10830 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10831 static SDValue
10832 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10833                                 const EVT PtrVT) {
10834   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10835                     X86::RAX, X86II::MO_TLSGD);
10836 }
10837
10838 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10839                                            SelectionDAG &DAG,
10840                                            const EVT PtrVT,
10841                                            bool is64Bit) {
10842   SDLoc dl(GA);
10843
10844   // Get the start address of the TLS block for this module.
10845   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10846       .getInfo<X86MachineFunctionInfo>();
10847   MFI->incNumLocalDynamicTLSAccesses();
10848
10849   SDValue Base;
10850   if (is64Bit) {
10851     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10852                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10853   } else {
10854     SDValue InFlag;
10855     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10856         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10857     InFlag = Chain.getValue(1);
10858     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10859                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10860   }
10861
10862   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10863   // of Base.
10864
10865   // Build x@dtpoff.
10866   unsigned char OperandFlags = X86II::MO_DTPOFF;
10867   unsigned WrapperKind = X86ISD::Wrapper;
10868   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10869                                            GA->getValueType(0),
10870                                            GA->getOffset(), OperandFlags);
10871   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10872
10873   // Add x@dtpoff with the base.
10874   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10875 }
10876
10877 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10878 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10879                                    const EVT PtrVT, TLSModel::Model model,
10880                                    bool is64Bit, bool isPIC) {
10881   SDLoc dl(GA);
10882
10883   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10884   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10885                                                          is64Bit ? 257 : 256));
10886
10887   SDValue ThreadPointer =
10888       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10889                   MachinePointerInfo(Ptr), false, false, false, 0);
10890
10891   unsigned char OperandFlags = 0;
10892   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10893   // initialexec.
10894   unsigned WrapperKind = X86ISD::Wrapper;
10895   if (model == TLSModel::LocalExec) {
10896     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10897   } else if (model == TLSModel::InitialExec) {
10898     if (is64Bit) {
10899       OperandFlags = X86II::MO_GOTTPOFF;
10900       WrapperKind = X86ISD::WrapperRIP;
10901     } else {
10902       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10903     }
10904   } else {
10905     llvm_unreachable("Unexpected model");
10906   }
10907
10908   // emit "addl x@ntpoff,%eax" (local exec)
10909   // or "addl x@indntpoff,%eax" (initial exec)
10910   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10911   SDValue TGA =
10912       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10913                                  GA->getOffset(), OperandFlags);
10914   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10915
10916   if (model == TLSModel::InitialExec) {
10917     if (isPIC && !is64Bit) {
10918       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10919                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10920                            Offset);
10921     }
10922
10923     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10924                          MachinePointerInfo::getGOT(), false, false, false, 0);
10925   }
10926
10927   // The address of the thread local variable is the add of the thread
10928   // pointer with the offset of the variable.
10929   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10930 }
10931
10932 SDValue
10933 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10934
10935   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10936   const GlobalValue *GV = GA->getGlobal();
10937
10938   if (Subtarget->isTargetELF()) {
10939     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10940
10941     switch (model) {
10942       case TLSModel::GeneralDynamic:
10943         if (Subtarget->is64Bit())
10944           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10945         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10946       case TLSModel::LocalDynamic:
10947         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10948                                            Subtarget->is64Bit());
10949       case TLSModel::InitialExec:
10950       case TLSModel::LocalExec:
10951         return LowerToTLSExecModel(
10952             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10953             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10954     }
10955     llvm_unreachable("Unknown TLS model.");
10956   }
10957
10958   if (Subtarget->isTargetDarwin()) {
10959     // Darwin only has one model of TLS.  Lower to that.
10960     unsigned char OpFlag = 0;
10961     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10962                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10963
10964     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10965     // global base reg.
10966     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10967                  !Subtarget->is64Bit();
10968     if (PIC32)
10969       OpFlag = X86II::MO_TLVP_PIC_BASE;
10970     else
10971       OpFlag = X86II::MO_TLVP;
10972     SDLoc DL(Op);
10973     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10974                                                 GA->getValueType(0),
10975                                                 GA->getOffset(), OpFlag);
10976     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10977
10978     // With PIC32, the address is actually $g + Offset.
10979     if (PIC32)
10980       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10981                            DAG.getNode(X86ISD::GlobalBaseReg,
10982                                        SDLoc(), getPointerTy()),
10983                            Offset);
10984
10985     // Lowering the machine isd will make sure everything is in the right
10986     // location.
10987     SDValue Chain = DAG.getEntryNode();
10988     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10989     SDValue Args[] = { Chain, Offset };
10990     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10991
10992     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10993     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10994     MFI->setAdjustsStack(true);
10995
10996     // And our return value (tls address) is in the standard call return value
10997     // location.
10998     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10999     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11000                               Chain.getValue(1));
11001   }
11002
11003   if (Subtarget->isTargetKnownWindowsMSVC() ||
11004       Subtarget->isTargetWindowsGNU()) {
11005     // Just use the implicit TLS architecture
11006     // Need to generate someting similar to:
11007     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11008     //                                  ; from TEB
11009     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11010     //   mov     rcx, qword [rdx+rcx*8]
11011     //   mov     eax, .tls$:tlsvar
11012     //   [rax+rcx] contains the address
11013     // Windows 64bit: gs:0x58
11014     // Windows 32bit: fs:__tls_array
11015
11016     SDLoc dl(GA);
11017     SDValue Chain = DAG.getEntryNode();
11018
11019     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11020     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11021     // use its literal value of 0x2C.
11022     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11023                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11024                                                              256)
11025                                         : Type::getInt32PtrTy(*DAG.getContext(),
11026                                                               257));
11027
11028     SDValue TlsArray =
11029         Subtarget->is64Bit()
11030             ? DAG.getIntPtrConstant(0x58)
11031             : (Subtarget->isTargetWindowsGNU()
11032                    ? DAG.getIntPtrConstant(0x2C)
11033                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11034
11035     SDValue ThreadPointer =
11036         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11037                     MachinePointerInfo(Ptr), false, false, false, 0);
11038
11039     // Load the _tls_index variable
11040     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11041     if (Subtarget->is64Bit())
11042       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11043                            IDX, MachinePointerInfo(), MVT::i32,
11044                            false, false, false, 0);
11045     else
11046       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11047                         false, false, false, 0);
11048
11049     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11050                                     getPointerTy());
11051     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11052
11053     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11054     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11055                       false, false, false, 0);
11056
11057     // Get the offset of start of .tls section
11058     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11059                                              GA->getValueType(0),
11060                                              GA->getOffset(), X86II::MO_SECREL);
11061     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11062
11063     // The address of the thread local variable is the add of the thread
11064     // pointer with the offset of the variable.
11065     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11066   }
11067
11068   llvm_unreachable("TLS not implemented for this target.");
11069 }
11070
11071 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11072 /// and take a 2 x i32 value to shift plus a shift amount.
11073 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11074   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11075   MVT VT = Op.getSimpleValueType();
11076   unsigned VTBits = VT.getSizeInBits();
11077   SDLoc dl(Op);
11078   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11079   SDValue ShOpLo = Op.getOperand(0);
11080   SDValue ShOpHi = Op.getOperand(1);
11081   SDValue ShAmt  = Op.getOperand(2);
11082   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11083   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11084   // during isel.
11085   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11086                                   DAG.getConstant(VTBits - 1, MVT::i8));
11087   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11088                                      DAG.getConstant(VTBits - 1, MVT::i8))
11089                        : DAG.getConstant(0, VT);
11090
11091   SDValue Tmp2, Tmp3;
11092   if (Op.getOpcode() == ISD::SHL_PARTS) {
11093     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11094     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11095   } else {
11096     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11097     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11098   }
11099
11100   // If the shift amount is larger or equal than the width of a part we can't
11101   // rely on the results of shld/shrd. Insert a test and select the appropriate
11102   // values for large shift amounts.
11103   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11104                                 DAG.getConstant(VTBits, MVT::i8));
11105   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11106                              AndNode, DAG.getConstant(0, MVT::i8));
11107
11108   SDValue Hi, Lo;
11109   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11110   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11111   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11112
11113   if (Op.getOpcode() == ISD::SHL_PARTS) {
11114     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11115     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11116   } else {
11117     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11118     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11119   }
11120
11121   SDValue Ops[2] = { Lo, Hi };
11122   return DAG.getMergeValues(Ops, dl);
11123 }
11124
11125 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11126                                            SelectionDAG &DAG) const {
11127   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11128   SDLoc dl(Op);
11129
11130   if (SrcVT.isVector()) {
11131     if (SrcVT.getVectorElementType() == MVT::i1) {
11132       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11133       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11134                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11135                                      Op.getOperand(0)));
11136     }
11137     return SDValue();
11138   }
11139
11140   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11141          "Unknown SINT_TO_FP to lower!");
11142
11143   // These are really Legal; return the operand so the caller accepts it as
11144   // Legal.
11145   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11146     return Op;
11147   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11148       Subtarget->is64Bit()) {
11149     return Op;
11150   }
11151
11152   unsigned Size = SrcVT.getSizeInBits()/8;
11153   MachineFunction &MF = DAG.getMachineFunction();
11154   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11155   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11156   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11157                                StackSlot,
11158                                MachinePointerInfo::getFixedStack(SSFI),
11159                                false, false, 0);
11160   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11161 }
11162
11163 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11164                                      SDValue StackSlot,
11165                                      SelectionDAG &DAG) const {
11166   // Build the FILD
11167   SDLoc DL(Op);
11168   SDVTList Tys;
11169   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11170   if (useSSE)
11171     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11172   else
11173     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11174
11175   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11176
11177   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11178   MachineMemOperand *MMO;
11179   if (FI) {
11180     int SSFI = FI->getIndex();
11181     MMO =
11182       DAG.getMachineFunction()
11183       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11184                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11185   } else {
11186     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11187     StackSlot = StackSlot.getOperand(1);
11188   }
11189   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11190   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11191                                            X86ISD::FILD, DL,
11192                                            Tys, Ops, SrcVT, MMO);
11193
11194   if (useSSE) {
11195     Chain = Result.getValue(1);
11196     SDValue InFlag = Result.getValue(2);
11197
11198     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11199     // shouldn't be necessary except that RFP cannot be live across
11200     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11201     MachineFunction &MF = DAG.getMachineFunction();
11202     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11203     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11204     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11205     Tys = DAG.getVTList(MVT::Other);
11206     SDValue Ops[] = {
11207       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11208     };
11209     MachineMemOperand *MMO =
11210       DAG.getMachineFunction()
11211       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11212                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11213
11214     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11215                                     Ops, Op.getValueType(), MMO);
11216     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11217                          MachinePointerInfo::getFixedStack(SSFI),
11218                          false, false, false, 0);
11219   }
11220
11221   return Result;
11222 }
11223
11224 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11225 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11226                                                SelectionDAG &DAG) const {
11227   // This algorithm is not obvious. Here it is what we're trying to output:
11228   /*
11229      movq       %rax,  %xmm0
11230      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11231      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11232      #ifdef __SSE3__
11233        haddpd   %xmm0, %xmm0
11234      #else
11235        pshufd   $0x4e, %xmm0, %xmm1
11236        addpd    %xmm1, %xmm0
11237      #endif
11238   */
11239
11240   SDLoc dl(Op);
11241   LLVMContext *Context = DAG.getContext();
11242
11243   // Build some magic constants.
11244   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11245   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11246   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11247
11248   SmallVector<Constant*,2> CV1;
11249   CV1.push_back(
11250     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11251                                       APInt(64, 0x4330000000000000ULL))));
11252   CV1.push_back(
11253     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11254                                       APInt(64, 0x4530000000000000ULL))));
11255   Constant *C1 = ConstantVector::get(CV1);
11256   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11257
11258   // Load the 64-bit value into an XMM register.
11259   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11260                             Op.getOperand(0));
11261   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11262                               MachinePointerInfo::getConstantPool(),
11263                               false, false, false, 16);
11264   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11265                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11266                               CLod0);
11267
11268   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11269                               MachinePointerInfo::getConstantPool(),
11270                               false, false, false, 16);
11271   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11272   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11273   SDValue Result;
11274
11275   if (Subtarget->hasSSE3()) {
11276     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11277     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11278   } else {
11279     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11280     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11281                                            S2F, 0x4E, DAG);
11282     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11283                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11284                          Sub);
11285   }
11286
11287   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11288                      DAG.getIntPtrConstant(0));
11289 }
11290
11291 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11292 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11293                                                SelectionDAG &DAG) const {
11294   SDLoc dl(Op);
11295   // FP constant to bias correct the final result.
11296   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11297                                    MVT::f64);
11298
11299   // Load the 32-bit value into an XMM register.
11300   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11301                              Op.getOperand(0));
11302
11303   // Zero out the upper parts of the register.
11304   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11305
11306   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11307                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11308                      DAG.getIntPtrConstant(0));
11309
11310   // Or the load with the bias.
11311   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11312                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11313                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11314                                                    MVT::v2f64, Load)),
11315                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11316                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11317                                                    MVT::v2f64, Bias)));
11318   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11319                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11320                    DAG.getIntPtrConstant(0));
11321
11322   // Subtract the bias.
11323   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11324
11325   // Handle final rounding.
11326   EVT DestVT = Op.getValueType();
11327
11328   if (DestVT.bitsLT(MVT::f64))
11329     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11330                        DAG.getIntPtrConstant(0));
11331   if (DestVT.bitsGT(MVT::f64))
11332     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11333
11334   // Handle final rounding.
11335   return Sub;
11336 }
11337
11338 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11339                                      const X86Subtarget &Subtarget) {
11340   // The algorithm is the following:
11341   // #ifdef __SSE4_1__
11342   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11343   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11344   //                                 (uint4) 0x53000000, 0xaa);
11345   // #else
11346   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11347   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11348   // #endif
11349   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11350   //     return (float4) lo + fhi;
11351
11352   SDLoc DL(Op);
11353   SDValue V = Op->getOperand(0);
11354   EVT VecIntVT = V.getValueType();
11355   bool Is128 = VecIntVT == MVT::v4i32;
11356   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11357   // If we convert to something else than the supported type, e.g., to v4f64,
11358   // abort early.
11359   if (VecFloatVT != Op->getValueType(0))
11360     return SDValue();
11361
11362   unsigned NumElts = VecIntVT.getVectorNumElements();
11363   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11364          "Unsupported custom type");
11365   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11366
11367   // In the #idef/#else code, we have in common:
11368   // - The vector of constants:
11369   // -- 0x4b000000
11370   // -- 0x53000000
11371   // - A shift:
11372   // -- v >> 16
11373
11374   // Create the splat vector for 0x4b000000.
11375   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11376   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11377                            CstLow, CstLow, CstLow, CstLow};
11378   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11379                                   makeArrayRef(&CstLowArray[0], NumElts));
11380   // Create the splat vector for 0x53000000.
11381   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11382   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11383                             CstHigh, CstHigh, CstHigh, CstHigh};
11384   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11385                                    makeArrayRef(&CstHighArray[0], NumElts));
11386
11387   // Create the right shift.
11388   SDValue CstShift = DAG.getConstant(16, MVT::i32);
11389   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11390                              CstShift, CstShift, CstShift, CstShift};
11391   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11392                                     makeArrayRef(&CstShiftArray[0], NumElts));
11393   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11394
11395   SDValue Low, High;
11396   if (Subtarget.hasSSE41()) {
11397     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11398     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11399     SDValue VecCstLowBitcast =
11400         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11401     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11402     // Low will be bitcasted right away, so do not bother bitcasting back to its
11403     // original type.
11404     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11405                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11406     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11407     //                                 (uint4) 0x53000000, 0xaa);
11408     SDValue VecCstHighBitcast =
11409         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11410     SDValue VecShiftBitcast =
11411         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11412     // High will be bitcasted right away, so do not bother bitcasting back to
11413     // its original type.
11414     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11415                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11416   } else {
11417     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11418     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11419                                      CstMask, CstMask, CstMask);
11420     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11421     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11422     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11423
11424     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11425     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11426   }
11427
11428   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11429   SDValue CstFAdd = DAG.getConstantFP(
11430       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11431   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11432                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11433   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11434                                    makeArrayRef(&CstFAddArray[0], NumElts));
11435
11436   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11437   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11438   SDValue FHigh =
11439       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11440   //     return (float4) lo + fhi;
11441   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11442   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11443 }
11444
11445 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11446                                                SelectionDAG &DAG) const {
11447   SDValue N0 = Op.getOperand(0);
11448   MVT SVT = N0.getSimpleValueType();
11449   SDLoc dl(Op);
11450
11451   switch (SVT.SimpleTy) {
11452   default:
11453     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11454   case MVT::v4i8:
11455   case MVT::v4i16:
11456   case MVT::v8i8:
11457   case MVT::v8i16: {
11458     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11459     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11460                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11461   }
11462   case MVT::v4i32:
11463   case MVT::v8i32:
11464     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11465   }
11466   llvm_unreachable(nullptr);
11467 }
11468
11469 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11470                                            SelectionDAG &DAG) const {
11471   SDValue N0 = Op.getOperand(0);
11472   SDLoc dl(Op);
11473
11474   if (Op.getValueType().isVector())
11475     return lowerUINT_TO_FP_vec(Op, DAG);
11476
11477   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11478   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11479   // the optimization here.
11480   if (DAG.SignBitIsZero(N0))
11481     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11482
11483   MVT SrcVT = N0.getSimpleValueType();
11484   MVT DstVT = Op.getSimpleValueType();
11485   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11486     return LowerUINT_TO_FP_i64(Op, DAG);
11487   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11488     return LowerUINT_TO_FP_i32(Op, DAG);
11489   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11490     return SDValue();
11491
11492   // Make a 64-bit buffer, and use it to build an FILD.
11493   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11494   if (SrcVT == MVT::i32) {
11495     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11496     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11497                                      getPointerTy(), StackSlot, WordOff);
11498     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11499                                   StackSlot, MachinePointerInfo(),
11500                                   false, false, 0);
11501     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11502                                   OffsetSlot, MachinePointerInfo(),
11503                                   false, false, 0);
11504     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11505     return Fild;
11506   }
11507
11508   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11509   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11510                                StackSlot, MachinePointerInfo(),
11511                                false, false, 0);
11512   // For i64 source, we need to add the appropriate power of 2 if the input
11513   // was negative.  This is the same as the optimization in
11514   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11515   // we must be careful to do the computation in x87 extended precision, not
11516   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11517   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11518   MachineMemOperand *MMO =
11519     DAG.getMachineFunction()
11520     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11521                           MachineMemOperand::MOLoad, 8, 8);
11522
11523   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11524   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11525   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11526                                          MVT::i64, MMO);
11527
11528   APInt FF(32, 0x5F800000ULL);
11529
11530   // Check whether the sign bit is set.
11531   SDValue SignSet = DAG.getSetCC(dl,
11532                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11533                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11534                                  ISD::SETLT);
11535
11536   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11537   SDValue FudgePtr = DAG.getConstantPool(
11538                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11539                                          getPointerTy());
11540
11541   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11542   SDValue Zero = DAG.getIntPtrConstant(0);
11543   SDValue Four = DAG.getIntPtrConstant(4);
11544   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11545                                Zero, Four);
11546   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11547
11548   // Load the value out, extending it from f32 to f80.
11549   // FIXME: Avoid the extend by constructing the right constant pool?
11550   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11551                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11552                                  MVT::f32, false, false, false, 4);
11553   // Extend everything to 80 bits to force it to be done on x87.
11554   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11555   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11556 }
11557
11558 std::pair<SDValue,SDValue>
11559 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11560                                     bool IsSigned, bool IsReplace) const {
11561   SDLoc DL(Op);
11562
11563   EVT DstTy = Op.getValueType();
11564
11565   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11566     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11567     DstTy = MVT::i64;
11568   }
11569
11570   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11571          DstTy.getSimpleVT() >= MVT::i16 &&
11572          "Unknown FP_TO_INT to lower!");
11573
11574   // These are really Legal.
11575   if (DstTy == MVT::i32 &&
11576       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11577     return std::make_pair(SDValue(), SDValue());
11578   if (Subtarget->is64Bit() &&
11579       DstTy == MVT::i64 &&
11580       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11581     return std::make_pair(SDValue(), SDValue());
11582
11583   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11584   // stack slot, or into the FTOL runtime function.
11585   MachineFunction &MF = DAG.getMachineFunction();
11586   unsigned MemSize = DstTy.getSizeInBits()/8;
11587   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11588   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11589
11590   unsigned Opc;
11591   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11592     Opc = X86ISD::WIN_FTOL;
11593   else
11594     switch (DstTy.getSimpleVT().SimpleTy) {
11595     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11596     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11597     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11598     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11599     }
11600
11601   SDValue Chain = DAG.getEntryNode();
11602   SDValue Value = Op.getOperand(0);
11603   EVT TheVT = Op.getOperand(0).getValueType();
11604   // FIXME This causes a redundant load/store if the SSE-class value is already
11605   // in memory, such as if it is on the callstack.
11606   if (isScalarFPTypeInSSEReg(TheVT)) {
11607     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11608     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11609                          MachinePointerInfo::getFixedStack(SSFI),
11610                          false, false, 0);
11611     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11612     SDValue Ops[] = {
11613       Chain, StackSlot, DAG.getValueType(TheVT)
11614     };
11615
11616     MachineMemOperand *MMO =
11617       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11618                               MachineMemOperand::MOLoad, MemSize, MemSize);
11619     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11620     Chain = Value.getValue(1);
11621     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11622     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11623   }
11624
11625   MachineMemOperand *MMO =
11626     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11627                             MachineMemOperand::MOStore, MemSize, MemSize);
11628
11629   if (Opc != X86ISD::WIN_FTOL) {
11630     // Build the FP_TO_INT*_IN_MEM
11631     SDValue Ops[] = { Chain, Value, StackSlot };
11632     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11633                                            Ops, DstTy, MMO);
11634     return std::make_pair(FIST, StackSlot);
11635   } else {
11636     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11637       DAG.getVTList(MVT::Other, MVT::Glue),
11638       Chain, Value);
11639     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11640       MVT::i32, ftol.getValue(1));
11641     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11642       MVT::i32, eax.getValue(2));
11643     SDValue Ops[] = { eax, edx };
11644     SDValue pair = IsReplace
11645       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11646       : DAG.getMergeValues(Ops, DL);
11647     return std::make_pair(pair, SDValue());
11648   }
11649 }
11650
11651 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11652                               const X86Subtarget *Subtarget) {
11653   MVT VT = Op->getSimpleValueType(0);
11654   SDValue In = Op->getOperand(0);
11655   MVT InVT = In.getSimpleValueType();
11656   SDLoc dl(Op);
11657
11658   // Optimize vectors in AVX mode:
11659   //
11660   //   v8i16 -> v8i32
11661   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11662   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11663   //   Concat upper and lower parts.
11664   //
11665   //   v4i32 -> v4i64
11666   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11667   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11668   //   Concat upper and lower parts.
11669   //
11670
11671   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11672       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11673       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11674     return SDValue();
11675
11676   if (Subtarget->hasInt256())
11677     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11678
11679   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11680   SDValue Undef = DAG.getUNDEF(InVT);
11681   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11682   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11683   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11684
11685   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11686                              VT.getVectorNumElements()/2);
11687
11688   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11689   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11690
11691   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11692 }
11693
11694 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11695                                         SelectionDAG &DAG) {
11696   MVT VT = Op->getSimpleValueType(0);
11697   SDValue In = Op->getOperand(0);
11698   MVT InVT = In.getSimpleValueType();
11699   SDLoc DL(Op);
11700   unsigned int NumElts = VT.getVectorNumElements();
11701   if (NumElts != 8 && NumElts != 16)
11702     return SDValue();
11703
11704   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11705     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11706
11707   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11708   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11709   // Now we have only mask extension
11710   assert(InVT.getVectorElementType() == MVT::i1);
11711   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11712   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11713   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11714   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11715   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11716                            MachinePointerInfo::getConstantPool(),
11717                            false, false, false, Alignment);
11718
11719   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11720   if (VT.is512BitVector())
11721     return Brcst;
11722   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11723 }
11724
11725 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11726                                SelectionDAG &DAG) {
11727   if (Subtarget->hasFp256()) {
11728     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11729     if (Res.getNode())
11730       return Res;
11731   }
11732
11733   return SDValue();
11734 }
11735
11736 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11737                                 SelectionDAG &DAG) {
11738   SDLoc DL(Op);
11739   MVT VT = Op.getSimpleValueType();
11740   SDValue In = Op.getOperand(0);
11741   MVT SVT = In.getSimpleValueType();
11742
11743   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11744     return LowerZERO_EXTEND_AVX512(Op, DAG);
11745
11746   if (Subtarget->hasFp256()) {
11747     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11748     if (Res.getNode())
11749       return Res;
11750   }
11751
11752   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11753          VT.getVectorNumElements() != SVT.getVectorNumElements());
11754   return SDValue();
11755 }
11756
11757 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11758   SDLoc DL(Op);
11759   MVT VT = Op.getSimpleValueType();
11760   SDValue In = Op.getOperand(0);
11761   MVT InVT = In.getSimpleValueType();
11762
11763   if (VT == MVT::i1) {
11764     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11765            "Invalid scalar TRUNCATE operation");
11766     if (InVT.getSizeInBits() >= 32)
11767       return SDValue();
11768     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11769     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11770   }
11771   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11772          "Invalid TRUNCATE operation");
11773
11774   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11775     if (VT.getVectorElementType().getSizeInBits() >=8)
11776       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11777
11778     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11779     unsigned NumElts = InVT.getVectorNumElements();
11780     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11781     if (InVT.getSizeInBits() < 512) {
11782       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11783       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11784       InVT = ExtVT;
11785     }
11786
11787     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11788     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11789     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11790     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11791     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11792                            MachinePointerInfo::getConstantPool(),
11793                            false, false, false, Alignment);
11794     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11795     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11796     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11797   }
11798
11799   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11800     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11801     if (Subtarget->hasInt256()) {
11802       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11803       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11804       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11805                                 ShufMask);
11806       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11807                          DAG.getIntPtrConstant(0));
11808     }
11809
11810     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11811                                DAG.getIntPtrConstant(0));
11812     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11813                                DAG.getIntPtrConstant(2));
11814     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11815     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11816     static const int ShufMask[] = {0, 2, 4, 6};
11817     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11818   }
11819
11820   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11821     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11822     if (Subtarget->hasInt256()) {
11823       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11824
11825       SmallVector<SDValue,32> pshufbMask;
11826       for (unsigned i = 0; i < 2; ++i) {
11827         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11828         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11829         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11830         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11831         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11832         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11833         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11834         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11835         for (unsigned j = 0; j < 8; ++j)
11836           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11837       }
11838       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11839       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11840       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11841
11842       static const int ShufMask[] = {0,  2,  -1,  -1};
11843       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11844                                 &ShufMask[0]);
11845       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11846                        DAG.getIntPtrConstant(0));
11847       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11848     }
11849
11850     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11851                                DAG.getIntPtrConstant(0));
11852
11853     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11854                                DAG.getIntPtrConstant(4));
11855
11856     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11857     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11858
11859     // The PSHUFB mask:
11860     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11861                                    -1, -1, -1, -1, -1, -1, -1, -1};
11862
11863     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11864     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11865     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11866
11867     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11868     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11869
11870     // The MOVLHPS Mask:
11871     static const int ShufMask2[] = {0, 1, 4, 5};
11872     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11873     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11874   }
11875
11876   // Handle truncation of V256 to V128 using shuffles.
11877   if (!VT.is128BitVector() || !InVT.is256BitVector())
11878     return SDValue();
11879
11880   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11881
11882   unsigned NumElems = VT.getVectorNumElements();
11883   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11884
11885   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11886   // Prepare truncation shuffle mask
11887   for (unsigned i = 0; i != NumElems; ++i)
11888     MaskVec[i] = i * 2;
11889   SDValue V = DAG.getVectorShuffle(NVT, DL,
11890                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11891                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11892   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11893                      DAG.getIntPtrConstant(0));
11894 }
11895
11896 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11897                                            SelectionDAG &DAG) const {
11898   assert(!Op.getSimpleValueType().isVector());
11899
11900   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11901     /*IsSigned=*/ true, /*IsReplace=*/ false);
11902   SDValue FIST = Vals.first, StackSlot = Vals.second;
11903   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11904   if (!FIST.getNode()) return Op;
11905
11906   if (StackSlot.getNode())
11907     // Load the result.
11908     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11909                        FIST, StackSlot, MachinePointerInfo(),
11910                        false, false, false, 0);
11911
11912   // The node is the result.
11913   return FIST;
11914 }
11915
11916 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11917                                            SelectionDAG &DAG) const {
11918   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11919     /*IsSigned=*/ false, /*IsReplace=*/ false);
11920   SDValue FIST = Vals.first, StackSlot = Vals.second;
11921   assert(FIST.getNode() && "Unexpected failure");
11922
11923   if (StackSlot.getNode())
11924     // Load the result.
11925     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11926                        FIST, StackSlot, MachinePointerInfo(),
11927                        false, false, false, 0);
11928
11929   // The node is the result.
11930   return FIST;
11931 }
11932
11933 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11934   SDLoc DL(Op);
11935   MVT VT = Op.getSimpleValueType();
11936   SDValue In = Op.getOperand(0);
11937   MVT SVT = In.getSimpleValueType();
11938
11939   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11940
11941   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11942                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11943                                  In, DAG.getUNDEF(SVT)));
11944 }
11945
11946 /// The only differences between FABS and FNEG are the mask and the logic op.
11947 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
11948 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
11949   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
11950          "Wrong opcode for lowering FABS or FNEG.");
11951
11952   bool IsFABS = (Op.getOpcode() == ISD::FABS);
11953
11954   // If this is a FABS and it has an FNEG user, bail out to fold the combination
11955   // into an FNABS. We'll lower the FABS after that if it is still in use.
11956   if (IsFABS)
11957     for (SDNode *User : Op->uses())
11958       if (User->getOpcode() == ISD::FNEG)
11959         return Op;
11960
11961   SDValue Op0 = Op.getOperand(0);
11962   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
11963
11964   SDLoc dl(Op);
11965   MVT VT = Op.getSimpleValueType();
11966   // Assume scalar op for initialization; update for vector if needed.
11967   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
11968   // generate a 16-byte vector constant and logic op even for the scalar case.
11969   // Using a 16-byte mask allows folding the load of the mask with
11970   // the logic op, so it can save (~4 bytes) on code size.
11971   MVT EltVT = VT;
11972   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11973   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
11974   // decide if we should generate a 16-byte constant mask when we only need 4 or
11975   // 8 bytes for the scalar case.
11976   if (VT.isVector()) {
11977     EltVT = VT.getVectorElementType();
11978     NumElts = VT.getVectorNumElements();
11979   }
11980
11981   unsigned EltBits = EltVT.getSizeInBits();
11982   LLVMContext *Context = DAG.getContext();
11983   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
11984   APInt MaskElt =
11985     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
11986   Constant *C = ConstantInt::get(*Context, MaskElt);
11987   C = ConstantVector::getSplat(NumElts, C);
11988   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11989   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11990   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11991   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11992                              MachinePointerInfo::getConstantPool(),
11993                              false, false, false, Alignment);
11994
11995   if (VT.isVector()) {
11996     // For a vector, cast operands to a vector type, perform the logic op,
11997     // and cast the result back to the original value type.
11998     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
11999     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12000     SDValue Operand = IsFNABS ?
12001       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12002       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12003     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12004     return DAG.getNode(ISD::BITCAST, dl, VT,
12005                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12006   }
12007
12008   // If not vector, then scalar.
12009   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12010   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12011   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12012 }
12013
12014 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12015   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12016   LLVMContext *Context = DAG.getContext();
12017   SDValue Op0 = Op.getOperand(0);
12018   SDValue Op1 = Op.getOperand(1);
12019   SDLoc dl(Op);
12020   MVT VT = Op.getSimpleValueType();
12021   MVT SrcVT = Op1.getSimpleValueType();
12022
12023   // If second operand is smaller, extend it first.
12024   if (SrcVT.bitsLT(VT)) {
12025     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12026     SrcVT = VT;
12027   }
12028   // And if it is bigger, shrink it first.
12029   if (SrcVT.bitsGT(VT)) {
12030     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12031     SrcVT = VT;
12032   }
12033
12034   // At this point the operands and the result should have the same
12035   // type, and that won't be f80 since that is not custom lowered.
12036
12037   const fltSemantics &Sem =
12038       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12039   const unsigned SizeInBits = VT.getSizeInBits();
12040
12041   SmallVector<Constant *, 4> CV(
12042       VT == MVT::f64 ? 2 : 4,
12043       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12044
12045   // First, clear all bits but the sign bit from the second operand (sign).
12046   CV[0] = ConstantFP::get(*Context,
12047                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12048   Constant *C = ConstantVector::get(CV);
12049   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12050   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12051                               MachinePointerInfo::getConstantPool(),
12052                               false, false, false, 16);
12053   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12054
12055   // Next, clear the sign bit from the first operand (magnitude).
12056   // If it's a constant, we can clear it here.
12057   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12058     APFloat APF = Op0CN->getValueAPF();
12059     // If the magnitude is a positive zero, the sign bit alone is enough.
12060     if (APF.isPosZero())
12061       return SignBit;
12062     APF.clearSign();
12063     CV[0] = ConstantFP::get(*Context, APF);
12064   } else {
12065     CV[0] = ConstantFP::get(
12066         *Context,
12067         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12068   }
12069   C = ConstantVector::get(CV);
12070   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12071   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12072                             MachinePointerInfo::getConstantPool(),
12073                             false, false, false, 16);
12074   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12075   if (!isa<ConstantFPSDNode>(Op0))
12076     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12077
12078   // OR the magnitude value with the sign bit.
12079   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12080 }
12081
12082 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12083   SDValue N0 = Op.getOperand(0);
12084   SDLoc dl(Op);
12085   MVT VT = Op.getSimpleValueType();
12086
12087   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12088   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12089                                   DAG.getConstant(1, VT));
12090   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12091 }
12092
12093 // Check whether an OR'd tree is PTEST-able.
12094 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12095                                       SelectionDAG &DAG) {
12096   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12097
12098   if (!Subtarget->hasSSE41())
12099     return SDValue();
12100
12101   if (!Op->hasOneUse())
12102     return SDValue();
12103
12104   SDNode *N = Op.getNode();
12105   SDLoc DL(N);
12106
12107   SmallVector<SDValue, 8> Opnds;
12108   DenseMap<SDValue, unsigned> VecInMap;
12109   SmallVector<SDValue, 8> VecIns;
12110   EVT VT = MVT::Other;
12111
12112   // Recognize a special case where a vector is casted into wide integer to
12113   // test all 0s.
12114   Opnds.push_back(N->getOperand(0));
12115   Opnds.push_back(N->getOperand(1));
12116
12117   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12118     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12119     // BFS traverse all OR'd operands.
12120     if (I->getOpcode() == ISD::OR) {
12121       Opnds.push_back(I->getOperand(0));
12122       Opnds.push_back(I->getOperand(1));
12123       // Re-evaluate the number of nodes to be traversed.
12124       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12125       continue;
12126     }
12127
12128     // Quit if a non-EXTRACT_VECTOR_ELT
12129     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12130       return SDValue();
12131
12132     // Quit if without a constant index.
12133     SDValue Idx = I->getOperand(1);
12134     if (!isa<ConstantSDNode>(Idx))
12135       return SDValue();
12136
12137     SDValue ExtractedFromVec = I->getOperand(0);
12138     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12139     if (M == VecInMap.end()) {
12140       VT = ExtractedFromVec.getValueType();
12141       // Quit if not 128/256-bit vector.
12142       if (!VT.is128BitVector() && !VT.is256BitVector())
12143         return SDValue();
12144       // Quit if not the same type.
12145       if (VecInMap.begin() != VecInMap.end() &&
12146           VT != VecInMap.begin()->first.getValueType())
12147         return SDValue();
12148       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12149       VecIns.push_back(ExtractedFromVec);
12150     }
12151     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12152   }
12153
12154   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12155          "Not extracted from 128-/256-bit vector.");
12156
12157   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12158
12159   for (DenseMap<SDValue, unsigned>::const_iterator
12160         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12161     // Quit if not all elements are used.
12162     if (I->second != FullMask)
12163       return SDValue();
12164   }
12165
12166   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12167
12168   // Cast all vectors into TestVT for PTEST.
12169   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12170     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12171
12172   // If more than one full vectors are evaluated, OR them first before PTEST.
12173   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12174     // Each iteration will OR 2 nodes and append the result until there is only
12175     // 1 node left, i.e. the final OR'd value of all vectors.
12176     SDValue LHS = VecIns[Slot];
12177     SDValue RHS = VecIns[Slot + 1];
12178     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12179   }
12180
12181   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12182                      VecIns.back(), VecIns.back());
12183 }
12184
12185 /// \brief return true if \c Op has a use that doesn't just read flags.
12186 static bool hasNonFlagsUse(SDValue Op) {
12187   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12188        ++UI) {
12189     SDNode *User = *UI;
12190     unsigned UOpNo = UI.getOperandNo();
12191     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12192       // Look pass truncate.
12193       UOpNo = User->use_begin().getOperandNo();
12194       User = *User->use_begin();
12195     }
12196
12197     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12198         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12199       return true;
12200   }
12201   return false;
12202 }
12203
12204 /// Emit nodes that will be selected as "test Op0,Op0", or something
12205 /// equivalent.
12206 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12207                                     SelectionDAG &DAG) const {
12208   if (Op.getValueType() == MVT::i1) {
12209     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12210     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12211                        DAG.getConstant(0, MVT::i8));
12212   }
12213   // CF and OF aren't always set the way we want. Determine which
12214   // of these we need.
12215   bool NeedCF = false;
12216   bool NeedOF = false;
12217   switch (X86CC) {
12218   default: break;
12219   case X86::COND_A: case X86::COND_AE:
12220   case X86::COND_B: case X86::COND_BE:
12221     NeedCF = true;
12222     break;
12223   case X86::COND_G: case X86::COND_GE:
12224   case X86::COND_L: case X86::COND_LE:
12225   case X86::COND_O: case X86::COND_NO: {
12226     // Check if we really need to set the
12227     // Overflow flag. If NoSignedWrap is present
12228     // that is not actually needed.
12229     switch (Op->getOpcode()) {
12230     case ISD::ADD:
12231     case ISD::SUB:
12232     case ISD::MUL:
12233     case ISD::SHL: {
12234       const BinaryWithFlagsSDNode *BinNode =
12235           cast<BinaryWithFlagsSDNode>(Op.getNode());
12236       if (BinNode->hasNoSignedWrap())
12237         break;
12238     }
12239     default:
12240       NeedOF = true;
12241       break;
12242     }
12243     break;
12244   }
12245   }
12246   // See if we can use the EFLAGS value from the operand instead of
12247   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12248   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12249   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12250     // Emit a CMP with 0, which is the TEST pattern.
12251     //if (Op.getValueType() == MVT::i1)
12252     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12253     //                     DAG.getConstant(0, MVT::i1));
12254     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12255                        DAG.getConstant(0, Op.getValueType()));
12256   }
12257   unsigned Opcode = 0;
12258   unsigned NumOperands = 0;
12259
12260   // Truncate operations may prevent the merge of the SETCC instruction
12261   // and the arithmetic instruction before it. Attempt to truncate the operands
12262   // of the arithmetic instruction and use a reduced bit-width instruction.
12263   bool NeedTruncation = false;
12264   SDValue ArithOp = Op;
12265   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12266     SDValue Arith = Op->getOperand(0);
12267     // Both the trunc and the arithmetic op need to have one user each.
12268     if (Arith->hasOneUse())
12269       switch (Arith.getOpcode()) {
12270         default: break;
12271         case ISD::ADD:
12272         case ISD::SUB:
12273         case ISD::AND:
12274         case ISD::OR:
12275         case ISD::XOR: {
12276           NeedTruncation = true;
12277           ArithOp = Arith;
12278         }
12279       }
12280   }
12281
12282   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12283   // which may be the result of a CAST.  We use the variable 'Op', which is the
12284   // non-casted variable when we check for possible users.
12285   switch (ArithOp.getOpcode()) {
12286   case ISD::ADD:
12287     // Due to an isel shortcoming, be conservative if this add is likely to be
12288     // selected as part of a load-modify-store instruction. When the root node
12289     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12290     // uses of other nodes in the match, such as the ADD in this case. This
12291     // leads to the ADD being left around and reselected, with the result being
12292     // two adds in the output.  Alas, even if none our users are stores, that
12293     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12294     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12295     // climbing the DAG back to the root, and it doesn't seem to be worth the
12296     // effort.
12297     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12298          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12299       if (UI->getOpcode() != ISD::CopyToReg &&
12300           UI->getOpcode() != ISD::SETCC &&
12301           UI->getOpcode() != ISD::STORE)
12302         goto default_case;
12303
12304     if (ConstantSDNode *C =
12305         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12306       // An add of one will be selected as an INC.
12307       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12308         Opcode = X86ISD::INC;
12309         NumOperands = 1;
12310         break;
12311       }
12312
12313       // An add of negative one (subtract of one) will be selected as a DEC.
12314       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12315         Opcode = X86ISD::DEC;
12316         NumOperands = 1;
12317         break;
12318       }
12319     }
12320
12321     // Otherwise use a regular EFLAGS-setting add.
12322     Opcode = X86ISD::ADD;
12323     NumOperands = 2;
12324     break;
12325   case ISD::SHL:
12326   case ISD::SRL:
12327     // If we have a constant logical shift that's only used in a comparison
12328     // against zero turn it into an equivalent AND. This allows turning it into
12329     // a TEST instruction later.
12330     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12331         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12332       EVT VT = Op.getValueType();
12333       unsigned BitWidth = VT.getSizeInBits();
12334       unsigned ShAmt = Op->getConstantOperandVal(1);
12335       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12336         break;
12337       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12338                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12339                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12340       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12341         break;
12342       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12343                                 DAG.getConstant(Mask, VT));
12344       DAG.ReplaceAllUsesWith(Op, New);
12345       Op = New;
12346     }
12347     break;
12348
12349   case ISD::AND:
12350     // If the primary and result isn't used, don't bother using X86ISD::AND,
12351     // because a TEST instruction will be better.
12352     if (!hasNonFlagsUse(Op))
12353       break;
12354     // FALL THROUGH
12355   case ISD::SUB:
12356   case ISD::OR:
12357   case ISD::XOR:
12358     // Due to the ISEL shortcoming noted above, be conservative if this op is
12359     // likely to be selected as part of a load-modify-store instruction.
12360     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12361            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12362       if (UI->getOpcode() == ISD::STORE)
12363         goto default_case;
12364
12365     // Otherwise use a regular EFLAGS-setting instruction.
12366     switch (ArithOp.getOpcode()) {
12367     default: llvm_unreachable("unexpected operator!");
12368     case ISD::SUB: Opcode = X86ISD::SUB; break;
12369     case ISD::XOR: Opcode = X86ISD::XOR; break;
12370     case ISD::AND: Opcode = X86ISD::AND; break;
12371     case ISD::OR: {
12372       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12373         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12374         if (EFLAGS.getNode())
12375           return EFLAGS;
12376       }
12377       Opcode = X86ISD::OR;
12378       break;
12379     }
12380     }
12381
12382     NumOperands = 2;
12383     break;
12384   case X86ISD::ADD:
12385   case X86ISD::SUB:
12386   case X86ISD::INC:
12387   case X86ISD::DEC:
12388   case X86ISD::OR:
12389   case X86ISD::XOR:
12390   case X86ISD::AND:
12391     return SDValue(Op.getNode(), 1);
12392   default:
12393   default_case:
12394     break;
12395   }
12396
12397   // If we found that truncation is beneficial, perform the truncation and
12398   // update 'Op'.
12399   if (NeedTruncation) {
12400     EVT VT = Op.getValueType();
12401     SDValue WideVal = Op->getOperand(0);
12402     EVT WideVT = WideVal.getValueType();
12403     unsigned ConvertedOp = 0;
12404     // Use a target machine opcode to prevent further DAGCombine
12405     // optimizations that may separate the arithmetic operations
12406     // from the setcc node.
12407     switch (WideVal.getOpcode()) {
12408       default: break;
12409       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12410       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12411       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12412       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12413       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12414     }
12415
12416     if (ConvertedOp) {
12417       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12418       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12419         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12420         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12421         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12422       }
12423     }
12424   }
12425
12426   if (Opcode == 0)
12427     // Emit a CMP with 0, which is the TEST pattern.
12428     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12429                        DAG.getConstant(0, Op.getValueType()));
12430
12431   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12432   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12433
12434   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12435   DAG.ReplaceAllUsesWith(Op, New);
12436   return SDValue(New.getNode(), 1);
12437 }
12438
12439 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12440 /// equivalent.
12441 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12442                                    SDLoc dl, SelectionDAG &DAG) const {
12443   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12444     if (C->getAPIntValue() == 0)
12445       return EmitTest(Op0, X86CC, dl, DAG);
12446
12447      if (Op0.getValueType() == MVT::i1)
12448        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12449   }
12450
12451   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12452        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12453     // Do the comparison at i32 if it's smaller, besides the Atom case.
12454     // This avoids subregister aliasing issues. Keep the smaller reference
12455     // if we're optimizing for size, however, as that'll allow better folding
12456     // of memory operations.
12457     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12458         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12459             Attribute::MinSize) &&
12460         !Subtarget->isAtom()) {
12461       unsigned ExtendOp =
12462           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12463       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12464       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12465     }
12466     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12467     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12468     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12469                               Op0, Op1);
12470     return SDValue(Sub.getNode(), 1);
12471   }
12472   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12473 }
12474
12475 /// Convert a comparison if required by the subtarget.
12476 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12477                                                  SelectionDAG &DAG) const {
12478   // If the subtarget does not support the FUCOMI instruction, floating-point
12479   // comparisons have to be converted.
12480   if (Subtarget->hasCMov() ||
12481       Cmp.getOpcode() != X86ISD::CMP ||
12482       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12483       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12484     return Cmp;
12485
12486   // The instruction selector will select an FUCOM instruction instead of
12487   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12488   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12489   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12490   SDLoc dl(Cmp);
12491   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12492   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12493   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12494                             DAG.getConstant(8, MVT::i8));
12495   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12496   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12497 }
12498
12499 /// The minimum architected relative accuracy is 2^-12. We need one
12500 /// Newton-Raphson step to have a good float result (24 bits of precision).
12501 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12502                                             DAGCombinerInfo &DCI,
12503                                             unsigned &RefinementSteps,
12504                                             bool &UseOneConstNR) const {
12505   // FIXME: We should use instruction latency models to calculate the cost of
12506   // each potential sequence, but this is very hard to do reliably because
12507   // at least Intel's Core* chips have variable timing based on the number of
12508   // significant digits in the divisor and/or sqrt operand.
12509   if (!Subtarget->useSqrtEst())
12510     return SDValue();
12511
12512   EVT VT = Op.getValueType();
12513
12514   // SSE1 has rsqrtss and rsqrtps.
12515   // TODO: Add support for AVX512 (v16f32).
12516   // It is likely not profitable to do this for f64 because a double-precision
12517   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12518   // instructions: convert to single, rsqrtss, convert back to double, refine
12519   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12520   // along with FMA, this could be a throughput win.
12521   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12522       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12523     RefinementSteps = 1;
12524     UseOneConstNR = false;
12525     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12526   }
12527   return SDValue();
12528 }
12529
12530 /// The minimum architected relative accuracy is 2^-12. We need one
12531 /// Newton-Raphson step to have a good float result (24 bits of precision).
12532 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12533                                             DAGCombinerInfo &DCI,
12534                                             unsigned &RefinementSteps) const {
12535   // FIXME: We should use instruction latency models to calculate the cost of
12536   // each potential sequence, but this is very hard to do reliably because
12537   // at least Intel's Core* chips have variable timing based on the number of
12538   // significant digits in the divisor.
12539   if (!Subtarget->useReciprocalEst())
12540     return SDValue();
12541
12542   EVT VT = Op.getValueType();
12543
12544   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12545   // TODO: Add support for AVX512 (v16f32).
12546   // It is likely not profitable to do this for f64 because a double-precision
12547   // reciprocal estimate with refinement on x86 prior to FMA requires
12548   // 15 instructions: convert to single, rcpss, convert back to double, refine
12549   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12550   // along with FMA, this could be a throughput win.
12551   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12552       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12553     RefinementSteps = ReciprocalEstimateRefinementSteps;
12554     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12555   }
12556   return SDValue();
12557 }
12558
12559 static bool isAllOnes(SDValue V) {
12560   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12561   return C && C->isAllOnesValue();
12562 }
12563
12564 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12565 /// if it's possible.
12566 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12567                                      SDLoc dl, SelectionDAG &DAG) const {
12568   SDValue Op0 = And.getOperand(0);
12569   SDValue Op1 = And.getOperand(1);
12570   if (Op0.getOpcode() == ISD::TRUNCATE)
12571     Op0 = Op0.getOperand(0);
12572   if (Op1.getOpcode() == ISD::TRUNCATE)
12573     Op1 = Op1.getOperand(0);
12574
12575   SDValue LHS, RHS;
12576   if (Op1.getOpcode() == ISD::SHL)
12577     std::swap(Op0, Op1);
12578   if (Op0.getOpcode() == ISD::SHL) {
12579     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12580       if (And00C->getZExtValue() == 1) {
12581         // If we looked past a truncate, check that it's only truncating away
12582         // known zeros.
12583         unsigned BitWidth = Op0.getValueSizeInBits();
12584         unsigned AndBitWidth = And.getValueSizeInBits();
12585         if (BitWidth > AndBitWidth) {
12586           APInt Zeros, Ones;
12587           DAG.computeKnownBits(Op0, Zeros, Ones);
12588           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12589             return SDValue();
12590         }
12591         LHS = Op1;
12592         RHS = Op0.getOperand(1);
12593       }
12594   } else if (Op1.getOpcode() == ISD::Constant) {
12595     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12596     uint64_t AndRHSVal = AndRHS->getZExtValue();
12597     SDValue AndLHS = Op0;
12598
12599     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12600       LHS = AndLHS.getOperand(0);
12601       RHS = AndLHS.getOperand(1);
12602     }
12603
12604     // Use BT if the immediate can't be encoded in a TEST instruction.
12605     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12606       LHS = AndLHS;
12607       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12608     }
12609   }
12610
12611   if (LHS.getNode()) {
12612     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12613     // instruction.  Since the shift amount is in-range-or-undefined, we know
12614     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12615     // the encoding for the i16 version is larger than the i32 version.
12616     // Also promote i16 to i32 for performance / code size reason.
12617     if (LHS.getValueType() == MVT::i8 ||
12618         LHS.getValueType() == MVT::i16)
12619       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12620
12621     // If the operand types disagree, extend the shift amount to match.  Since
12622     // BT ignores high bits (like shifts) we can use anyextend.
12623     if (LHS.getValueType() != RHS.getValueType())
12624       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12625
12626     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12627     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12628     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12629                        DAG.getConstant(Cond, MVT::i8), BT);
12630   }
12631
12632   return SDValue();
12633 }
12634
12635 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12636 /// mask CMPs.
12637 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12638                               SDValue &Op1) {
12639   unsigned SSECC;
12640   bool Swap = false;
12641
12642   // SSE Condition code mapping:
12643   //  0 - EQ
12644   //  1 - LT
12645   //  2 - LE
12646   //  3 - UNORD
12647   //  4 - NEQ
12648   //  5 - NLT
12649   //  6 - NLE
12650   //  7 - ORD
12651   switch (SetCCOpcode) {
12652   default: llvm_unreachable("Unexpected SETCC condition");
12653   case ISD::SETOEQ:
12654   case ISD::SETEQ:  SSECC = 0; break;
12655   case ISD::SETOGT:
12656   case ISD::SETGT:  Swap = true; // Fallthrough
12657   case ISD::SETLT:
12658   case ISD::SETOLT: SSECC = 1; break;
12659   case ISD::SETOGE:
12660   case ISD::SETGE:  Swap = true; // Fallthrough
12661   case ISD::SETLE:
12662   case ISD::SETOLE: SSECC = 2; break;
12663   case ISD::SETUO:  SSECC = 3; break;
12664   case ISD::SETUNE:
12665   case ISD::SETNE:  SSECC = 4; break;
12666   case ISD::SETULE: Swap = true; // Fallthrough
12667   case ISD::SETUGE: SSECC = 5; break;
12668   case ISD::SETULT: Swap = true; // Fallthrough
12669   case ISD::SETUGT: SSECC = 6; break;
12670   case ISD::SETO:   SSECC = 7; break;
12671   case ISD::SETUEQ:
12672   case ISD::SETONE: SSECC = 8; break;
12673   }
12674   if (Swap)
12675     std::swap(Op0, Op1);
12676
12677   return SSECC;
12678 }
12679
12680 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12681 // ones, and then concatenate the result back.
12682 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12683   MVT VT = Op.getSimpleValueType();
12684
12685   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12686          "Unsupported value type for operation");
12687
12688   unsigned NumElems = VT.getVectorNumElements();
12689   SDLoc dl(Op);
12690   SDValue CC = Op.getOperand(2);
12691
12692   // Extract the LHS vectors
12693   SDValue LHS = Op.getOperand(0);
12694   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12695   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12696
12697   // Extract the RHS vectors
12698   SDValue RHS = Op.getOperand(1);
12699   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12700   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12701
12702   // Issue the operation on the smaller types and concatenate the result back
12703   MVT EltVT = VT.getVectorElementType();
12704   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12705   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12706                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12707                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12708 }
12709
12710 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12711                                      const X86Subtarget *Subtarget) {
12712   SDValue Op0 = Op.getOperand(0);
12713   SDValue Op1 = Op.getOperand(1);
12714   SDValue CC = Op.getOperand(2);
12715   MVT VT = Op.getSimpleValueType();
12716   SDLoc dl(Op);
12717
12718   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12719          Op.getValueType().getScalarType() == MVT::i1 &&
12720          "Cannot set masked compare for this operation");
12721
12722   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12723   unsigned  Opc = 0;
12724   bool Unsigned = false;
12725   bool Swap = false;
12726   unsigned SSECC;
12727   switch (SetCCOpcode) {
12728   default: llvm_unreachable("Unexpected SETCC condition");
12729   case ISD::SETNE:  SSECC = 4; break;
12730   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12731   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12732   case ISD::SETLT:  Swap = true; //fall-through
12733   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12734   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12735   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12736   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12737   case ISD::SETULE: Unsigned = true; //fall-through
12738   case ISD::SETLE:  SSECC = 2; break;
12739   }
12740
12741   if (Swap)
12742     std::swap(Op0, Op1);
12743   if (Opc)
12744     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12745   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12746   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12747                      DAG.getConstant(SSECC, MVT::i8));
12748 }
12749
12750 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12751 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12752 /// return an empty value.
12753 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12754 {
12755   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12756   if (!BV)
12757     return SDValue();
12758
12759   MVT VT = Op1.getSimpleValueType();
12760   MVT EVT = VT.getVectorElementType();
12761   unsigned n = VT.getVectorNumElements();
12762   SmallVector<SDValue, 8> ULTOp1;
12763
12764   for (unsigned i = 0; i < n; ++i) {
12765     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12766     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12767       return SDValue();
12768
12769     // Avoid underflow.
12770     APInt Val = Elt->getAPIntValue();
12771     if (Val == 0)
12772       return SDValue();
12773
12774     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12775   }
12776
12777   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12778 }
12779
12780 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12781                            SelectionDAG &DAG) {
12782   SDValue Op0 = Op.getOperand(0);
12783   SDValue Op1 = Op.getOperand(1);
12784   SDValue CC = Op.getOperand(2);
12785   MVT VT = Op.getSimpleValueType();
12786   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12787   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12788   SDLoc dl(Op);
12789
12790   if (isFP) {
12791 #ifndef NDEBUG
12792     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12793     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12794 #endif
12795
12796     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12797     unsigned Opc = X86ISD::CMPP;
12798     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12799       assert(VT.getVectorNumElements() <= 16);
12800       Opc = X86ISD::CMPM;
12801     }
12802     // In the two special cases we can't handle, emit two comparisons.
12803     if (SSECC == 8) {
12804       unsigned CC0, CC1;
12805       unsigned CombineOpc;
12806       if (SetCCOpcode == ISD::SETUEQ) {
12807         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12808       } else {
12809         assert(SetCCOpcode == ISD::SETONE);
12810         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12811       }
12812
12813       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12814                                  DAG.getConstant(CC0, MVT::i8));
12815       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12816                                  DAG.getConstant(CC1, MVT::i8));
12817       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12818     }
12819     // Handle all other FP comparisons here.
12820     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12821                        DAG.getConstant(SSECC, MVT::i8));
12822   }
12823
12824   // Break 256-bit integer vector compare into smaller ones.
12825   if (VT.is256BitVector() && !Subtarget->hasInt256())
12826     return Lower256IntVSETCC(Op, DAG);
12827
12828   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12829   EVT OpVT = Op1.getValueType();
12830   if (Subtarget->hasAVX512()) {
12831     if (Op1.getValueType().is512BitVector() ||
12832         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
12833         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12834       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12835
12836     // In AVX-512 architecture setcc returns mask with i1 elements,
12837     // But there is no compare instruction for i8 and i16 elements in KNL.
12838     // We are not talking about 512-bit operands in this case, these
12839     // types are illegal.
12840     if (MaskResult &&
12841         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12842          OpVT.getVectorElementType().getSizeInBits() >= 8))
12843       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12844                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12845   }
12846
12847   // We are handling one of the integer comparisons here.  Since SSE only has
12848   // GT and EQ comparisons for integer, swapping operands and multiple
12849   // operations may be required for some comparisons.
12850   unsigned Opc;
12851   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12852   bool Subus = false;
12853
12854   switch (SetCCOpcode) {
12855   default: llvm_unreachable("Unexpected SETCC condition");
12856   case ISD::SETNE:  Invert = true;
12857   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12858   case ISD::SETLT:  Swap = true;
12859   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12860   case ISD::SETGE:  Swap = true;
12861   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12862                     Invert = true; break;
12863   case ISD::SETULT: Swap = true;
12864   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12865                     FlipSigns = true; break;
12866   case ISD::SETUGE: Swap = true;
12867   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12868                     FlipSigns = true; Invert = true; break;
12869   }
12870
12871   // Special case: Use min/max operations for SETULE/SETUGE
12872   MVT VET = VT.getVectorElementType();
12873   bool hasMinMax =
12874        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12875     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12876
12877   if (hasMinMax) {
12878     switch (SetCCOpcode) {
12879     default: break;
12880     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12881     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12882     }
12883
12884     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12885   }
12886
12887   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12888   if (!MinMax && hasSubus) {
12889     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12890     // Op0 u<= Op1:
12891     //   t = psubus Op0, Op1
12892     //   pcmpeq t, <0..0>
12893     switch (SetCCOpcode) {
12894     default: break;
12895     case ISD::SETULT: {
12896       // If the comparison is against a constant we can turn this into a
12897       // setule.  With psubus, setule does not require a swap.  This is
12898       // beneficial because the constant in the register is no longer
12899       // destructed as the destination so it can be hoisted out of a loop.
12900       // Only do this pre-AVX since vpcmp* is no longer destructive.
12901       if (Subtarget->hasAVX())
12902         break;
12903       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12904       if (ULEOp1.getNode()) {
12905         Op1 = ULEOp1;
12906         Subus = true; Invert = false; Swap = false;
12907       }
12908       break;
12909     }
12910     // Psubus is better than flip-sign because it requires no inversion.
12911     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12912     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12913     }
12914
12915     if (Subus) {
12916       Opc = X86ISD::SUBUS;
12917       FlipSigns = false;
12918     }
12919   }
12920
12921   if (Swap)
12922     std::swap(Op0, Op1);
12923
12924   // Check that the operation in question is available (most are plain SSE2,
12925   // but PCMPGTQ and PCMPEQQ have different requirements).
12926   if (VT == MVT::v2i64) {
12927     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12928       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12929
12930       // First cast everything to the right type.
12931       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12932       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12933
12934       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12935       // bits of the inputs before performing those operations. The lower
12936       // compare is always unsigned.
12937       SDValue SB;
12938       if (FlipSigns) {
12939         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12940       } else {
12941         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12942         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12943         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12944                          Sign, Zero, Sign, Zero);
12945       }
12946       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12947       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12948
12949       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12950       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12951       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12952
12953       // Create masks for only the low parts/high parts of the 64 bit integers.
12954       static const int MaskHi[] = { 1, 1, 3, 3 };
12955       static const int MaskLo[] = { 0, 0, 2, 2 };
12956       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12957       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12958       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12959
12960       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12961       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12962
12963       if (Invert)
12964         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12965
12966       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12967     }
12968
12969     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12970       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12971       // pcmpeqd + pshufd + pand.
12972       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12973
12974       // First cast everything to the right type.
12975       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12976       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12977
12978       // Do the compare.
12979       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12980
12981       // Make sure the lower and upper halves are both all-ones.
12982       static const int Mask[] = { 1, 0, 3, 2 };
12983       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12984       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12985
12986       if (Invert)
12987         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12988
12989       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12990     }
12991   }
12992
12993   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12994   // bits of the inputs before performing those operations.
12995   if (FlipSigns) {
12996     EVT EltVT = VT.getVectorElementType();
12997     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12998     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12999     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13000   }
13001
13002   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13003
13004   // If the logical-not of the result is required, perform that now.
13005   if (Invert)
13006     Result = DAG.getNOT(dl, Result, VT);
13007
13008   if (MinMax)
13009     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13010
13011   if (Subus)
13012     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13013                          getZeroVector(VT, Subtarget, DAG, dl));
13014
13015   return Result;
13016 }
13017
13018 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13019
13020   MVT VT = Op.getSimpleValueType();
13021
13022   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13023
13024   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13025          && "SetCC type must be 8-bit or 1-bit integer");
13026   SDValue Op0 = Op.getOperand(0);
13027   SDValue Op1 = Op.getOperand(1);
13028   SDLoc dl(Op);
13029   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13030
13031   // Optimize to BT if possible.
13032   // Lower (X & (1 << N)) == 0 to BT(X, N).
13033   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13034   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13035   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13036       Op1.getOpcode() == ISD::Constant &&
13037       cast<ConstantSDNode>(Op1)->isNullValue() &&
13038       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13039     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13040     if (NewSetCC.getNode()) {
13041       if (VT == MVT::i1)
13042         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13043       return NewSetCC;
13044     }
13045   }
13046
13047   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13048   // these.
13049   if (Op1.getOpcode() == ISD::Constant &&
13050       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13051        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13052       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13053
13054     // If the input is a setcc, then reuse the input setcc or use a new one with
13055     // the inverted condition.
13056     if (Op0.getOpcode() == X86ISD::SETCC) {
13057       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13058       bool Invert = (CC == ISD::SETNE) ^
13059         cast<ConstantSDNode>(Op1)->isNullValue();
13060       if (!Invert)
13061         return Op0;
13062
13063       CCode = X86::GetOppositeBranchCondition(CCode);
13064       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13065                                   DAG.getConstant(CCode, MVT::i8),
13066                                   Op0.getOperand(1));
13067       if (VT == MVT::i1)
13068         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13069       return SetCC;
13070     }
13071   }
13072   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13073       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13074       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13075
13076     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13077     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13078   }
13079
13080   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13081   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13082   if (X86CC == X86::COND_INVALID)
13083     return SDValue();
13084
13085   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13086   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13087   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13088                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13089   if (VT == MVT::i1)
13090     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13091   return SetCC;
13092 }
13093
13094 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13095 static bool isX86LogicalCmp(SDValue Op) {
13096   unsigned Opc = Op.getNode()->getOpcode();
13097   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13098       Opc == X86ISD::SAHF)
13099     return true;
13100   if (Op.getResNo() == 1 &&
13101       (Opc == X86ISD::ADD ||
13102        Opc == X86ISD::SUB ||
13103        Opc == X86ISD::ADC ||
13104        Opc == X86ISD::SBB ||
13105        Opc == X86ISD::SMUL ||
13106        Opc == X86ISD::UMUL ||
13107        Opc == X86ISD::INC ||
13108        Opc == X86ISD::DEC ||
13109        Opc == X86ISD::OR ||
13110        Opc == X86ISD::XOR ||
13111        Opc == X86ISD::AND))
13112     return true;
13113
13114   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13115     return true;
13116
13117   return false;
13118 }
13119
13120 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13121   if (V.getOpcode() != ISD::TRUNCATE)
13122     return false;
13123
13124   SDValue VOp0 = V.getOperand(0);
13125   unsigned InBits = VOp0.getValueSizeInBits();
13126   unsigned Bits = V.getValueSizeInBits();
13127   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13128 }
13129
13130 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13131   bool addTest = true;
13132   SDValue Cond  = Op.getOperand(0);
13133   SDValue Op1 = Op.getOperand(1);
13134   SDValue Op2 = Op.getOperand(2);
13135   SDLoc DL(Op);
13136   EVT VT = Op1.getValueType();
13137   SDValue CC;
13138
13139   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13140   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13141   // sequence later on.
13142   if (Cond.getOpcode() == ISD::SETCC &&
13143       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13144        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13145       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13146     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13147     int SSECC = translateX86FSETCC(
13148         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13149
13150     if (SSECC != 8) {
13151       if (Subtarget->hasAVX512()) {
13152         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13153                                   DAG.getConstant(SSECC, MVT::i8));
13154         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13155       }
13156       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13157                                 DAG.getConstant(SSECC, MVT::i8));
13158       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13159       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13160       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13161     }
13162   }
13163
13164   if (Cond.getOpcode() == ISD::SETCC) {
13165     SDValue NewCond = LowerSETCC(Cond, DAG);
13166     if (NewCond.getNode())
13167       Cond = NewCond;
13168   }
13169
13170   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13171   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13172   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13173   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13174   if (Cond.getOpcode() == X86ISD::SETCC &&
13175       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13176       isZero(Cond.getOperand(1).getOperand(1))) {
13177     SDValue Cmp = Cond.getOperand(1);
13178
13179     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13180
13181     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13182         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13183       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13184
13185       SDValue CmpOp0 = Cmp.getOperand(0);
13186       // Apply further optimizations for special cases
13187       // (select (x != 0), -1, 0) -> neg & sbb
13188       // (select (x == 0), 0, -1) -> neg & sbb
13189       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13190         if (YC->isNullValue() &&
13191             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13192           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13193           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13194                                     DAG.getConstant(0, CmpOp0.getValueType()),
13195                                     CmpOp0);
13196           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13197                                     DAG.getConstant(X86::COND_B, MVT::i8),
13198                                     SDValue(Neg.getNode(), 1));
13199           return Res;
13200         }
13201
13202       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13203                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13204       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13205
13206       SDValue Res =   // Res = 0 or -1.
13207         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13208                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13209
13210       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13211         Res = DAG.getNOT(DL, Res, Res.getValueType());
13212
13213       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13214       if (!N2C || !N2C->isNullValue())
13215         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13216       return Res;
13217     }
13218   }
13219
13220   // Look past (and (setcc_carry (cmp ...)), 1).
13221   if (Cond.getOpcode() == ISD::AND &&
13222       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13223     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13224     if (C && C->getAPIntValue() == 1)
13225       Cond = Cond.getOperand(0);
13226   }
13227
13228   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13229   // setting operand in place of the X86ISD::SETCC.
13230   unsigned CondOpcode = Cond.getOpcode();
13231   if (CondOpcode == X86ISD::SETCC ||
13232       CondOpcode == X86ISD::SETCC_CARRY) {
13233     CC = Cond.getOperand(0);
13234
13235     SDValue Cmp = Cond.getOperand(1);
13236     unsigned Opc = Cmp.getOpcode();
13237     MVT VT = Op.getSimpleValueType();
13238
13239     bool IllegalFPCMov = false;
13240     if (VT.isFloatingPoint() && !VT.isVector() &&
13241         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13242       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13243
13244     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13245         Opc == X86ISD::BT) { // FIXME
13246       Cond = Cmp;
13247       addTest = false;
13248     }
13249   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13250              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13251              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13252               Cond.getOperand(0).getValueType() != MVT::i8)) {
13253     SDValue LHS = Cond.getOperand(0);
13254     SDValue RHS = Cond.getOperand(1);
13255     unsigned X86Opcode;
13256     unsigned X86Cond;
13257     SDVTList VTs;
13258     switch (CondOpcode) {
13259     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13260     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13261     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13262     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13263     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13264     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13265     default: llvm_unreachable("unexpected overflowing operator");
13266     }
13267     if (CondOpcode == ISD::UMULO)
13268       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13269                           MVT::i32);
13270     else
13271       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13272
13273     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13274
13275     if (CondOpcode == ISD::UMULO)
13276       Cond = X86Op.getValue(2);
13277     else
13278       Cond = X86Op.getValue(1);
13279
13280     CC = DAG.getConstant(X86Cond, MVT::i8);
13281     addTest = false;
13282   }
13283
13284   if (addTest) {
13285     // Look pass the truncate if the high bits are known zero.
13286     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13287         Cond = Cond.getOperand(0);
13288
13289     // We know the result of AND is compared against zero. Try to match
13290     // it to BT.
13291     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13292       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13293       if (NewSetCC.getNode()) {
13294         CC = NewSetCC.getOperand(0);
13295         Cond = NewSetCC.getOperand(1);
13296         addTest = false;
13297       }
13298     }
13299   }
13300
13301   if (addTest) {
13302     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13303     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13304   }
13305
13306   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13307   // a <  b ?  0 : -1 -> RES = setcc_carry
13308   // a >= b ? -1 :  0 -> RES = setcc_carry
13309   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13310   if (Cond.getOpcode() == X86ISD::SUB) {
13311     Cond = ConvertCmpIfNecessary(Cond, DAG);
13312     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13313
13314     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13315         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13316       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13317                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13318       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13319         return DAG.getNOT(DL, Res, Res.getValueType());
13320       return Res;
13321     }
13322   }
13323
13324   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13325   // widen the cmov and push the truncate through. This avoids introducing a new
13326   // branch during isel and doesn't add any extensions.
13327   if (Op.getValueType() == MVT::i8 &&
13328       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13329     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13330     if (T1.getValueType() == T2.getValueType() &&
13331         // Blacklist CopyFromReg to avoid partial register stalls.
13332         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13333       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13334       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13335       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13336     }
13337   }
13338
13339   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13340   // condition is true.
13341   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13342   SDValue Ops[] = { Op2, Op1, CC, Cond };
13343   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13344 }
13345
13346 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13347                                        SelectionDAG &DAG) {
13348   MVT VT = Op->getSimpleValueType(0);
13349   SDValue In = Op->getOperand(0);
13350   MVT InVT = In.getSimpleValueType();
13351   MVT VTElt = VT.getVectorElementType();
13352   MVT InVTElt = InVT.getVectorElementType();
13353   SDLoc dl(Op);
13354
13355   // SKX processor
13356   if ((InVTElt == MVT::i1) &&
13357       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13358         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13359
13360        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13361         VTElt.getSizeInBits() <= 16)) ||
13362
13363        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13364         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13365
13366        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13367         VTElt.getSizeInBits() >= 32))))
13368     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13369
13370   unsigned int NumElts = VT.getVectorNumElements();
13371
13372   if (NumElts != 8 && NumElts != 16)
13373     return SDValue();
13374
13375   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13376     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13377       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13378     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13379   }
13380
13381   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13382   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13383
13384   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13385   Constant *C = ConstantInt::get(*DAG.getContext(),
13386     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13387
13388   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13389   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13390   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13391                           MachinePointerInfo::getConstantPool(),
13392                           false, false, false, Alignment);
13393   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13394   if (VT.is512BitVector())
13395     return Brcst;
13396   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13397 }
13398
13399 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13400                                 SelectionDAG &DAG) {
13401   MVT VT = Op->getSimpleValueType(0);
13402   SDValue In = Op->getOperand(0);
13403   MVT InVT = In.getSimpleValueType();
13404   SDLoc dl(Op);
13405
13406   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13407     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13408
13409   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13410       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13411       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13412     return SDValue();
13413
13414   if (Subtarget->hasInt256())
13415     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13416
13417   // Optimize vectors in AVX mode
13418   // Sign extend  v8i16 to v8i32 and
13419   //              v4i32 to v4i64
13420   //
13421   // Divide input vector into two parts
13422   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13423   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13424   // concat the vectors to original VT
13425
13426   unsigned NumElems = InVT.getVectorNumElements();
13427   SDValue Undef = DAG.getUNDEF(InVT);
13428
13429   SmallVector<int,8> ShufMask1(NumElems, -1);
13430   for (unsigned i = 0; i != NumElems/2; ++i)
13431     ShufMask1[i] = i;
13432
13433   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13434
13435   SmallVector<int,8> ShufMask2(NumElems, -1);
13436   for (unsigned i = 0; i != NumElems/2; ++i)
13437     ShufMask2[i] = i + NumElems/2;
13438
13439   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13440
13441   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13442                                 VT.getVectorNumElements()/2);
13443
13444   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13445   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13446
13447   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13448 }
13449
13450 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13451 // may emit an illegal shuffle but the expansion is still better than scalar
13452 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13453 // we'll emit a shuffle and a arithmetic shift.
13454 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13455 // TODO: It is possible to support ZExt by zeroing the undef values during
13456 // the shuffle phase or after the shuffle.
13457 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13458                                  SelectionDAG &DAG) {
13459   MVT RegVT = Op.getSimpleValueType();
13460   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13461   assert(RegVT.isInteger() &&
13462          "We only custom lower integer vector sext loads.");
13463
13464   // Nothing useful we can do without SSE2 shuffles.
13465   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13466
13467   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13468   SDLoc dl(Ld);
13469   EVT MemVT = Ld->getMemoryVT();
13470   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13471   unsigned RegSz = RegVT.getSizeInBits();
13472
13473   ISD::LoadExtType Ext = Ld->getExtensionType();
13474
13475   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13476          && "Only anyext and sext are currently implemented.");
13477   assert(MemVT != RegVT && "Cannot extend to the same type");
13478   assert(MemVT.isVector() && "Must load a vector from memory");
13479
13480   unsigned NumElems = RegVT.getVectorNumElements();
13481   unsigned MemSz = MemVT.getSizeInBits();
13482   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13483
13484   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13485     // The only way in which we have a legal 256-bit vector result but not the
13486     // integer 256-bit operations needed to directly lower a sextload is if we
13487     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13488     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13489     // correctly legalized. We do this late to allow the canonical form of
13490     // sextload to persist throughout the rest of the DAG combiner -- it wants
13491     // to fold together any extensions it can, and so will fuse a sign_extend
13492     // of an sextload into a sextload targeting a wider value.
13493     SDValue Load;
13494     if (MemSz == 128) {
13495       // Just switch this to a normal load.
13496       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13497                                        "it must be a legal 128-bit vector "
13498                                        "type!");
13499       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13500                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13501                   Ld->isInvariant(), Ld->getAlignment());
13502     } else {
13503       assert(MemSz < 128 &&
13504              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13505       // Do an sext load to a 128-bit vector type. We want to use the same
13506       // number of elements, but elements half as wide. This will end up being
13507       // recursively lowered by this routine, but will succeed as we definitely
13508       // have all the necessary features if we're using AVX1.
13509       EVT HalfEltVT =
13510           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13511       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13512       Load =
13513           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13514                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13515                          Ld->isNonTemporal(), Ld->isInvariant(),
13516                          Ld->getAlignment());
13517     }
13518
13519     // Replace chain users with the new chain.
13520     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13521     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13522
13523     // Finally, do a normal sign-extend to the desired register.
13524     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13525   }
13526
13527   // All sizes must be a power of two.
13528   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13529          "Non-power-of-two elements are not custom lowered!");
13530
13531   // Attempt to load the original value using scalar loads.
13532   // Find the largest scalar type that divides the total loaded size.
13533   MVT SclrLoadTy = MVT::i8;
13534   for (MVT Tp : MVT::integer_valuetypes()) {
13535     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13536       SclrLoadTy = Tp;
13537     }
13538   }
13539
13540   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13541   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13542       (64 <= MemSz))
13543     SclrLoadTy = MVT::f64;
13544
13545   // Calculate the number of scalar loads that we need to perform
13546   // in order to load our vector from memory.
13547   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13548
13549   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13550          "Can only lower sext loads with a single scalar load!");
13551
13552   unsigned loadRegZize = RegSz;
13553   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13554     loadRegZize /= 2;
13555
13556   // Represent our vector as a sequence of elements which are the
13557   // largest scalar that we can load.
13558   EVT LoadUnitVecVT = EVT::getVectorVT(
13559       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13560
13561   // Represent the data using the same element type that is stored in
13562   // memory. In practice, we ''widen'' MemVT.
13563   EVT WideVecVT =
13564       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13565                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13566
13567   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13568          "Invalid vector type");
13569
13570   // We can't shuffle using an illegal type.
13571   assert(TLI.isTypeLegal(WideVecVT) &&
13572          "We only lower types that form legal widened vector types");
13573
13574   SmallVector<SDValue, 8> Chains;
13575   SDValue Ptr = Ld->getBasePtr();
13576   SDValue Increment =
13577       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13578   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13579
13580   for (unsigned i = 0; i < NumLoads; ++i) {
13581     // Perform a single load.
13582     SDValue ScalarLoad =
13583         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13584                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13585                     Ld->getAlignment());
13586     Chains.push_back(ScalarLoad.getValue(1));
13587     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13588     // another round of DAGCombining.
13589     if (i == 0)
13590       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13591     else
13592       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13593                         ScalarLoad, DAG.getIntPtrConstant(i));
13594
13595     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13596   }
13597
13598   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13599
13600   // Bitcast the loaded value to a vector of the original element type, in
13601   // the size of the target vector type.
13602   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13603   unsigned SizeRatio = RegSz / MemSz;
13604
13605   if (Ext == ISD::SEXTLOAD) {
13606     // If we have SSE4.1, we can directly emit a VSEXT node.
13607     if (Subtarget->hasSSE41()) {
13608       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13609       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13610       return Sext;
13611     }
13612
13613     // Otherwise we'll shuffle the small elements in the high bits of the
13614     // larger type and perform an arithmetic shift. If the shift is not legal
13615     // it's better to scalarize.
13616     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13617            "We can't implement a sext load without an arithmetic right shift!");
13618
13619     // Redistribute the loaded elements into the different locations.
13620     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13621     for (unsigned i = 0; i != NumElems; ++i)
13622       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13623
13624     SDValue Shuff = DAG.getVectorShuffle(
13625         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13626
13627     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13628
13629     // Build the arithmetic shift.
13630     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13631                    MemVT.getVectorElementType().getSizeInBits();
13632     Shuff =
13633         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13634
13635     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13636     return Shuff;
13637   }
13638
13639   // Redistribute the loaded elements into the different locations.
13640   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13641   for (unsigned i = 0; i != NumElems; ++i)
13642     ShuffleVec[i * SizeRatio] = i;
13643
13644   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13645                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13646
13647   // Bitcast to the requested type.
13648   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13649   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13650   return Shuff;
13651 }
13652
13653 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13654 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13655 // from the AND / OR.
13656 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13657   Opc = Op.getOpcode();
13658   if (Opc != ISD::OR && Opc != ISD::AND)
13659     return false;
13660   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13661           Op.getOperand(0).hasOneUse() &&
13662           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13663           Op.getOperand(1).hasOneUse());
13664 }
13665
13666 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13667 // 1 and that the SETCC node has a single use.
13668 static bool isXor1OfSetCC(SDValue Op) {
13669   if (Op.getOpcode() != ISD::XOR)
13670     return false;
13671   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13672   if (N1C && N1C->getAPIntValue() == 1) {
13673     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13674       Op.getOperand(0).hasOneUse();
13675   }
13676   return false;
13677 }
13678
13679 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13680   bool addTest = true;
13681   SDValue Chain = Op.getOperand(0);
13682   SDValue Cond  = Op.getOperand(1);
13683   SDValue Dest  = Op.getOperand(2);
13684   SDLoc dl(Op);
13685   SDValue CC;
13686   bool Inverted = false;
13687
13688   if (Cond.getOpcode() == ISD::SETCC) {
13689     // Check for setcc([su]{add,sub,mul}o == 0).
13690     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13691         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13692         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13693         Cond.getOperand(0).getResNo() == 1 &&
13694         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13695          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13696          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13697          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13698          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13699          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13700       Inverted = true;
13701       Cond = Cond.getOperand(0);
13702     } else {
13703       SDValue NewCond = LowerSETCC(Cond, DAG);
13704       if (NewCond.getNode())
13705         Cond = NewCond;
13706     }
13707   }
13708 #if 0
13709   // FIXME: LowerXALUO doesn't handle these!!
13710   else if (Cond.getOpcode() == X86ISD::ADD  ||
13711            Cond.getOpcode() == X86ISD::SUB  ||
13712            Cond.getOpcode() == X86ISD::SMUL ||
13713            Cond.getOpcode() == X86ISD::UMUL)
13714     Cond = LowerXALUO(Cond, DAG);
13715 #endif
13716
13717   // Look pass (and (setcc_carry (cmp ...)), 1).
13718   if (Cond.getOpcode() == ISD::AND &&
13719       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13720     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13721     if (C && C->getAPIntValue() == 1)
13722       Cond = Cond.getOperand(0);
13723   }
13724
13725   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13726   // setting operand in place of the X86ISD::SETCC.
13727   unsigned CondOpcode = Cond.getOpcode();
13728   if (CondOpcode == X86ISD::SETCC ||
13729       CondOpcode == X86ISD::SETCC_CARRY) {
13730     CC = Cond.getOperand(0);
13731
13732     SDValue Cmp = Cond.getOperand(1);
13733     unsigned Opc = Cmp.getOpcode();
13734     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13735     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13736       Cond = Cmp;
13737       addTest = false;
13738     } else {
13739       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13740       default: break;
13741       case X86::COND_O:
13742       case X86::COND_B:
13743         // These can only come from an arithmetic instruction with overflow,
13744         // e.g. SADDO, UADDO.
13745         Cond = Cond.getNode()->getOperand(1);
13746         addTest = false;
13747         break;
13748       }
13749     }
13750   }
13751   CondOpcode = Cond.getOpcode();
13752   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13753       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13754       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13755        Cond.getOperand(0).getValueType() != MVT::i8)) {
13756     SDValue LHS = Cond.getOperand(0);
13757     SDValue RHS = Cond.getOperand(1);
13758     unsigned X86Opcode;
13759     unsigned X86Cond;
13760     SDVTList VTs;
13761     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13762     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13763     // X86ISD::INC).
13764     switch (CondOpcode) {
13765     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13766     case ISD::SADDO:
13767       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13768         if (C->isOne()) {
13769           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13770           break;
13771         }
13772       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13773     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13774     case ISD::SSUBO:
13775       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13776         if (C->isOne()) {
13777           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13778           break;
13779         }
13780       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13781     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13782     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13783     default: llvm_unreachable("unexpected overflowing operator");
13784     }
13785     if (Inverted)
13786       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13787     if (CondOpcode == ISD::UMULO)
13788       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13789                           MVT::i32);
13790     else
13791       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13792
13793     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13794
13795     if (CondOpcode == ISD::UMULO)
13796       Cond = X86Op.getValue(2);
13797     else
13798       Cond = X86Op.getValue(1);
13799
13800     CC = DAG.getConstant(X86Cond, MVT::i8);
13801     addTest = false;
13802   } else {
13803     unsigned CondOpc;
13804     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13805       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13806       if (CondOpc == ISD::OR) {
13807         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13808         // two branches instead of an explicit OR instruction with a
13809         // separate test.
13810         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13811             isX86LogicalCmp(Cmp)) {
13812           CC = Cond.getOperand(0).getOperand(0);
13813           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13814                               Chain, Dest, CC, Cmp);
13815           CC = Cond.getOperand(1).getOperand(0);
13816           Cond = Cmp;
13817           addTest = false;
13818         }
13819       } else { // ISD::AND
13820         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13821         // two branches instead of an explicit AND instruction with a
13822         // separate test. However, we only do this if this block doesn't
13823         // have a fall-through edge, because this requires an explicit
13824         // jmp when the condition is false.
13825         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13826             isX86LogicalCmp(Cmp) &&
13827             Op.getNode()->hasOneUse()) {
13828           X86::CondCode CCode =
13829             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13830           CCode = X86::GetOppositeBranchCondition(CCode);
13831           CC = DAG.getConstant(CCode, MVT::i8);
13832           SDNode *User = *Op.getNode()->use_begin();
13833           // Look for an unconditional branch following this conditional branch.
13834           // We need this because we need to reverse the successors in order
13835           // to implement FCMP_OEQ.
13836           if (User->getOpcode() == ISD::BR) {
13837             SDValue FalseBB = User->getOperand(1);
13838             SDNode *NewBR =
13839               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13840             assert(NewBR == User);
13841             (void)NewBR;
13842             Dest = FalseBB;
13843
13844             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13845                                 Chain, Dest, CC, Cmp);
13846             X86::CondCode CCode =
13847               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13848             CCode = X86::GetOppositeBranchCondition(CCode);
13849             CC = DAG.getConstant(CCode, MVT::i8);
13850             Cond = Cmp;
13851             addTest = false;
13852           }
13853         }
13854       }
13855     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13856       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13857       // It should be transformed during dag combiner except when the condition
13858       // is set by a arithmetics with overflow node.
13859       X86::CondCode CCode =
13860         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13861       CCode = X86::GetOppositeBranchCondition(CCode);
13862       CC = DAG.getConstant(CCode, MVT::i8);
13863       Cond = Cond.getOperand(0).getOperand(1);
13864       addTest = false;
13865     } else if (Cond.getOpcode() == ISD::SETCC &&
13866                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13867       // For FCMP_OEQ, we can emit
13868       // two branches instead of an explicit AND instruction with a
13869       // separate test. However, we only do this if this block doesn't
13870       // have a fall-through edge, because this requires an explicit
13871       // jmp when the condition is false.
13872       if (Op.getNode()->hasOneUse()) {
13873         SDNode *User = *Op.getNode()->use_begin();
13874         // Look for an unconditional branch following this conditional branch.
13875         // We need this because we need to reverse the successors in order
13876         // to implement FCMP_OEQ.
13877         if (User->getOpcode() == ISD::BR) {
13878           SDValue FalseBB = User->getOperand(1);
13879           SDNode *NewBR =
13880             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13881           assert(NewBR == User);
13882           (void)NewBR;
13883           Dest = FalseBB;
13884
13885           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13886                                     Cond.getOperand(0), Cond.getOperand(1));
13887           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13888           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13889           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13890                               Chain, Dest, CC, Cmp);
13891           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13892           Cond = Cmp;
13893           addTest = false;
13894         }
13895       }
13896     } else if (Cond.getOpcode() == ISD::SETCC &&
13897                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13898       // For FCMP_UNE, we can emit
13899       // two branches instead of an explicit AND instruction with a
13900       // separate test. However, we only do this if this block doesn't
13901       // have a fall-through edge, because this requires an explicit
13902       // jmp when the condition is false.
13903       if (Op.getNode()->hasOneUse()) {
13904         SDNode *User = *Op.getNode()->use_begin();
13905         // Look for an unconditional branch following this conditional branch.
13906         // We need this because we need to reverse the successors in order
13907         // to implement FCMP_UNE.
13908         if (User->getOpcode() == ISD::BR) {
13909           SDValue FalseBB = User->getOperand(1);
13910           SDNode *NewBR =
13911             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13912           assert(NewBR == User);
13913           (void)NewBR;
13914
13915           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13916                                     Cond.getOperand(0), Cond.getOperand(1));
13917           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13918           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13919           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13920                               Chain, Dest, CC, Cmp);
13921           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13922           Cond = Cmp;
13923           addTest = false;
13924           Dest = FalseBB;
13925         }
13926       }
13927     }
13928   }
13929
13930   if (addTest) {
13931     // Look pass the truncate if the high bits are known zero.
13932     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13933         Cond = Cond.getOperand(0);
13934
13935     // We know the result of AND is compared against zero. Try to match
13936     // it to BT.
13937     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13938       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13939       if (NewSetCC.getNode()) {
13940         CC = NewSetCC.getOperand(0);
13941         Cond = NewSetCC.getOperand(1);
13942         addTest = false;
13943       }
13944     }
13945   }
13946
13947   if (addTest) {
13948     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13949     CC = DAG.getConstant(X86Cond, MVT::i8);
13950     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13951   }
13952   Cond = ConvertCmpIfNecessary(Cond, DAG);
13953   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13954                      Chain, Dest, CC, Cond);
13955 }
13956
13957 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13958 // Calls to _alloca are needed to probe the stack when allocating more than 4k
13959 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13960 // that the guard pages used by the OS virtual memory manager are allocated in
13961 // correct sequence.
13962 SDValue
13963 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13964                                            SelectionDAG &DAG) const {
13965   MachineFunction &MF = DAG.getMachineFunction();
13966   bool SplitStack = MF.shouldSplitStack();
13967   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
13968                SplitStack;
13969   SDLoc dl(Op);
13970
13971   if (!Lower) {
13972     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13973     SDNode* Node = Op.getNode();
13974
13975     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13976     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13977         " not tell us which reg is the stack pointer!");
13978     EVT VT = Node->getValueType(0);
13979     SDValue Tmp1 = SDValue(Node, 0);
13980     SDValue Tmp2 = SDValue(Node, 1);
13981     SDValue Tmp3 = Node->getOperand(2);
13982     SDValue Chain = Tmp1.getOperand(0);
13983
13984     // Chain the dynamic stack allocation so that it doesn't modify the stack
13985     // pointer when other instructions are using the stack.
13986     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13987         SDLoc(Node));
13988
13989     SDValue Size = Tmp2.getOperand(1);
13990     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13991     Chain = SP.getValue(1);
13992     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13993     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
13994     unsigned StackAlign = TFI.getStackAlignment();
13995     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13996     if (Align > StackAlign)
13997       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13998           DAG.getConstant(-(uint64_t)Align, VT));
13999     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14000
14001     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14002         DAG.getIntPtrConstant(0, true), SDValue(),
14003         SDLoc(Node));
14004
14005     SDValue Ops[2] = { Tmp1, Tmp2 };
14006     return DAG.getMergeValues(Ops, dl);
14007   }
14008
14009   // Get the inputs.
14010   SDValue Chain = Op.getOperand(0);
14011   SDValue Size  = Op.getOperand(1);
14012   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14013   EVT VT = Op.getNode()->getValueType(0);
14014
14015   bool Is64Bit = Subtarget->is64Bit();
14016   EVT SPTy = getPointerTy();
14017
14018   if (SplitStack) {
14019     MachineRegisterInfo &MRI = MF.getRegInfo();
14020
14021     if (Is64Bit) {
14022       // The 64 bit implementation of segmented stacks needs to clobber both r10
14023       // r11. This makes it impossible to use it along with nested parameters.
14024       const Function *F = MF.getFunction();
14025
14026       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14027            I != E; ++I)
14028         if (I->hasNestAttr())
14029           report_fatal_error("Cannot use segmented stacks with functions that "
14030                              "have nested arguments.");
14031     }
14032
14033     const TargetRegisterClass *AddrRegClass =
14034       getRegClassFor(getPointerTy());
14035     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14036     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14037     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14038                                 DAG.getRegister(Vreg, SPTy));
14039     SDValue Ops1[2] = { Value, Chain };
14040     return DAG.getMergeValues(Ops1, dl);
14041   } else {
14042     SDValue Flag;
14043     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14044
14045     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14046     Flag = Chain.getValue(1);
14047     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14048
14049     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14050
14051     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14052     unsigned SPReg = RegInfo->getStackRegister();
14053     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14054     Chain = SP.getValue(1);
14055
14056     if (Align) {
14057       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14058                        DAG.getConstant(-(uint64_t)Align, VT));
14059       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14060     }
14061
14062     SDValue Ops1[2] = { SP, Chain };
14063     return DAG.getMergeValues(Ops1, dl);
14064   }
14065 }
14066
14067 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14068   MachineFunction &MF = DAG.getMachineFunction();
14069   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14070
14071   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14072   SDLoc DL(Op);
14073
14074   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14075     // vastart just stores the address of the VarArgsFrameIndex slot into the
14076     // memory location argument.
14077     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14078                                    getPointerTy());
14079     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14080                         MachinePointerInfo(SV), false, false, 0);
14081   }
14082
14083   // __va_list_tag:
14084   //   gp_offset         (0 - 6 * 8)
14085   //   fp_offset         (48 - 48 + 8 * 16)
14086   //   overflow_arg_area (point to parameters coming in memory).
14087   //   reg_save_area
14088   SmallVector<SDValue, 8> MemOps;
14089   SDValue FIN = Op.getOperand(1);
14090   // Store gp_offset
14091   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14092                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14093                                                MVT::i32),
14094                                FIN, MachinePointerInfo(SV), false, false, 0);
14095   MemOps.push_back(Store);
14096
14097   // Store fp_offset
14098   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14099                     FIN, DAG.getIntPtrConstant(4));
14100   Store = DAG.getStore(Op.getOperand(0), DL,
14101                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14102                                        MVT::i32),
14103                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14104   MemOps.push_back(Store);
14105
14106   // Store ptr to overflow_arg_area
14107   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14108                     FIN, DAG.getIntPtrConstant(4));
14109   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14110                                     getPointerTy());
14111   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14112                        MachinePointerInfo(SV, 8),
14113                        false, false, 0);
14114   MemOps.push_back(Store);
14115
14116   // Store ptr to reg_save_area.
14117   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14118                     FIN, DAG.getIntPtrConstant(8));
14119   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14120                                     getPointerTy());
14121   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14122                        MachinePointerInfo(SV, 16), false, false, 0);
14123   MemOps.push_back(Store);
14124   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14125 }
14126
14127 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14128   assert(Subtarget->is64Bit() &&
14129          "LowerVAARG only handles 64-bit va_arg!");
14130   assert((Subtarget->isTargetLinux() ||
14131           Subtarget->isTargetDarwin()) &&
14132           "Unhandled target in LowerVAARG");
14133   assert(Op.getNode()->getNumOperands() == 4);
14134   SDValue Chain = Op.getOperand(0);
14135   SDValue SrcPtr = Op.getOperand(1);
14136   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14137   unsigned Align = Op.getConstantOperandVal(3);
14138   SDLoc dl(Op);
14139
14140   EVT ArgVT = Op.getNode()->getValueType(0);
14141   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14142   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14143   uint8_t ArgMode;
14144
14145   // Decide which area this value should be read from.
14146   // TODO: Implement the AMD64 ABI in its entirety. This simple
14147   // selection mechanism works only for the basic types.
14148   if (ArgVT == MVT::f80) {
14149     llvm_unreachable("va_arg for f80 not yet implemented");
14150   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14151     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14152   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14153     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14154   } else {
14155     llvm_unreachable("Unhandled argument type in LowerVAARG");
14156   }
14157
14158   if (ArgMode == 2) {
14159     // Sanity Check: Make sure using fp_offset makes sense.
14160     assert(!DAG.getTarget().Options.UseSoftFloat &&
14161            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14162                Attribute::NoImplicitFloat)) &&
14163            Subtarget->hasSSE1());
14164   }
14165
14166   // Insert VAARG_64 node into the DAG
14167   // VAARG_64 returns two values: Variable Argument Address, Chain
14168   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14169                        DAG.getConstant(ArgMode, MVT::i8),
14170                        DAG.getConstant(Align, MVT::i32)};
14171   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14172   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14173                                           VTs, InstOps, MVT::i64,
14174                                           MachinePointerInfo(SV),
14175                                           /*Align=*/0,
14176                                           /*Volatile=*/false,
14177                                           /*ReadMem=*/true,
14178                                           /*WriteMem=*/true);
14179   Chain = VAARG.getValue(1);
14180
14181   // Load the next argument and return it
14182   return DAG.getLoad(ArgVT, dl,
14183                      Chain,
14184                      VAARG,
14185                      MachinePointerInfo(),
14186                      false, false, false, 0);
14187 }
14188
14189 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14190                            SelectionDAG &DAG) {
14191   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14192   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14193   SDValue Chain = Op.getOperand(0);
14194   SDValue DstPtr = Op.getOperand(1);
14195   SDValue SrcPtr = Op.getOperand(2);
14196   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14197   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14198   SDLoc DL(Op);
14199
14200   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14201                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14202                        false,
14203                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14204 }
14205
14206 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14207 // amount is a constant. Takes immediate version of shift as input.
14208 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14209                                           SDValue SrcOp, uint64_t ShiftAmt,
14210                                           SelectionDAG &DAG) {
14211   MVT ElementType = VT.getVectorElementType();
14212
14213   // Fold this packed shift into its first operand if ShiftAmt is 0.
14214   if (ShiftAmt == 0)
14215     return SrcOp;
14216
14217   // Check for ShiftAmt >= element width
14218   if (ShiftAmt >= ElementType.getSizeInBits()) {
14219     if (Opc == X86ISD::VSRAI)
14220       ShiftAmt = ElementType.getSizeInBits() - 1;
14221     else
14222       return DAG.getConstant(0, VT);
14223   }
14224
14225   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14226          && "Unknown target vector shift-by-constant node");
14227
14228   // Fold this packed vector shift into a build vector if SrcOp is a
14229   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14230   if (VT == SrcOp.getSimpleValueType() &&
14231       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14232     SmallVector<SDValue, 8> Elts;
14233     unsigned NumElts = SrcOp->getNumOperands();
14234     ConstantSDNode *ND;
14235
14236     switch(Opc) {
14237     default: llvm_unreachable(nullptr);
14238     case X86ISD::VSHLI:
14239       for (unsigned i=0; i!=NumElts; ++i) {
14240         SDValue CurrentOp = SrcOp->getOperand(i);
14241         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14242           Elts.push_back(CurrentOp);
14243           continue;
14244         }
14245         ND = cast<ConstantSDNode>(CurrentOp);
14246         const APInt &C = ND->getAPIntValue();
14247         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14248       }
14249       break;
14250     case X86ISD::VSRLI:
14251       for (unsigned i=0; i!=NumElts; ++i) {
14252         SDValue CurrentOp = SrcOp->getOperand(i);
14253         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14254           Elts.push_back(CurrentOp);
14255           continue;
14256         }
14257         ND = cast<ConstantSDNode>(CurrentOp);
14258         const APInt &C = ND->getAPIntValue();
14259         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14260       }
14261       break;
14262     case X86ISD::VSRAI:
14263       for (unsigned i=0; i!=NumElts; ++i) {
14264         SDValue CurrentOp = SrcOp->getOperand(i);
14265         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14266           Elts.push_back(CurrentOp);
14267           continue;
14268         }
14269         ND = cast<ConstantSDNode>(CurrentOp);
14270         const APInt &C = ND->getAPIntValue();
14271         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14272       }
14273       break;
14274     }
14275
14276     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14277   }
14278
14279   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14280 }
14281
14282 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14283 // may or may not be a constant. Takes immediate version of shift as input.
14284 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14285                                    SDValue SrcOp, SDValue ShAmt,
14286                                    SelectionDAG &DAG) {
14287   MVT SVT = ShAmt.getSimpleValueType();
14288   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14289
14290   // Catch shift-by-constant.
14291   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14292     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14293                                       CShAmt->getZExtValue(), DAG);
14294
14295   // Change opcode to non-immediate version
14296   switch (Opc) {
14297     default: llvm_unreachable("Unknown target vector shift node");
14298     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14299     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14300     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14301   }
14302
14303   const X86Subtarget &Subtarget =
14304       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14305   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14306       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14307     // Let the shuffle legalizer expand this shift amount node.
14308     SDValue Op0 = ShAmt.getOperand(0);
14309     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14310     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14311   } else {
14312     // Need to build a vector containing shift amount.
14313     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14314     SmallVector<SDValue, 4> ShOps;
14315     ShOps.push_back(ShAmt);
14316     if (SVT == MVT::i32) {
14317       ShOps.push_back(DAG.getConstant(0, SVT));
14318       ShOps.push_back(DAG.getUNDEF(SVT));
14319     }
14320     ShOps.push_back(DAG.getUNDEF(SVT));
14321
14322     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14323     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14324   }
14325
14326   // The return type has to be a 128-bit type with the same element
14327   // type as the input type.
14328   MVT EltVT = VT.getVectorElementType();
14329   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14330
14331   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14332   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14333 }
14334
14335 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14336 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14337 /// necessary casting for \p Mask when lowering masking intrinsics.
14338 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14339                                     SDValue PreservedSrc,
14340                                     const X86Subtarget *Subtarget,
14341                                     SelectionDAG &DAG) {
14342     EVT VT = Op.getValueType();
14343     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14344                                   MVT::i1, VT.getVectorNumElements());
14345     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14346                                      Mask.getValueType().getSizeInBits());
14347     SDLoc dl(Op);
14348
14349     assert(MaskVT.isSimple() && "invalid mask type");
14350
14351     if (isAllOnes(Mask))
14352       return Op;
14353
14354     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14355     // are extracted by EXTRACT_SUBVECTOR.
14356     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14357                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14358                               DAG.getIntPtrConstant(0));
14359
14360     switch (Op.getOpcode()) {
14361       default: break;
14362       case X86ISD::PCMPEQM:
14363       case X86ISD::PCMPGTM:
14364       case X86ISD::CMPM:
14365       case X86ISD::CMPMU:
14366         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14367     }
14368     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14369       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14370     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14371 }
14372
14373 /// \brief Creates an SDNode for a predicated scalar operation.
14374 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14375 /// The mask is comming as MVT::i8 and it should be truncated
14376 /// to MVT::i1 while lowering masking intrinsics.
14377 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14378 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14379 /// a scalar instruction.
14380 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14381                                     SDValue PreservedSrc,
14382                                     const X86Subtarget *Subtarget,
14383                                     SelectionDAG &DAG) {
14384     if (isAllOnes(Mask))
14385       return Op;
14386
14387     EVT VT = Op.getValueType();
14388     SDLoc dl(Op);
14389     // The mask should be of type MVT::i1
14390     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14391
14392     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14393       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14394     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14395 }
14396
14397 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14398                                        SelectionDAG &DAG) {
14399   SDLoc dl(Op);
14400   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14401   EVT VT = Op.getValueType();
14402   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14403   if (IntrData) {
14404     switch(IntrData->Type) {
14405     case INTR_TYPE_1OP:
14406       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14407     case INTR_TYPE_2OP:
14408       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14409         Op.getOperand(2));
14410     case INTR_TYPE_3OP:
14411       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14412         Op.getOperand(2), Op.getOperand(3));
14413     case INTR_TYPE_1OP_MASK_RM: {
14414       SDValue Src = Op.getOperand(1);
14415       SDValue Src0 = Op.getOperand(2);
14416       SDValue Mask = Op.getOperand(3);
14417       SDValue RoundingMode = Op.getOperand(4);
14418       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14419                                               RoundingMode),
14420                                   Mask, Src0, Subtarget, DAG);
14421     }
14422     case INTR_TYPE_SCALAR_MASK_RM: {
14423       SDValue Src1 = Op.getOperand(1);
14424       SDValue Src2 = Op.getOperand(2);
14425       SDValue Src0 = Op.getOperand(3);
14426       SDValue Mask = Op.getOperand(4);
14427       SDValue RoundingMode = Op.getOperand(5);
14428       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14429                                               RoundingMode),
14430                                   Mask, Src0, Subtarget, DAG);
14431     }
14432     case INTR_TYPE_2OP_MASK: {
14433       SDValue Src1 = Op.getOperand(1);
14434       SDValue Src2 = Op.getOperand(2);
14435       SDValue PassThru = Op.getOperand(3);
14436       SDValue Mask = Op.getOperand(4);
14437       // We specify 2 possible opcodes for intrinsics with rounding modes.
14438       // First, we check if the intrinsic may have non-default rounding mode,
14439       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14440       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14441       if (IntrWithRoundingModeOpcode != 0) {
14442         SDValue Rnd = Op.getOperand(5);
14443         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14444         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14445           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14446                                       dl, Op.getValueType(),
14447                                       Src1, Src2, Rnd),
14448                                       Mask, PassThru, Subtarget, DAG);
14449         }
14450       }
14451       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14452                                               Src1,Src2),
14453                                   Mask, PassThru, Subtarget, DAG);
14454     }
14455     case FMA_OP_MASK: {
14456       SDValue Src1 = Op.getOperand(1);
14457       SDValue Src2 = Op.getOperand(2);
14458       SDValue Src3 = Op.getOperand(3);
14459       SDValue Mask = Op.getOperand(4);
14460       // We specify 2 possible opcodes for intrinsics with rounding modes.
14461       // First, we check if the intrinsic may have non-default rounding mode,
14462       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14463       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14464       if (IntrWithRoundingModeOpcode != 0) {
14465         SDValue Rnd = Op.getOperand(5);
14466         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14467             X86::STATIC_ROUNDING::CUR_DIRECTION)
14468           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14469                                                   dl, Op.getValueType(),
14470                                                   Src1, Src2, Src3, Rnd),
14471                                       Mask, Src1, Subtarget, DAG);
14472       }
14473       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14474                                               dl, Op.getValueType(),
14475                                               Src1, Src2, Src3),
14476                                   Mask, Src1, Subtarget, DAG);
14477     }
14478     case CMP_MASK:
14479     case CMP_MASK_CC: {
14480       // Comparison intrinsics with masks.
14481       // Example of transformation:
14482       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14483       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14484       // (i8 (bitcast
14485       //   (v8i1 (insert_subvector undef,
14486       //           (v2i1 (and (PCMPEQM %a, %b),
14487       //                      (extract_subvector
14488       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14489       EVT VT = Op.getOperand(1).getValueType();
14490       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14491                                     VT.getVectorNumElements());
14492       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14493       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14494                                        Mask.getValueType().getSizeInBits());
14495       SDValue Cmp;
14496       if (IntrData->Type == CMP_MASK_CC) {
14497         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14498                     Op.getOperand(2), Op.getOperand(3));
14499       } else {
14500         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14501         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14502                     Op.getOperand(2));
14503       }
14504       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14505                                              DAG.getTargetConstant(0, MaskVT),
14506                                              Subtarget, DAG);
14507       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14508                                 DAG.getUNDEF(BitcastVT), CmpMask,
14509                                 DAG.getIntPtrConstant(0));
14510       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14511     }
14512     case COMI: { // Comparison intrinsics
14513       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14514       SDValue LHS = Op.getOperand(1);
14515       SDValue RHS = Op.getOperand(2);
14516       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14517       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14518       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14519       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14520                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14521       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14522     }
14523     case VSHIFT:
14524       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14525                                  Op.getOperand(1), Op.getOperand(2), DAG);
14526     case VSHIFT_MASK:
14527       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14528                                                       Op.getSimpleValueType(),
14529                                                       Op.getOperand(1),
14530                                                       Op.getOperand(2), DAG),
14531                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
14532                                   DAG);
14533     case COMPRESS_EXPAND_IN_REG: {
14534       SDValue Mask = Op.getOperand(3);
14535       SDValue DataToCompress = Op.getOperand(1);
14536       SDValue PassThru = Op.getOperand(2);
14537       if (isAllOnes(Mask)) // return data as is
14538         return Op.getOperand(1);
14539       EVT VT = Op.getValueType();
14540       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14541                                     VT.getVectorNumElements());
14542       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14543                                        Mask.getValueType().getSizeInBits());
14544       SDLoc dl(Op);
14545       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14546                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14547                                   DAG.getIntPtrConstant(0));
14548
14549       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14550                          PassThru);
14551     }
14552     case BLEND: {
14553       SDValue Mask = Op.getOperand(3);
14554       EVT VT = Op.getValueType();
14555       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14556                                     VT.getVectorNumElements());
14557       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14558                                        Mask.getValueType().getSizeInBits());
14559       SDLoc dl(Op);
14560       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14561                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14562                                   DAG.getIntPtrConstant(0));
14563       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14564                          Op.getOperand(2));
14565     }
14566     default:
14567       break;
14568     }
14569   }
14570
14571   switch (IntNo) {
14572   default: return SDValue();    // Don't custom lower most intrinsics.
14573
14574   case Intrinsic::x86_avx512_mask_valign_q_512:
14575   case Intrinsic::x86_avx512_mask_valign_d_512:
14576     // Vector source operands are swapped.
14577     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14578                                             Op.getValueType(), Op.getOperand(2),
14579                                             Op.getOperand(1),
14580                                             Op.getOperand(3)),
14581                                 Op.getOperand(5), Op.getOperand(4),
14582                                 Subtarget, DAG);
14583
14584   // ptest and testp intrinsics. The intrinsic these come from are designed to
14585   // return an integer value, not just an instruction so lower it to the ptest
14586   // or testp pattern and a setcc for the result.
14587   case Intrinsic::x86_sse41_ptestz:
14588   case Intrinsic::x86_sse41_ptestc:
14589   case Intrinsic::x86_sse41_ptestnzc:
14590   case Intrinsic::x86_avx_ptestz_256:
14591   case Intrinsic::x86_avx_ptestc_256:
14592   case Intrinsic::x86_avx_ptestnzc_256:
14593   case Intrinsic::x86_avx_vtestz_ps:
14594   case Intrinsic::x86_avx_vtestc_ps:
14595   case Intrinsic::x86_avx_vtestnzc_ps:
14596   case Intrinsic::x86_avx_vtestz_pd:
14597   case Intrinsic::x86_avx_vtestc_pd:
14598   case Intrinsic::x86_avx_vtestnzc_pd:
14599   case Intrinsic::x86_avx_vtestz_ps_256:
14600   case Intrinsic::x86_avx_vtestc_ps_256:
14601   case Intrinsic::x86_avx_vtestnzc_ps_256:
14602   case Intrinsic::x86_avx_vtestz_pd_256:
14603   case Intrinsic::x86_avx_vtestc_pd_256:
14604   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14605     bool IsTestPacked = false;
14606     unsigned X86CC;
14607     switch (IntNo) {
14608     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14609     case Intrinsic::x86_avx_vtestz_ps:
14610     case Intrinsic::x86_avx_vtestz_pd:
14611     case Intrinsic::x86_avx_vtestz_ps_256:
14612     case Intrinsic::x86_avx_vtestz_pd_256:
14613       IsTestPacked = true; // Fallthrough
14614     case Intrinsic::x86_sse41_ptestz:
14615     case Intrinsic::x86_avx_ptestz_256:
14616       // ZF = 1
14617       X86CC = X86::COND_E;
14618       break;
14619     case Intrinsic::x86_avx_vtestc_ps:
14620     case Intrinsic::x86_avx_vtestc_pd:
14621     case Intrinsic::x86_avx_vtestc_ps_256:
14622     case Intrinsic::x86_avx_vtestc_pd_256:
14623       IsTestPacked = true; // Fallthrough
14624     case Intrinsic::x86_sse41_ptestc:
14625     case Intrinsic::x86_avx_ptestc_256:
14626       // CF = 1
14627       X86CC = X86::COND_B;
14628       break;
14629     case Intrinsic::x86_avx_vtestnzc_ps:
14630     case Intrinsic::x86_avx_vtestnzc_pd:
14631     case Intrinsic::x86_avx_vtestnzc_ps_256:
14632     case Intrinsic::x86_avx_vtestnzc_pd_256:
14633       IsTestPacked = true; // Fallthrough
14634     case Intrinsic::x86_sse41_ptestnzc:
14635     case Intrinsic::x86_avx_ptestnzc_256:
14636       // ZF and CF = 0
14637       X86CC = X86::COND_A;
14638       break;
14639     }
14640
14641     SDValue LHS = Op.getOperand(1);
14642     SDValue RHS = Op.getOperand(2);
14643     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14644     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14645     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14646     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14647     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14648   }
14649   case Intrinsic::x86_avx512_kortestz_w:
14650   case Intrinsic::x86_avx512_kortestc_w: {
14651     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14652     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14653     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14654     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14655     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14656     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14657     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14658   }
14659
14660   case Intrinsic::x86_sse42_pcmpistria128:
14661   case Intrinsic::x86_sse42_pcmpestria128:
14662   case Intrinsic::x86_sse42_pcmpistric128:
14663   case Intrinsic::x86_sse42_pcmpestric128:
14664   case Intrinsic::x86_sse42_pcmpistrio128:
14665   case Intrinsic::x86_sse42_pcmpestrio128:
14666   case Intrinsic::x86_sse42_pcmpistris128:
14667   case Intrinsic::x86_sse42_pcmpestris128:
14668   case Intrinsic::x86_sse42_pcmpistriz128:
14669   case Intrinsic::x86_sse42_pcmpestriz128: {
14670     unsigned Opcode;
14671     unsigned X86CC;
14672     switch (IntNo) {
14673     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14674     case Intrinsic::x86_sse42_pcmpistria128:
14675       Opcode = X86ISD::PCMPISTRI;
14676       X86CC = X86::COND_A;
14677       break;
14678     case Intrinsic::x86_sse42_pcmpestria128:
14679       Opcode = X86ISD::PCMPESTRI;
14680       X86CC = X86::COND_A;
14681       break;
14682     case Intrinsic::x86_sse42_pcmpistric128:
14683       Opcode = X86ISD::PCMPISTRI;
14684       X86CC = X86::COND_B;
14685       break;
14686     case Intrinsic::x86_sse42_pcmpestric128:
14687       Opcode = X86ISD::PCMPESTRI;
14688       X86CC = X86::COND_B;
14689       break;
14690     case Intrinsic::x86_sse42_pcmpistrio128:
14691       Opcode = X86ISD::PCMPISTRI;
14692       X86CC = X86::COND_O;
14693       break;
14694     case Intrinsic::x86_sse42_pcmpestrio128:
14695       Opcode = X86ISD::PCMPESTRI;
14696       X86CC = X86::COND_O;
14697       break;
14698     case Intrinsic::x86_sse42_pcmpistris128:
14699       Opcode = X86ISD::PCMPISTRI;
14700       X86CC = X86::COND_S;
14701       break;
14702     case Intrinsic::x86_sse42_pcmpestris128:
14703       Opcode = X86ISD::PCMPESTRI;
14704       X86CC = X86::COND_S;
14705       break;
14706     case Intrinsic::x86_sse42_pcmpistriz128:
14707       Opcode = X86ISD::PCMPISTRI;
14708       X86CC = X86::COND_E;
14709       break;
14710     case Intrinsic::x86_sse42_pcmpestriz128:
14711       Opcode = X86ISD::PCMPESTRI;
14712       X86CC = X86::COND_E;
14713       break;
14714     }
14715     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14716     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14717     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14718     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14719                                 DAG.getConstant(X86CC, MVT::i8),
14720                                 SDValue(PCMP.getNode(), 1));
14721     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14722   }
14723
14724   case Intrinsic::x86_sse42_pcmpistri128:
14725   case Intrinsic::x86_sse42_pcmpestri128: {
14726     unsigned Opcode;
14727     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14728       Opcode = X86ISD::PCMPISTRI;
14729     else
14730       Opcode = X86ISD::PCMPESTRI;
14731
14732     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14733     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14734     return DAG.getNode(Opcode, dl, VTs, NewOps);
14735   }
14736   }
14737 }
14738
14739 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14740                               SDValue Src, SDValue Mask, SDValue Base,
14741                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14742                               const X86Subtarget * Subtarget) {
14743   SDLoc dl(Op);
14744   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14745   assert(C && "Invalid scale type");
14746   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14747   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14748                              Index.getSimpleValueType().getVectorNumElements());
14749   SDValue MaskInReg;
14750   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14751   if (MaskC)
14752     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14753   else
14754     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14755   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14756   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14757   SDValue Segment = DAG.getRegister(0, MVT::i32);
14758   if (Src.getOpcode() == ISD::UNDEF)
14759     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14760   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14761   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14762   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14763   return DAG.getMergeValues(RetOps, dl);
14764 }
14765
14766 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14767                                SDValue Src, SDValue Mask, SDValue Base,
14768                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14769   SDLoc dl(Op);
14770   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14771   assert(C && "Invalid scale type");
14772   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14773   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14774   SDValue Segment = DAG.getRegister(0, MVT::i32);
14775   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14776                              Index.getSimpleValueType().getVectorNumElements());
14777   SDValue MaskInReg;
14778   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14779   if (MaskC)
14780     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14781   else
14782     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14783   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14784   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14785   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14786   return SDValue(Res, 1);
14787 }
14788
14789 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14790                                SDValue Mask, SDValue Base, SDValue Index,
14791                                SDValue ScaleOp, SDValue Chain) {
14792   SDLoc dl(Op);
14793   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14794   assert(C && "Invalid scale type");
14795   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14796   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14797   SDValue Segment = DAG.getRegister(0, MVT::i32);
14798   EVT MaskVT =
14799     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14800   SDValue MaskInReg;
14801   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14802   if (MaskC)
14803     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14804   else
14805     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14806   //SDVTList VTs = DAG.getVTList(MVT::Other);
14807   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14808   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14809   return SDValue(Res, 0);
14810 }
14811
14812 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14813 // read performance monitor counters (x86_rdpmc).
14814 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14815                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14816                               SmallVectorImpl<SDValue> &Results) {
14817   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14818   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14819   SDValue LO, HI;
14820
14821   // The ECX register is used to select the index of the performance counter
14822   // to read.
14823   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14824                                    N->getOperand(2));
14825   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14826
14827   // Reads the content of a 64-bit performance counter and returns it in the
14828   // registers EDX:EAX.
14829   if (Subtarget->is64Bit()) {
14830     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14831     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14832                             LO.getValue(2));
14833   } else {
14834     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14835     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14836                             LO.getValue(2));
14837   }
14838   Chain = HI.getValue(1);
14839
14840   if (Subtarget->is64Bit()) {
14841     // The EAX register is loaded with the low-order 32 bits. The EDX register
14842     // is loaded with the supported high-order bits of the counter.
14843     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14844                               DAG.getConstant(32, MVT::i8));
14845     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14846     Results.push_back(Chain);
14847     return;
14848   }
14849
14850   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14851   SDValue Ops[] = { LO, HI };
14852   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14853   Results.push_back(Pair);
14854   Results.push_back(Chain);
14855 }
14856
14857 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14858 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14859 // also used to custom lower READCYCLECOUNTER nodes.
14860 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14861                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14862                               SmallVectorImpl<SDValue> &Results) {
14863   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14864   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14865   SDValue LO, HI;
14866
14867   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14868   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14869   // and the EAX register is loaded with the low-order 32 bits.
14870   if (Subtarget->is64Bit()) {
14871     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14872     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14873                             LO.getValue(2));
14874   } else {
14875     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14876     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14877                             LO.getValue(2));
14878   }
14879   SDValue Chain = HI.getValue(1);
14880
14881   if (Opcode == X86ISD::RDTSCP_DAG) {
14882     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14883
14884     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14885     // the ECX register. Add 'ecx' explicitly to the chain.
14886     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14887                                      HI.getValue(2));
14888     // Explicitly store the content of ECX at the location passed in input
14889     // to the 'rdtscp' intrinsic.
14890     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14891                          MachinePointerInfo(), false, false, 0);
14892   }
14893
14894   if (Subtarget->is64Bit()) {
14895     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14896     // the EAX register is loaded with the low-order 32 bits.
14897     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14898                               DAG.getConstant(32, MVT::i8));
14899     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14900     Results.push_back(Chain);
14901     return;
14902   }
14903
14904   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14905   SDValue Ops[] = { LO, HI };
14906   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14907   Results.push_back(Pair);
14908   Results.push_back(Chain);
14909 }
14910
14911 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14912                                      SelectionDAG &DAG) {
14913   SmallVector<SDValue, 2> Results;
14914   SDLoc DL(Op);
14915   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14916                           Results);
14917   return DAG.getMergeValues(Results, DL);
14918 }
14919
14920
14921 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14922                                       SelectionDAG &DAG) {
14923   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14924
14925   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
14926   if (!IntrData)
14927     return SDValue();
14928
14929   SDLoc dl(Op);
14930   switch(IntrData->Type) {
14931   default:
14932     llvm_unreachable("Unknown Intrinsic Type");
14933     break;
14934   case RDSEED:
14935   case RDRAND: {
14936     // Emit the node with the right value type.
14937     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14938     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
14939
14940     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14941     // Otherwise return the value from Rand, which is always 0, casted to i32.
14942     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14943                       DAG.getConstant(1, Op->getValueType(1)),
14944                       DAG.getConstant(X86::COND_B, MVT::i32),
14945                       SDValue(Result.getNode(), 1) };
14946     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14947                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14948                                   Ops);
14949
14950     // Return { result, isValid, chain }.
14951     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14952                        SDValue(Result.getNode(), 2));
14953   }
14954   case GATHER: {
14955   //gather(v1, mask, index, base, scale);
14956     SDValue Chain = Op.getOperand(0);
14957     SDValue Src   = Op.getOperand(2);
14958     SDValue Base  = Op.getOperand(3);
14959     SDValue Index = Op.getOperand(4);
14960     SDValue Mask  = Op.getOperand(5);
14961     SDValue Scale = Op.getOperand(6);
14962     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14963                           Subtarget);
14964   }
14965   case SCATTER: {
14966   //scatter(base, mask, index, v1, scale);
14967     SDValue Chain = Op.getOperand(0);
14968     SDValue Base  = Op.getOperand(2);
14969     SDValue Mask  = Op.getOperand(3);
14970     SDValue Index = Op.getOperand(4);
14971     SDValue Src   = Op.getOperand(5);
14972     SDValue Scale = Op.getOperand(6);
14973     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14974   }
14975   case PREFETCH: {
14976     SDValue Hint = Op.getOperand(6);
14977     unsigned HintVal;
14978     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14979         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14980       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14981     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
14982     SDValue Chain = Op.getOperand(0);
14983     SDValue Mask  = Op.getOperand(2);
14984     SDValue Index = Op.getOperand(3);
14985     SDValue Base  = Op.getOperand(4);
14986     SDValue Scale = Op.getOperand(5);
14987     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14988   }
14989   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14990   case RDTSC: {
14991     SmallVector<SDValue, 2> Results;
14992     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
14993     return DAG.getMergeValues(Results, dl);
14994   }
14995   // Read Performance Monitoring Counters.
14996   case RDPMC: {
14997     SmallVector<SDValue, 2> Results;
14998     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14999     return DAG.getMergeValues(Results, dl);
15000   }
15001   // XTEST intrinsics.
15002   case XTEST: {
15003     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15004     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15005     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15006                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15007                                 InTrans);
15008     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15009     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15010                        Ret, SDValue(InTrans.getNode(), 1));
15011   }
15012   // ADC/ADCX/SBB
15013   case ADX: {
15014     SmallVector<SDValue, 2> Results;
15015     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15016     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15017     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15018                                 DAG.getConstant(-1, MVT::i8));
15019     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15020                               Op.getOperand(4), GenCF.getValue(1));
15021     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15022                                  Op.getOperand(5), MachinePointerInfo(),
15023                                  false, false, 0);
15024     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15025                                 DAG.getConstant(X86::COND_B, MVT::i8),
15026                                 Res.getValue(1));
15027     Results.push_back(SetCC);
15028     Results.push_back(Store);
15029     return DAG.getMergeValues(Results, dl);
15030   }
15031   case COMPRESS_TO_MEM: {
15032     SDLoc dl(Op);
15033     SDValue Mask = Op.getOperand(4);
15034     SDValue DataToCompress = Op.getOperand(3);
15035     SDValue Addr = Op.getOperand(2);
15036     SDValue Chain = Op.getOperand(0);
15037
15038     if (isAllOnes(Mask)) // return just a store
15039       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15040                           MachinePointerInfo(), false, false, 0);
15041
15042     EVT VT = DataToCompress.getValueType();
15043     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15044                                   VT.getVectorNumElements());
15045     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15046                                      Mask.getValueType().getSizeInBits());
15047     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15048                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15049                                 DAG.getIntPtrConstant(0));
15050
15051     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15052                                       DataToCompress, DAG.getUNDEF(VT));
15053     return DAG.getStore(Chain, dl, Compressed, Addr,
15054                         MachinePointerInfo(), false, false, 0);
15055   }
15056   case EXPAND_FROM_MEM: {
15057     SDLoc dl(Op);
15058     SDValue Mask = Op.getOperand(4);
15059     SDValue PathThru = Op.getOperand(3);
15060     SDValue Addr = Op.getOperand(2);
15061     SDValue Chain = Op.getOperand(0);
15062     EVT VT = Op.getValueType();
15063
15064     if (isAllOnes(Mask)) // return just a load
15065       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15066                          false, 0);
15067     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15068                                   VT.getVectorNumElements());
15069     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15070                                      Mask.getValueType().getSizeInBits());
15071     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15072                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15073                                 DAG.getIntPtrConstant(0));
15074
15075     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15076                                    false, false, false, 0);
15077
15078     SDValue Results[] = {
15079         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15080         Chain};
15081     return DAG.getMergeValues(Results, dl);
15082   }
15083   }
15084 }
15085
15086 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15087                                            SelectionDAG &DAG) const {
15088   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15089   MFI->setReturnAddressIsTaken(true);
15090
15091   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15092     return SDValue();
15093
15094   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15095   SDLoc dl(Op);
15096   EVT PtrVT = getPointerTy();
15097
15098   if (Depth > 0) {
15099     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15100     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15101     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15102     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15103                        DAG.getNode(ISD::ADD, dl, PtrVT,
15104                                    FrameAddr, Offset),
15105                        MachinePointerInfo(), false, false, false, 0);
15106   }
15107
15108   // Just load the return address.
15109   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15110   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15111                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15112 }
15113
15114 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15115   MachineFunction &MF = DAG.getMachineFunction();
15116   MachineFrameInfo *MFI = MF.getFrameInfo();
15117   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15118   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15119   EVT VT = Op.getValueType();
15120
15121   MFI->setFrameAddressIsTaken(true);
15122
15123   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15124     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15125     // is not possible to crawl up the stack without looking at the unwind codes
15126     // simultaneously.
15127     int FrameAddrIndex = FuncInfo->getFAIndex();
15128     if (!FrameAddrIndex) {
15129       // Set up a frame object for the return address.
15130       unsigned SlotSize = RegInfo->getSlotSize();
15131       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15132           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15133       FuncInfo->setFAIndex(FrameAddrIndex);
15134     }
15135     return DAG.getFrameIndex(FrameAddrIndex, VT);
15136   }
15137
15138   unsigned FrameReg =
15139       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15140   SDLoc dl(Op);  // FIXME probably not meaningful
15141   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15142   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15143           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15144          "Invalid Frame Register!");
15145   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15146   while (Depth--)
15147     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15148                             MachinePointerInfo(),
15149                             false, false, false, 0);
15150   return FrameAddr;
15151 }
15152
15153 // FIXME? Maybe this could be a TableGen attribute on some registers and
15154 // this table could be generated automatically from RegInfo.
15155 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15156                                               EVT VT) const {
15157   unsigned Reg = StringSwitch<unsigned>(RegName)
15158                        .Case("esp", X86::ESP)
15159                        .Case("rsp", X86::RSP)
15160                        .Default(0);
15161   if (Reg)
15162     return Reg;
15163   report_fatal_error("Invalid register name global variable");
15164 }
15165
15166 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15167                                                      SelectionDAG &DAG) const {
15168   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15169   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15170 }
15171
15172 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15173   SDValue Chain     = Op.getOperand(0);
15174   SDValue Offset    = Op.getOperand(1);
15175   SDValue Handler   = Op.getOperand(2);
15176   SDLoc dl      (Op);
15177
15178   EVT PtrVT = getPointerTy();
15179   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15180   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15181   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15182           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15183          "Invalid Frame Register!");
15184   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15185   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15186
15187   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15188                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15189   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15190   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15191                        false, false, 0);
15192   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15193
15194   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15195                      DAG.getRegister(StoreAddrReg, PtrVT));
15196 }
15197
15198 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15199                                                SelectionDAG &DAG) const {
15200   SDLoc DL(Op);
15201   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15202                      DAG.getVTList(MVT::i32, MVT::Other),
15203                      Op.getOperand(0), Op.getOperand(1));
15204 }
15205
15206 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15207                                                 SelectionDAG &DAG) const {
15208   SDLoc DL(Op);
15209   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15210                      Op.getOperand(0), Op.getOperand(1));
15211 }
15212
15213 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15214   return Op.getOperand(0);
15215 }
15216
15217 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15218                                                 SelectionDAG &DAG) const {
15219   SDValue Root = Op.getOperand(0);
15220   SDValue Trmp = Op.getOperand(1); // trampoline
15221   SDValue FPtr = Op.getOperand(2); // nested function
15222   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15223   SDLoc dl (Op);
15224
15225   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15226   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15227
15228   if (Subtarget->is64Bit()) {
15229     SDValue OutChains[6];
15230
15231     // Large code-model.
15232     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15233     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15234
15235     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15236     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15237
15238     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15239
15240     // Load the pointer to the nested function into R11.
15241     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15242     SDValue Addr = Trmp;
15243     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15244                                 Addr, MachinePointerInfo(TrmpAddr),
15245                                 false, false, 0);
15246
15247     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15248                        DAG.getConstant(2, MVT::i64));
15249     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15250                                 MachinePointerInfo(TrmpAddr, 2),
15251                                 false, false, 2);
15252
15253     // Load the 'nest' parameter value into R10.
15254     // R10 is specified in X86CallingConv.td
15255     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15256     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15257                        DAG.getConstant(10, MVT::i64));
15258     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15259                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15260                                 false, false, 0);
15261
15262     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15263                        DAG.getConstant(12, MVT::i64));
15264     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15265                                 MachinePointerInfo(TrmpAddr, 12),
15266                                 false, false, 2);
15267
15268     // Jump to the nested function.
15269     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15270     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15271                        DAG.getConstant(20, MVT::i64));
15272     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15273                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15274                                 false, false, 0);
15275
15276     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15277     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15278                        DAG.getConstant(22, MVT::i64));
15279     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15280                                 MachinePointerInfo(TrmpAddr, 22),
15281                                 false, false, 0);
15282
15283     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15284   } else {
15285     const Function *Func =
15286       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15287     CallingConv::ID CC = Func->getCallingConv();
15288     unsigned NestReg;
15289
15290     switch (CC) {
15291     default:
15292       llvm_unreachable("Unsupported calling convention");
15293     case CallingConv::C:
15294     case CallingConv::X86_StdCall: {
15295       // Pass 'nest' parameter in ECX.
15296       // Must be kept in sync with X86CallingConv.td
15297       NestReg = X86::ECX;
15298
15299       // Check that ECX wasn't needed by an 'inreg' parameter.
15300       FunctionType *FTy = Func->getFunctionType();
15301       const AttributeSet &Attrs = Func->getAttributes();
15302
15303       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15304         unsigned InRegCount = 0;
15305         unsigned Idx = 1;
15306
15307         for (FunctionType::param_iterator I = FTy->param_begin(),
15308              E = FTy->param_end(); I != E; ++I, ++Idx)
15309           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15310             // FIXME: should only count parameters that are lowered to integers.
15311             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15312
15313         if (InRegCount > 2) {
15314           report_fatal_error("Nest register in use - reduce number of inreg"
15315                              " parameters!");
15316         }
15317       }
15318       break;
15319     }
15320     case CallingConv::X86_FastCall:
15321     case CallingConv::X86_ThisCall:
15322     case CallingConv::Fast:
15323       // Pass 'nest' parameter in EAX.
15324       // Must be kept in sync with X86CallingConv.td
15325       NestReg = X86::EAX;
15326       break;
15327     }
15328
15329     SDValue OutChains[4];
15330     SDValue Addr, Disp;
15331
15332     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15333                        DAG.getConstant(10, MVT::i32));
15334     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15335
15336     // This is storing the opcode for MOV32ri.
15337     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15338     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15339     OutChains[0] = DAG.getStore(Root, dl,
15340                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15341                                 Trmp, MachinePointerInfo(TrmpAddr),
15342                                 false, false, 0);
15343
15344     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15345                        DAG.getConstant(1, MVT::i32));
15346     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15347                                 MachinePointerInfo(TrmpAddr, 1),
15348                                 false, false, 1);
15349
15350     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15351     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15352                        DAG.getConstant(5, MVT::i32));
15353     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15354                                 MachinePointerInfo(TrmpAddr, 5),
15355                                 false, false, 1);
15356
15357     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15358                        DAG.getConstant(6, MVT::i32));
15359     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15360                                 MachinePointerInfo(TrmpAddr, 6),
15361                                 false, false, 1);
15362
15363     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15364   }
15365 }
15366
15367 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15368                                             SelectionDAG &DAG) const {
15369   /*
15370    The rounding mode is in bits 11:10 of FPSR, and has the following
15371    settings:
15372      00 Round to nearest
15373      01 Round to -inf
15374      10 Round to +inf
15375      11 Round to 0
15376
15377   FLT_ROUNDS, on the other hand, expects the following:
15378     -1 Undefined
15379      0 Round to 0
15380      1 Round to nearest
15381      2 Round to +inf
15382      3 Round to -inf
15383
15384   To perform the conversion, we do:
15385     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15386   */
15387
15388   MachineFunction &MF = DAG.getMachineFunction();
15389   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15390   unsigned StackAlignment = TFI.getStackAlignment();
15391   MVT VT = Op.getSimpleValueType();
15392   SDLoc DL(Op);
15393
15394   // Save FP Control Word to stack slot
15395   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15396   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15397
15398   MachineMemOperand *MMO =
15399    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15400                            MachineMemOperand::MOStore, 2, 2);
15401
15402   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15403   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15404                                           DAG.getVTList(MVT::Other),
15405                                           Ops, MVT::i16, MMO);
15406
15407   // Load FP Control Word from stack slot
15408   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15409                             MachinePointerInfo(), false, false, false, 0);
15410
15411   // Transform as necessary
15412   SDValue CWD1 =
15413     DAG.getNode(ISD::SRL, DL, MVT::i16,
15414                 DAG.getNode(ISD::AND, DL, MVT::i16,
15415                             CWD, DAG.getConstant(0x800, MVT::i16)),
15416                 DAG.getConstant(11, MVT::i8));
15417   SDValue CWD2 =
15418     DAG.getNode(ISD::SRL, DL, MVT::i16,
15419                 DAG.getNode(ISD::AND, DL, MVT::i16,
15420                             CWD, DAG.getConstant(0x400, MVT::i16)),
15421                 DAG.getConstant(9, MVT::i8));
15422
15423   SDValue RetVal =
15424     DAG.getNode(ISD::AND, DL, MVT::i16,
15425                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15426                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15427                             DAG.getConstant(1, MVT::i16)),
15428                 DAG.getConstant(3, MVT::i16));
15429
15430   return DAG.getNode((VT.getSizeInBits() < 16 ?
15431                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15432 }
15433
15434 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15435   MVT VT = Op.getSimpleValueType();
15436   EVT OpVT = VT;
15437   unsigned NumBits = VT.getSizeInBits();
15438   SDLoc dl(Op);
15439
15440   Op = Op.getOperand(0);
15441   if (VT == MVT::i8) {
15442     // Zero extend to i32 since there is not an i8 bsr.
15443     OpVT = MVT::i32;
15444     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15445   }
15446
15447   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15448   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15449   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15450
15451   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15452   SDValue Ops[] = {
15453     Op,
15454     DAG.getConstant(NumBits+NumBits-1, OpVT),
15455     DAG.getConstant(X86::COND_E, MVT::i8),
15456     Op.getValue(1)
15457   };
15458   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15459
15460   // Finally xor with NumBits-1.
15461   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15462
15463   if (VT == MVT::i8)
15464     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15465   return Op;
15466 }
15467
15468 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15469   MVT VT = Op.getSimpleValueType();
15470   EVT OpVT = VT;
15471   unsigned NumBits = VT.getSizeInBits();
15472   SDLoc dl(Op);
15473
15474   Op = Op.getOperand(0);
15475   if (VT == MVT::i8) {
15476     // Zero extend to i32 since there is not an i8 bsr.
15477     OpVT = MVT::i32;
15478     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15479   }
15480
15481   // Issue a bsr (scan bits in reverse).
15482   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15483   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15484
15485   // And xor with NumBits-1.
15486   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15487
15488   if (VT == MVT::i8)
15489     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15490   return Op;
15491 }
15492
15493 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15494   MVT VT = Op.getSimpleValueType();
15495   unsigned NumBits = VT.getSizeInBits();
15496   SDLoc dl(Op);
15497   Op = Op.getOperand(0);
15498
15499   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15500   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15501   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15502
15503   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15504   SDValue Ops[] = {
15505     Op,
15506     DAG.getConstant(NumBits, VT),
15507     DAG.getConstant(X86::COND_E, MVT::i8),
15508     Op.getValue(1)
15509   };
15510   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15511 }
15512
15513 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15514 // ones, and then concatenate the result back.
15515 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15516   MVT VT = Op.getSimpleValueType();
15517
15518   assert(VT.is256BitVector() && VT.isInteger() &&
15519          "Unsupported value type for operation");
15520
15521   unsigned NumElems = VT.getVectorNumElements();
15522   SDLoc dl(Op);
15523
15524   // Extract the LHS vectors
15525   SDValue LHS = Op.getOperand(0);
15526   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15527   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15528
15529   // Extract the RHS vectors
15530   SDValue RHS = Op.getOperand(1);
15531   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15532   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15533
15534   MVT EltVT = VT.getVectorElementType();
15535   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15536
15537   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15538                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15539                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15540 }
15541
15542 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15543   assert(Op.getSimpleValueType().is256BitVector() &&
15544          Op.getSimpleValueType().isInteger() &&
15545          "Only handle AVX 256-bit vector integer operation");
15546   return Lower256IntArith(Op, DAG);
15547 }
15548
15549 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15550   assert(Op.getSimpleValueType().is256BitVector() &&
15551          Op.getSimpleValueType().isInteger() &&
15552          "Only handle AVX 256-bit vector integer operation");
15553   return Lower256IntArith(Op, DAG);
15554 }
15555
15556 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15557                         SelectionDAG &DAG) {
15558   SDLoc dl(Op);
15559   MVT VT = Op.getSimpleValueType();
15560
15561   // Decompose 256-bit ops into smaller 128-bit ops.
15562   if (VT.is256BitVector() && !Subtarget->hasInt256())
15563     return Lower256IntArith(Op, DAG);
15564
15565   SDValue A = Op.getOperand(0);
15566   SDValue B = Op.getOperand(1);
15567
15568   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15569   if (VT == MVT::v4i32) {
15570     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15571            "Should not custom lower when pmuldq is available!");
15572
15573     // Extract the odd parts.
15574     static const int UnpackMask[] = { 1, -1, 3, -1 };
15575     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15576     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15577
15578     // Multiply the even parts.
15579     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15580     // Now multiply odd parts.
15581     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15582
15583     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15584     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15585
15586     // Merge the two vectors back together with a shuffle. This expands into 2
15587     // shuffles.
15588     static const int ShufMask[] = { 0, 4, 2, 6 };
15589     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15590   }
15591
15592   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15593          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15594
15595   //  Ahi = psrlqi(a, 32);
15596   //  Bhi = psrlqi(b, 32);
15597   //
15598   //  AloBlo = pmuludq(a, b);
15599   //  AloBhi = pmuludq(a, Bhi);
15600   //  AhiBlo = pmuludq(Ahi, b);
15601
15602   //  AloBhi = psllqi(AloBhi, 32);
15603   //  AhiBlo = psllqi(AhiBlo, 32);
15604   //  return AloBlo + AloBhi + AhiBlo;
15605
15606   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15607   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15608
15609   // Bit cast to 32-bit vectors for MULUDQ
15610   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15611                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15612   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15613   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15614   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15615   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15616
15617   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15618   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15619   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15620
15621   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15622   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15623
15624   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15625   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15626 }
15627
15628 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15629   assert(Subtarget->isTargetWin64() && "Unexpected target");
15630   EVT VT = Op.getValueType();
15631   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15632          "Unexpected return type for lowering");
15633
15634   RTLIB::Libcall LC;
15635   bool isSigned;
15636   switch (Op->getOpcode()) {
15637   default: llvm_unreachable("Unexpected request for libcall!");
15638   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15639   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15640   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15641   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15642   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15643   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15644   }
15645
15646   SDLoc dl(Op);
15647   SDValue InChain = DAG.getEntryNode();
15648
15649   TargetLowering::ArgListTy Args;
15650   TargetLowering::ArgListEntry Entry;
15651   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15652     EVT ArgVT = Op->getOperand(i).getValueType();
15653     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15654            "Unexpected argument type for lowering");
15655     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15656     Entry.Node = StackPtr;
15657     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15658                            false, false, 16);
15659     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15660     Entry.Ty = PointerType::get(ArgTy,0);
15661     Entry.isSExt = false;
15662     Entry.isZExt = false;
15663     Args.push_back(Entry);
15664   }
15665
15666   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15667                                          getPointerTy());
15668
15669   TargetLowering::CallLoweringInfo CLI(DAG);
15670   CLI.setDebugLoc(dl).setChain(InChain)
15671     .setCallee(getLibcallCallingConv(LC),
15672                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15673                Callee, std::move(Args), 0)
15674     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15675
15676   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15677   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15678 }
15679
15680 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15681                              SelectionDAG &DAG) {
15682   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15683   EVT VT = Op0.getValueType();
15684   SDLoc dl(Op);
15685
15686   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15687          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15688
15689   // PMULxD operations multiply each even value (starting at 0) of LHS with
15690   // the related value of RHS and produce a widen result.
15691   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15692   // => <2 x i64> <ae|cg>
15693   //
15694   // In other word, to have all the results, we need to perform two PMULxD:
15695   // 1. one with the even values.
15696   // 2. one with the odd values.
15697   // To achieve #2, with need to place the odd values at an even position.
15698   //
15699   // Place the odd value at an even position (basically, shift all values 1
15700   // step to the left):
15701   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15702   // <a|b|c|d> => <b|undef|d|undef>
15703   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15704   // <e|f|g|h> => <f|undef|h|undef>
15705   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15706
15707   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15708   // ints.
15709   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15710   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15711   unsigned Opcode =
15712       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15713   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15714   // => <2 x i64> <ae|cg>
15715   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15716                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15717   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15718   // => <2 x i64> <bf|dh>
15719   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15720                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15721
15722   // Shuffle it back into the right order.
15723   SDValue Highs, Lows;
15724   if (VT == MVT::v8i32) {
15725     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15726     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15727     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15728     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15729   } else {
15730     const int HighMask[] = {1, 5, 3, 7};
15731     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15732     const int LowMask[] = {0, 4, 2, 6};
15733     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15734   }
15735
15736   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15737   // unsigned multiply.
15738   if (IsSigned && !Subtarget->hasSSE41()) {
15739     SDValue ShAmt =
15740         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15741     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15742                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15743     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15744                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15745
15746     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15747     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15748   }
15749
15750   // The first result of MUL_LOHI is actually the low value, followed by the
15751   // high value.
15752   SDValue Ops[] = {Lows, Highs};
15753   return DAG.getMergeValues(Ops, dl);
15754 }
15755
15756 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15757                                          const X86Subtarget *Subtarget) {
15758   MVT VT = Op.getSimpleValueType();
15759   SDLoc dl(Op);
15760   SDValue R = Op.getOperand(0);
15761   SDValue Amt = Op.getOperand(1);
15762
15763   // Optimize shl/srl/sra with constant shift amount.
15764   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15765     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15766       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15767
15768       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15769           (Subtarget->hasInt256() &&
15770            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15771           (Subtarget->hasAVX512() &&
15772            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15773         if (Op.getOpcode() == ISD::SHL)
15774           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15775                                             DAG);
15776         if (Op.getOpcode() == ISD::SRL)
15777           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15778                                             DAG);
15779         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15780           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15781                                             DAG);
15782       }
15783
15784       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
15785         unsigned NumElts = VT.getVectorNumElements();
15786         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
15787
15788         if (Op.getOpcode() == ISD::SHL) {
15789           // Make a large shift.
15790           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
15791                                                    R, ShiftAmt, DAG);
15792           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15793           // Zero out the rightmost bits.
15794           SmallVector<SDValue, 32> V(
15795               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
15796           return DAG.getNode(ISD::AND, dl, VT, SHL,
15797                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15798         }
15799         if (Op.getOpcode() == ISD::SRL) {
15800           // Make a large shift.
15801           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
15802                                                    R, ShiftAmt, DAG);
15803           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15804           // Zero out the leftmost bits.
15805           SmallVector<SDValue, 32> V(
15806               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
15807           return DAG.getNode(ISD::AND, dl, VT, SRL,
15808                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15809         }
15810         if (Op.getOpcode() == ISD::SRA) {
15811           if (ShiftAmt == 7) {
15812             // R s>> 7  ===  R s< 0
15813             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15814             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15815           }
15816
15817           // R s>> a === ((R u>> a) ^ m) - m
15818           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15819           SmallVector<SDValue, 32> V(NumElts,
15820                                      DAG.getConstant(128 >> ShiftAmt, MVT::i8));
15821           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15822           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15823           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15824           return Res;
15825         }
15826         llvm_unreachable("Unknown shift opcode.");
15827       }
15828     }
15829   }
15830
15831   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15832   if (!Subtarget->is64Bit() &&
15833       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15834       Amt.getOpcode() == ISD::BITCAST &&
15835       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15836     Amt = Amt.getOperand(0);
15837     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15838                      VT.getVectorNumElements();
15839     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15840     uint64_t ShiftAmt = 0;
15841     for (unsigned i = 0; i != Ratio; ++i) {
15842       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15843       if (!C)
15844         return SDValue();
15845       // 6 == Log2(64)
15846       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15847     }
15848     // Check remaining shift amounts.
15849     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15850       uint64_t ShAmt = 0;
15851       for (unsigned j = 0; j != Ratio; ++j) {
15852         ConstantSDNode *C =
15853           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15854         if (!C)
15855           return SDValue();
15856         // 6 == Log2(64)
15857         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15858       }
15859       if (ShAmt != ShiftAmt)
15860         return SDValue();
15861     }
15862     switch (Op.getOpcode()) {
15863     default:
15864       llvm_unreachable("Unknown shift opcode!");
15865     case ISD::SHL:
15866       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15867                                         DAG);
15868     case ISD::SRL:
15869       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15870                                         DAG);
15871     case ISD::SRA:
15872       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15873                                         DAG);
15874     }
15875   }
15876
15877   return SDValue();
15878 }
15879
15880 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15881                                         const X86Subtarget* Subtarget) {
15882   MVT VT = Op.getSimpleValueType();
15883   SDLoc dl(Op);
15884   SDValue R = Op.getOperand(0);
15885   SDValue Amt = Op.getOperand(1);
15886
15887   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15888       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15889       (Subtarget->hasInt256() &&
15890        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15891         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15892        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15893     SDValue BaseShAmt;
15894     EVT EltVT = VT.getVectorElementType();
15895
15896     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
15897       // Check if this build_vector node is doing a splat.
15898       // If so, then set BaseShAmt equal to the splat value.
15899       BaseShAmt = BV->getSplatValue();
15900       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
15901         BaseShAmt = SDValue();
15902     } else {
15903       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15904         Amt = Amt.getOperand(0);
15905
15906       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
15907       if (SVN && SVN->isSplat()) {
15908         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
15909         SDValue InVec = Amt.getOperand(0);
15910         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15911           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
15912                  "Unexpected shuffle index found!");
15913           BaseShAmt = InVec.getOperand(SplatIdx);
15914         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15915            if (ConstantSDNode *C =
15916                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15917              if (C->getZExtValue() == SplatIdx)
15918                BaseShAmt = InVec.getOperand(1);
15919            }
15920         }
15921
15922         if (!BaseShAmt)
15923           // Avoid introducing an extract element from a shuffle.
15924           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
15925                                     DAG.getIntPtrConstant(SplatIdx));
15926       }
15927     }
15928
15929     if (BaseShAmt.getNode()) {
15930       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
15931       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
15932         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
15933       else if (EltVT.bitsLT(MVT::i32))
15934         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15935
15936       switch (Op.getOpcode()) {
15937       default:
15938         llvm_unreachable("Unknown shift opcode!");
15939       case ISD::SHL:
15940         switch (VT.SimpleTy) {
15941         default: return SDValue();
15942         case MVT::v2i64:
15943         case MVT::v4i32:
15944         case MVT::v8i16:
15945         case MVT::v4i64:
15946         case MVT::v8i32:
15947         case MVT::v16i16:
15948         case MVT::v16i32:
15949         case MVT::v8i64:
15950           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15951         }
15952       case ISD::SRA:
15953         switch (VT.SimpleTy) {
15954         default: return SDValue();
15955         case MVT::v4i32:
15956         case MVT::v8i16:
15957         case MVT::v8i32:
15958         case MVT::v16i16:
15959         case MVT::v16i32:
15960         case MVT::v8i64:
15961           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15962         }
15963       case ISD::SRL:
15964         switch (VT.SimpleTy) {
15965         default: return SDValue();
15966         case MVT::v2i64:
15967         case MVT::v4i32:
15968         case MVT::v8i16:
15969         case MVT::v4i64:
15970         case MVT::v8i32:
15971         case MVT::v16i16:
15972         case MVT::v16i32:
15973         case MVT::v8i64:
15974           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15975         }
15976       }
15977     }
15978   }
15979
15980   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15981   if (!Subtarget->is64Bit() &&
15982       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15983       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15984       Amt.getOpcode() == ISD::BITCAST &&
15985       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15986     Amt = Amt.getOperand(0);
15987     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15988                      VT.getVectorNumElements();
15989     std::vector<SDValue> Vals(Ratio);
15990     for (unsigned i = 0; i != Ratio; ++i)
15991       Vals[i] = Amt.getOperand(i);
15992     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15993       for (unsigned j = 0; j != Ratio; ++j)
15994         if (Vals[j] != Amt.getOperand(i + j))
15995           return SDValue();
15996     }
15997     switch (Op.getOpcode()) {
15998     default:
15999       llvm_unreachable("Unknown shift opcode!");
16000     case ISD::SHL:
16001       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16002     case ISD::SRL:
16003       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16004     case ISD::SRA:
16005       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16006     }
16007   }
16008
16009   return SDValue();
16010 }
16011
16012 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16013                           SelectionDAG &DAG) {
16014   MVT VT = Op.getSimpleValueType();
16015   SDLoc dl(Op);
16016   SDValue R = Op.getOperand(0);
16017   SDValue Amt = Op.getOperand(1);
16018   SDValue V;
16019
16020   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16021   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16022
16023   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16024   if (V.getNode())
16025     return V;
16026
16027   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16028   if (V.getNode())
16029       return V;
16030
16031   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16032     return Op;
16033   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16034   if (Subtarget->hasInt256()) {
16035     if (Op.getOpcode() == ISD::SRL &&
16036         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16037          VT == MVT::v4i64 || VT == MVT::v8i32))
16038       return Op;
16039     if (Op.getOpcode() == ISD::SHL &&
16040         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16041          VT == MVT::v4i64 || VT == MVT::v8i32))
16042       return Op;
16043     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16044       return Op;
16045   }
16046
16047   // If possible, lower this packed shift into a vector multiply instead of
16048   // expanding it into a sequence of scalar shifts.
16049   // Do this only if the vector shift count is a constant build_vector.
16050   if (Op.getOpcode() == ISD::SHL &&
16051       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16052        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16053       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16054     SmallVector<SDValue, 8> Elts;
16055     EVT SVT = VT.getScalarType();
16056     unsigned SVTBits = SVT.getSizeInBits();
16057     const APInt &One = APInt(SVTBits, 1);
16058     unsigned NumElems = VT.getVectorNumElements();
16059
16060     for (unsigned i=0; i !=NumElems; ++i) {
16061       SDValue Op = Amt->getOperand(i);
16062       if (Op->getOpcode() == ISD::UNDEF) {
16063         Elts.push_back(Op);
16064         continue;
16065       }
16066
16067       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16068       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16069       uint64_t ShAmt = C.getZExtValue();
16070       if (ShAmt >= SVTBits) {
16071         Elts.push_back(DAG.getUNDEF(SVT));
16072         continue;
16073       }
16074       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16075     }
16076     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16077     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16078   }
16079
16080   // Lower SHL with variable shift amount.
16081   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16082     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16083
16084     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16085     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16086     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16087     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16088   }
16089
16090   // If possible, lower this shift as a sequence of two shifts by
16091   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16092   // Example:
16093   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16094   //
16095   // Could be rewritten as:
16096   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16097   //
16098   // The advantage is that the two shifts from the example would be
16099   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16100   // the vector shift into four scalar shifts plus four pairs of vector
16101   // insert/extract.
16102   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16103       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16104     unsigned TargetOpcode = X86ISD::MOVSS;
16105     bool CanBeSimplified;
16106     // The splat value for the first packed shift (the 'X' from the example).
16107     SDValue Amt1 = Amt->getOperand(0);
16108     // The splat value for the second packed shift (the 'Y' from the example).
16109     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16110                                         Amt->getOperand(2);
16111
16112     // See if it is possible to replace this node with a sequence of
16113     // two shifts followed by a MOVSS/MOVSD
16114     if (VT == MVT::v4i32) {
16115       // Check if it is legal to use a MOVSS.
16116       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16117                         Amt2 == Amt->getOperand(3);
16118       if (!CanBeSimplified) {
16119         // Otherwise, check if we can still simplify this node using a MOVSD.
16120         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16121                           Amt->getOperand(2) == Amt->getOperand(3);
16122         TargetOpcode = X86ISD::MOVSD;
16123         Amt2 = Amt->getOperand(2);
16124       }
16125     } else {
16126       // Do similar checks for the case where the machine value type
16127       // is MVT::v8i16.
16128       CanBeSimplified = Amt1 == Amt->getOperand(1);
16129       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16130         CanBeSimplified = Amt2 == Amt->getOperand(i);
16131
16132       if (!CanBeSimplified) {
16133         TargetOpcode = X86ISD::MOVSD;
16134         CanBeSimplified = true;
16135         Amt2 = Amt->getOperand(4);
16136         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16137           CanBeSimplified = Amt1 == Amt->getOperand(i);
16138         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16139           CanBeSimplified = Amt2 == Amt->getOperand(j);
16140       }
16141     }
16142
16143     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16144         isa<ConstantSDNode>(Amt2)) {
16145       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16146       EVT CastVT = MVT::v4i32;
16147       SDValue Splat1 =
16148         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16149       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16150       SDValue Splat2 =
16151         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16152       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16153       if (TargetOpcode == X86ISD::MOVSD)
16154         CastVT = MVT::v2i64;
16155       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16156       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16157       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16158                                             BitCast1, DAG);
16159       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16160     }
16161   }
16162
16163   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16164     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16165
16166     // a = a << 5;
16167     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16168     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16169
16170     // Turn 'a' into a mask suitable for VSELECT
16171     SDValue VSelM = DAG.getConstant(0x80, VT);
16172     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16173     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16174
16175     SDValue CM1 = DAG.getConstant(0x0f, VT);
16176     SDValue CM2 = DAG.getConstant(0x3f, VT);
16177
16178     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16179     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16180     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16181     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16182     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16183
16184     // a += a
16185     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16186     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16187     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16188
16189     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16190     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16191     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16192     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16193     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16194
16195     // a += a
16196     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16197     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16198     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16199
16200     // return VSELECT(r, r+r, a);
16201     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16202                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16203     return R;
16204   }
16205
16206   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16207   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16208   // solution better.
16209   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16210     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16211     unsigned ExtOpc =
16212         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16213     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16214     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16215     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16216                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16217     }
16218
16219   // Decompose 256-bit shifts into smaller 128-bit shifts.
16220   if (VT.is256BitVector()) {
16221     unsigned NumElems = VT.getVectorNumElements();
16222     MVT EltVT = VT.getVectorElementType();
16223     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16224
16225     // Extract the two vectors
16226     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16227     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16228
16229     // Recreate the shift amount vectors
16230     SDValue Amt1, Amt2;
16231     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16232       // Constant shift amount
16233       SmallVector<SDValue, 4> Amt1Csts;
16234       SmallVector<SDValue, 4> Amt2Csts;
16235       for (unsigned i = 0; i != NumElems/2; ++i)
16236         Amt1Csts.push_back(Amt->getOperand(i));
16237       for (unsigned i = NumElems/2; i != NumElems; ++i)
16238         Amt2Csts.push_back(Amt->getOperand(i));
16239
16240       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16241       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16242     } else {
16243       // Variable shift amount
16244       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16245       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16246     }
16247
16248     // Issue new vector shifts for the smaller types
16249     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16250     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16251
16252     // Concatenate the result back
16253     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16254   }
16255
16256   return SDValue();
16257 }
16258
16259 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16260   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16261   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16262   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16263   // has only one use.
16264   SDNode *N = Op.getNode();
16265   SDValue LHS = N->getOperand(0);
16266   SDValue RHS = N->getOperand(1);
16267   unsigned BaseOp = 0;
16268   unsigned Cond = 0;
16269   SDLoc DL(Op);
16270   switch (Op.getOpcode()) {
16271   default: llvm_unreachable("Unknown ovf instruction!");
16272   case ISD::SADDO:
16273     // A subtract of one will be selected as a INC. Note that INC doesn't
16274     // set CF, so we can't do this for UADDO.
16275     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16276       if (C->isOne()) {
16277         BaseOp = X86ISD::INC;
16278         Cond = X86::COND_O;
16279         break;
16280       }
16281     BaseOp = X86ISD::ADD;
16282     Cond = X86::COND_O;
16283     break;
16284   case ISD::UADDO:
16285     BaseOp = X86ISD::ADD;
16286     Cond = X86::COND_B;
16287     break;
16288   case ISD::SSUBO:
16289     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16290     // set CF, so we can't do this for USUBO.
16291     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16292       if (C->isOne()) {
16293         BaseOp = X86ISD::DEC;
16294         Cond = X86::COND_O;
16295         break;
16296       }
16297     BaseOp = X86ISD::SUB;
16298     Cond = X86::COND_O;
16299     break;
16300   case ISD::USUBO:
16301     BaseOp = X86ISD::SUB;
16302     Cond = X86::COND_B;
16303     break;
16304   case ISD::SMULO:
16305     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16306     Cond = X86::COND_O;
16307     break;
16308   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16309     if (N->getValueType(0) == MVT::i8) {
16310       BaseOp = X86ISD::UMUL8;
16311       Cond = X86::COND_O;
16312       break;
16313     }
16314     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16315                                  MVT::i32);
16316     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16317
16318     SDValue SetCC =
16319       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16320                   DAG.getConstant(X86::COND_O, MVT::i32),
16321                   SDValue(Sum.getNode(), 2));
16322
16323     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16324   }
16325   }
16326
16327   // Also sets EFLAGS.
16328   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16329   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16330
16331   SDValue SetCC =
16332     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16333                 DAG.getConstant(Cond, MVT::i32),
16334                 SDValue(Sum.getNode(), 1));
16335
16336   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16337 }
16338
16339 // Sign extension of the low part of vector elements. This may be used either
16340 // when sign extend instructions are not available or if the vector element
16341 // sizes already match the sign-extended size. If the vector elements are in
16342 // their pre-extended size and sign extend instructions are available, that will
16343 // be handled by LowerSIGN_EXTEND.
16344 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16345                                                   SelectionDAG &DAG) const {
16346   SDLoc dl(Op);
16347   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16348   MVT VT = Op.getSimpleValueType();
16349
16350   if (!Subtarget->hasSSE2() || !VT.isVector())
16351     return SDValue();
16352
16353   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16354                       ExtraVT.getScalarType().getSizeInBits();
16355
16356   switch (VT.SimpleTy) {
16357     default: return SDValue();
16358     case MVT::v8i32:
16359     case MVT::v16i16:
16360       if (!Subtarget->hasFp256())
16361         return SDValue();
16362       if (!Subtarget->hasInt256()) {
16363         // needs to be split
16364         unsigned NumElems = VT.getVectorNumElements();
16365
16366         // Extract the LHS vectors
16367         SDValue LHS = Op.getOperand(0);
16368         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16369         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16370
16371         MVT EltVT = VT.getVectorElementType();
16372         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16373
16374         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16375         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16376         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16377                                    ExtraNumElems/2);
16378         SDValue Extra = DAG.getValueType(ExtraVT);
16379
16380         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16381         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16382
16383         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16384       }
16385       // fall through
16386     case MVT::v4i32:
16387     case MVT::v8i16: {
16388       SDValue Op0 = Op.getOperand(0);
16389
16390       // This is a sign extension of some low part of vector elements without
16391       // changing the size of the vector elements themselves:
16392       // Shift-Left + Shift-Right-Algebraic.
16393       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
16394                                                BitsDiff, DAG);
16395       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
16396                                         DAG);
16397     }
16398   }
16399 }
16400
16401 /// Returns true if the operand type is exactly twice the native width, and
16402 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16403 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16404 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16405 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16406   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16407
16408   if (OpWidth == 64)
16409     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16410   else if (OpWidth == 128)
16411     return Subtarget->hasCmpxchg16b();
16412   else
16413     return false;
16414 }
16415
16416 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16417   return needsCmpXchgNb(SI->getValueOperand()->getType());
16418 }
16419
16420 // Note: this turns large loads into lock cmpxchg8b/16b.
16421 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16422 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16423   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16424   return needsCmpXchgNb(PTy->getElementType());
16425 }
16426
16427 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16428   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16429   const Type *MemType = AI->getType();
16430
16431   // If the operand is too big, we must see if cmpxchg8/16b is available
16432   // and default to library calls otherwise.
16433   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16434     return needsCmpXchgNb(MemType);
16435
16436   AtomicRMWInst::BinOp Op = AI->getOperation();
16437   switch (Op) {
16438   default:
16439     llvm_unreachable("Unknown atomic operation");
16440   case AtomicRMWInst::Xchg:
16441   case AtomicRMWInst::Add:
16442   case AtomicRMWInst::Sub:
16443     // It's better to use xadd, xsub or xchg for these in all cases.
16444     return false;
16445   case AtomicRMWInst::Or:
16446   case AtomicRMWInst::And:
16447   case AtomicRMWInst::Xor:
16448     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16449     // prefix to a normal instruction for these operations.
16450     return !AI->use_empty();
16451   case AtomicRMWInst::Nand:
16452   case AtomicRMWInst::Max:
16453   case AtomicRMWInst::Min:
16454   case AtomicRMWInst::UMax:
16455   case AtomicRMWInst::UMin:
16456     // These always require a non-trivial set of data operations on x86. We must
16457     // use a cmpxchg loop.
16458     return true;
16459   }
16460 }
16461
16462 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16463   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16464   // no-sse2). There isn't any reason to disable it if the target processor
16465   // supports it.
16466   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16467 }
16468
16469 LoadInst *
16470 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16471   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16472   const Type *MemType = AI->getType();
16473   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16474   // there is no benefit in turning such RMWs into loads, and it is actually
16475   // harmful as it introduces a mfence.
16476   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16477     return nullptr;
16478
16479   auto Builder = IRBuilder<>(AI);
16480   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16481   auto SynchScope = AI->getSynchScope();
16482   // We must restrict the ordering to avoid generating loads with Release or
16483   // ReleaseAcquire orderings.
16484   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16485   auto Ptr = AI->getPointerOperand();
16486
16487   // Before the load we need a fence. Here is an example lifted from
16488   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16489   // is required:
16490   // Thread 0:
16491   //   x.store(1, relaxed);
16492   //   r1 = y.fetch_add(0, release);
16493   // Thread 1:
16494   //   y.fetch_add(42, acquire);
16495   //   r2 = x.load(relaxed);
16496   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16497   // lowered to just a load without a fence. A mfence flushes the store buffer,
16498   // making the optimization clearly correct.
16499   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16500   // otherwise, we might be able to be more agressive on relaxed idempotent
16501   // rmw. In practice, they do not look useful, so we don't try to be
16502   // especially clever.
16503   if (SynchScope == SingleThread) {
16504     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16505     // the IR level, so we must wrap it in an intrinsic.
16506     return nullptr;
16507   } else if (hasMFENCE(*Subtarget)) {
16508     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16509             Intrinsic::x86_sse2_mfence);
16510     Builder.CreateCall(MFence);
16511   } else {
16512     // FIXME: it might make sense to use a locked operation here but on a
16513     // different cache-line to prevent cache-line bouncing. In practice it
16514     // is probably a small win, and x86 processors without mfence are rare
16515     // enough that we do not bother.
16516     return nullptr;
16517   }
16518
16519   // Finally we can emit the atomic load.
16520   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16521           AI->getType()->getPrimitiveSizeInBits());
16522   Loaded->setAtomic(Order, SynchScope);
16523   AI->replaceAllUsesWith(Loaded);
16524   AI->eraseFromParent();
16525   return Loaded;
16526 }
16527
16528 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16529                                  SelectionDAG &DAG) {
16530   SDLoc dl(Op);
16531   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16532     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16533   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16534     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16535
16536   // The only fence that needs an instruction is a sequentially-consistent
16537   // cross-thread fence.
16538   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16539     if (hasMFENCE(*Subtarget))
16540       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16541
16542     SDValue Chain = Op.getOperand(0);
16543     SDValue Zero = DAG.getConstant(0, MVT::i32);
16544     SDValue Ops[] = {
16545       DAG.getRegister(X86::ESP, MVT::i32), // Base
16546       DAG.getTargetConstant(1, MVT::i8),   // Scale
16547       DAG.getRegister(0, MVT::i32),        // Index
16548       DAG.getTargetConstant(0, MVT::i32),  // Disp
16549       DAG.getRegister(0, MVT::i32),        // Segment.
16550       Zero,
16551       Chain
16552     };
16553     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16554     return SDValue(Res, 0);
16555   }
16556
16557   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16558   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16559 }
16560
16561 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16562                              SelectionDAG &DAG) {
16563   MVT T = Op.getSimpleValueType();
16564   SDLoc DL(Op);
16565   unsigned Reg = 0;
16566   unsigned size = 0;
16567   switch(T.SimpleTy) {
16568   default: llvm_unreachable("Invalid value type!");
16569   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16570   case MVT::i16: Reg = X86::AX;  size = 2; break;
16571   case MVT::i32: Reg = X86::EAX; size = 4; break;
16572   case MVT::i64:
16573     assert(Subtarget->is64Bit() && "Node not type legal!");
16574     Reg = X86::RAX; size = 8;
16575     break;
16576   }
16577   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16578                                   Op.getOperand(2), SDValue());
16579   SDValue Ops[] = { cpIn.getValue(0),
16580                     Op.getOperand(1),
16581                     Op.getOperand(3),
16582                     DAG.getTargetConstant(size, MVT::i8),
16583                     cpIn.getValue(1) };
16584   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16585   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16586   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16587                                            Ops, T, MMO);
16588
16589   SDValue cpOut =
16590     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16591   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16592                                       MVT::i32, cpOut.getValue(2));
16593   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16594                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16595
16596   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16597   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16598   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16599   return SDValue();
16600 }
16601
16602 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16603                             SelectionDAG &DAG) {
16604   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16605   MVT DstVT = Op.getSimpleValueType();
16606
16607   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16608     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16609     if (DstVT != MVT::f64)
16610       // This conversion needs to be expanded.
16611       return SDValue();
16612
16613     SDValue InVec = Op->getOperand(0);
16614     SDLoc dl(Op);
16615     unsigned NumElts = SrcVT.getVectorNumElements();
16616     EVT SVT = SrcVT.getVectorElementType();
16617
16618     // Widen the vector in input in the case of MVT::v2i32.
16619     // Example: from MVT::v2i32 to MVT::v4i32.
16620     SmallVector<SDValue, 16> Elts;
16621     for (unsigned i = 0, e = NumElts; i != e; ++i)
16622       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16623                                  DAG.getIntPtrConstant(i)));
16624
16625     // Explicitly mark the extra elements as Undef.
16626     Elts.append(NumElts, DAG.getUNDEF(SVT));
16627
16628     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16629     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16630     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16631     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16632                        DAG.getIntPtrConstant(0));
16633   }
16634
16635   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16636          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16637   assert((DstVT == MVT::i64 ||
16638           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16639          "Unexpected custom BITCAST");
16640   // i64 <=> MMX conversions are Legal.
16641   if (SrcVT==MVT::i64 && DstVT.isVector())
16642     return Op;
16643   if (DstVT==MVT::i64 && SrcVT.isVector())
16644     return Op;
16645   // MMX <=> MMX conversions are Legal.
16646   if (SrcVT.isVector() && DstVT.isVector())
16647     return Op;
16648   // All other conversions need to be expanded.
16649   return SDValue();
16650 }
16651
16652 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16653                           SelectionDAG &DAG) {
16654   SDNode *Node = Op.getNode();
16655   SDLoc dl(Node);
16656
16657   Op = Op.getOperand(0);
16658   EVT VT = Op.getValueType();
16659   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16660          "CTPOP lowering only implemented for 128/256-bit wide vector types");
16661
16662   unsigned NumElts = VT.getVectorNumElements();
16663   EVT EltVT = VT.getVectorElementType();
16664   unsigned Len = EltVT.getSizeInBits();
16665
16666   // This is the vectorized version of the "best" algorithm from
16667   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16668   // with a minor tweak to use a series of adds + shifts instead of vector
16669   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16670   //
16671   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16672   //  v8i32 => Always profitable
16673   //
16674   // FIXME: There a couple of possible improvements:
16675   //
16676   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16677   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16678   //
16679   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16680          "CTPOP not implemented for this vector element type.");
16681
16682   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16683   // extra legalization.
16684   bool NeedsBitcast = EltVT == MVT::i32;
16685   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16686
16687   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16688   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16689   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16690
16691   // v = v - ((v >> 1) & 0x55555555...)
16692   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16693   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16694   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16695   if (NeedsBitcast)
16696     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16697
16698   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16699   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16700   if (NeedsBitcast)
16701     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16702
16703   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16704   if (VT != And.getValueType())
16705     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16706   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16707
16708   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16709   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16710   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16711   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16712   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16713
16714   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16715   if (NeedsBitcast) {
16716     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16717     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16718     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16719   }
16720
16721   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16722   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16723   if (VT != AndRHS.getValueType()) {
16724     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16725     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16726   }
16727   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16728
16729   // v = (v + (v >> 4)) & 0x0F0F0F0F...
16730   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16731   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16732   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16733   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16734
16735   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16736   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16737   if (NeedsBitcast) {
16738     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16739     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16740   }
16741   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16742   if (VT != And.getValueType())
16743     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16744
16745   // The algorithm mentioned above uses:
16746   //    v = (v * 0x01010101...) >> (Len - 8)
16747   //
16748   // Change it to use vector adds + vector shifts which yield faster results on
16749   // Haswell than using vector integer multiplication.
16750   //
16751   // For i32 elements:
16752   //    v = v + (v >> 8)
16753   //    v = v + (v >> 16)
16754   //
16755   // For i64 elements:
16756   //    v = v + (v >> 8)
16757   //    v = v + (v >> 16)
16758   //    v = v + (v >> 32)
16759   //
16760   Add = And;
16761   SmallVector<SDValue, 8> Csts;
16762   for (unsigned i = 8; i <= Len/2; i *= 2) {
16763     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
16764     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
16765     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
16766     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16767     Csts.clear();
16768   }
16769
16770   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
16771   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
16772   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
16773   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
16774   if (NeedsBitcast) {
16775     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16776     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
16777   }
16778   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
16779   if (VT != And.getValueType())
16780     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16781
16782   return And;
16783 }
16784
16785 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16786   SDNode *Node = Op.getNode();
16787   SDLoc dl(Node);
16788   EVT T = Node->getValueType(0);
16789   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16790                               DAG.getConstant(0, T), Node->getOperand(2));
16791   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16792                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16793                        Node->getOperand(0),
16794                        Node->getOperand(1), negOp,
16795                        cast<AtomicSDNode>(Node)->getMemOperand(),
16796                        cast<AtomicSDNode>(Node)->getOrdering(),
16797                        cast<AtomicSDNode>(Node)->getSynchScope());
16798 }
16799
16800 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16801   SDNode *Node = Op.getNode();
16802   SDLoc dl(Node);
16803   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16804
16805   // Convert seq_cst store -> xchg
16806   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16807   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16808   //        (The only way to get a 16-byte store is cmpxchg16b)
16809   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16810   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16811       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16812     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16813                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16814                                  Node->getOperand(0),
16815                                  Node->getOperand(1), Node->getOperand(2),
16816                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16817                                  cast<AtomicSDNode>(Node)->getOrdering(),
16818                                  cast<AtomicSDNode>(Node)->getSynchScope());
16819     return Swap.getValue(1);
16820   }
16821   // Other atomic stores have a simple pattern.
16822   return Op;
16823 }
16824
16825 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16826   EVT VT = Op.getNode()->getSimpleValueType(0);
16827
16828   // Let legalize expand this if it isn't a legal type yet.
16829   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16830     return SDValue();
16831
16832   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16833
16834   unsigned Opc;
16835   bool ExtraOp = false;
16836   switch (Op.getOpcode()) {
16837   default: llvm_unreachable("Invalid code");
16838   case ISD::ADDC: Opc = X86ISD::ADD; break;
16839   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16840   case ISD::SUBC: Opc = X86ISD::SUB; break;
16841   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16842   }
16843
16844   if (!ExtraOp)
16845     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16846                        Op.getOperand(1));
16847   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16848                      Op.getOperand(1), Op.getOperand(2));
16849 }
16850
16851 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16852                             SelectionDAG &DAG) {
16853   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16854
16855   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16856   // which returns the values as { float, float } (in XMM0) or
16857   // { double, double } (which is returned in XMM0, XMM1).
16858   SDLoc dl(Op);
16859   SDValue Arg = Op.getOperand(0);
16860   EVT ArgVT = Arg.getValueType();
16861   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16862
16863   TargetLowering::ArgListTy Args;
16864   TargetLowering::ArgListEntry Entry;
16865
16866   Entry.Node = Arg;
16867   Entry.Ty = ArgTy;
16868   Entry.isSExt = false;
16869   Entry.isZExt = false;
16870   Args.push_back(Entry);
16871
16872   bool isF64 = ArgVT == MVT::f64;
16873   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16874   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16875   // the results are returned via SRet in memory.
16876   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16878   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16879
16880   Type *RetTy = isF64
16881     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
16882     : (Type*)VectorType::get(ArgTy, 4);
16883
16884   TargetLowering::CallLoweringInfo CLI(DAG);
16885   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16886     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16887
16888   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16889
16890   if (isF64)
16891     // Returned in xmm0 and xmm1.
16892     return CallResult.first;
16893
16894   // Returned in bits 0:31 and 32:64 xmm0.
16895   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16896                                CallResult.first, DAG.getIntPtrConstant(0));
16897   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16898                                CallResult.first, DAG.getIntPtrConstant(1));
16899   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16900   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16901 }
16902
16903 /// LowerOperation - Provide custom lowering hooks for some operations.
16904 ///
16905 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16906   switch (Op.getOpcode()) {
16907   default: llvm_unreachable("Should not custom lower this!");
16908   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16909   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16910   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16911     return LowerCMP_SWAP(Op, Subtarget, DAG);
16912   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
16913   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16914   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16915   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16916   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16917   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
16918   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16919   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16920   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16921   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16922   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16923   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16924   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16925   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16926   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16927   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16928   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16929   case ISD::SHL_PARTS:
16930   case ISD::SRA_PARTS:
16931   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16932   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16933   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16934   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16935   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16936   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16937   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16938   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16939   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16940   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16941   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16942   case ISD::FABS:
16943   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
16944   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16945   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16946   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16947   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16948   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16949   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16950   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16951   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16952   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16953   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
16954   case ISD::INTRINSIC_VOID:
16955   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16956   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16957   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16958   case ISD::FRAME_TO_ARGS_OFFSET:
16959                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16960   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16961   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16962   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16963   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16964   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16965   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16966   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16967   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16968   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16969   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16970   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16971   case ISD::UMUL_LOHI:
16972   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16973   case ISD::SRA:
16974   case ISD::SRL:
16975   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16976   case ISD::SADDO:
16977   case ISD::UADDO:
16978   case ISD::SSUBO:
16979   case ISD::USUBO:
16980   case ISD::SMULO:
16981   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16982   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16983   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16984   case ISD::ADDC:
16985   case ISD::ADDE:
16986   case ISD::SUBC:
16987   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16988   case ISD::ADD:                return LowerADD(Op, DAG);
16989   case ISD::SUB:                return LowerSUB(Op, DAG);
16990   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16991   }
16992 }
16993
16994 /// ReplaceNodeResults - Replace a node with an illegal result type
16995 /// with a new node built out of custom code.
16996 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16997                                            SmallVectorImpl<SDValue>&Results,
16998                                            SelectionDAG &DAG) const {
16999   SDLoc dl(N);
17000   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17001   switch (N->getOpcode()) {
17002   default:
17003     llvm_unreachable("Do not know how to custom type legalize this operation!");
17004   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17005   case X86ISD::FMINC:
17006   case X86ISD::FMIN:
17007   case X86ISD::FMAXC:
17008   case X86ISD::FMAX: {
17009     EVT VT = N->getValueType(0);
17010     if (VT != MVT::v2f32)
17011       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17012     SDValue UNDEF = DAG.getUNDEF(VT);
17013     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17014                               N->getOperand(0), UNDEF);
17015     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17016                               N->getOperand(1), UNDEF);
17017     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17018     return;
17019   }
17020   case ISD::SIGN_EXTEND_INREG:
17021   case ISD::ADDC:
17022   case ISD::ADDE:
17023   case ISD::SUBC:
17024   case ISD::SUBE:
17025     // We don't want to expand or promote these.
17026     return;
17027   case ISD::SDIV:
17028   case ISD::UDIV:
17029   case ISD::SREM:
17030   case ISD::UREM:
17031   case ISD::SDIVREM:
17032   case ISD::UDIVREM: {
17033     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17034     Results.push_back(V);
17035     return;
17036   }
17037   case ISD::FP_TO_SINT:
17038   case ISD::FP_TO_UINT: {
17039     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17040
17041     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17042       return;
17043
17044     std::pair<SDValue,SDValue> Vals =
17045         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17046     SDValue FIST = Vals.first, StackSlot = Vals.second;
17047     if (FIST.getNode()) {
17048       EVT VT = N->getValueType(0);
17049       // Return a load from the stack slot.
17050       if (StackSlot.getNode())
17051         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17052                                       MachinePointerInfo(),
17053                                       false, false, false, 0));
17054       else
17055         Results.push_back(FIST);
17056     }
17057     return;
17058   }
17059   case ISD::UINT_TO_FP: {
17060     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17061     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17062         N->getValueType(0) != MVT::v2f32)
17063       return;
17064     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17065                                  N->getOperand(0));
17066     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17067                                      MVT::f64);
17068     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17069     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17070                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17071     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17072     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17073     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17074     return;
17075   }
17076   case ISD::FP_ROUND: {
17077     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17078         return;
17079     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17080     Results.push_back(V);
17081     return;
17082   }
17083   case ISD::INTRINSIC_W_CHAIN: {
17084     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17085     switch (IntNo) {
17086     default : llvm_unreachable("Do not know how to custom type "
17087                                "legalize this intrinsic operation!");
17088     case Intrinsic::x86_rdtsc:
17089       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17090                                      Results);
17091     case Intrinsic::x86_rdtscp:
17092       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17093                                      Results);
17094     case Intrinsic::x86_rdpmc:
17095       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17096     }
17097   }
17098   case ISD::READCYCLECOUNTER: {
17099     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17100                                    Results);
17101   }
17102   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17103     EVT T = N->getValueType(0);
17104     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17105     bool Regs64bit = T == MVT::i128;
17106     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17107     SDValue cpInL, cpInH;
17108     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17109                         DAG.getConstant(0, HalfT));
17110     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17111                         DAG.getConstant(1, HalfT));
17112     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17113                              Regs64bit ? X86::RAX : X86::EAX,
17114                              cpInL, SDValue());
17115     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17116                              Regs64bit ? X86::RDX : X86::EDX,
17117                              cpInH, cpInL.getValue(1));
17118     SDValue swapInL, swapInH;
17119     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17120                           DAG.getConstant(0, HalfT));
17121     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17122                           DAG.getConstant(1, HalfT));
17123     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17124                                Regs64bit ? X86::RBX : X86::EBX,
17125                                swapInL, cpInH.getValue(1));
17126     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17127                                Regs64bit ? X86::RCX : X86::ECX,
17128                                swapInH, swapInL.getValue(1));
17129     SDValue Ops[] = { swapInH.getValue(0),
17130                       N->getOperand(1),
17131                       swapInH.getValue(1) };
17132     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17133     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17134     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17135                                   X86ISD::LCMPXCHG8_DAG;
17136     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17137     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17138                                         Regs64bit ? X86::RAX : X86::EAX,
17139                                         HalfT, Result.getValue(1));
17140     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17141                                         Regs64bit ? X86::RDX : X86::EDX,
17142                                         HalfT, cpOutL.getValue(2));
17143     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17144
17145     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17146                                         MVT::i32, cpOutH.getValue(2));
17147     SDValue Success =
17148         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17149                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17150     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17151
17152     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17153     Results.push_back(Success);
17154     Results.push_back(EFLAGS.getValue(1));
17155     return;
17156   }
17157   case ISD::ATOMIC_SWAP:
17158   case ISD::ATOMIC_LOAD_ADD:
17159   case ISD::ATOMIC_LOAD_SUB:
17160   case ISD::ATOMIC_LOAD_AND:
17161   case ISD::ATOMIC_LOAD_OR:
17162   case ISD::ATOMIC_LOAD_XOR:
17163   case ISD::ATOMIC_LOAD_NAND:
17164   case ISD::ATOMIC_LOAD_MIN:
17165   case ISD::ATOMIC_LOAD_MAX:
17166   case ISD::ATOMIC_LOAD_UMIN:
17167   case ISD::ATOMIC_LOAD_UMAX:
17168   case ISD::ATOMIC_LOAD: {
17169     // Delegate to generic TypeLegalization. Situations we can really handle
17170     // should have already been dealt with by AtomicExpandPass.cpp.
17171     break;
17172   }
17173   case ISD::BITCAST: {
17174     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17175     EVT DstVT = N->getValueType(0);
17176     EVT SrcVT = N->getOperand(0)->getValueType(0);
17177
17178     if (SrcVT != MVT::f64 ||
17179         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17180       return;
17181
17182     unsigned NumElts = DstVT.getVectorNumElements();
17183     EVT SVT = DstVT.getVectorElementType();
17184     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17185     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17186                                    MVT::v2f64, N->getOperand(0));
17187     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17188
17189     if (ExperimentalVectorWideningLegalization) {
17190       // If we are legalizing vectors by widening, we already have the desired
17191       // legal vector type, just return it.
17192       Results.push_back(ToVecInt);
17193       return;
17194     }
17195
17196     SmallVector<SDValue, 8> Elts;
17197     for (unsigned i = 0, e = NumElts; i != e; ++i)
17198       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17199                                    ToVecInt, DAG.getIntPtrConstant(i)));
17200
17201     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17202   }
17203   }
17204 }
17205
17206 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17207   switch (Opcode) {
17208   default: return nullptr;
17209   case X86ISD::BSF:                return "X86ISD::BSF";
17210   case X86ISD::BSR:                return "X86ISD::BSR";
17211   case X86ISD::SHLD:               return "X86ISD::SHLD";
17212   case X86ISD::SHRD:               return "X86ISD::SHRD";
17213   case X86ISD::FAND:               return "X86ISD::FAND";
17214   case X86ISD::FANDN:              return "X86ISD::FANDN";
17215   case X86ISD::FOR:                return "X86ISD::FOR";
17216   case X86ISD::FXOR:               return "X86ISD::FXOR";
17217   case X86ISD::FSRL:               return "X86ISD::FSRL";
17218   case X86ISD::FILD:               return "X86ISD::FILD";
17219   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17220   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17221   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17222   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17223   case X86ISD::FLD:                return "X86ISD::FLD";
17224   case X86ISD::FST:                return "X86ISD::FST";
17225   case X86ISD::CALL:               return "X86ISD::CALL";
17226   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17227   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17228   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17229   case X86ISD::BT:                 return "X86ISD::BT";
17230   case X86ISD::CMP:                return "X86ISD::CMP";
17231   case X86ISD::COMI:               return "X86ISD::COMI";
17232   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17233   case X86ISD::CMPM:               return "X86ISD::CMPM";
17234   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17235   case X86ISD::SETCC:              return "X86ISD::SETCC";
17236   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17237   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17238   case X86ISD::CMOV:               return "X86ISD::CMOV";
17239   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17240   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17241   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17242   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17243   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17244   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17245   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17246   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17247   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17248   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17249   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17250   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17251   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17252   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17253   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17254   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17255   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17256   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17257   case X86ISD::HADD:               return "X86ISD::HADD";
17258   case X86ISD::HSUB:               return "X86ISD::HSUB";
17259   case X86ISD::FHADD:              return "X86ISD::FHADD";
17260   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17261   case X86ISD::UMAX:               return "X86ISD::UMAX";
17262   case X86ISD::UMIN:               return "X86ISD::UMIN";
17263   case X86ISD::SMAX:               return "X86ISD::SMAX";
17264   case X86ISD::SMIN:               return "X86ISD::SMIN";
17265   case X86ISD::FMAX:               return "X86ISD::FMAX";
17266   case X86ISD::FMIN:               return "X86ISD::FMIN";
17267   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17268   case X86ISD::FMINC:              return "X86ISD::FMINC";
17269   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17270   case X86ISD::FRCP:               return "X86ISD::FRCP";
17271   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17272   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17273   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17274   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17275   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17276   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17277   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17278   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17279   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17280   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17281   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17282   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17283   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17284   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17285   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17286   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17287   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17288   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17289   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17290   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17291   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17292   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17293   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17294   case X86ISD::VSHL:               return "X86ISD::VSHL";
17295   case X86ISD::VSRL:               return "X86ISD::VSRL";
17296   case X86ISD::VSRA:               return "X86ISD::VSRA";
17297   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17298   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17299   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17300   case X86ISD::CMPP:               return "X86ISD::CMPP";
17301   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17302   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17303   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17304   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17305   case X86ISD::ADD:                return "X86ISD::ADD";
17306   case X86ISD::SUB:                return "X86ISD::SUB";
17307   case X86ISD::ADC:                return "X86ISD::ADC";
17308   case X86ISD::SBB:                return "X86ISD::SBB";
17309   case X86ISD::SMUL:               return "X86ISD::SMUL";
17310   case X86ISD::UMUL:               return "X86ISD::UMUL";
17311   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17312   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17313   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17314   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17315   case X86ISD::INC:                return "X86ISD::INC";
17316   case X86ISD::DEC:                return "X86ISD::DEC";
17317   case X86ISD::OR:                 return "X86ISD::OR";
17318   case X86ISD::XOR:                return "X86ISD::XOR";
17319   case X86ISD::AND:                return "X86ISD::AND";
17320   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17321   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17322   case X86ISD::PTEST:              return "X86ISD::PTEST";
17323   case X86ISD::TESTP:              return "X86ISD::TESTP";
17324   case X86ISD::TESTM:              return "X86ISD::TESTM";
17325   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17326   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17327   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17328   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17329   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17330   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17331   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17332   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17333   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17334   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17335   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17336   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17337   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17338   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17339   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17340   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17341   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17342   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17343   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17344   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17345   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17346   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17347   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17348   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17349   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17350   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17351   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17352   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17353   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17354   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17355   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17356   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17357   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17358   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17359   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17360   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17361   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17362   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17363   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17364   case X86ISD::SAHF:               return "X86ISD::SAHF";
17365   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17366   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17367   case X86ISD::FMADD:              return "X86ISD::FMADD";
17368   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17369   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17370   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17371   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17372   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17373   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17374   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17375   case X86ISD::XTEST:              return "X86ISD::XTEST";
17376   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17377   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17378   case X86ISD::SELECT:             return "X86ISD::SELECT";
17379   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17380   case X86ISD::RCP28:              return "X86ISD::RCP28";
17381   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17382   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
17383   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
17384   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
17385   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
17386   }
17387 }
17388
17389 // isLegalAddressingMode - Return true if the addressing mode represented
17390 // by AM is legal for this target, for a load/store of the specified type.
17391 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17392                                               Type *Ty) const {
17393   // X86 supports extremely general addressing modes.
17394   CodeModel::Model M = getTargetMachine().getCodeModel();
17395   Reloc::Model R = getTargetMachine().getRelocationModel();
17396
17397   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17398   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17399     return false;
17400
17401   if (AM.BaseGV) {
17402     unsigned GVFlags =
17403       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17404
17405     // If a reference to this global requires an extra load, we can't fold it.
17406     if (isGlobalStubReference(GVFlags))
17407       return false;
17408
17409     // If BaseGV requires a register for the PIC base, we cannot also have a
17410     // BaseReg specified.
17411     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17412       return false;
17413
17414     // If lower 4G is not available, then we must use rip-relative addressing.
17415     if ((M != CodeModel::Small || R != Reloc::Static) &&
17416         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17417       return false;
17418   }
17419
17420   switch (AM.Scale) {
17421   case 0:
17422   case 1:
17423   case 2:
17424   case 4:
17425   case 8:
17426     // These scales always work.
17427     break;
17428   case 3:
17429   case 5:
17430   case 9:
17431     // These scales are formed with basereg+scalereg.  Only accept if there is
17432     // no basereg yet.
17433     if (AM.HasBaseReg)
17434       return false;
17435     break;
17436   default:  // Other stuff never works.
17437     return false;
17438   }
17439
17440   return true;
17441 }
17442
17443 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17444   unsigned Bits = Ty->getScalarSizeInBits();
17445
17446   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17447   // particularly cheaper than those without.
17448   if (Bits == 8)
17449     return false;
17450
17451   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17452   // variable shifts just as cheap as scalar ones.
17453   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17454     return false;
17455
17456   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17457   // fully general vector.
17458   return true;
17459 }
17460
17461 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17462   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17463     return false;
17464   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17465   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17466   return NumBits1 > NumBits2;
17467 }
17468
17469 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17470   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17471     return false;
17472
17473   if (!isTypeLegal(EVT::getEVT(Ty1)))
17474     return false;
17475
17476   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17477
17478   // Assuming the caller doesn't have a zeroext or signext return parameter,
17479   // truncation all the way down to i1 is valid.
17480   return true;
17481 }
17482
17483 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17484   return isInt<32>(Imm);
17485 }
17486
17487 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17488   // Can also use sub to handle negated immediates.
17489   return isInt<32>(Imm);
17490 }
17491
17492 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17493   if (!VT1.isInteger() || !VT2.isInteger())
17494     return false;
17495   unsigned NumBits1 = VT1.getSizeInBits();
17496   unsigned NumBits2 = VT2.getSizeInBits();
17497   return NumBits1 > NumBits2;
17498 }
17499
17500 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17501   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17502   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17503 }
17504
17505 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17506   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17507   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17508 }
17509
17510 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17511   EVT VT1 = Val.getValueType();
17512   if (isZExtFree(VT1, VT2))
17513     return true;
17514
17515   if (Val.getOpcode() != ISD::LOAD)
17516     return false;
17517
17518   if (!VT1.isSimple() || !VT1.isInteger() ||
17519       !VT2.isSimple() || !VT2.isInteger())
17520     return false;
17521
17522   switch (VT1.getSimpleVT().SimpleTy) {
17523   default: break;
17524   case MVT::i8:
17525   case MVT::i16:
17526   case MVT::i32:
17527     // X86 has 8, 16, and 32-bit zero-extending loads.
17528     return true;
17529   }
17530
17531   return false;
17532 }
17533
17534 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17535
17536 bool
17537 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17538   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17539     return false;
17540
17541   VT = VT.getScalarType();
17542
17543   if (!VT.isSimple())
17544     return false;
17545
17546   switch (VT.getSimpleVT().SimpleTy) {
17547   case MVT::f32:
17548   case MVT::f64:
17549     return true;
17550   default:
17551     break;
17552   }
17553
17554   return false;
17555 }
17556
17557 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17558   // i16 instructions are longer (0x66 prefix) and potentially slower.
17559   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17560 }
17561
17562 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17563 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17564 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17565 /// are assumed to be legal.
17566 bool
17567 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17568                                       EVT VT) const {
17569   if (!VT.isSimple())
17570     return false;
17571
17572   // Very little shuffling can be done for 64-bit vectors right now.
17573   if (VT.getSizeInBits() == 64)
17574     return false;
17575
17576   // We only care that the types being shuffled are legal. The lowering can
17577   // handle any possible shuffle mask that results.
17578   return isTypeLegal(VT.getSimpleVT());
17579 }
17580
17581 bool
17582 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17583                                           EVT VT) const {
17584   // Just delegate to the generic legality, clear masks aren't special.
17585   return isShuffleMaskLegal(Mask, VT);
17586 }
17587
17588 //===----------------------------------------------------------------------===//
17589 //                           X86 Scheduler Hooks
17590 //===----------------------------------------------------------------------===//
17591
17592 /// Utility function to emit xbegin specifying the start of an RTM region.
17593 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17594                                      const TargetInstrInfo *TII) {
17595   DebugLoc DL = MI->getDebugLoc();
17596
17597   const BasicBlock *BB = MBB->getBasicBlock();
17598   MachineFunction::iterator I = MBB;
17599   ++I;
17600
17601   // For the v = xbegin(), we generate
17602   //
17603   // thisMBB:
17604   //  xbegin sinkMBB
17605   //
17606   // mainMBB:
17607   //  eax = -1
17608   //
17609   // sinkMBB:
17610   //  v = eax
17611
17612   MachineBasicBlock *thisMBB = MBB;
17613   MachineFunction *MF = MBB->getParent();
17614   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17615   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17616   MF->insert(I, mainMBB);
17617   MF->insert(I, sinkMBB);
17618
17619   // Transfer the remainder of BB and its successor edges to sinkMBB.
17620   sinkMBB->splice(sinkMBB->begin(), MBB,
17621                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17622   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17623
17624   // thisMBB:
17625   //  xbegin sinkMBB
17626   //  # fallthrough to mainMBB
17627   //  # abortion to sinkMBB
17628   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17629   thisMBB->addSuccessor(mainMBB);
17630   thisMBB->addSuccessor(sinkMBB);
17631
17632   // mainMBB:
17633   //  EAX = -1
17634   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17635   mainMBB->addSuccessor(sinkMBB);
17636
17637   // sinkMBB:
17638   // EAX is live into the sinkMBB
17639   sinkMBB->addLiveIn(X86::EAX);
17640   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17641           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17642     .addReg(X86::EAX);
17643
17644   MI->eraseFromParent();
17645   return sinkMBB;
17646 }
17647
17648 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17649 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17650 // in the .td file.
17651 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17652                                        const TargetInstrInfo *TII) {
17653   unsigned Opc;
17654   switch (MI->getOpcode()) {
17655   default: llvm_unreachable("illegal opcode!");
17656   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17657   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17658   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17659   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17660   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17661   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17662   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17663   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17664   }
17665
17666   DebugLoc dl = MI->getDebugLoc();
17667   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17668
17669   unsigned NumArgs = MI->getNumOperands();
17670   for (unsigned i = 1; i < NumArgs; ++i) {
17671     MachineOperand &Op = MI->getOperand(i);
17672     if (!(Op.isReg() && Op.isImplicit()))
17673       MIB.addOperand(Op);
17674   }
17675   if (MI->hasOneMemOperand())
17676     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17677
17678   BuildMI(*BB, MI, dl,
17679     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17680     .addReg(X86::XMM0);
17681
17682   MI->eraseFromParent();
17683   return BB;
17684 }
17685
17686 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17687 // defs in an instruction pattern
17688 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17689                                        const TargetInstrInfo *TII) {
17690   unsigned Opc;
17691   switch (MI->getOpcode()) {
17692   default: llvm_unreachable("illegal opcode!");
17693   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17694   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17695   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17696   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17697   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17698   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17699   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17700   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17701   }
17702
17703   DebugLoc dl = MI->getDebugLoc();
17704   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17705
17706   unsigned NumArgs = MI->getNumOperands(); // remove the results
17707   for (unsigned i = 1; i < NumArgs; ++i) {
17708     MachineOperand &Op = MI->getOperand(i);
17709     if (!(Op.isReg() && Op.isImplicit()))
17710       MIB.addOperand(Op);
17711   }
17712   if (MI->hasOneMemOperand())
17713     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17714
17715   BuildMI(*BB, MI, dl,
17716     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17717     .addReg(X86::ECX);
17718
17719   MI->eraseFromParent();
17720   return BB;
17721 }
17722
17723 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17724                                       const X86Subtarget *Subtarget) {
17725   DebugLoc dl = MI->getDebugLoc();
17726   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17727   // Address into RAX/EAX, other two args into ECX, EDX.
17728   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17729   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17730   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17731   for (int i = 0; i < X86::AddrNumOperands; ++i)
17732     MIB.addOperand(MI->getOperand(i));
17733
17734   unsigned ValOps = X86::AddrNumOperands;
17735   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17736     .addReg(MI->getOperand(ValOps).getReg());
17737   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17738     .addReg(MI->getOperand(ValOps+1).getReg());
17739
17740   // The instruction doesn't actually take any operands though.
17741   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17742
17743   MI->eraseFromParent(); // The pseudo is gone now.
17744   return BB;
17745 }
17746
17747 MachineBasicBlock *
17748 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17749                                                  MachineBasicBlock *MBB) const {
17750   // Emit va_arg instruction on X86-64.
17751
17752   // Operands to this pseudo-instruction:
17753   // 0  ) Output        : destination address (reg)
17754   // 1-5) Input         : va_list address (addr, i64mem)
17755   // 6  ) ArgSize       : Size (in bytes) of vararg type
17756   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17757   // 8  ) Align         : Alignment of type
17758   // 9  ) EFLAGS (implicit-def)
17759
17760   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17761   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17762
17763   unsigned DestReg = MI->getOperand(0).getReg();
17764   MachineOperand &Base = MI->getOperand(1);
17765   MachineOperand &Scale = MI->getOperand(2);
17766   MachineOperand &Index = MI->getOperand(3);
17767   MachineOperand &Disp = MI->getOperand(4);
17768   MachineOperand &Segment = MI->getOperand(5);
17769   unsigned ArgSize = MI->getOperand(6).getImm();
17770   unsigned ArgMode = MI->getOperand(7).getImm();
17771   unsigned Align = MI->getOperand(8).getImm();
17772
17773   // Memory Reference
17774   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17775   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17776   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17777
17778   // Machine Information
17779   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17780   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17781   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17782   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17783   DebugLoc DL = MI->getDebugLoc();
17784
17785   // struct va_list {
17786   //   i32   gp_offset
17787   //   i32   fp_offset
17788   //   i64   overflow_area (address)
17789   //   i64   reg_save_area (address)
17790   // }
17791   // sizeof(va_list) = 24
17792   // alignment(va_list) = 8
17793
17794   unsigned TotalNumIntRegs = 6;
17795   unsigned TotalNumXMMRegs = 8;
17796   bool UseGPOffset = (ArgMode == 1);
17797   bool UseFPOffset = (ArgMode == 2);
17798   unsigned MaxOffset = TotalNumIntRegs * 8 +
17799                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17800
17801   /* Align ArgSize to a multiple of 8 */
17802   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17803   bool NeedsAlign = (Align > 8);
17804
17805   MachineBasicBlock *thisMBB = MBB;
17806   MachineBasicBlock *overflowMBB;
17807   MachineBasicBlock *offsetMBB;
17808   MachineBasicBlock *endMBB;
17809
17810   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17811   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17812   unsigned OffsetReg = 0;
17813
17814   if (!UseGPOffset && !UseFPOffset) {
17815     // If we only pull from the overflow region, we don't create a branch.
17816     // We don't need to alter control flow.
17817     OffsetDestReg = 0; // unused
17818     OverflowDestReg = DestReg;
17819
17820     offsetMBB = nullptr;
17821     overflowMBB = thisMBB;
17822     endMBB = thisMBB;
17823   } else {
17824     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17825     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17826     // If not, pull from overflow_area. (branch to overflowMBB)
17827     //
17828     //       thisMBB
17829     //         |     .
17830     //         |        .
17831     //     offsetMBB   overflowMBB
17832     //         |        .
17833     //         |     .
17834     //        endMBB
17835
17836     // Registers for the PHI in endMBB
17837     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17838     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17839
17840     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17841     MachineFunction *MF = MBB->getParent();
17842     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17843     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17844     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17845
17846     MachineFunction::iterator MBBIter = MBB;
17847     ++MBBIter;
17848
17849     // Insert the new basic blocks
17850     MF->insert(MBBIter, offsetMBB);
17851     MF->insert(MBBIter, overflowMBB);
17852     MF->insert(MBBIter, endMBB);
17853
17854     // Transfer the remainder of MBB and its successor edges to endMBB.
17855     endMBB->splice(endMBB->begin(), thisMBB,
17856                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17857     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17858
17859     // Make offsetMBB and overflowMBB successors of thisMBB
17860     thisMBB->addSuccessor(offsetMBB);
17861     thisMBB->addSuccessor(overflowMBB);
17862
17863     // endMBB is a successor of both offsetMBB and overflowMBB
17864     offsetMBB->addSuccessor(endMBB);
17865     overflowMBB->addSuccessor(endMBB);
17866
17867     // Load the offset value into a register
17868     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17869     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17870       .addOperand(Base)
17871       .addOperand(Scale)
17872       .addOperand(Index)
17873       .addDisp(Disp, UseFPOffset ? 4 : 0)
17874       .addOperand(Segment)
17875       .setMemRefs(MMOBegin, MMOEnd);
17876
17877     // Check if there is enough room left to pull this argument.
17878     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17879       .addReg(OffsetReg)
17880       .addImm(MaxOffset + 8 - ArgSizeA8);
17881
17882     // Branch to "overflowMBB" if offset >= max
17883     // Fall through to "offsetMBB" otherwise
17884     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17885       .addMBB(overflowMBB);
17886   }
17887
17888   // In offsetMBB, emit code to use the reg_save_area.
17889   if (offsetMBB) {
17890     assert(OffsetReg != 0);
17891
17892     // Read the reg_save_area address.
17893     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17894     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17895       .addOperand(Base)
17896       .addOperand(Scale)
17897       .addOperand(Index)
17898       .addDisp(Disp, 16)
17899       .addOperand(Segment)
17900       .setMemRefs(MMOBegin, MMOEnd);
17901
17902     // Zero-extend the offset
17903     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17904       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17905         .addImm(0)
17906         .addReg(OffsetReg)
17907         .addImm(X86::sub_32bit);
17908
17909     // Add the offset to the reg_save_area to get the final address.
17910     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17911       .addReg(OffsetReg64)
17912       .addReg(RegSaveReg);
17913
17914     // Compute the offset for the next argument
17915     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17916     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17917       .addReg(OffsetReg)
17918       .addImm(UseFPOffset ? 16 : 8);
17919
17920     // Store it back into the va_list.
17921     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17922       .addOperand(Base)
17923       .addOperand(Scale)
17924       .addOperand(Index)
17925       .addDisp(Disp, UseFPOffset ? 4 : 0)
17926       .addOperand(Segment)
17927       .addReg(NextOffsetReg)
17928       .setMemRefs(MMOBegin, MMOEnd);
17929
17930     // Jump to endMBB
17931     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
17932       .addMBB(endMBB);
17933   }
17934
17935   //
17936   // Emit code to use overflow area
17937   //
17938
17939   // Load the overflow_area address into a register.
17940   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17941   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17942     .addOperand(Base)
17943     .addOperand(Scale)
17944     .addOperand(Index)
17945     .addDisp(Disp, 8)
17946     .addOperand(Segment)
17947     .setMemRefs(MMOBegin, MMOEnd);
17948
17949   // If we need to align it, do so. Otherwise, just copy the address
17950   // to OverflowDestReg.
17951   if (NeedsAlign) {
17952     // Align the overflow address
17953     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17954     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17955
17956     // aligned_addr = (addr + (align-1)) & ~(align-1)
17957     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17958       .addReg(OverflowAddrReg)
17959       .addImm(Align-1);
17960
17961     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17962       .addReg(TmpReg)
17963       .addImm(~(uint64_t)(Align-1));
17964   } else {
17965     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17966       .addReg(OverflowAddrReg);
17967   }
17968
17969   // Compute the next overflow address after this argument.
17970   // (the overflow address should be kept 8-byte aligned)
17971   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17972   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17973     .addReg(OverflowDestReg)
17974     .addImm(ArgSizeA8);
17975
17976   // Store the new overflow address.
17977   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17978     .addOperand(Base)
17979     .addOperand(Scale)
17980     .addOperand(Index)
17981     .addDisp(Disp, 8)
17982     .addOperand(Segment)
17983     .addReg(NextAddrReg)
17984     .setMemRefs(MMOBegin, MMOEnd);
17985
17986   // If we branched, emit the PHI to the front of endMBB.
17987   if (offsetMBB) {
17988     BuildMI(*endMBB, endMBB->begin(), DL,
17989             TII->get(X86::PHI), DestReg)
17990       .addReg(OffsetDestReg).addMBB(offsetMBB)
17991       .addReg(OverflowDestReg).addMBB(overflowMBB);
17992   }
17993
17994   // Erase the pseudo instruction
17995   MI->eraseFromParent();
17996
17997   return endMBB;
17998 }
17999
18000 MachineBasicBlock *
18001 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18002                                                  MachineInstr *MI,
18003                                                  MachineBasicBlock *MBB) const {
18004   // Emit code to save XMM registers to the stack. The ABI says that the
18005   // number of registers to save is given in %al, so it's theoretically
18006   // possible to do an indirect jump trick to avoid saving all of them,
18007   // however this code takes a simpler approach and just executes all
18008   // of the stores if %al is non-zero. It's less code, and it's probably
18009   // easier on the hardware branch predictor, and stores aren't all that
18010   // expensive anyway.
18011
18012   // Create the new basic blocks. One block contains all the XMM stores,
18013   // and one block is the final destination regardless of whether any
18014   // stores were performed.
18015   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18016   MachineFunction *F = MBB->getParent();
18017   MachineFunction::iterator MBBIter = MBB;
18018   ++MBBIter;
18019   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18020   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18021   F->insert(MBBIter, XMMSaveMBB);
18022   F->insert(MBBIter, EndMBB);
18023
18024   // Transfer the remainder of MBB and its successor edges to EndMBB.
18025   EndMBB->splice(EndMBB->begin(), MBB,
18026                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18027   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18028
18029   // The original block will now fall through to the XMM save block.
18030   MBB->addSuccessor(XMMSaveMBB);
18031   // The XMMSaveMBB will fall through to the end block.
18032   XMMSaveMBB->addSuccessor(EndMBB);
18033
18034   // Now add the instructions.
18035   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18036   DebugLoc DL = MI->getDebugLoc();
18037
18038   unsigned CountReg = MI->getOperand(0).getReg();
18039   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18040   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18041
18042   if (!Subtarget->isTargetWin64()) {
18043     // If %al is 0, branch around the XMM save block.
18044     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18045     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18046     MBB->addSuccessor(EndMBB);
18047   }
18048
18049   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18050   // that was just emitted, but clearly shouldn't be "saved".
18051   assert((MI->getNumOperands() <= 3 ||
18052           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18053           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18054          && "Expected last argument to be EFLAGS");
18055   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18056   // In the XMM save block, save all the XMM argument registers.
18057   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18058     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18059     MachineMemOperand *MMO =
18060       F->getMachineMemOperand(
18061           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18062         MachineMemOperand::MOStore,
18063         /*Size=*/16, /*Align=*/16);
18064     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18065       .addFrameIndex(RegSaveFrameIndex)
18066       .addImm(/*Scale=*/1)
18067       .addReg(/*IndexReg=*/0)
18068       .addImm(/*Disp=*/Offset)
18069       .addReg(/*Segment=*/0)
18070       .addReg(MI->getOperand(i).getReg())
18071       .addMemOperand(MMO);
18072   }
18073
18074   MI->eraseFromParent();   // The pseudo instruction is gone now.
18075
18076   return EndMBB;
18077 }
18078
18079 // The EFLAGS operand of SelectItr might be missing a kill marker
18080 // because there were multiple uses of EFLAGS, and ISel didn't know
18081 // which to mark. Figure out whether SelectItr should have had a
18082 // kill marker, and set it if it should. Returns the correct kill
18083 // marker value.
18084 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18085                                      MachineBasicBlock* BB,
18086                                      const TargetRegisterInfo* TRI) {
18087   // Scan forward through BB for a use/def of EFLAGS.
18088   MachineBasicBlock::iterator miI(std::next(SelectItr));
18089   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18090     const MachineInstr& mi = *miI;
18091     if (mi.readsRegister(X86::EFLAGS))
18092       return false;
18093     if (mi.definesRegister(X86::EFLAGS))
18094       break; // Should have kill-flag - update below.
18095   }
18096
18097   // If we hit the end of the block, check whether EFLAGS is live into a
18098   // successor.
18099   if (miI == BB->end()) {
18100     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18101                                           sEnd = BB->succ_end();
18102          sItr != sEnd; ++sItr) {
18103       MachineBasicBlock* succ = *sItr;
18104       if (succ->isLiveIn(X86::EFLAGS))
18105         return false;
18106     }
18107   }
18108
18109   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18110   // out. SelectMI should have a kill flag on EFLAGS.
18111   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18112   return true;
18113 }
18114
18115 MachineBasicBlock *
18116 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18117                                      MachineBasicBlock *BB) const {
18118   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18119   DebugLoc DL = MI->getDebugLoc();
18120
18121   // To "insert" a SELECT_CC instruction, we actually have to insert the
18122   // diamond control-flow pattern.  The incoming instruction knows the
18123   // destination vreg to set, the condition code register to branch on, the
18124   // true/false values to select between, and a branch opcode to use.
18125   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18126   MachineFunction::iterator It = BB;
18127   ++It;
18128
18129   //  thisMBB:
18130   //  ...
18131   //   TrueVal = ...
18132   //   cmpTY ccX, r1, r2
18133   //   bCC copy1MBB
18134   //   fallthrough --> copy0MBB
18135   MachineBasicBlock *thisMBB = BB;
18136   MachineFunction *F = BB->getParent();
18137   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18138   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18139   F->insert(It, copy0MBB);
18140   F->insert(It, sinkMBB);
18141
18142   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18143   // live into the sink and copy blocks.
18144   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18145   if (!MI->killsRegister(X86::EFLAGS) &&
18146       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18147     copy0MBB->addLiveIn(X86::EFLAGS);
18148     sinkMBB->addLiveIn(X86::EFLAGS);
18149   }
18150
18151   // Transfer the remainder of BB and its successor edges to sinkMBB.
18152   sinkMBB->splice(sinkMBB->begin(), BB,
18153                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18154   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18155
18156   // Add the true and fallthrough blocks as its successors.
18157   BB->addSuccessor(copy0MBB);
18158   BB->addSuccessor(sinkMBB);
18159
18160   // Create the conditional branch instruction.
18161   unsigned Opc =
18162     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18163   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18164
18165   //  copy0MBB:
18166   //   %FalseValue = ...
18167   //   # fallthrough to sinkMBB
18168   copy0MBB->addSuccessor(sinkMBB);
18169
18170   //  sinkMBB:
18171   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18172   //  ...
18173   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18174           TII->get(X86::PHI), MI->getOperand(0).getReg())
18175     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18176     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18177
18178   MI->eraseFromParent();   // The pseudo instruction is gone now.
18179   return sinkMBB;
18180 }
18181
18182 MachineBasicBlock *
18183 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18184                                         MachineBasicBlock *BB) const {
18185   MachineFunction *MF = BB->getParent();
18186   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18187   DebugLoc DL = MI->getDebugLoc();
18188   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18189
18190   assert(MF->shouldSplitStack());
18191
18192   const bool Is64Bit = Subtarget->is64Bit();
18193   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18194
18195   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18196   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18197
18198   // BB:
18199   //  ... [Till the alloca]
18200   // If stacklet is not large enough, jump to mallocMBB
18201   //
18202   // bumpMBB:
18203   //  Allocate by subtracting from RSP
18204   //  Jump to continueMBB
18205   //
18206   // mallocMBB:
18207   //  Allocate by call to runtime
18208   //
18209   // continueMBB:
18210   //  ...
18211   //  [rest of original BB]
18212   //
18213
18214   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18215   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18216   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18217
18218   MachineRegisterInfo &MRI = MF->getRegInfo();
18219   const TargetRegisterClass *AddrRegClass =
18220     getRegClassFor(getPointerTy());
18221
18222   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18223     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18224     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18225     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18226     sizeVReg = MI->getOperand(1).getReg(),
18227     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18228
18229   MachineFunction::iterator MBBIter = BB;
18230   ++MBBIter;
18231
18232   MF->insert(MBBIter, bumpMBB);
18233   MF->insert(MBBIter, mallocMBB);
18234   MF->insert(MBBIter, continueMBB);
18235
18236   continueMBB->splice(continueMBB->begin(), BB,
18237                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18238   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18239
18240   // Add code to the main basic block to check if the stack limit has been hit,
18241   // and if so, jump to mallocMBB otherwise to bumpMBB.
18242   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18243   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18244     .addReg(tmpSPVReg).addReg(sizeVReg);
18245   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18246     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18247     .addReg(SPLimitVReg);
18248   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18249
18250   // bumpMBB simply decreases the stack pointer, since we know the current
18251   // stacklet has enough space.
18252   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18253     .addReg(SPLimitVReg);
18254   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18255     .addReg(SPLimitVReg);
18256   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18257
18258   // Calls into a routine in libgcc to allocate more space from the heap.
18259   const uint32_t *RegMask =
18260       Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18261   if (IsLP64) {
18262     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18263       .addReg(sizeVReg);
18264     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18265       .addExternalSymbol("__morestack_allocate_stack_space")
18266       .addRegMask(RegMask)
18267       .addReg(X86::RDI, RegState::Implicit)
18268       .addReg(X86::RAX, RegState::ImplicitDefine);
18269   } else if (Is64Bit) {
18270     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18271       .addReg(sizeVReg);
18272     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18273       .addExternalSymbol("__morestack_allocate_stack_space")
18274       .addRegMask(RegMask)
18275       .addReg(X86::EDI, RegState::Implicit)
18276       .addReg(X86::EAX, RegState::ImplicitDefine);
18277   } else {
18278     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18279       .addImm(12);
18280     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18281     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18282       .addExternalSymbol("__morestack_allocate_stack_space")
18283       .addRegMask(RegMask)
18284       .addReg(X86::EAX, RegState::ImplicitDefine);
18285   }
18286
18287   if (!Is64Bit)
18288     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18289       .addImm(16);
18290
18291   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18292     .addReg(IsLP64 ? X86::RAX : X86::EAX);
18293   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18294
18295   // Set up the CFG correctly.
18296   BB->addSuccessor(bumpMBB);
18297   BB->addSuccessor(mallocMBB);
18298   mallocMBB->addSuccessor(continueMBB);
18299   bumpMBB->addSuccessor(continueMBB);
18300
18301   // Take care of the PHI nodes.
18302   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18303           MI->getOperand(0).getReg())
18304     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18305     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18306
18307   // Delete the original pseudo instruction.
18308   MI->eraseFromParent();
18309
18310   // And we're done.
18311   return continueMBB;
18312 }
18313
18314 MachineBasicBlock *
18315 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18316                                         MachineBasicBlock *BB) const {
18317   DebugLoc DL = MI->getDebugLoc();
18318
18319   assert(!Subtarget->isTargetMachO());
18320
18321   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18322
18323   MI->eraseFromParent();   // The pseudo instruction is gone now.
18324   return BB;
18325 }
18326
18327 MachineBasicBlock *
18328 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18329                                       MachineBasicBlock *BB) const {
18330   // This is pretty easy.  We're taking the value that we received from
18331   // our load from the relocation, sticking it in either RDI (x86-64)
18332   // or EAX and doing an indirect call.  The return value will then
18333   // be in the normal return register.
18334   MachineFunction *F = BB->getParent();
18335   const X86InstrInfo *TII = Subtarget->getInstrInfo();
18336   DebugLoc DL = MI->getDebugLoc();
18337
18338   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18339   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18340
18341   // Get a register mask for the lowered call.
18342   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18343   // proper register mask.
18344   const uint32_t *RegMask =
18345       Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18346   if (Subtarget->is64Bit()) {
18347     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18348                                       TII->get(X86::MOV64rm), X86::RDI)
18349     .addReg(X86::RIP)
18350     .addImm(0).addReg(0)
18351     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18352                       MI->getOperand(3).getTargetFlags())
18353     .addReg(0);
18354     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18355     addDirectMem(MIB, X86::RDI);
18356     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18357   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18358     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18359                                       TII->get(X86::MOV32rm), X86::EAX)
18360     .addReg(0)
18361     .addImm(0).addReg(0)
18362     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18363                       MI->getOperand(3).getTargetFlags())
18364     .addReg(0);
18365     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18366     addDirectMem(MIB, X86::EAX);
18367     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18368   } else {
18369     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18370                                       TII->get(X86::MOV32rm), X86::EAX)
18371     .addReg(TII->getGlobalBaseReg(F))
18372     .addImm(0).addReg(0)
18373     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18374                       MI->getOperand(3).getTargetFlags())
18375     .addReg(0);
18376     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18377     addDirectMem(MIB, X86::EAX);
18378     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18379   }
18380
18381   MI->eraseFromParent(); // The pseudo instruction is gone now.
18382   return BB;
18383 }
18384
18385 MachineBasicBlock *
18386 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18387                                     MachineBasicBlock *MBB) const {
18388   DebugLoc DL = MI->getDebugLoc();
18389   MachineFunction *MF = MBB->getParent();
18390   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18391   MachineRegisterInfo &MRI = MF->getRegInfo();
18392
18393   const BasicBlock *BB = MBB->getBasicBlock();
18394   MachineFunction::iterator I = MBB;
18395   ++I;
18396
18397   // Memory Reference
18398   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18399   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18400
18401   unsigned DstReg;
18402   unsigned MemOpndSlot = 0;
18403
18404   unsigned CurOp = 0;
18405
18406   DstReg = MI->getOperand(CurOp++).getReg();
18407   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18408   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18409   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18410   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18411
18412   MemOpndSlot = CurOp;
18413
18414   MVT PVT = getPointerTy();
18415   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18416          "Invalid Pointer Size!");
18417
18418   // For v = setjmp(buf), we generate
18419   //
18420   // thisMBB:
18421   //  buf[LabelOffset] = restoreMBB
18422   //  SjLjSetup restoreMBB
18423   //
18424   // mainMBB:
18425   //  v_main = 0
18426   //
18427   // sinkMBB:
18428   //  v = phi(main, restore)
18429   //
18430   // restoreMBB:
18431   //  if base pointer being used, load it from frame
18432   //  v_restore = 1
18433
18434   MachineBasicBlock *thisMBB = MBB;
18435   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18436   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18437   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18438   MF->insert(I, mainMBB);
18439   MF->insert(I, sinkMBB);
18440   MF->push_back(restoreMBB);
18441
18442   MachineInstrBuilder MIB;
18443
18444   // Transfer the remainder of BB and its successor edges to sinkMBB.
18445   sinkMBB->splice(sinkMBB->begin(), MBB,
18446                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18447   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18448
18449   // thisMBB:
18450   unsigned PtrStoreOpc = 0;
18451   unsigned LabelReg = 0;
18452   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18453   Reloc::Model RM = MF->getTarget().getRelocationModel();
18454   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18455                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18456
18457   // Prepare IP either in reg or imm.
18458   if (!UseImmLabel) {
18459     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18460     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18461     LabelReg = MRI.createVirtualRegister(PtrRC);
18462     if (Subtarget->is64Bit()) {
18463       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18464               .addReg(X86::RIP)
18465               .addImm(0)
18466               .addReg(0)
18467               .addMBB(restoreMBB)
18468               .addReg(0);
18469     } else {
18470       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18471       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18472               .addReg(XII->getGlobalBaseReg(MF))
18473               .addImm(0)
18474               .addReg(0)
18475               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18476               .addReg(0);
18477     }
18478   } else
18479     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18480   // Store IP
18481   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18482   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18483     if (i == X86::AddrDisp)
18484       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18485     else
18486       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18487   }
18488   if (!UseImmLabel)
18489     MIB.addReg(LabelReg);
18490   else
18491     MIB.addMBB(restoreMBB);
18492   MIB.setMemRefs(MMOBegin, MMOEnd);
18493   // Setup
18494   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18495           .addMBB(restoreMBB);
18496
18497   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18498   MIB.addRegMask(RegInfo->getNoPreservedMask());
18499   thisMBB->addSuccessor(mainMBB);
18500   thisMBB->addSuccessor(restoreMBB);
18501
18502   // mainMBB:
18503   //  EAX = 0
18504   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18505   mainMBB->addSuccessor(sinkMBB);
18506
18507   // sinkMBB:
18508   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18509           TII->get(X86::PHI), DstReg)
18510     .addReg(mainDstReg).addMBB(mainMBB)
18511     .addReg(restoreDstReg).addMBB(restoreMBB);
18512
18513   // restoreMBB:
18514   if (RegInfo->hasBasePointer(*MF)) {
18515     const bool Uses64BitFramePtr =
18516         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18517     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18518     X86FI->setRestoreBasePointer(MF);
18519     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18520     unsigned BasePtr = RegInfo->getBaseRegister();
18521     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18522     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18523                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
18524       .setMIFlag(MachineInstr::FrameSetup);
18525   }
18526   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18527   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18528   restoreMBB->addSuccessor(sinkMBB);
18529
18530   MI->eraseFromParent();
18531   return sinkMBB;
18532 }
18533
18534 MachineBasicBlock *
18535 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18536                                      MachineBasicBlock *MBB) const {
18537   DebugLoc DL = MI->getDebugLoc();
18538   MachineFunction *MF = MBB->getParent();
18539   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18540   MachineRegisterInfo &MRI = MF->getRegInfo();
18541
18542   // Memory Reference
18543   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18544   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18545
18546   MVT PVT = getPointerTy();
18547   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18548          "Invalid Pointer Size!");
18549
18550   const TargetRegisterClass *RC =
18551     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18552   unsigned Tmp = MRI.createVirtualRegister(RC);
18553   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18554   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18555   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18556   unsigned SP = RegInfo->getStackRegister();
18557
18558   MachineInstrBuilder MIB;
18559
18560   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18561   const int64_t SPOffset = 2 * PVT.getStoreSize();
18562
18563   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18564   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18565
18566   // Reload FP
18567   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18568   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18569     MIB.addOperand(MI->getOperand(i));
18570   MIB.setMemRefs(MMOBegin, MMOEnd);
18571   // Reload IP
18572   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18573   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18574     if (i == X86::AddrDisp)
18575       MIB.addDisp(MI->getOperand(i), LabelOffset);
18576     else
18577       MIB.addOperand(MI->getOperand(i));
18578   }
18579   MIB.setMemRefs(MMOBegin, MMOEnd);
18580   // Reload SP
18581   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18582   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18583     if (i == X86::AddrDisp)
18584       MIB.addDisp(MI->getOperand(i), SPOffset);
18585     else
18586       MIB.addOperand(MI->getOperand(i));
18587   }
18588   MIB.setMemRefs(MMOBegin, MMOEnd);
18589   // Jump
18590   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18591
18592   MI->eraseFromParent();
18593   return MBB;
18594 }
18595
18596 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18597 // accumulator loops. Writing back to the accumulator allows the coalescer
18598 // to remove extra copies in the loop.
18599 MachineBasicBlock *
18600 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18601                                  MachineBasicBlock *MBB) const {
18602   MachineOperand &AddendOp = MI->getOperand(3);
18603
18604   // Bail out early if the addend isn't a register - we can't switch these.
18605   if (!AddendOp.isReg())
18606     return MBB;
18607
18608   MachineFunction &MF = *MBB->getParent();
18609   MachineRegisterInfo &MRI = MF.getRegInfo();
18610
18611   // Check whether the addend is defined by a PHI:
18612   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18613   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18614   if (!AddendDef.isPHI())
18615     return MBB;
18616
18617   // Look for the following pattern:
18618   // loop:
18619   //   %addend = phi [%entry, 0], [%loop, %result]
18620   //   ...
18621   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18622
18623   // Replace with:
18624   //   loop:
18625   //   %addend = phi [%entry, 0], [%loop, %result]
18626   //   ...
18627   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18628
18629   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18630     assert(AddendDef.getOperand(i).isReg());
18631     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18632     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18633     if (&PHISrcInst == MI) {
18634       // Found a matching instruction.
18635       unsigned NewFMAOpc = 0;
18636       switch (MI->getOpcode()) {
18637         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18638         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18639         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18640         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18641         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18642         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18643         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18644         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18645         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18646         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18647         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18648         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18649         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18650         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18651         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18652         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18653         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
18654         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
18655         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
18656         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
18657
18658         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18659         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18660         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18661         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18662         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18663         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18664         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18665         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18666         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
18667         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
18668         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
18669         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
18670         default: llvm_unreachable("Unrecognized FMA variant.");
18671       }
18672
18673       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
18674       MachineInstrBuilder MIB =
18675         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18676         .addOperand(MI->getOperand(0))
18677         .addOperand(MI->getOperand(3))
18678         .addOperand(MI->getOperand(2))
18679         .addOperand(MI->getOperand(1));
18680       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18681       MI->eraseFromParent();
18682     }
18683   }
18684
18685   return MBB;
18686 }
18687
18688 MachineBasicBlock *
18689 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18690                                                MachineBasicBlock *BB) const {
18691   switch (MI->getOpcode()) {
18692   default: llvm_unreachable("Unexpected instr type to insert");
18693   case X86::TAILJMPd64:
18694   case X86::TAILJMPr64:
18695   case X86::TAILJMPm64:
18696   case X86::TAILJMPd64_REX:
18697   case X86::TAILJMPr64_REX:
18698   case X86::TAILJMPm64_REX:
18699     llvm_unreachable("TAILJMP64 would not be touched here.");
18700   case X86::TCRETURNdi64:
18701   case X86::TCRETURNri64:
18702   case X86::TCRETURNmi64:
18703     return BB;
18704   case X86::WIN_ALLOCA:
18705     return EmitLoweredWinAlloca(MI, BB);
18706   case X86::SEG_ALLOCA_32:
18707   case X86::SEG_ALLOCA_64:
18708     return EmitLoweredSegAlloca(MI, BB);
18709   case X86::TLSCall_32:
18710   case X86::TLSCall_64:
18711     return EmitLoweredTLSCall(MI, BB);
18712   case X86::CMOV_GR8:
18713   case X86::CMOV_FR32:
18714   case X86::CMOV_FR64:
18715   case X86::CMOV_V4F32:
18716   case X86::CMOV_V2F64:
18717   case X86::CMOV_V2I64:
18718   case X86::CMOV_V8F32:
18719   case X86::CMOV_V4F64:
18720   case X86::CMOV_V4I64:
18721   case X86::CMOV_V16F32:
18722   case X86::CMOV_V8F64:
18723   case X86::CMOV_V8I64:
18724   case X86::CMOV_GR16:
18725   case X86::CMOV_GR32:
18726   case X86::CMOV_RFP32:
18727   case X86::CMOV_RFP64:
18728   case X86::CMOV_RFP80:
18729     return EmitLoweredSelect(MI, BB);
18730
18731   case X86::FP32_TO_INT16_IN_MEM:
18732   case X86::FP32_TO_INT32_IN_MEM:
18733   case X86::FP32_TO_INT64_IN_MEM:
18734   case X86::FP64_TO_INT16_IN_MEM:
18735   case X86::FP64_TO_INT32_IN_MEM:
18736   case X86::FP64_TO_INT64_IN_MEM:
18737   case X86::FP80_TO_INT16_IN_MEM:
18738   case X86::FP80_TO_INT32_IN_MEM:
18739   case X86::FP80_TO_INT64_IN_MEM: {
18740     MachineFunction *F = BB->getParent();
18741     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18742     DebugLoc DL = MI->getDebugLoc();
18743
18744     // Change the floating point control register to use "round towards zero"
18745     // mode when truncating to an integer value.
18746     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18747     addFrameReference(BuildMI(*BB, MI, DL,
18748                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18749
18750     // Load the old value of the high byte of the control word...
18751     unsigned OldCW =
18752       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18753     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18754                       CWFrameIdx);
18755
18756     // Set the high part to be round to zero...
18757     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18758       .addImm(0xC7F);
18759
18760     // Reload the modified control word now...
18761     addFrameReference(BuildMI(*BB, MI, DL,
18762                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18763
18764     // Restore the memory image of control word to original value
18765     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18766       .addReg(OldCW);
18767
18768     // Get the X86 opcode to use.
18769     unsigned Opc;
18770     switch (MI->getOpcode()) {
18771     default: llvm_unreachable("illegal opcode!");
18772     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18773     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18774     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18775     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18776     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18777     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18778     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18779     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18780     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18781     }
18782
18783     X86AddressMode AM;
18784     MachineOperand &Op = MI->getOperand(0);
18785     if (Op.isReg()) {
18786       AM.BaseType = X86AddressMode::RegBase;
18787       AM.Base.Reg = Op.getReg();
18788     } else {
18789       AM.BaseType = X86AddressMode::FrameIndexBase;
18790       AM.Base.FrameIndex = Op.getIndex();
18791     }
18792     Op = MI->getOperand(1);
18793     if (Op.isImm())
18794       AM.Scale = Op.getImm();
18795     Op = MI->getOperand(2);
18796     if (Op.isImm())
18797       AM.IndexReg = Op.getImm();
18798     Op = MI->getOperand(3);
18799     if (Op.isGlobal()) {
18800       AM.GV = Op.getGlobal();
18801     } else {
18802       AM.Disp = Op.getImm();
18803     }
18804     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18805                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18806
18807     // Reload the original control word now.
18808     addFrameReference(BuildMI(*BB, MI, DL,
18809                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18810
18811     MI->eraseFromParent();   // The pseudo instruction is gone now.
18812     return BB;
18813   }
18814     // String/text processing lowering.
18815   case X86::PCMPISTRM128REG:
18816   case X86::VPCMPISTRM128REG:
18817   case X86::PCMPISTRM128MEM:
18818   case X86::VPCMPISTRM128MEM:
18819   case X86::PCMPESTRM128REG:
18820   case X86::VPCMPESTRM128REG:
18821   case X86::PCMPESTRM128MEM:
18822   case X86::VPCMPESTRM128MEM:
18823     assert(Subtarget->hasSSE42() &&
18824            "Target must have SSE4.2 or AVX features enabled");
18825     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
18826
18827   // String/text processing lowering.
18828   case X86::PCMPISTRIREG:
18829   case X86::VPCMPISTRIREG:
18830   case X86::PCMPISTRIMEM:
18831   case X86::VPCMPISTRIMEM:
18832   case X86::PCMPESTRIREG:
18833   case X86::VPCMPESTRIREG:
18834   case X86::PCMPESTRIMEM:
18835   case X86::VPCMPESTRIMEM:
18836     assert(Subtarget->hasSSE42() &&
18837            "Target must have SSE4.2 or AVX features enabled");
18838     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
18839
18840   // Thread synchronization.
18841   case X86::MONITOR:
18842     return EmitMonitor(MI, BB, Subtarget);
18843
18844   // xbegin
18845   case X86::XBEGIN:
18846     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
18847
18848   case X86::VASTART_SAVE_XMM_REGS:
18849     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18850
18851   case X86::VAARG_64:
18852     return EmitVAARG64WithCustomInserter(MI, BB);
18853
18854   case X86::EH_SjLj_SetJmp32:
18855   case X86::EH_SjLj_SetJmp64:
18856     return emitEHSjLjSetJmp(MI, BB);
18857
18858   case X86::EH_SjLj_LongJmp32:
18859   case X86::EH_SjLj_LongJmp64:
18860     return emitEHSjLjLongJmp(MI, BB);
18861
18862   case TargetOpcode::STATEPOINT:
18863     // As an implementation detail, STATEPOINT shares the STACKMAP format at
18864     // this point in the process.  We diverge later.
18865     return emitPatchPoint(MI, BB);
18866
18867   case TargetOpcode::STACKMAP:
18868   case TargetOpcode::PATCHPOINT:
18869     return emitPatchPoint(MI, BB);
18870
18871   case X86::VFMADDPDr213r:
18872   case X86::VFMADDPSr213r:
18873   case X86::VFMADDSDr213r:
18874   case X86::VFMADDSSr213r:
18875   case X86::VFMSUBPDr213r:
18876   case X86::VFMSUBPSr213r:
18877   case X86::VFMSUBSDr213r:
18878   case X86::VFMSUBSSr213r:
18879   case X86::VFNMADDPDr213r:
18880   case X86::VFNMADDPSr213r:
18881   case X86::VFNMADDSDr213r:
18882   case X86::VFNMADDSSr213r:
18883   case X86::VFNMSUBPDr213r:
18884   case X86::VFNMSUBPSr213r:
18885   case X86::VFNMSUBSDr213r:
18886   case X86::VFNMSUBSSr213r:
18887   case X86::VFMADDSUBPDr213r:
18888   case X86::VFMADDSUBPSr213r:
18889   case X86::VFMSUBADDPDr213r:
18890   case X86::VFMSUBADDPSr213r:
18891   case X86::VFMADDPDr213rY:
18892   case X86::VFMADDPSr213rY:
18893   case X86::VFMSUBPDr213rY:
18894   case X86::VFMSUBPSr213rY:
18895   case X86::VFNMADDPDr213rY:
18896   case X86::VFNMADDPSr213rY:
18897   case X86::VFNMSUBPDr213rY:
18898   case X86::VFNMSUBPSr213rY:
18899   case X86::VFMADDSUBPDr213rY:
18900   case X86::VFMADDSUBPSr213rY:
18901   case X86::VFMSUBADDPDr213rY:
18902   case X86::VFMSUBADDPSr213rY:
18903     return emitFMA3Instr(MI, BB);
18904   }
18905 }
18906
18907 //===----------------------------------------------------------------------===//
18908 //                           X86 Optimization Hooks
18909 //===----------------------------------------------------------------------===//
18910
18911 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18912                                                       APInt &KnownZero,
18913                                                       APInt &KnownOne,
18914                                                       const SelectionDAG &DAG,
18915                                                       unsigned Depth) const {
18916   unsigned BitWidth = KnownZero.getBitWidth();
18917   unsigned Opc = Op.getOpcode();
18918   assert((Opc >= ISD::BUILTIN_OP_END ||
18919           Opc == ISD::INTRINSIC_WO_CHAIN ||
18920           Opc == ISD::INTRINSIC_W_CHAIN ||
18921           Opc == ISD::INTRINSIC_VOID) &&
18922          "Should use MaskedValueIsZero if you don't know whether Op"
18923          " is a target node!");
18924
18925   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18926   switch (Opc) {
18927   default: break;
18928   case X86ISD::ADD:
18929   case X86ISD::SUB:
18930   case X86ISD::ADC:
18931   case X86ISD::SBB:
18932   case X86ISD::SMUL:
18933   case X86ISD::UMUL:
18934   case X86ISD::INC:
18935   case X86ISD::DEC:
18936   case X86ISD::OR:
18937   case X86ISD::XOR:
18938   case X86ISD::AND:
18939     // These nodes' second result is a boolean.
18940     if (Op.getResNo() == 0)
18941       break;
18942     // Fallthrough
18943   case X86ISD::SETCC:
18944     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18945     break;
18946   case ISD::INTRINSIC_WO_CHAIN: {
18947     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18948     unsigned NumLoBits = 0;
18949     switch (IntId) {
18950     default: break;
18951     case Intrinsic::x86_sse_movmsk_ps:
18952     case Intrinsic::x86_avx_movmsk_ps_256:
18953     case Intrinsic::x86_sse2_movmsk_pd:
18954     case Intrinsic::x86_avx_movmsk_pd_256:
18955     case Intrinsic::x86_mmx_pmovmskb:
18956     case Intrinsic::x86_sse2_pmovmskb_128:
18957     case Intrinsic::x86_avx2_pmovmskb: {
18958       // High bits of movmskp{s|d}, pmovmskb are known zero.
18959       switch (IntId) {
18960         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18961         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18962         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18963         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18964         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18965         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18966         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18967         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18968       }
18969       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18970       break;
18971     }
18972     }
18973     break;
18974   }
18975   }
18976 }
18977
18978 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18979   SDValue Op,
18980   const SelectionDAG &,
18981   unsigned Depth) const {
18982   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18983   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18984     return Op.getValueType().getScalarType().getSizeInBits();
18985
18986   // Fallback case.
18987   return 1;
18988 }
18989
18990 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18991 /// node is a GlobalAddress + offset.
18992 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18993                                        const GlobalValue* &GA,
18994                                        int64_t &Offset) const {
18995   if (N->getOpcode() == X86ISD::Wrapper) {
18996     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18997       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18998       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18999       return true;
19000     }
19001   }
19002   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19003 }
19004
19005 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19006 /// same as extracting the high 128-bit part of 256-bit vector and then
19007 /// inserting the result into the low part of a new 256-bit vector
19008 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19009   EVT VT = SVOp->getValueType(0);
19010   unsigned NumElems = VT.getVectorNumElements();
19011
19012   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19013   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19014     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19015         SVOp->getMaskElt(j) >= 0)
19016       return false;
19017
19018   return true;
19019 }
19020
19021 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19022 /// same as extracting the low 128-bit part of 256-bit vector and then
19023 /// inserting the result into the high part of a new 256-bit vector
19024 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19025   EVT VT = SVOp->getValueType(0);
19026   unsigned NumElems = VT.getVectorNumElements();
19027
19028   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19029   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19030     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19031         SVOp->getMaskElt(j) >= 0)
19032       return false;
19033
19034   return true;
19035 }
19036
19037 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19038 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19039                                         TargetLowering::DAGCombinerInfo &DCI,
19040                                         const X86Subtarget* Subtarget) {
19041   SDLoc dl(N);
19042   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19043   SDValue V1 = SVOp->getOperand(0);
19044   SDValue V2 = SVOp->getOperand(1);
19045   EVT VT = SVOp->getValueType(0);
19046   unsigned NumElems = VT.getVectorNumElements();
19047
19048   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19049       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19050     //
19051     //                   0,0,0,...
19052     //                      |
19053     //    V      UNDEF    BUILD_VECTOR    UNDEF
19054     //     \      /           \           /
19055     //  CONCAT_VECTOR         CONCAT_VECTOR
19056     //         \                  /
19057     //          \                /
19058     //          RESULT: V + zero extended
19059     //
19060     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19061         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19062         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19063       return SDValue();
19064
19065     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19066       return SDValue();
19067
19068     // To match the shuffle mask, the first half of the mask should
19069     // be exactly the first vector, and all the rest a splat with the
19070     // first element of the second one.
19071     for (unsigned i = 0; i != NumElems/2; ++i)
19072       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19073           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19074         return SDValue();
19075
19076     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19077     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19078       if (Ld->hasNUsesOfValue(1, 0)) {
19079         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19080         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19081         SDValue ResNode =
19082           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19083                                   Ld->getMemoryVT(),
19084                                   Ld->getPointerInfo(),
19085                                   Ld->getAlignment(),
19086                                   false/*isVolatile*/, true/*ReadMem*/,
19087                                   false/*WriteMem*/);
19088
19089         // Make sure the newly-created LOAD is in the same position as Ld in
19090         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19091         // and update uses of Ld's output chain to use the TokenFactor.
19092         if (Ld->hasAnyUseOfValue(1)) {
19093           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19094                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19095           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19096           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19097                                  SDValue(ResNode.getNode(), 1));
19098         }
19099
19100         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19101       }
19102     }
19103
19104     // Emit a zeroed vector and insert the desired subvector on its
19105     // first half.
19106     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19107     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19108     return DCI.CombineTo(N, InsV);
19109   }
19110
19111   //===--------------------------------------------------------------------===//
19112   // Combine some shuffles into subvector extracts and inserts:
19113   //
19114
19115   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19116   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19117     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19118     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19119     return DCI.CombineTo(N, InsV);
19120   }
19121
19122   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19123   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19124     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19125     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19126     return DCI.CombineTo(N, InsV);
19127   }
19128
19129   return SDValue();
19130 }
19131
19132 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19133 /// possible.
19134 ///
19135 /// This is the leaf of the recursive combinine below. When we have found some
19136 /// chain of single-use x86 shuffle instructions and accumulated the combined
19137 /// shuffle mask represented by them, this will try to pattern match that mask
19138 /// into either a single instruction if there is a special purpose instruction
19139 /// for this operation, or into a PSHUFB instruction which is a fully general
19140 /// instruction but should only be used to replace chains over a certain depth.
19141 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19142                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19143                                    TargetLowering::DAGCombinerInfo &DCI,
19144                                    const X86Subtarget *Subtarget) {
19145   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19146
19147   // Find the operand that enters the chain. Note that multiple uses are OK
19148   // here, we're not going to remove the operand we find.
19149   SDValue Input = Op.getOperand(0);
19150   while (Input.getOpcode() == ISD::BITCAST)
19151     Input = Input.getOperand(0);
19152
19153   MVT VT = Input.getSimpleValueType();
19154   MVT RootVT = Root.getSimpleValueType();
19155   SDLoc DL(Root);
19156
19157   // Just remove no-op shuffle masks.
19158   if (Mask.size() == 1) {
19159     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19160                   /*AddTo*/ true);
19161     return true;
19162   }
19163
19164   // Use the float domain if the operand type is a floating point type.
19165   bool FloatDomain = VT.isFloatingPoint();
19166
19167   // For floating point shuffles, we don't have free copies in the shuffle
19168   // instructions or the ability to load as part of the instruction, so
19169   // canonicalize their shuffles to UNPCK or MOV variants.
19170   //
19171   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19172   // vectors because it can have a load folded into it that UNPCK cannot. This
19173   // doesn't preclude something switching to the shorter encoding post-RA.
19174   if (FloatDomain) {
19175     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19176       bool Lo = Mask.equals(0, 0);
19177       unsigned Shuffle;
19178       MVT ShuffleVT;
19179       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19180       // is no slower than UNPCKLPD but has the option to fold the input operand
19181       // into even an unaligned memory load.
19182       if (Lo && Subtarget->hasSSE3()) {
19183         Shuffle = X86ISD::MOVDDUP;
19184         ShuffleVT = MVT::v2f64;
19185       } else {
19186         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19187         // than the UNPCK variants.
19188         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19189         ShuffleVT = MVT::v4f32;
19190       }
19191       if (Depth == 1 && Root->getOpcode() == Shuffle)
19192         return false; // Nothing to do!
19193       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19194       DCI.AddToWorklist(Op.getNode());
19195       if (Shuffle == X86ISD::MOVDDUP)
19196         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19197       else
19198         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19199       DCI.AddToWorklist(Op.getNode());
19200       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19201                     /*AddTo*/ true);
19202       return true;
19203     }
19204     if (Subtarget->hasSSE3() &&
19205         (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
19206       bool Lo = Mask.equals(0, 0, 2, 2);
19207       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19208       MVT ShuffleVT = MVT::v4f32;
19209       if (Depth == 1 && Root->getOpcode() == Shuffle)
19210         return false; // Nothing to do!
19211       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19212       DCI.AddToWorklist(Op.getNode());
19213       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19214       DCI.AddToWorklist(Op.getNode());
19215       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19216                     /*AddTo*/ true);
19217       return true;
19218     }
19219     if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
19220       bool Lo = Mask.equals(0, 0, 1, 1);
19221       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19222       MVT ShuffleVT = MVT::v4f32;
19223       if (Depth == 1 && Root->getOpcode() == Shuffle)
19224         return false; // Nothing to do!
19225       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19226       DCI.AddToWorklist(Op.getNode());
19227       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19228       DCI.AddToWorklist(Op.getNode());
19229       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19230                     /*AddTo*/ true);
19231       return true;
19232     }
19233   }
19234
19235   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19236   // variants as none of these have single-instruction variants that are
19237   // superior to the UNPCK formulation.
19238   if (!FloatDomain &&
19239       (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19240        Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19241        Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19242        Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19243                    15))) {
19244     bool Lo = Mask[0] == 0;
19245     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19246     if (Depth == 1 && Root->getOpcode() == Shuffle)
19247       return false; // Nothing to do!
19248     MVT ShuffleVT;
19249     switch (Mask.size()) {
19250     case 8:
19251       ShuffleVT = MVT::v8i16;
19252       break;
19253     case 16:
19254       ShuffleVT = MVT::v16i8;
19255       break;
19256     default:
19257       llvm_unreachable("Impossible mask size!");
19258     };
19259     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19260     DCI.AddToWorklist(Op.getNode());
19261     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19262     DCI.AddToWorklist(Op.getNode());
19263     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19264                   /*AddTo*/ true);
19265     return true;
19266   }
19267
19268   // Don't try to re-form single instruction chains under any circumstances now
19269   // that we've done encoding canonicalization for them.
19270   if (Depth < 2)
19271     return false;
19272
19273   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19274   // can replace them with a single PSHUFB instruction profitably. Intel's
19275   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19276   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19277   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19278     SmallVector<SDValue, 16> PSHUFBMask;
19279     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19280     int Ratio = 16 / Mask.size();
19281     for (unsigned i = 0; i < 16; ++i) {
19282       if (Mask[i / Ratio] == SM_SentinelUndef) {
19283         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19284         continue;
19285       }
19286       int M = Mask[i / Ratio] != SM_SentinelZero
19287                   ? Ratio * Mask[i / Ratio] + i % Ratio
19288                   : 255;
19289       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19290     }
19291     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19292     DCI.AddToWorklist(Op.getNode());
19293     SDValue PSHUFBMaskOp =
19294         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19295     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19296     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19297     DCI.AddToWorklist(Op.getNode());
19298     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19299                   /*AddTo*/ true);
19300     return true;
19301   }
19302
19303   // Failed to find any combines.
19304   return false;
19305 }
19306
19307 /// \brief Fully generic combining of x86 shuffle instructions.
19308 ///
19309 /// This should be the last combine run over the x86 shuffle instructions. Once
19310 /// they have been fully optimized, this will recursively consider all chains
19311 /// of single-use shuffle instructions, build a generic model of the cumulative
19312 /// shuffle operation, and check for simpler instructions which implement this
19313 /// operation. We use this primarily for two purposes:
19314 ///
19315 /// 1) Collapse generic shuffles to specialized single instructions when
19316 ///    equivalent. In most cases, this is just an encoding size win, but
19317 ///    sometimes we will collapse multiple generic shuffles into a single
19318 ///    special-purpose shuffle.
19319 /// 2) Look for sequences of shuffle instructions with 3 or more total
19320 ///    instructions, and replace them with the slightly more expensive SSSE3
19321 ///    PSHUFB instruction if available. We do this as the last combining step
19322 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19323 ///    a suitable short sequence of other instructions. The PHUFB will either
19324 ///    use a register or have to read from memory and so is slightly (but only
19325 ///    slightly) more expensive than the other shuffle instructions.
19326 ///
19327 /// Because this is inherently a quadratic operation (for each shuffle in
19328 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19329 /// This should never be an issue in practice as the shuffle lowering doesn't
19330 /// produce sequences of more than 8 instructions.
19331 ///
19332 /// FIXME: We will currently miss some cases where the redundant shuffling
19333 /// would simplify under the threshold for PSHUFB formation because of
19334 /// combine-ordering. To fix this, we should do the redundant instruction
19335 /// combining in this recursive walk.
19336 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19337                                           ArrayRef<int> RootMask,
19338                                           int Depth, bool HasPSHUFB,
19339                                           SelectionDAG &DAG,
19340                                           TargetLowering::DAGCombinerInfo &DCI,
19341                                           const X86Subtarget *Subtarget) {
19342   // Bound the depth of our recursive combine because this is ultimately
19343   // quadratic in nature.
19344   if (Depth > 8)
19345     return false;
19346
19347   // Directly rip through bitcasts to find the underlying operand.
19348   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19349     Op = Op.getOperand(0);
19350
19351   MVT VT = Op.getSimpleValueType();
19352   if (!VT.isVector())
19353     return false; // Bail if we hit a non-vector.
19354   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19355   // version should be added.
19356   if (VT.getSizeInBits() != 128)
19357     return false;
19358
19359   assert(Root.getSimpleValueType().isVector() &&
19360          "Shuffles operate on vector types!");
19361   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19362          "Can only combine shuffles of the same vector register size.");
19363
19364   if (!isTargetShuffle(Op.getOpcode()))
19365     return false;
19366   SmallVector<int, 16> OpMask;
19367   bool IsUnary;
19368   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19369   // We only can combine unary shuffles which we can decode the mask for.
19370   if (!HaveMask || !IsUnary)
19371     return false;
19372
19373   assert(VT.getVectorNumElements() == OpMask.size() &&
19374          "Different mask size from vector size!");
19375   assert(((RootMask.size() > OpMask.size() &&
19376            RootMask.size() % OpMask.size() == 0) ||
19377           (OpMask.size() > RootMask.size() &&
19378            OpMask.size() % RootMask.size() == 0) ||
19379           OpMask.size() == RootMask.size()) &&
19380          "The smaller number of elements must divide the larger.");
19381   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19382   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19383   assert(((RootRatio == 1 && OpRatio == 1) ||
19384           (RootRatio == 1) != (OpRatio == 1)) &&
19385          "Must not have a ratio for both incoming and op masks!");
19386
19387   SmallVector<int, 16> Mask;
19388   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19389
19390   // Merge this shuffle operation's mask into our accumulated mask. Note that
19391   // this shuffle's mask will be the first applied to the input, followed by the
19392   // root mask to get us all the way to the root value arrangement. The reason
19393   // for this order is that we are recursing up the operation chain.
19394   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19395     int RootIdx = i / RootRatio;
19396     if (RootMask[RootIdx] < 0) {
19397       // This is a zero or undef lane, we're done.
19398       Mask.push_back(RootMask[RootIdx]);
19399       continue;
19400     }
19401
19402     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19403     int OpIdx = RootMaskedIdx / OpRatio;
19404     if (OpMask[OpIdx] < 0) {
19405       // The incoming lanes are zero or undef, it doesn't matter which ones we
19406       // are using.
19407       Mask.push_back(OpMask[OpIdx]);
19408       continue;
19409     }
19410
19411     // Ok, we have non-zero lanes, map them through.
19412     Mask.push_back(OpMask[OpIdx] * OpRatio +
19413                    RootMaskedIdx % OpRatio);
19414   }
19415
19416   // See if we can recurse into the operand to combine more things.
19417   switch (Op.getOpcode()) {
19418     case X86ISD::PSHUFB:
19419       HasPSHUFB = true;
19420     case X86ISD::PSHUFD:
19421     case X86ISD::PSHUFHW:
19422     case X86ISD::PSHUFLW:
19423       if (Op.getOperand(0).hasOneUse() &&
19424           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19425                                         HasPSHUFB, DAG, DCI, Subtarget))
19426         return true;
19427       break;
19428
19429     case X86ISD::UNPCKL:
19430     case X86ISD::UNPCKH:
19431       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19432       // We can't check for single use, we have to check that this shuffle is the only user.
19433       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19434           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19435                                         HasPSHUFB, DAG, DCI, Subtarget))
19436           return true;
19437       break;
19438   }
19439
19440   // Minor canonicalization of the accumulated shuffle mask to make it easier
19441   // to match below. All this does is detect masks with squential pairs of
19442   // elements, and shrink them to the half-width mask. It does this in a loop
19443   // so it will reduce the size of the mask to the minimal width mask which
19444   // performs an equivalent shuffle.
19445   SmallVector<int, 16> WidenedMask;
19446   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19447     Mask = std::move(WidenedMask);
19448     WidenedMask.clear();
19449   }
19450
19451   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19452                                 Subtarget);
19453 }
19454
19455 /// \brief Get the PSHUF-style mask from PSHUF node.
19456 ///
19457 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19458 /// PSHUF-style masks that can be reused with such instructions.
19459 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19460   SmallVector<int, 4> Mask;
19461   bool IsUnary;
19462   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19463   (void)HaveMask;
19464   assert(HaveMask);
19465
19466   switch (N.getOpcode()) {
19467   case X86ISD::PSHUFD:
19468     return Mask;
19469   case X86ISD::PSHUFLW:
19470     Mask.resize(4);
19471     return Mask;
19472   case X86ISD::PSHUFHW:
19473     Mask.erase(Mask.begin(), Mask.begin() + 4);
19474     for (int &M : Mask)
19475       M -= 4;
19476     return Mask;
19477   default:
19478     llvm_unreachable("No valid shuffle instruction found!");
19479   }
19480 }
19481
19482 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19483 ///
19484 /// We walk up the chain and look for a combinable shuffle, skipping over
19485 /// shuffles that we could hoist this shuffle's transformation past without
19486 /// altering anything.
19487 static SDValue
19488 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19489                              SelectionDAG &DAG,
19490                              TargetLowering::DAGCombinerInfo &DCI) {
19491   assert(N.getOpcode() == X86ISD::PSHUFD &&
19492          "Called with something other than an x86 128-bit half shuffle!");
19493   SDLoc DL(N);
19494
19495   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19496   // of the shuffles in the chain so that we can form a fresh chain to replace
19497   // this one.
19498   SmallVector<SDValue, 8> Chain;
19499   SDValue V = N.getOperand(0);
19500   for (; V.hasOneUse(); V = V.getOperand(0)) {
19501     switch (V.getOpcode()) {
19502     default:
19503       return SDValue(); // Nothing combined!
19504
19505     case ISD::BITCAST:
19506       // Skip bitcasts as we always know the type for the target specific
19507       // instructions.
19508       continue;
19509
19510     case X86ISD::PSHUFD:
19511       // Found another dword shuffle.
19512       break;
19513
19514     case X86ISD::PSHUFLW:
19515       // Check that the low words (being shuffled) are the identity in the
19516       // dword shuffle, and the high words are self-contained.
19517       if (Mask[0] != 0 || Mask[1] != 1 ||
19518           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19519         return SDValue();
19520
19521       Chain.push_back(V);
19522       continue;
19523
19524     case X86ISD::PSHUFHW:
19525       // Check that the high words (being shuffled) are the identity in the
19526       // dword shuffle, and the low words are self-contained.
19527       if (Mask[2] != 2 || Mask[3] != 3 ||
19528           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19529         return SDValue();
19530
19531       Chain.push_back(V);
19532       continue;
19533
19534     case X86ISD::UNPCKL:
19535     case X86ISD::UNPCKH:
19536       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19537       // shuffle into a preceding word shuffle.
19538       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19539         return SDValue();
19540
19541       // Search for a half-shuffle which we can combine with.
19542       unsigned CombineOp =
19543           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19544       if (V.getOperand(0) != V.getOperand(1) ||
19545           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19546         return SDValue();
19547       Chain.push_back(V);
19548       V = V.getOperand(0);
19549       do {
19550         switch (V.getOpcode()) {
19551         default:
19552           return SDValue(); // Nothing to combine.
19553
19554         case X86ISD::PSHUFLW:
19555         case X86ISD::PSHUFHW:
19556           if (V.getOpcode() == CombineOp)
19557             break;
19558
19559           Chain.push_back(V);
19560
19561           // Fallthrough!
19562         case ISD::BITCAST:
19563           V = V.getOperand(0);
19564           continue;
19565         }
19566         break;
19567       } while (V.hasOneUse());
19568       break;
19569     }
19570     // Break out of the loop if we break out of the switch.
19571     break;
19572   }
19573
19574   if (!V.hasOneUse())
19575     // We fell out of the loop without finding a viable combining instruction.
19576     return SDValue();
19577
19578   // Merge this node's mask and our incoming mask.
19579   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19580   for (int &M : Mask)
19581     M = VMask[M];
19582   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19583                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19584
19585   // Rebuild the chain around this new shuffle.
19586   while (!Chain.empty()) {
19587     SDValue W = Chain.pop_back_val();
19588
19589     if (V.getValueType() != W.getOperand(0).getValueType())
19590       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19591
19592     switch (W.getOpcode()) {
19593     default:
19594       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19595
19596     case X86ISD::UNPCKL:
19597     case X86ISD::UNPCKH:
19598       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19599       break;
19600
19601     case X86ISD::PSHUFD:
19602     case X86ISD::PSHUFLW:
19603     case X86ISD::PSHUFHW:
19604       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19605       break;
19606     }
19607   }
19608   if (V.getValueType() != N.getValueType())
19609     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19610
19611   // Return the new chain to replace N.
19612   return V;
19613 }
19614
19615 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19616 ///
19617 /// We walk up the chain, skipping shuffles of the other half and looking
19618 /// through shuffles which switch halves trying to find a shuffle of the same
19619 /// pair of dwords.
19620 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19621                                         SelectionDAG &DAG,
19622                                         TargetLowering::DAGCombinerInfo &DCI) {
19623   assert(
19624       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19625       "Called with something other than an x86 128-bit half shuffle!");
19626   SDLoc DL(N);
19627   unsigned CombineOpcode = N.getOpcode();
19628
19629   // Walk up a single-use chain looking for a combinable shuffle.
19630   SDValue V = N.getOperand(0);
19631   for (; V.hasOneUse(); V = V.getOperand(0)) {
19632     switch (V.getOpcode()) {
19633     default:
19634       return false; // Nothing combined!
19635
19636     case ISD::BITCAST:
19637       // Skip bitcasts as we always know the type for the target specific
19638       // instructions.
19639       continue;
19640
19641     case X86ISD::PSHUFLW:
19642     case X86ISD::PSHUFHW:
19643       if (V.getOpcode() == CombineOpcode)
19644         break;
19645
19646       // Other-half shuffles are no-ops.
19647       continue;
19648     }
19649     // Break out of the loop if we break out of the switch.
19650     break;
19651   }
19652
19653   if (!V.hasOneUse())
19654     // We fell out of the loop without finding a viable combining instruction.
19655     return false;
19656
19657   // Combine away the bottom node as its shuffle will be accumulated into
19658   // a preceding shuffle.
19659   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19660
19661   // Record the old value.
19662   SDValue Old = V;
19663
19664   // Merge this node's mask and our incoming mask (adjusted to account for all
19665   // the pshufd instructions encountered).
19666   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19667   for (int &M : Mask)
19668     M = VMask[M];
19669   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19670                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19671
19672   // Check that the shuffles didn't cancel each other out. If not, we need to
19673   // combine to the new one.
19674   if (Old != V)
19675     // Replace the combinable shuffle with the combined one, updating all users
19676     // so that we re-evaluate the chain here.
19677     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19678
19679   return true;
19680 }
19681
19682 /// \brief Try to combine x86 target specific shuffles.
19683 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19684                                            TargetLowering::DAGCombinerInfo &DCI,
19685                                            const X86Subtarget *Subtarget) {
19686   SDLoc DL(N);
19687   MVT VT = N.getSimpleValueType();
19688   SmallVector<int, 4> Mask;
19689
19690   switch (N.getOpcode()) {
19691   case X86ISD::PSHUFD:
19692   case X86ISD::PSHUFLW:
19693   case X86ISD::PSHUFHW:
19694     Mask = getPSHUFShuffleMask(N);
19695     assert(Mask.size() == 4);
19696     break;
19697   default:
19698     return SDValue();
19699   }
19700
19701   // Nuke no-op shuffles that show up after combining.
19702   if (isNoopShuffleMask(Mask))
19703     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19704
19705   // Look for simplifications involving one or two shuffle instructions.
19706   SDValue V = N.getOperand(0);
19707   switch (N.getOpcode()) {
19708   default:
19709     break;
19710   case X86ISD::PSHUFLW:
19711   case X86ISD::PSHUFHW:
19712     assert(VT == MVT::v8i16);
19713     (void)VT;
19714
19715     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19716       return SDValue(); // We combined away this shuffle, so we're done.
19717
19718     // See if this reduces to a PSHUFD which is no more expensive and can
19719     // combine with more operations. Note that it has to at least flip the
19720     // dwords as otherwise it would have been removed as a no-op.
19721     if (Mask[0] == 2 && Mask[1] == 3 && Mask[2] == 0 && Mask[3] == 1) {
19722       int DMask[] = {0, 1, 2, 3};
19723       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19724       DMask[DOffset + 0] = DOffset + 1;
19725       DMask[DOffset + 1] = DOffset + 0;
19726       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19727       DCI.AddToWorklist(V.getNode());
19728       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19729                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19730       DCI.AddToWorklist(V.getNode());
19731       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19732     }
19733
19734     // Look for shuffle patterns which can be implemented as a single unpack.
19735     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19736     // only works when we have a PSHUFD followed by two half-shuffles.
19737     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19738         (V.getOpcode() == X86ISD::PSHUFLW ||
19739          V.getOpcode() == X86ISD::PSHUFHW) &&
19740         V.getOpcode() != N.getOpcode() &&
19741         V.hasOneUse()) {
19742       SDValue D = V.getOperand(0);
19743       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19744         D = D.getOperand(0);
19745       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19746         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19747         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19748         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19749         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19750         int WordMask[8];
19751         for (int i = 0; i < 4; ++i) {
19752           WordMask[i + NOffset] = Mask[i] + NOffset;
19753           WordMask[i + VOffset] = VMask[i] + VOffset;
19754         }
19755         // Map the word mask through the DWord mask.
19756         int MappedMask[8];
19757         for (int i = 0; i < 8; ++i)
19758           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19759         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19760         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19761         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19762                        std::begin(UnpackLoMask)) ||
19763             std::equal(std::begin(MappedMask), std::end(MappedMask),
19764                        std::begin(UnpackHiMask))) {
19765           // We can replace all three shuffles with an unpack.
19766           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19767           DCI.AddToWorklist(V.getNode());
19768           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19769                                                 : X86ISD::UNPCKH,
19770                              DL, MVT::v8i16, V, V);
19771         }
19772       }
19773     }
19774
19775     break;
19776
19777   case X86ISD::PSHUFD:
19778     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19779       return NewN;
19780
19781     break;
19782   }
19783
19784   return SDValue();
19785 }
19786
19787 /// \brief Try to combine a shuffle into a target-specific add-sub node.
19788 ///
19789 /// We combine this directly on the abstract vector shuffle nodes so it is
19790 /// easier to generically match. We also insert dummy vector shuffle nodes for
19791 /// the operands which explicitly discard the lanes which are unused by this
19792 /// operation to try to flow through the rest of the combiner the fact that
19793 /// they're unused.
19794 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
19795   SDLoc DL(N);
19796   EVT VT = N->getValueType(0);
19797
19798   // We only handle target-independent shuffles.
19799   // FIXME: It would be easy and harmless to use the target shuffle mask
19800   // extraction tool to support more.
19801   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
19802     return SDValue();
19803
19804   auto *SVN = cast<ShuffleVectorSDNode>(N);
19805   ArrayRef<int> Mask = SVN->getMask();
19806   SDValue V1 = N->getOperand(0);
19807   SDValue V2 = N->getOperand(1);
19808
19809   // We require the first shuffle operand to be the SUB node, and the second to
19810   // be the ADD node.
19811   // FIXME: We should support the commuted patterns.
19812   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
19813     return SDValue();
19814
19815   // If there are other uses of these operations we can't fold them.
19816   if (!V1->hasOneUse() || !V2->hasOneUse())
19817     return SDValue();
19818
19819   // Ensure that both operations have the same operands. Note that we can
19820   // commute the FADD operands.
19821   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
19822   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
19823       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
19824     return SDValue();
19825
19826   // We're looking for blends between FADD and FSUB nodes. We insist on these
19827   // nodes being lined up in a specific expected pattern.
19828   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
19829         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
19830         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
19831     return SDValue();
19832
19833   // Only specific types are legal at this point, assert so we notice if and
19834   // when these change.
19835   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
19836           VT == MVT::v4f64) &&
19837          "Unknown vector type encountered!");
19838
19839   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
19840 }
19841
19842 /// PerformShuffleCombine - Performs several different shuffle combines.
19843 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19844                                      TargetLowering::DAGCombinerInfo &DCI,
19845                                      const X86Subtarget *Subtarget) {
19846   SDLoc dl(N);
19847   SDValue N0 = N->getOperand(0);
19848   SDValue N1 = N->getOperand(1);
19849   EVT VT = N->getValueType(0);
19850
19851   // Don't create instructions with illegal types after legalize types has run.
19852   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19853   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19854     return SDValue();
19855
19856   // If we have legalized the vector types, look for blends of FADD and FSUB
19857   // nodes that we can fuse into an ADDSUB node.
19858   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
19859     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
19860       return AddSub;
19861
19862   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19863   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19864       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19865     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19866
19867   // During Type Legalization, when promoting illegal vector types,
19868   // the backend might introduce new shuffle dag nodes and bitcasts.
19869   //
19870   // This code performs the following transformation:
19871   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19872   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19873   //
19874   // We do this only if both the bitcast and the BINOP dag nodes have
19875   // one use. Also, perform this transformation only if the new binary
19876   // operation is legal. This is to avoid introducing dag nodes that
19877   // potentially need to be further expanded (or custom lowered) into a
19878   // less optimal sequence of dag nodes.
19879   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19880       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19881       N0.getOpcode() == ISD::BITCAST) {
19882     SDValue BC0 = N0.getOperand(0);
19883     EVT SVT = BC0.getValueType();
19884     unsigned Opcode = BC0.getOpcode();
19885     unsigned NumElts = VT.getVectorNumElements();
19886
19887     if (BC0.hasOneUse() && SVT.isVector() &&
19888         SVT.getVectorNumElements() * 2 == NumElts &&
19889         TLI.isOperationLegal(Opcode, VT)) {
19890       bool CanFold = false;
19891       switch (Opcode) {
19892       default : break;
19893       case ISD::ADD :
19894       case ISD::FADD :
19895       case ISD::SUB :
19896       case ISD::FSUB :
19897       case ISD::MUL :
19898       case ISD::FMUL :
19899         CanFold = true;
19900       }
19901
19902       unsigned SVTNumElts = SVT.getVectorNumElements();
19903       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19904       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19905         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19906       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19907         CanFold = SVOp->getMaskElt(i) < 0;
19908
19909       if (CanFold) {
19910         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19911         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19912         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19913         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19914       }
19915     }
19916   }
19917
19918   // Only handle 128 wide vector from here on.
19919   if (!VT.is128BitVector())
19920     return SDValue();
19921
19922   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19923   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19924   // consecutive, non-overlapping, and in the right order.
19925   SmallVector<SDValue, 16> Elts;
19926   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19927     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19928
19929   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19930   if (LD.getNode())
19931     return LD;
19932
19933   if (isTargetShuffle(N->getOpcode())) {
19934     SDValue Shuffle =
19935         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19936     if (Shuffle.getNode())
19937       return Shuffle;
19938
19939     // Try recursively combining arbitrary sequences of x86 shuffle
19940     // instructions into higher-order shuffles. We do this after combining
19941     // specific PSHUF instruction sequences into their minimal form so that we
19942     // can evaluate how many specialized shuffle instructions are involved in
19943     // a particular chain.
19944     SmallVector<int, 1> NonceMask; // Just a placeholder.
19945     NonceMask.push_back(0);
19946     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19947                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19948                                       DCI, Subtarget))
19949       return SDValue(); // This routine will use CombineTo to replace N.
19950   }
19951
19952   return SDValue();
19953 }
19954
19955 /// PerformTruncateCombine - Converts truncate operation to
19956 /// a sequence of vector shuffle operations.
19957 /// It is possible when we truncate 256-bit vector to 128-bit vector
19958 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19959                                       TargetLowering::DAGCombinerInfo &DCI,
19960                                       const X86Subtarget *Subtarget)  {
19961   return SDValue();
19962 }
19963
19964 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19965 /// specific shuffle of a load can be folded into a single element load.
19966 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19967 /// shuffles have been custom lowered so we need to handle those here.
19968 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19969                                          TargetLowering::DAGCombinerInfo &DCI) {
19970   if (DCI.isBeforeLegalizeOps())
19971     return SDValue();
19972
19973   SDValue InVec = N->getOperand(0);
19974   SDValue EltNo = N->getOperand(1);
19975
19976   if (!isa<ConstantSDNode>(EltNo))
19977     return SDValue();
19978
19979   EVT OriginalVT = InVec.getValueType();
19980
19981   if (InVec.getOpcode() == ISD::BITCAST) {
19982     // Don't duplicate a load with other uses.
19983     if (!InVec.hasOneUse())
19984       return SDValue();
19985     EVT BCVT = InVec.getOperand(0).getValueType();
19986     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
19987       return SDValue();
19988     InVec = InVec.getOperand(0);
19989   }
19990
19991   EVT CurrentVT = InVec.getValueType();
19992
19993   if (!isTargetShuffle(InVec.getOpcode()))
19994     return SDValue();
19995
19996   // Don't duplicate a load with other uses.
19997   if (!InVec.hasOneUse())
19998     return SDValue();
19999
20000   SmallVector<int, 16> ShuffleMask;
20001   bool UnaryShuffle;
20002   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20003                             ShuffleMask, UnaryShuffle))
20004     return SDValue();
20005
20006   // Select the input vector, guarding against out of range extract vector.
20007   unsigned NumElems = CurrentVT.getVectorNumElements();
20008   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20009   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20010   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20011                                          : InVec.getOperand(1);
20012
20013   // If inputs to shuffle are the same for both ops, then allow 2 uses
20014   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20015                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20016
20017   if (LdNode.getOpcode() == ISD::BITCAST) {
20018     // Don't duplicate a load with other uses.
20019     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20020       return SDValue();
20021
20022     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20023     LdNode = LdNode.getOperand(0);
20024   }
20025
20026   if (!ISD::isNormalLoad(LdNode.getNode()))
20027     return SDValue();
20028
20029   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20030
20031   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20032     return SDValue();
20033
20034   EVT EltVT = N->getValueType(0);
20035   // If there's a bitcast before the shuffle, check if the load type and
20036   // alignment is valid.
20037   unsigned Align = LN0->getAlignment();
20038   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20039   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20040       EltVT.getTypeForEVT(*DAG.getContext()));
20041
20042   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20043     return SDValue();
20044
20045   // All checks match so transform back to vector_shuffle so that DAG combiner
20046   // can finish the job
20047   SDLoc dl(N);
20048
20049   // Create shuffle node taking into account the case that its a unary shuffle
20050   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20051                                    : InVec.getOperand(1);
20052   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20053                                  InVec.getOperand(0), Shuffle,
20054                                  &ShuffleMask[0]);
20055   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20056   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20057                      EltNo);
20058 }
20059
20060 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20061 /// special and don't usually play with other vector types, it's better to
20062 /// handle them early to be sure we emit efficient code by avoiding
20063 /// store-load conversions.
20064 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20065   if (N->getValueType(0) != MVT::x86mmx ||
20066       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20067       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20068     return SDValue();
20069
20070   SDValue V = N->getOperand(0);
20071   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20072   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20073     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20074                        N->getValueType(0), V.getOperand(0));
20075
20076   return SDValue();
20077 }
20078
20079 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20080 /// generation and convert it from being a bunch of shuffles and extracts
20081 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20082 /// storing the value and loading scalars back, while for x64 we should
20083 /// use 64-bit extracts and shifts.
20084 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20085                                          TargetLowering::DAGCombinerInfo &DCI) {
20086   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20087   if (NewOp.getNode())
20088     return NewOp;
20089
20090   SDValue InputVector = N->getOperand(0);
20091
20092   // Detect mmx to i32 conversion through a v2i32 elt extract.
20093   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20094       N->getValueType(0) == MVT::i32 &&
20095       InputVector.getValueType() == MVT::v2i32) {
20096
20097     // The bitcast source is a direct mmx result.
20098     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20099     if (MMXSrc.getValueType() == MVT::x86mmx)
20100       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20101                          N->getValueType(0),
20102                          InputVector.getNode()->getOperand(0));
20103
20104     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20105     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20106     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20107         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20108         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20109         MMXSrcOp.getValueType() == MVT::v1i64 &&
20110         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20111       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20112                          N->getValueType(0),
20113                          MMXSrcOp.getOperand(0));
20114   }
20115
20116   // Only operate on vectors of 4 elements, where the alternative shuffling
20117   // gets to be more expensive.
20118   if (InputVector.getValueType() != MVT::v4i32)
20119     return SDValue();
20120
20121   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20122   // single use which is a sign-extend or zero-extend, and all elements are
20123   // used.
20124   SmallVector<SDNode *, 4> Uses;
20125   unsigned ExtractedElements = 0;
20126   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20127        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20128     if (UI.getUse().getResNo() != InputVector.getResNo())
20129       return SDValue();
20130
20131     SDNode *Extract = *UI;
20132     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20133       return SDValue();
20134
20135     if (Extract->getValueType(0) != MVT::i32)
20136       return SDValue();
20137     if (!Extract->hasOneUse())
20138       return SDValue();
20139     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20140         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20141       return SDValue();
20142     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20143       return SDValue();
20144
20145     // Record which element was extracted.
20146     ExtractedElements |=
20147       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20148
20149     Uses.push_back(Extract);
20150   }
20151
20152   // If not all the elements were used, this may not be worthwhile.
20153   if (ExtractedElements != 15)
20154     return SDValue();
20155
20156   // Ok, we've now decided to do the transformation.
20157   // If 64-bit shifts are legal, use the extract-shift sequence,
20158   // otherwise bounce the vector off the cache.
20159   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20160   SDValue Vals[4];
20161   SDLoc dl(InputVector);
20162
20163   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20164     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20165     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20166     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20167       DAG.getConstant(0, VecIdxTy));
20168     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20169       DAG.getConstant(1, VecIdxTy));
20170
20171     SDValue ShAmt = DAG.getConstant(32,
20172       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20173     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20174     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20175       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20176     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20177     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20178       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20179   } else {
20180     // Store the value to a temporary stack slot.
20181     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20182     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20183       MachinePointerInfo(), false, false, 0);
20184
20185     EVT ElementType = InputVector.getValueType().getVectorElementType();
20186     unsigned EltSize = ElementType.getSizeInBits() / 8;
20187
20188     // Replace each use (extract) with a load of the appropriate element.
20189     for (unsigned i = 0; i < 4; ++i) {
20190       uint64_t Offset = EltSize * i;
20191       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20192
20193       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20194                                        StackPtr, OffsetVal);
20195
20196       // Load the scalar.
20197       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20198                             ScalarAddr, MachinePointerInfo(),
20199                             false, false, false, 0);
20200
20201     }
20202   }
20203
20204   // Replace the extracts
20205   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20206     UE = Uses.end(); UI != UE; ++UI) {
20207     SDNode *Extract = *UI;
20208
20209     SDValue Idx = Extract->getOperand(1);
20210     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20211     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20212   }
20213
20214   // The replacement was made in place; don't return anything.
20215   return SDValue();
20216 }
20217
20218 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20219 static std::pair<unsigned, bool>
20220 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20221                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20222   if (!VT.isVector())
20223     return std::make_pair(0, false);
20224
20225   bool NeedSplit = false;
20226   switch (VT.getSimpleVT().SimpleTy) {
20227   default: return std::make_pair(0, false);
20228   case MVT::v4i64:
20229   case MVT::v2i64:
20230     if (!Subtarget->hasVLX())
20231       return std::make_pair(0, false);
20232     break;
20233   case MVT::v64i8:
20234   case MVT::v32i16:
20235     if (!Subtarget->hasBWI())
20236       return std::make_pair(0, false);
20237     break;
20238   case MVT::v16i32:
20239   case MVT::v8i64:
20240     if (!Subtarget->hasAVX512())
20241       return std::make_pair(0, false);
20242     break;
20243   case MVT::v32i8:
20244   case MVT::v16i16:
20245   case MVT::v8i32:
20246     if (!Subtarget->hasAVX2())
20247       NeedSplit = true;
20248     if (!Subtarget->hasAVX())
20249       return std::make_pair(0, false);
20250     break;
20251   case MVT::v16i8:
20252   case MVT::v8i16:
20253   case MVT::v4i32:
20254     if (!Subtarget->hasSSE2())
20255       return std::make_pair(0, false);
20256   }
20257
20258   // SSE2 has only a small subset of the operations.
20259   bool hasUnsigned = Subtarget->hasSSE41() ||
20260                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20261   bool hasSigned = Subtarget->hasSSE41() ||
20262                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20263
20264   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20265
20266   unsigned Opc = 0;
20267   // Check for x CC y ? x : y.
20268   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20269       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20270     switch (CC) {
20271     default: break;
20272     case ISD::SETULT:
20273     case ISD::SETULE:
20274       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20275     case ISD::SETUGT:
20276     case ISD::SETUGE:
20277       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20278     case ISD::SETLT:
20279     case ISD::SETLE:
20280       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20281     case ISD::SETGT:
20282     case ISD::SETGE:
20283       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20284     }
20285   // Check for x CC y ? y : x -- a min/max with reversed arms.
20286   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20287              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20288     switch (CC) {
20289     default: break;
20290     case ISD::SETULT:
20291     case ISD::SETULE:
20292       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20293     case ISD::SETUGT:
20294     case ISD::SETUGE:
20295       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20296     case ISD::SETLT:
20297     case ISD::SETLE:
20298       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20299     case ISD::SETGT:
20300     case ISD::SETGE:
20301       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20302     }
20303   }
20304
20305   return std::make_pair(Opc, NeedSplit);
20306 }
20307
20308 static SDValue
20309 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20310                                       const X86Subtarget *Subtarget) {
20311   SDLoc dl(N);
20312   SDValue Cond = N->getOperand(0);
20313   SDValue LHS = N->getOperand(1);
20314   SDValue RHS = N->getOperand(2);
20315
20316   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20317     SDValue CondSrc = Cond->getOperand(0);
20318     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20319       Cond = CondSrc->getOperand(0);
20320   }
20321
20322   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20323     return SDValue();
20324
20325   // A vselect where all conditions and data are constants can be optimized into
20326   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20327   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20328       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20329     return SDValue();
20330
20331   unsigned MaskValue = 0;
20332   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20333     return SDValue();
20334
20335   MVT VT = N->getSimpleValueType(0);
20336   unsigned NumElems = VT.getVectorNumElements();
20337   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20338   for (unsigned i = 0; i < NumElems; ++i) {
20339     // Be sure we emit undef where we can.
20340     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20341       ShuffleMask[i] = -1;
20342     else
20343       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20344   }
20345
20346   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20347   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20348     return SDValue();
20349   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20350 }
20351
20352 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20353 /// nodes.
20354 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20355                                     TargetLowering::DAGCombinerInfo &DCI,
20356                                     const X86Subtarget *Subtarget) {
20357   SDLoc DL(N);
20358   SDValue Cond = N->getOperand(0);
20359   // Get the LHS/RHS of the select.
20360   SDValue LHS = N->getOperand(1);
20361   SDValue RHS = N->getOperand(2);
20362   EVT VT = LHS.getValueType();
20363   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20364
20365   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20366   // instructions match the semantics of the common C idiom x<y?x:y but not
20367   // x<=y?x:y, because of how they handle negative zero (which can be
20368   // ignored in unsafe-math mode).
20369   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20370   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20371       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20372       (Subtarget->hasSSE2() ||
20373        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20374     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20375
20376     unsigned Opcode = 0;
20377     // Check for x CC y ? x : y.
20378     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20379         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20380       switch (CC) {
20381       default: break;
20382       case ISD::SETULT:
20383         // Converting this to a min would handle NaNs incorrectly, and swapping
20384         // the operands would cause it to handle comparisons between positive
20385         // and negative zero incorrectly.
20386         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20387           if (!DAG.getTarget().Options.UnsafeFPMath &&
20388               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20389             break;
20390           std::swap(LHS, RHS);
20391         }
20392         Opcode = X86ISD::FMIN;
20393         break;
20394       case ISD::SETOLE:
20395         // Converting this to a min would handle comparisons between positive
20396         // and negative zero incorrectly.
20397         if (!DAG.getTarget().Options.UnsafeFPMath &&
20398             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20399           break;
20400         Opcode = X86ISD::FMIN;
20401         break;
20402       case ISD::SETULE:
20403         // Converting this to a min would handle both negative zeros and NaNs
20404         // incorrectly, but we can swap the operands to fix both.
20405         std::swap(LHS, RHS);
20406       case ISD::SETOLT:
20407       case ISD::SETLT:
20408       case ISD::SETLE:
20409         Opcode = X86ISD::FMIN;
20410         break;
20411
20412       case ISD::SETOGE:
20413         // Converting this to a max would handle comparisons between positive
20414         // and negative zero incorrectly.
20415         if (!DAG.getTarget().Options.UnsafeFPMath &&
20416             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20417           break;
20418         Opcode = X86ISD::FMAX;
20419         break;
20420       case ISD::SETUGT:
20421         // Converting this to a max would handle NaNs incorrectly, and swapping
20422         // the operands would cause it to handle comparisons between positive
20423         // and negative zero incorrectly.
20424         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20425           if (!DAG.getTarget().Options.UnsafeFPMath &&
20426               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20427             break;
20428           std::swap(LHS, RHS);
20429         }
20430         Opcode = X86ISD::FMAX;
20431         break;
20432       case ISD::SETUGE:
20433         // Converting this to a max would handle both negative zeros and NaNs
20434         // incorrectly, but we can swap the operands to fix both.
20435         std::swap(LHS, RHS);
20436       case ISD::SETOGT:
20437       case ISD::SETGT:
20438       case ISD::SETGE:
20439         Opcode = X86ISD::FMAX;
20440         break;
20441       }
20442     // Check for x CC y ? y : x -- a min/max with reversed arms.
20443     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20444                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20445       switch (CC) {
20446       default: break;
20447       case ISD::SETOGE:
20448         // Converting this to a min would handle comparisons between positive
20449         // and negative zero incorrectly, and swapping the operands would
20450         // cause it to handle NaNs incorrectly.
20451         if (!DAG.getTarget().Options.UnsafeFPMath &&
20452             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20453           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20454             break;
20455           std::swap(LHS, RHS);
20456         }
20457         Opcode = X86ISD::FMIN;
20458         break;
20459       case ISD::SETUGT:
20460         // Converting this to a min would handle NaNs incorrectly.
20461         if (!DAG.getTarget().Options.UnsafeFPMath &&
20462             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20463           break;
20464         Opcode = X86ISD::FMIN;
20465         break;
20466       case ISD::SETUGE:
20467         // Converting this to a min would handle both negative zeros and NaNs
20468         // incorrectly, but we can swap the operands to fix both.
20469         std::swap(LHS, RHS);
20470       case ISD::SETOGT:
20471       case ISD::SETGT:
20472       case ISD::SETGE:
20473         Opcode = X86ISD::FMIN;
20474         break;
20475
20476       case ISD::SETULT:
20477         // Converting this to a max would handle NaNs incorrectly.
20478         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20479           break;
20480         Opcode = X86ISD::FMAX;
20481         break;
20482       case ISD::SETOLE:
20483         // Converting this to a max would handle comparisons between positive
20484         // and negative zero incorrectly, and swapping the operands would
20485         // cause it to handle NaNs incorrectly.
20486         if (!DAG.getTarget().Options.UnsafeFPMath &&
20487             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20488           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20489             break;
20490           std::swap(LHS, RHS);
20491         }
20492         Opcode = X86ISD::FMAX;
20493         break;
20494       case ISD::SETULE:
20495         // Converting this to a max would handle both negative zeros and NaNs
20496         // incorrectly, but we can swap the operands to fix both.
20497         std::swap(LHS, RHS);
20498       case ISD::SETOLT:
20499       case ISD::SETLT:
20500       case ISD::SETLE:
20501         Opcode = X86ISD::FMAX;
20502         break;
20503       }
20504     }
20505
20506     if (Opcode)
20507       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20508   }
20509
20510   EVT CondVT = Cond.getValueType();
20511   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20512       CondVT.getVectorElementType() == MVT::i1) {
20513     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20514     // lowering on KNL. In this case we convert it to
20515     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20516     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20517     // Since SKX these selects have a proper lowering.
20518     EVT OpVT = LHS.getValueType();
20519     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20520         (OpVT.getVectorElementType() == MVT::i8 ||
20521          OpVT.getVectorElementType() == MVT::i16) &&
20522         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20523       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20524       DCI.AddToWorklist(Cond.getNode());
20525       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20526     }
20527   }
20528   // If this is a select between two integer constants, try to do some
20529   // optimizations.
20530   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20531     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20532       // Don't do this for crazy integer types.
20533       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20534         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20535         // so that TrueC (the true value) is larger than FalseC.
20536         bool NeedsCondInvert = false;
20537
20538         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20539             // Efficiently invertible.
20540             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20541              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20542               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20543           NeedsCondInvert = true;
20544           std::swap(TrueC, FalseC);
20545         }
20546
20547         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20548         if (FalseC->getAPIntValue() == 0 &&
20549             TrueC->getAPIntValue().isPowerOf2()) {
20550           if (NeedsCondInvert) // Invert the condition if needed.
20551             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20552                                DAG.getConstant(1, Cond.getValueType()));
20553
20554           // Zero extend the condition if needed.
20555           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20556
20557           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20558           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20559                              DAG.getConstant(ShAmt, MVT::i8));
20560         }
20561
20562         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20563         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20564           if (NeedsCondInvert) // Invert the condition if needed.
20565             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20566                                DAG.getConstant(1, Cond.getValueType()));
20567
20568           // Zero extend the condition if needed.
20569           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20570                              FalseC->getValueType(0), Cond);
20571           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20572                              SDValue(FalseC, 0));
20573         }
20574
20575         // Optimize cases that will turn into an LEA instruction.  This requires
20576         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20577         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20578           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20579           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20580
20581           bool isFastMultiplier = false;
20582           if (Diff < 10) {
20583             switch ((unsigned char)Diff) {
20584               default: break;
20585               case 1:  // result = add base, cond
20586               case 2:  // result = lea base(    , cond*2)
20587               case 3:  // result = lea base(cond, cond*2)
20588               case 4:  // result = lea base(    , cond*4)
20589               case 5:  // result = lea base(cond, cond*4)
20590               case 8:  // result = lea base(    , cond*8)
20591               case 9:  // result = lea base(cond, cond*8)
20592                 isFastMultiplier = true;
20593                 break;
20594             }
20595           }
20596
20597           if (isFastMultiplier) {
20598             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20599             if (NeedsCondInvert) // Invert the condition if needed.
20600               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20601                                  DAG.getConstant(1, Cond.getValueType()));
20602
20603             // Zero extend the condition if needed.
20604             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20605                                Cond);
20606             // Scale the condition by the difference.
20607             if (Diff != 1)
20608               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20609                                  DAG.getConstant(Diff, Cond.getValueType()));
20610
20611             // Add the base if non-zero.
20612             if (FalseC->getAPIntValue() != 0)
20613               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20614                                  SDValue(FalseC, 0));
20615             return Cond;
20616           }
20617         }
20618       }
20619   }
20620
20621   // Canonicalize max and min:
20622   // (x > y) ? x : y -> (x >= y) ? x : y
20623   // (x < y) ? x : y -> (x <= y) ? x : y
20624   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20625   // the need for an extra compare
20626   // against zero. e.g.
20627   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20628   // subl   %esi, %edi
20629   // testl  %edi, %edi
20630   // movl   $0, %eax
20631   // cmovgl %edi, %eax
20632   // =>
20633   // xorl   %eax, %eax
20634   // subl   %esi, $edi
20635   // cmovsl %eax, %edi
20636   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20637       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20638       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20639     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20640     switch (CC) {
20641     default: break;
20642     case ISD::SETLT:
20643     case ISD::SETGT: {
20644       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20645       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20646                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20647       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20648     }
20649     }
20650   }
20651
20652   // Early exit check
20653   if (!TLI.isTypeLegal(VT))
20654     return SDValue();
20655
20656   // Match VSELECTs into subs with unsigned saturation.
20657   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20658       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20659       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20660        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20661     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20662
20663     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20664     // left side invert the predicate to simplify logic below.
20665     SDValue Other;
20666     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20667       Other = RHS;
20668       CC = ISD::getSetCCInverse(CC, true);
20669     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20670       Other = LHS;
20671     }
20672
20673     if (Other.getNode() && Other->getNumOperands() == 2 &&
20674         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20675       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20676       SDValue CondRHS = Cond->getOperand(1);
20677
20678       // Look for a general sub with unsigned saturation first.
20679       // x >= y ? x-y : 0 --> subus x, y
20680       // x >  y ? x-y : 0 --> subus x, y
20681       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20682           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20683         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20684
20685       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20686         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20687           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20688             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20689               // If the RHS is a constant we have to reverse the const
20690               // canonicalization.
20691               // x > C-1 ? x+-C : 0 --> subus x, C
20692               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20693                   CondRHSConst->getAPIntValue() ==
20694                       (-OpRHSConst->getAPIntValue() - 1))
20695                 return DAG.getNode(
20696                     X86ISD::SUBUS, DL, VT, OpLHS,
20697                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20698
20699           // Another special case: If C was a sign bit, the sub has been
20700           // canonicalized into a xor.
20701           // FIXME: Would it be better to use computeKnownBits to determine
20702           //        whether it's safe to decanonicalize the xor?
20703           // x s< 0 ? x^C : 0 --> subus x, C
20704           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20705               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20706               OpRHSConst->getAPIntValue().isSignBit())
20707             // Note that we have to rebuild the RHS constant here to ensure we
20708             // don't rely on particular values of undef lanes.
20709             return DAG.getNode(
20710                 X86ISD::SUBUS, DL, VT, OpLHS,
20711                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20712         }
20713     }
20714   }
20715
20716   // Try to match a min/max vector operation.
20717   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20718     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20719     unsigned Opc = ret.first;
20720     bool NeedSplit = ret.second;
20721
20722     if (Opc && NeedSplit) {
20723       unsigned NumElems = VT.getVectorNumElements();
20724       // Extract the LHS vectors
20725       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20726       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20727
20728       // Extract the RHS vectors
20729       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20730       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20731
20732       // Create min/max for each subvector
20733       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20734       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20735
20736       // Merge the result
20737       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20738     } else if (Opc)
20739       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20740   }
20741
20742   // Simplify vector selection if condition value type matches vselect
20743   // operand type
20744   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
20745     assert(Cond.getValueType().isVector() &&
20746            "vector select expects a vector selector!");
20747
20748     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20749     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20750
20751     // Try invert the condition if true value is not all 1s and false value
20752     // is not all 0s.
20753     if (!TValIsAllOnes && !FValIsAllZeros &&
20754         // Check if the selector will be produced by CMPP*/PCMP*
20755         Cond.getOpcode() == ISD::SETCC &&
20756         // Check if SETCC has already been promoted
20757         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
20758       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20759       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20760
20761       if (TValIsAllZeros || FValIsAllOnes) {
20762         SDValue CC = Cond.getOperand(2);
20763         ISD::CondCode NewCC =
20764           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20765                                Cond.getOperand(0).getValueType().isInteger());
20766         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20767         std::swap(LHS, RHS);
20768         TValIsAllOnes = FValIsAllOnes;
20769         FValIsAllZeros = TValIsAllZeros;
20770       }
20771     }
20772
20773     if (TValIsAllOnes || FValIsAllZeros) {
20774       SDValue Ret;
20775
20776       if (TValIsAllOnes && FValIsAllZeros)
20777         Ret = Cond;
20778       else if (TValIsAllOnes)
20779         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20780                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20781       else if (FValIsAllZeros)
20782         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20783                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20784
20785       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20786     }
20787   }
20788
20789   // If we know that this node is legal then we know that it is going to be
20790   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20791   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20792   // to simplify previous instructions.
20793   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20794       !DCI.isBeforeLegalize() &&
20795       // We explicitly check against SSE4.1, v8i16 and v16i16 because, although
20796       // vselect nodes may be marked as Custom, they might only be legal when
20797       // Cond is a build_vector of constants. This will be taken care in
20798       // a later condition.
20799       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) &&
20800        Subtarget->hasSSE41() && VT != MVT::v16i16 && VT != MVT::v8i16) &&
20801       // Don't optimize vector of constants. Those are handled by
20802       // the generic code and all the bits must be properly set for
20803       // the generic optimizer.
20804       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
20805     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20806
20807     // Don't optimize vector selects that map to mask-registers.
20808     if (BitWidth == 1)
20809       return SDValue();
20810
20811     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20812     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20813
20814     APInt KnownZero, KnownOne;
20815     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20816                                           DCI.isBeforeLegalizeOps());
20817     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20818         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
20819                                  TLO)) {
20820       // If we changed the computation somewhere in the DAG, this change
20821       // will affect all users of Cond.
20822       // Make sure it is fine and update all the nodes so that we do not
20823       // use the generic VSELECT anymore. Otherwise, we may perform
20824       // wrong optimizations as we messed up with the actual expectation
20825       // for the vector boolean values.
20826       if (Cond != TLO.Old) {
20827         // Check all uses of that condition operand to check whether it will be
20828         // consumed by non-BLEND instructions, which may depend on all bits are
20829         // set properly.
20830         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20831              I != E; ++I)
20832           if (I->getOpcode() != ISD::VSELECT)
20833             // TODO: Add other opcodes eventually lowered into BLEND.
20834             return SDValue();
20835
20836         // Update all the users of the condition, before committing the change,
20837         // so that the VSELECT optimizations that expect the correct vector
20838         // boolean value will not be triggered.
20839         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20840              I != E; ++I)
20841           DAG.ReplaceAllUsesOfValueWith(
20842               SDValue(*I, 0),
20843               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
20844                           Cond, I->getOperand(1), I->getOperand(2)));
20845         DCI.CommitTargetLoweringOpt(TLO);
20846         return SDValue();
20847       }
20848       // At this point, only Cond is changed. Change the condition
20849       // just for N to keep the opportunity to optimize all other
20850       // users their own way.
20851       DAG.ReplaceAllUsesOfValueWith(
20852           SDValue(N, 0),
20853           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
20854                       TLO.New, N->getOperand(1), N->getOperand(2)));
20855       return SDValue();
20856     }
20857   }
20858
20859   // We should generate an X86ISD::BLENDI from a vselect if its argument
20860   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20861   // constants. This specific pattern gets generated when we split a
20862   // selector for a 512 bit vector in a machine without AVX512 (but with
20863   // 256-bit vectors), during legalization:
20864   //
20865   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20866   //
20867   // Iff we find this pattern and the build_vectors are built from
20868   // constants, we translate the vselect into a shuffle_vector that we
20869   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20870   if ((N->getOpcode() == ISD::VSELECT ||
20871        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
20872       !DCI.isBeforeLegalize()) {
20873     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20874     if (Shuffle.getNode())
20875       return Shuffle;
20876   }
20877
20878   return SDValue();
20879 }
20880
20881 // Check whether a boolean test is testing a boolean value generated by
20882 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20883 // code.
20884 //
20885 // Simplify the following patterns:
20886 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20887 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20888 // to (Op EFLAGS Cond)
20889 //
20890 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20891 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20892 // to (Op EFLAGS !Cond)
20893 //
20894 // where Op could be BRCOND or CMOV.
20895 //
20896 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20897   // Quit if not CMP and SUB with its value result used.
20898   if (Cmp.getOpcode() != X86ISD::CMP &&
20899       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20900       return SDValue();
20901
20902   // Quit if not used as a boolean value.
20903   if (CC != X86::COND_E && CC != X86::COND_NE)
20904     return SDValue();
20905
20906   // Check CMP operands. One of them should be 0 or 1 and the other should be
20907   // an SetCC or extended from it.
20908   SDValue Op1 = Cmp.getOperand(0);
20909   SDValue Op2 = Cmp.getOperand(1);
20910
20911   SDValue SetCC;
20912   const ConstantSDNode* C = nullptr;
20913   bool needOppositeCond = (CC == X86::COND_E);
20914   bool checkAgainstTrue = false; // Is it a comparison against 1?
20915
20916   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20917     SetCC = Op2;
20918   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20919     SetCC = Op1;
20920   else // Quit if all operands are not constants.
20921     return SDValue();
20922
20923   if (C->getZExtValue() == 1) {
20924     needOppositeCond = !needOppositeCond;
20925     checkAgainstTrue = true;
20926   } else if (C->getZExtValue() != 0)
20927     // Quit if the constant is neither 0 or 1.
20928     return SDValue();
20929
20930   bool truncatedToBoolWithAnd = false;
20931   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20932   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20933          SetCC.getOpcode() == ISD::TRUNCATE ||
20934          SetCC.getOpcode() == ISD::AND) {
20935     if (SetCC.getOpcode() == ISD::AND) {
20936       int OpIdx = -1;
20937       ConstantSDNode *CS;
20938       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20939           CS->getZExtValue() == 1)
20940         OpIdx = 1;
20941       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20942           CS->getZExtValue() == 1)
20943         OpIdx = 0;
20944       if (OpIdx == -1)
20945         break;
20946       SetCC = SetCC.getOperand(OpIdx);
20947       truncatedToBoolWithAnd = true;
20948     } else
20949       SetCC = SetCC.getOperand(0);
20950   }
20951
20952   switch (SetCC.getOpcode()) {
20953   case X86ISD::SETCC_CARRY:
20954     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20955     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20956     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20957     // truncated to i1 using 'and'.
20958     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20959       break;
20960     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20961            "Invalid use of SETCC_CARRY!");
20962     // FALL THROUGH
20963   case X86ISD::SETCC:
20964     // Set the condition code or opposite one if necessary.
20965     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20966     if (needOppositeCond)
20967       CC = X86::GetOppositeBranchCondition(CC);
20968     return SetCC.getOperand(1);
20969   case X86ISD::CMOV: {
20970     // Check whether false/true value has canonical one, i.e. 0 or 1.
20971     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20972     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20973     // Quit if true value is not a constant.
20974     if (!TVal)
20975       return SDValue();
20976     // Quit if false value is not a constant.
20977     if (!FVal) {
20978       SDValue Op = SetCC.getOperand(0);
20979       // Skip 'zext' or 'trunc' node.
20980       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20981           Op.getOpcode() == ISD::TRUNCATE)
20982         Op = Op.getOperand(0);
20983       // A special case for rdrand/rdseed, where 0 is set if false cond is
20984       // found.
20985       if ((Op.getOpcode() != X86ISD::RDRAND &&
20986            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20987         return SDValue();
20988     }
20989     // Quit if false value is not the constant 0 or 1.
20990     bool FValIsFalse = true;
20991     if (FVal && FVal->getZExtValue() != 0) {
20992       if (FVal->getZExtValue() != 1)
20993         return SDValue();
20994       // If FVal is 1, opposite cond is needed.
20995       needOppositeCond = !needOppositeCond;
20996       FValIsFalse = false;
20997     }
20998     // Quit if TVal is not the constant opposite of FVal.
20999     if (FValIsFalse && TVal->getZExtValue() != 1)
21000       return SDValue();
21001     if (!FValIsFalse && TVal->getZExtValue() != 0)
21002       return SDValue();
21003     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21004     if (needOppositeCond)
21005       CC = X86::GetOppositeBranchCondition(CC);
21006     return SetCC.getOperand(3);
21007   }
21008   }
21009
21010   return SDValue();
21011 }
21012
21013 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21014 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21015                                   TargetLowering::DAGCombinerInfo &DCI,
21016                                   const X86Subtarget *Subtarget) {
21017   SDLoc DL(N);
21018
21019   // If the flag operand isn't dead, don't touch this CMOV.
21020   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21021     return SDValue();
21022
21023   SDValue FalseOp = N->getOperand(0);
21024   SDValue TrueOp = N->getOperand(1);
21025   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21026   SDValue Cond = N->getOperand(3);
21027
21028   if (CC == X86::COND_E || CC == X86::COND_NE) {
21029     switch (Cond.getOpcode()) {
21030     default: break;
21031     case X86ISD::BSR:
21032     case X86ISD::BSF:
21033       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21034       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21035         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21036     }
21037   }
21038
21039   SDValue Flags;
21040
21041   Flags = checkBoolTestSetCCCombine(Cond, CC);
21042   if (Flags.getNode() &&
21043       // Extra check as FCMOV only supports a subset of X86 cond.
21044       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21045     SDValue Ops[] = { FalseOp, TrueOp,
21046                       DAG.getConstant(CC, MVT::i8), Flags };
21047     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21048   }
21049
21050   // If this is a select between two integer constants, try to do some
21051   // optimizations.  Note that the operands are ordered the opposite of SELECT
21052   // operands.
21053   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21054     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21055       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21056       // larger than FalseC (the false value).
21057       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21058         CC = X86::GetOppositeBranchCondition(CC);
21059         std::swap(TrueC, FalseC);
21060         std::swap(TrueOp, FalseOp);
21061       }
21062
21063       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21064       // This is efficient for any integer data type (including i8/i16) and
21065       // shift amount.
21066       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21067         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21068                            DAG.getConstant(CC, MVT::i8), Cond);
21069
21070         // Zero extend the condition if needed.
21071         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21072
21073         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21074         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21075                            DAG.getConstant(ShAmt, MVT::i8));
21076         if (N->getNumValues() == 2)  // Dead flag value?
21077           return DCI.CombineTo(N, Cond, SDValue());
21078         return Cond;
21079       }
21080
21081       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21082       // for any integer data type, including i8/i16.
21083       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21084         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21085                            DAG.getConstant(CC, MVT::i8), Cond);
21086
21087         // Zero extend the condition if needed.
21088         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21089                            FalseC->getValueType(0), Cond);
21090         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21091                            SDValue(FalseC, 0));
21092
21093         if (N->getNumValues() == 2)  // Dead flag value?
21094           return DCI.CombineTo(N, Cond, SDValue());
21095         return Cond;
21096       }
21097
21098       // Optimize cases that will turn into an LEA instruction.  This requires
21099       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21100       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21101         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21102         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21103
21104         bool isFastMultiplier = false;
21105         if (Diff < 10) {
21106           switch ((unsigned char)Diff) {
21107           default: break;
21108           case 1:  // result = add base, cond
21109           case 2:  // result = lea base(    , cond*2)
21110           case 3:  // result = lea base(cond, cond*2)
21111           case 4:  // result = lea base(    , cond*4)
21112           case 5:  // result = lea base(cond, cond*4)
21113           case 8:  // result = lea base(    , cond*8)
21114           case 9:  // result = lea base(cond, cond*8)
21115             isFastMultiplier = true;
21116             break;
21117           }
21118         }
21119
21120         if (isFastMultiplier) {
21121           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21122           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21123                              DAG.getConstant(CC, MVT::i8), Cond);
21124           // Zero extend the condition if needed.
21125           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21126                              Cond);
21127           // Scale the condition by the difference.
21128           if (Diff != 1)
21129             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21130                                DAG.getConstant(Diff, Cond.getValueType()));
21131
21132           // Add the base if non-zero.
21133           if (FalseC->getAPIntValue() != 0)
21134             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21135                                SDValue(FalseC, 0));
21136           if (N->getNumValues() == 2)  // Dead flag value?
21137             return DCI.CombineTo(N, Cond, SDValue());
21138           return Cond;
21139         }
21140       }
21141     }
21142   }
21143
21144   // Handle these cases:
21145   //   (select (x != c), e, c) -> select (x != c), e, x),
21146   //   (select (x == c), c, e) -> select (x == c), x, e)
21147   // where the c is an integer constant, and the "select" is the combination
21148   // of CMOV and CMP.
21149   //
21150   // The rationale for this change is that the conditional-move from a constant
21151   // needs two instructions, however, conditional-move from a register needs
21152   // only one instruction.
21153   //
21154   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21155   //  some instruction-combining opportunities. This opt needs to be
21156   //  postponed as late as possible.
21157   //
21158   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21159     // the DCI.xxxx conditions are provided to postpone the optimization as
21160     // late as possible.
21161
21162     ConstantSDNode *CmpAgainst = nullptr;
21163     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21164         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21165         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21166
21167       if (CC == X86::COND_NE &&
21168           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21169         CC = X86::GetOppositeBranchCondition(CC);
21170         std::swap(TrueOp, FalseOp);
21171       }
21172
21173       if (CC == X86::COND_E &&
21174           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21175         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21176                           DAG.getConstant(CC, MVT::i8), Cond };
21177         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21178       }
21179     }
21180   }
21181
21182   return SDValue();
21183 }
21184
21185 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21186                                                 const X86Subtarget *Subtarget) {
21187   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21188   switch (IntNo) {
21189   default: return SDValue();
21190   // SSE/AVX/AVX2 blend intrinsics.
21191   case Intrinsic::x86_avx2_pblendvb:
21192   case Intrinsic::x86_avx2_pblendw:
21193   case Intrinsic::x86_avx2_pblendd_128:
21194   case Intrinsic::x86_avx2_pblendd_256:
21195     // Don't try to simplify this intrinsic if we don't have AVX2.
21196     if (!Subtarget->hasAVX2())
21197       return SDValue();
21198     // FALL-THROUGH
21199   case Intrinsic::x86_avx_blend_pd_256:
21200   case Intrinsic::x86_avx_blend_ps_256:
21201   case Intrinsic::x86_avx_blendv_pd_256:
21202   case Intrinsic::x86_avx_blendv_ps_256:
21203     // Don't try to simplify this intrinsic if we don't have AVX.
21204     if (!Subtarget->hasAVX())
21205       return SDValue();
21206     // FALL-THROUGH
21207   case Intrinsic::x86_sse41_pblendw:
21208   case Intrinsic::x86_sse41_blendpd:
21209   case Intrinsic::x86_sse41_blendps:
21210   case Intrinsic::x86_sse41_blendvps:
21211   case Intrinsic::x86_sse41_blendvpd:
21212   case Intrinsic::x86_sse41_pblendvb: {
21213     SDValue Op0 = N->getOperand(1);
21214     SDValue Op1 = N->getOperand(2);
21215     SDValue Mask = N->getOperand(3);
21216
21217     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21218     if (!Subtarget->hasSSE41())
21219       return SDValue();
21220
21221     // fold (blend A, A, Mask) -> A
21222     if (Op0 == Op1)
21223       return Op0;
21224     // fold (blend A, B, allZeros) -> A
21225     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21226       return Op0;
21227     // fold (blend A, B, allOnes) -> B
21228     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21229       return Op1;
21230
21231     // Simplify the case where the mask is a constant i32 value.
21232     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21233       if (C->isNullValue())
21234         return Op0;
21235       if (C->isAllOnesValue())
21236         return Op1;
21237     }
21238
21239     return SDValue();
21240   }
21241
21242   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21243   case Intrinsic::x86_sse2_psrai_w:
21244   case Intrinsic::x86_sse2_psrai_d:
21245   case Intrinsic::x86_avx2_psrai_w:
21246   case Intrinsic::x86_avx2_psrai_d:
21247   case Intrinsic::x86_sse2_psra_w:
21248   case Intrinsic::x86_sse2_psra_d:
21249   case Intrinsic::x86_avx2_psra_w:
21250   case Intrinsic::x86_avx2_psra_d: {
21251     SDValue Op0 = N->getOperand(1);
21252     SDValue Op1 = N->getOperand(2);
21253     EVT VT = Op0.getValueType();
21254     assert(VT.isVector() && "Expected a vector type!");
21255
21256     if (isa<BuildVectorSDNode>(Op1))
21257       Op1 = Op1.getOperand(0);
21258
21259     if (!isa<ConstantSDNode>(Op1))
21260       return SDValue();
21261
21262     EVT SVT = VT.getVectorElementType();
21263     unsigned SVTBits = SVT.getSizeInBits();
21264
21265     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21266     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21267     uint64_t ShAmt = C.getZExtValue();
21268
21269     // Don't try to convert this shift into a ISD::SRA if the shift
21270     // count is bigger than or equal to the element size.
21271     if (ShAmt >= SVTBits)
21272       return SDValue();
21273
21274     // Trivial case: if the shift count is zero, then fold this
21275     // into the first operand.
21276     if (ShAmt == 0)
21277       return Op0;
21278
21279     // Replace this packed shift intrinsic with a target independent
21280     // shift dag node.
21281     SDValue Splat = DAG.getConstant(C, VT);
21282     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21283   }
21284   }
21285 }
21286
21287 /// PerformMulCombine - Optimize a single multiply with constant into two
21288 /// in order to implement it with two cheaper instructions, e.g.
21289 /// LEA + SHL, LEA + LEA.
21290 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21291                                  TargetLowering::DAGCombinerInfo &DCI) {
21292   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21293     return SDValue();
21294
21295   EVT VT = N->getValueType(0);
21296   if (VT != MVT::i64 && VT != MVT::i32)
21297     return SDValue();
21298
21299   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21300   if (!C)
21301     return SDValue();
21302   uint64_t MulAmt = C->getZExtValue();
21303   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21304     return SDValue();
21305
21306   uint64_t MulAmt1 = 0;
21307   uint64_t MulAmt2 = 0;
21308   if ((MulAmt % 9) == 0) {
21309     MulAmt1 = 9;
21310     MulAmt2 = MulAmt / 9;
21311   } else if ((MulAmt % 5) == 0) {
21312     MulAmt1 = 5;
21313     MulAmt2 = MulAmt / 5;
21314   } else if ((MulAmt % 3) == 0) {
21315     MulAmt1 = 3;
21316     MulAmt2 = MulAmt / 3;
21317   }
21318   if (MulAmt2 &&
21319       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21320     SDLoc DL(N);
21321
21322     if (isPowerOf2_64(MulAmt2) &&
21323         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21324       // If second multiplifer is pow2, issue it first. We want the multiply by
21325       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21326       // is an add.
21327       std::swap(MulAmt1, MulAmt2);
21328
21329     SDValue NewMul;
21330     if (isPowerOf2_64(MulAmt1))
21331       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21332                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21333     else
21334       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21335                            DAG.getConstant(MulAmt1, VT));
21336
21337     if (isPowerOf2_64(MulAmt2))
21338       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21339                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21340     else
21341       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21342                            DAG.getConstant(MulAmt2, VT));
21343
21344     // Do not add new nodes to DAG combiner worklist.
21345     DCI.CombineTo(N, NewMul, false);
21346   }
21347   return SDValue();
21348 }
21349
21350 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21351   SDValue N0 = N->getOperand(0);
21352   SDValue N1 = N->getOperand(1);
21353   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21354   EVT VT = N0.getValueType();
21355
21356   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21357   // since the result of setcc_c is all zero's or all ones.
21358   if (VT.isInteger() && !VT.isVector() &&
21359       N1C && N0.getOpcode() == ISD::AND &&
21360       N0.getOperand(1).getOpcode() == ISD::Constant) {
21361     SDValue N00 = N0.getOperand(0);
21362     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21363         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21364           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21365          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21366       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21367       APInt ShAmt = N1C->getAPIntValue();
21368       Mask = Mask.shl(ShAmt);
21369       if (Mask != 0)
21370         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21371                            N00, DAG.getConstant(Mask, VT));
21372     }
21373   }
21374
21375   // Hardware support for vector shifts is sparse which makes us scalarize the
21376   // vector operations in many cases. Also, on sandybridge ADD is faster than
21377   // shl.
21378   // (shl V, 1) -> add V,V
21379   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21380     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21381       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21382       // We shift all of the values by one. In many cases we do not have
21383       // hardware support for this operation. This is better expressed as an ADD
21384       // of two values.
21385       if (N1SplatC->getZExtValue() == 1)
21386         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21387     }
21388
21389   return SDValue();
21390 }
21391
21392 /// \brief Returns a vector of 0s if the node in input is a vector logical
21393 /// shift by a constant amount which is known to be bigger than or equal
21394 /// to the vector element size in bits.
21395 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21396                                       const X86Subtarget *Subtarget) {
21397   EVT VT = N->getValueType(0);
21398
21399   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21400       (!Subtarget->hasInt256() ||
21401        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21402     return SDValue();
21403
21404   SDValue Amt = N->getOperand(1);
21405   SDLoc DL(N);
21406   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21407     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21408       APInt ShiftAmt = AmtSplat->getAPIntValue();
21409       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21410
21411       // SSE2/AVX2 logical shifts always return a vector of 0s
21412       // if the shift amount is bigger than or equal to
21413       // the element size. The constant shift amount will be
21414       // encoded as a 8-bit immediate.
21415       if (ShiftAmt.trunc(8).uge(MaxAmount))
21416         return getZeroVector(VT, Subtarget, DAG, DL);
21417     }
21418
21419   return SDValue();
21420 }
21421
21422 /// PerformShiftCombine - Combine shifts.
21423 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21424                                    TargetLowering::DAGCombinerInfo &DCI,
21425                                    const X86Subtarget *Subtarget) {
21426   if (N->getOpcode() == ISD::SHL) {
21427     SDValue V = PerformSHLCombine(N, DAG);
21428     if (V.getNode()) return V;
21429   }
21430
21431   if (N->getOpcode() != ISD::SRA) {
21432     // Try to fold this logical shift into a zero vector.
21433     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21434     if (V.getNode()) return V;
21435   }
21436
21437   return SDValue();
21438 }
21439
21440 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21441 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21442 // and friends.  Likewise for OR -> CMPNEQSS.
21443 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21444                             TargetLowering::DAGCombinerInfo &DCI,
21445                             const X86Subtarget *Subtarget) {
21446   unsigned opcode;
21447
21448   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21449   // we're requiring SSE2 for both.
21450   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21451     SDValue N0 = N->getOperand(0);
21452     SDValue N1 = N->getOperand(1);
21453     SDValue CMP0 = N0->getOperand(1);
21454     SDValue CMP1 = N1->getOperand(1);
21455     SDLoc DL(N);
21456
21457     // The SETCCs should both refer to the same CMP.
21458     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21459       return SDValue();
21460
21461     SDValue CMP00 = CMP0->getOperand(0);
21462     SDValue CMP01 = CMP0->getOperand(1);
21463     EVT     VT    = CMP00.getValueType();
21464
21465     if (VT == MVT::f32 || VT == MVT::f64) {
21466       bool ExpectingFlags = false;
21467       // Check for any users that want flags:
21468       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21469            !ExpectingFlags && UI != UE; ++UI)
21470         switch (UI->getOpcode()) {
21471         default:
21472         case ISD::BR_CC:
21473         case ISD::BRCOND:
21474         case ISD::SELECT:
21475           ExpectingFlags = true;
21476           break;
21477         case ISD::CopyToReg:
21478         case ISD::SIGN_EXTEND:
21479         case ISD::ZERO_EXTEND:
21480         case ISD::ANY_EXTEND:
21481           break;
21482         }
21483
21484       if (!ExpectingFlags) {
21485         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21486         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21487
21488         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21489           X86::CondCode tmp = cc0;
21490           cc0 = cc1;
21491           cc1 = tmp;
21492         }
21493
21494         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21495             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21496           // FIXME: need symbolic constants for these magic numbers.
21497           // See X86ATTInstPrinter.cpp:printSSECC().
21498           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21499           if (Subtarget->hasAVX512()) {
21500             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21501                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21502             if (N->getValueType(0) != MVT::i1)
21503               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21504                                  FSetCC);
21505             return FSetCC;
21506           }
21507           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21508                                               CMP00.getValueType(), CMP00, CMP01,
21509                                               DAG.getConstant(x86cc, MVT::i8));
21510
21511           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21512           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21513
21514           if (is64BitFP && !Subtarget->is64Bit()) {
21515             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21516             // 64-bit integer, since that's not a legal type. Since
21517             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21518             // bits, but can do this little dance to extract the lowest 32 bits
21519             // and work with those going forward.
21520             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21521                                            OnesOrZeroesF);
21522             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21523                                            Vector64);
21524             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21525                                         Vector32, DAG.getIntPtrConstant(0));
21526             IntVT = MVT::i32;
21527           }
21528
21529           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21530           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21531                                       DAG.getConstant(1, IntVT));
21532           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21533           return OneBitOfTruth;
21534         }
21535       }
21536     }
21537   }
21538   return SDValue();
21539 }
21540
21541 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21542 /// so it can be folded inside ANDNP.
21543 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21544   EVT VT = N->getValueType(0);
21545
21546   // Match direct AllOnes for 128 and 256-bit vectors
21547   if (ISD::isBuildVectorAllOnes(N))
21548     return true;
21549
21550   // Look through a bit convert.
21551   if (N->getOpcode() == ISD::BITCAST)
21552     N = N->getOperand(0).getNode();
21553
21554   // Sometimes the operand may come from a insert_subvector building a 256-bit
21555   // allones vector
21556   if (VT.is256BitVector() &&
21557       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21558     SDValue V1 = N->getOperand(0);
21559     SDValue V2 = N->getOperand(1);
21560
21561     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21562         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21563         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21564         ISD::isBuildVectorAllOnes(V2.getNode()))
21565       return true;
21566   }
21567
21568   return false;
21569 }
21570
21571 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21572 // register. In most cases we actually compare or select YMM-sized registers
21573 // and mixing the two types creates horrible code. This method optimizes
21574 // some of the transition sequences.
21575 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21576                                  TargetLowering::DAGCombinerInfo &DCI,
21577                                  const X86Subtarget *Subtarget) {
21578   EVT VT = N->getValueType(0);
21579   if (!VT.is256BitVector())
21580     return SDValue();
21581
21582   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21583           N->getOpcode() == ISD::ZERO_EXTEND ||
21584           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21585
21586   SDValue Narrow = N->getOperand(0);
21587   EVT NarrowVT = Narrow->getValueType(0);
21588   if (!NarrowVT.is128BitVector())
21589     return SDValue();
21590
21591   if (Narrow->getOpcode() != ISD::XOR &&
21592       Narrow->getOpcode() != ISD::AND &&
21593       Narrow->getOpcode() != ISD::OR)
21594     return SDValue();
21595
21596   SDValue N0  = Narrow->getOperand(0);
21597   SDValue N1  = Narrow->getOperand(1);
21598   SDLoc DL(Narrow);
21599
21600   // The Left side has to be a trunc.
21601   if (N0.getOpcode() != ISD::TRUNCATE)
21602     return SDValue();
21603
21604   // The type of the truncated inputs.
21605   EVT WideVT = N0->getOperand(0)->getValueType(0);
21606   if (WideVT != VT)
21607     return SDValue();
21608
21609   // The right side has to be a 'trunc' or a constant vector.
21610   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21611   ConstantSDNode *RHSConstSplat = nullptr;
21612   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21613     RHSConstSplat = RHSBV->getConstantSplatNode();
21614   if (!RHSTrunc && !RHSConstSplat)
21615     return SDValue();
21616
21617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21618
21619   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21620     return SDValue();
21621
21622   // Set N0 and N1 to hold the inputs to the new wide operation.
21623   N0 = N0->getOperand(0);
21624   if (RHSConstSplat) {
21625     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21626                      SDValue(RHSConstSplat, 0));
21627     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21628     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21629   } else if (RHSTrunc) {
21630     N1 = N1->getOperand(0);
21631   }
21632
21633   // Generate the wide operation.
21634   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21635   unsigned Opcode = N->getOpcode();
21636   switch (Opcode) {
21637   case ISD::ANY_EXTEND:
21638     return Op;
21639   case ISD::ZERO_EXTEND: {
21640     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21641     APInt Mask = APInt::getAllOnesValue(InBits);
21642     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21643     return DAG.getNode(ISD::AND, DL, VT,
21644                        Op, DAG.getConstant(Mask, VT));
21645   }
21646   case ISD::SIGN_EXTEND:
21647     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21648                        Op, DAG.getValueType(NarrowVT));
21649   default:
21650     llvm_unreachable("Unexpected opcode");
21651   }
21652 }
21653
21654 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
21655                                  TargetLowering::DAGCombinerInfo &DCI,
21656                                  const X86Subtarget *Subtarget) {
21657   SDValue N0 = N->getOperand(0);
21658   SDValue N1 = N->getOperand(1);
21659   SDLoc DL(N);
21660
21661   // A vector zext_in_reg may be represented as a shuffle,
21662   // feeding into a bitcast (this represents anyext) feeding into
21663   // an and with a mask.
21664   // We'd like to try to combine that into a shuffle with zero
21665   // plus a bitcast, removing the and.
21666   if (N0.getOpcode() != ISD::BITCAST || 
21667       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
21668     return SDValue();
21669
21670   // The other side of the AND should be a splat of 2^C, where C
21671   // is the number of bits in the source type.
21672   if (N1.getOpcode() == ISD::BITCAST)
21673     N1 = N1.getOperand(0);
21674   if (N1.getOpcode() != ISD::BUILD_VECTOR)
21675     return SDValue();
21676   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
21677
21678   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
21679   EVT SrcType = Shuffle->getValueType(0);
21680
21681   // We expect a single-source shuffle
21682   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
21683     return SDValue();
21684
21685   unsigned SrcSize = SrcType.getScalarSizeInBits();
21686
21687   APInt SplatValue, SplatUndef;
21688   unsigned SplatBitSize;
21689   bool HasAnyUndefs;
21690   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
21691                                 SplatBitSize, HasAnyUndefs))
21692     return SDValue();
21693
21694   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
21695   // Make sure the splat matches the mask we expect
21696   if (SplatBitSize > ResSize || 
21697       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
21698     return SDValue();
21699
21700   // Make sure the input and output size make sense
21701   if (SrcSize >= ResSize || ResSize % SrcSize)
21702     return SDValue();
21703
21704   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
21705   // The number of u's between each two values depends on the ratio between
21706   // the source and dest type.
21707   unsigned ZextRatio = ResSize / SrcSize;
21708   bool IsZext = true;
21709   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
21710     if (i % ZextRatio) {
21711       if (Shuffle->getMaskElt(i) > 0) {
21712         // Expected undef
21713         IsZext = false;
21714         break;
21715       }
21716     } else {
21717       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
21718         // Expected element number
21719         IsZext = false;
21720         break;
21721       }
21722     }
21723   }
21724
21725   if (!IsZext)
21726     return SDValue();
21727
21728   // Ok, perform the transformation - replace the shuffle with
21729   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
21730   // (instead of undef) where the k elements come from the zero vector.
21731   SmallVector<int, 8> Mask;
21732   unsigned NumElems = SrcType.getVectorNumElements();
21733   for (unsigned i = 0; i < NumElems; ++i)
21734     if (i % ZextRatio)
21735       Mask.push_back(NumElems);
21736     else
21737       Mask.push_back(i / ZextRatio);
21738
21739   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
21740     Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
21741   return DAG.getNode(ISD::BITCAST, DL,  N0.getValueType(), NewShuffle);
21742 }
21743
21744 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21745                                  TargetLowering::DAGCombinerInfo &DCI,
21746                                  const X86Subtarget *Subtarget) {
21747   if (DCI.isBeforeLegalizeOps())
21748     return SDValue();
21749
21750   SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget);
21751   if (Zext.getNode())
21752     return Zext;
21753
21754   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21755   if (R.getNode())
21756     return R;
21757
21758   EVT VT = N->getValueType(0);
21759   SDValue N0 = N->getOperand(0);
21760   SDValue N1 = N->getOperand(1);
21761   SDLoc DL(N);
21762
21763   // Create BEXTR instructions
21764   // BEXTR is ((X >> imm) & (2**size-1))
21765   if (VT == MVT::i32 || VT == MVT::i64) {
21766     // Check for BEXTR.
21767     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21768         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21769       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21770       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21771       if (MaskNode && ShiftNode) {
21772         uint64_t Mask = MaskNode->getZExtValue();
21773         uint64_t Shift = ShiftNode->getZExtValue();
21774         if (isMask_64(Mask)) {
21775           uint64_t MaskSize = countPopulation(Mask);
21776           if (Shift + MaskSize <= VT.getSizeInBits())
21777             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21778                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21779         }
21780       }
21781     } // BEXTR
21782
21783     return SDValue();
21784   }
21785
21786   // Want to form ANDNP nodes:
21787   // 1) In the hopes of then easily combining them with OR and AND nodes
21788   //    to form PBLEND/PSIGN.
21789   // 2) To match ANDN packed intrinsics
21790   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21791     return SDValue();
21792
21793   // Check LHS for vnot
21794   if (N0.getOpcode() == ISD::XOR &&
21795       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21796       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21797     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21798
21799   // Check RHS for vnot
21800   if (N1.getOpcode() == ISD::XOR &&
21801       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21802       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21803     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21804
21805   return SDValue();
21806 }
21807
21808 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21809                                 TargetLowering::DAGCombinerInfo &DCI,
21810                                 const X86Subtarget *Subtarget) {
21811   if (DCI.isBeforeLegalizeOps())
21812     return SDValue();
21813
21814   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21815   if (R.getNode())
21816     return R;
21817
21818   SDValue N0 = N->getOperand(0);
21819   SDValue N1 = N->getOperand(1);
21820   EVT VT = N->getValueType(0);
21821
21822   // look for psign/blend
21823   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21824     if (!Subtarget->hasSSSE3() ||
21825         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21826       return SDValue();
21827
21828     // Canonicalize pandn to RHS
21829     if (N0.getOpcode() == X86ISD::ANDNP)
21830       std::swap(N0, N1);
21831     // or (and (m, y), (pandn m, x))
21832     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21833       SDValue Mask = N1.getOperand(0);
21834       SDValue X    = N1.getOperand(1);
21835       SDValue Y;
21836       if (N0.getOperand(0) == Mask)
21837         Y = N0.getOperand(1);
21838       if (N0.getOperand(1) == Mask)
21839         Y = N0.getOperand(0);
21840
21841       // Check to see if the mask appeared in both the AND and ANDNP and
21842       if (!Y.getNode())
21843         return SDValue();
21844
21845       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21846       // Look through mask bitcast.
21847       if (Mask.getOpcode() == ISD::BITCAST)
21848         Mask = Mask.getOperand(0);
21849       if (X.getOpcode() == ISD::BITCAST)
21850         X = X.getOperand(0);
21851       if (Y.getOpcode() == ISD::BITCAST)
21852         Y = Y.getOperand(0);
21853
21854       EVT MaskVT = Mask.getValueType();
21855
21856       // Validate that the Mask operand is a vector sra node.
21857       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21858       // there is no psrai.b
21859       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21860       unsigned SraAmt = ~0;
21861       if (Mask.getOpcode() == ISD::SRA) {
21862         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21863           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21864             SraAmt = AmtConst->getZExtValue();
21865       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21866         SDValue SraC = Mask.getOperand(1);
21867         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21868       }
21869       if ((SraAmt + 1) != EltBits)
21870         return SDValue();
21871
21872       SDLoc DL(N);
21873
21874       // Now we know we at least have a plendvb with the mask val.  See if
21875       // we can form a psignb/w/d.
21876       // psign = x.type == y.type == mask.type && y = sub(0, x);
21877       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21878           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21879           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21880         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21881                "Unsupported VT for PSIGN");
21882         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21883         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21884       }
21885       // PBLENDVB only available on SSE 4.1
21886       if (!Subtarget->hasSSE41())
21887         return SDValue();
21888
21889       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21890
21891       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21892       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21893       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21894       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21895       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21896     }
21897   }
21898
21899   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21900     return SDValue();
21901
21902   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21903   MachineFunction &MF = DAG.getMachineFunction();
21904   bool OptForSize =
21905       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
21906
21907   // SHLD/SHRD instructions have lower register pressure, but on some
21908   // platforms they have higher latency than the equivalent
21909   // series of shifts/or that would otherwise be generated.
21910   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21911   // have higher latencies and we are not optimizing for size.
21912   if (!OptForSize && Subtarget->isSHLDSlow())
21913     return SDValue();
21914
21915   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21916     std::swap(N0, N1);
21917   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21918     return SDValue();
21919   if (!N0.hasOneUse() || !N1.hasOneUse())
21920     return SDValue();
21921
21922   SDValue ShAmt0 = N0.getOperand(1);
21923   if (ShAmt0.getValueType() != MVT::i8)
21924     return SDValue();
21925   SDValue ShAmt1 = N1.getOperand(1);
21926   if (ShAmt1.getValueType() != MVT::i8)
21927     return SDValue();
21928   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21929     ShAmt0 = ShAmt0.getOperand(0);
21930   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21931     ShAmt1 = ShAmt1.getOperand(0);
21932
21933   SDLoc DL(N);
21934   unsigned Opc = X86ISD::SHLD;
21935   SDValue Op0 = N0.getOperand(0);
21936   SDValue Op1 = N1.getOperand(0);
21937   if (ShAmt0.getOpcode() == ISD::SUB) {
21938     Opc = X86ISD::SHRD;
21939     std::swap(Op0, Op1);
21940     std::swap(ShAmt0, ShAmt1);
21941   }
21942
21943   unsigned Bits = VT.getSizeInBits();
21944   if (ShAmt1.getOpcode() == ISD::SUB) {
21945     SDValue Sum = ShAmt1.getOperand(0);
21946     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21947       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21948       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21949         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21950       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21951         return DAG.getNode(Opc, DL, VT,
21952                            Op0, Op1,
21953                            DAG.getNode(ISD::TRUNCATE, DL,
21954                                        MVT::i8, ShAmt0));
21955     }
21956   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21957     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21958     if (ShAmt0C &&
21959         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21960       return DAG.getNode(Opc, DL, VT,
21961                          N0.getOperand(0), N1.getOperand(0),
21962                          DAG.getNode(ISD::TRUNCATE, DL,
21963                                        MVT::i8, ShAmt0));
21964   }
21965
21966   return SDValue();
21967 }
21968
21969 // Generate NEG and CMOV for integer abs.
21970 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21971   EVT VT = N->getValueType(0);
21972
21973   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21974   // 8-bit integer abs to NEG and CMOV.
21975   if (VT.isInteger() && VT.getSizeInBits() == 8)
21976     return SDValue();
21977
21978   SDValue N0 = N->getOperand(0);
21979   SDValue N1 = N->getOperand(1);
21980   SDLoc DL(N);
21981
21982   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21983   // and change it to SUB and CMOV.
21984   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21985       N0.getOpcode() == ISD::ADD &&
21986       N0.getOperand(1) == N1 &&
21987       N1.getOpcode() == ISD::SRA &&
21988       N1.getOperand(0) == N0.getOperand(0))
21989     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21990       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21991         // Generate SUB & CMOV.
21992         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21993                                   DAG.getConstant(0, VT), N0.getOperand(0));
21994
21995         SDValue Ops[] = { N0.getOperand(0), Neg,
21996                           DAG.getConstant(X86::COND_GE, MVT::i8),
21997                           SDValue(Neg.getNode(), 1) };
21998         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21999       }
22000   return SDValue();
22001 }
22002
22003 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22004 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22005                                  TargetLowering::DAGCombinerInfo &DCI,
22006                                  const X86Subtarget *Subtarget) {
22007   if (DCI.isBeforeLegalizeOps())
22008     return SDValue();
22009
22010   if (Subtarget->hasCMov()) {
22011     SDValue RV = performIntegerAbsCombine(N, DAG);
22012     if (RV.getNode())
22013       return RV;
22014   }
22015
22016   return SDValue();
22017 }
22018
22019 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22020 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22021                                   TargetLowering::DAGCombinerInfo &DCI,
22022                                   const X86Subtarget *Subtarget) {
22023   LoadSDNode *Ld = cast<LoadSDNode>(N);
22024   EVT RegVT = Ld->getValueType(0);
22025   EVT MemVT = Ld->getMemoryVT();
22026   SDLoc dl(Ld);
22027   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22028
22029   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22030   // into two 16-byte operations.
22031   ISD::LoadExtType Ext = Ld->getExtensionType();
22032   unsigned Alignment = Ld->getAlignment();
22033   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22034   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22035       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22036     unsigned NumElems = RegVT.getVectorNumElements();
22037     if (NumElems < 2)
22038       return SDValue();
22039
22040     SDValue Ptr = Ld->getBasePtr();
22041     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22042
22043     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22044                                   NumElems/2);
22045     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22046                                 Ld->getPointerInfo(), Ld->isVolatile(),
22047                                 Ld->isNonTemporal(), Ld->isInvariant(),
22048                                 Alignment);
22049     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22050     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22051                                 Ld->getPointerInfo(), Ld->isVolatile(),
22052                                 Ld->isNonTemporal(), Ld->isInvariant(),
22053                                 std::min(16U, Alignment));
22054     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22055                              Load1.getValue(1),
22056                              Load2.getValue(1));
22057
22058     SDValue NewVec = DAG.getUNDEF(RegVT);
22059     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22060     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22061     return DCI.CombineTo(N, NewVec, TF, true);
22062   }
22063
22064   return SDValue();
22065 }
22066
22067 /// PerformMLOADCombine - Resolve extending loads
22068 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22069                                    TargetLowering::DAGCombinerInfo &DCI,
22070                                    const X86Subtarget *Subtarget) {
22071   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22072   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22073     return SDValue();
22074
22075   EVT VT = Mld->getValueType(0);
22076   unsigned NumElems = VT.getVectorNumElements();
22077   EVT LdVT = Mld->getMemoryVT();
22078   SDLoc dl(Mld);
22079
22080   assert(LdVT != VT && "Cannot extend to the same type");
22081   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22082   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22083   // From, To sizes and ElemCount must be pow of two
22084   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22085     "Unexpected size for extending masked load");
22086
22087   unsigned SizeRatio  = ToSz / FromSz;
22088   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22089
22090   // Create a type on which we perform the shuffle
22091   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22092           LdVT.getScalarType(), NumElems*SizeRatio);
22093   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22094
22095   // Convert Src0 value
22096   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22097   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22098     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22099     for (unsigned i = 0; i != NumElems; ++i)
22100       ShuffleVec[i] = i * SizeRatio;
22101
22102     // Can't shuffle using an illegal type.
22103     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22104             && "WideVecVT should be legal");
22105     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22106                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22107   }
22108   // Prepare the new mask
22109   SDValue NewMask;
22110   SDValue Mask = Mld->getMask();
22111   if (Mask.getValueType() == VT) {
22112     // Mask and original value have the same type
22113     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22114     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22115     for (unsigned i = 0; i != NumElems; ++i)
22116       ShuffleVec[i] = i * SizeRatio;
22117     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22118       ShuffleVec[i] = NumElems*SizeRatio;
22119     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22120                                    DAG.getConstant(0, WideVecVT),
22121                                    &ShuffleVec[0]);
22122   }
22123   else {
22124     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22125     unsigned WidenNumElts = NumElems*SizeRatio;
22126     unsigned MaskNumElts = VT.getVectorNumElements();
22127     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22128                                      WidenNumElts);
22129
22130     unsigned NumConcat = WidenNumElts / MaskNumElts;
22131     SmallVector<SDValue, 16> Ops(NumConcat);
22132     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22133     Ops[0] = Mask;
22134     for (unsigned i = 1; i != NumConcat; ++i)
22135       Ops[i] = ZeroVal;
22136
22137     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22138   }
22139
22140   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22141                                      Mld->getBasePtr(), NewMask, WideSrc0,
22142                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22143                                      ISD::NON_EXTLOAD);
22144   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22145   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22146
22147 }
22148 /// PerformMSTORECombine - Resolve truncating stores
22149 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22150                                     const X86Subtarget *Subtarget) {
22151   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22152   if (!Mst->isTruncatingStore())
22153     return SDValue();
22154
22155   EVT VT = Mst->getValue().getValueType();
22156   unsigned NumElems = VT.getVectorNumElements();
22157   EVT StVT = Mst->getMemoryVT();
22158   SDLoc dl(Mst);
22159
22160   assert(StVT != VT && "Cannot truncate to the same type");
22161   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22162   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22163
22164   // From, To sizes and ElemCount must be pow of two
22165   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22166     "Unexpected size for truncating masked store");
22167   // We are going to use the original vector elt for storing.
22168   // Accumulated smaller vector elements must be a multiple of the store size.
22169   assert (((NumElems * FromSz) % ToSz) == 0 &&
22170           "Unexpected ratio for truncating masked store");
22171
22172   unsigned SizeRatio  = FromSz / ToSz;
22173   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22174
22175   // Create a type on which we perform the shuffle
22176   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22177           StVT.getScalarType(), NumElems*SizeRatio);
22178
22179   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22180
22181   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22182   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22183   for (unsigned i = 0; i != NumElems; ++i)
22184     ShuffleVec[i] = i * SizeRatio;
22185
22186   // Can't shuffle using an illegal type.
22187   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22188           && "WideVecVT should be legal");
22189
22190   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22191                                         DAG.getUNDEF(WideVecVT),
22192                                         &ShuffleVec[0]);
22193
22194   SDValue NewMask;
22195   SDValue Mask = Mst->getMask();
22196   if (Mask.getValueType() == VT) {
22197     // Mask and original value have the same type
22198     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22199     for (unsigned i = 0; i != NumElems; ++i)
22200       ShuffleVec[i] = i * SizeRatio;
22201     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22202       ShuffleVec[i] = NumElems*SizeRatio;
22203     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22204                                    DAG.getConstant(0, WideVecVT),
22205                                    &ShuffleVec[0]);
22206   }
22207   else {
22208     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22209     unsigned WidenNumElts = NumElems*SizeRatio;
22210     unsigned MaskNumElts = VT.getVectorNumElements();
22211     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22212                                      WidenNumElts);
22213
22214     unsigned NumConcat = WidenNumElts / MaskNumElts;
22215     SmallVector<SDValue, 16> Ops(NumConcat);
22216     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22217     Ops[0] = Mask;
22218     for (unsigned i = 1; i != NumConcat; ++i)
22219       Ops[i] = ZeroVal;
22220
22221     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22222   }
22223
22224   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22225                             NewMask, StVT, Mst->getMemOperand(), false);
22226 }
22227 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22228 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22229                                    const X86Subtarget *Subtarget) {
22230   StoreSDNode *St = cast<StoreSDNode>(N);
22231   EVT VT = St->getValue().getValueType();
22232   EVT StVT = St->getMemoryVT();
22233   SDLoc dl(St);
22234   SDValue StoredVal = St->getOperand(1);
22235   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22236
22237   // If we are saving a concatenation of two XMM registers and 32-byte stores
22238   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22239   unsigned Alignment = St->getAlignment();
22240   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22241   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22242       StVT == VT && !IsAligned) {
22243     unsigned NumElems = VT.getVectorNumElements();
22244     if (NumElems < 2)
22245       return SDValue();
22246
22247     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22248     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22249
22250     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22251     SDValue Ptr0 = St->getBasePtr();
22252     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22253
22254     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22255                                 St->getPointerInfo(), St->isVolatile(),
22256                                 St->isNonTemporal(), Alignment);
22257     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22258                                 St->getPointerInfo(), St->isVolatile(),
22259                                 St->isNonTemporal(),
22260                                 std::min(16U, Alignment));
22261     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22262   }
22263
22264   // Optimize trunc store (of multiple scalars) to shuffle and store.
22265   // First, pack all of the elements in one place. Next, store to memory
22266   // in fewer chunks.
22267   if (St->isTruncatingStore() && VT.isVector()) {
22268     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22269     unsigned NumElems = VT.getVectorNumElements();
22270     assert(StVT != VT && "Cannot truncate to the same type");
22271     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22272     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22273
22274     // From, To sizes and ElemCount must be pow of two
22275     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22276     // We are going to use the original vector elt for storing.
22277     // Accumulated smaller vector elements must be a multiple of the store size.
22278     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22279
22280     unsigned SizeRatio  = FromSz / ToSz;
22281
22282     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22283
22284     // Create a type on which we perform the shuffle
22285     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22286             StVT.getScalarType(), NumElems*SizeRatio);
22287
22288     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22289
22290     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22291     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22292     for (unsigned i = 0; i != NumElems; ++i)
22293       ShuffleVec[i] = i * SizeRatio;
22294
22295     // Can't shuffle using an illegal type.
22296     if (!TLI.isTypeLegal(WideVecVT))
22297       return SDValue();
22298
22299     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22300                                          DAG.getUNDEF(WideVecVT),
22301                                          &ShuffleVec[0]);
22302     // At this point all of the data is stored at the bottom of the
22303     // register. We now need to save it to mem.
22304
22305     // Find the largest store unit
22306     MVT StoreType = MVT::i8;
22307     for (MVT Tp : MVT::integer_valuetypes()) {
22308       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22309         StoreType = Tp;
22310     }
22311
22312     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22313     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22314         (64 <= NumElems * ToSz))
22315       StoreType = MVT::f64;
22316
22317     // Bitcast the original vector into a vector of store-size units
22318     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22319             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22320     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22321     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22322     SmallVector<SDValue, 8> Chains;
22323     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22324                                         TLI.getPointerTy());
22325     SDValue Ptr = St->getBasePtr();
22326
22327     // Perform one or more big stores into memory.
22328     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22329       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22330                                    StoreType, ShuffWide,
22331                                    DAG.getIntPtrConstant(i));
22332       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22333                                 St->getPointerInfo(), St->isVolatile(),
22334                                 St->isNonTemporal(), St->getAlignment());
22335       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22336       Chains.push_back(Ch);
22337     }
22338
22339     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22340   }
22341
22342   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22343   // the FP state in cases where an emms may be missing.
22344   // A preferable solution to the general problem is to figure out the right
22345   // places to insert EMMS.  This qualifies as a quick hack.
22346
22347   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22348   if (VT.getSizeInBits() != 64)
22349     return SDValue();
22350
22351   const Function *F = DAG.getMachineFunction().getFunction();
22352   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22353   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22354                      && Subtarget->hasSSE2();
22355   if ((VT.isVector() ||
22356        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22357       isa<LoadSDNode>(St->getValue()) &&
22358       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22359       St->getChain().hasOneUse() && !St->isVolatile()) {
22360     SDNode* LdVal = St->getValue().getNode();
22361     LoadSDNode *Ld = nullptr;
22362     int TokenFactorIndex = -1;
22363     SmallVector<SDValue, 8> Ops;
22364     SDNode* ChainVal = St->getChain().getNode();
22365     // Must be a store of a load.  We currently handle two cases:  the load
22366     // is a direct child, and it's under an intervening TokenFactor.  It is
22367     // possible to dig deeper under nested TokenFactors.
22368     if (ChainVal == LdVal)
22369       Ld = cast<LoadSDNode>(St->getChain());
22370     else if (St->getValue().hasOneUse() &&
22371              ChainVal->getOpcode() == ISD::TokenFactor) {
22372       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22373         if (ChainVal->getOperand(i).getNode() == LdVal) {
22374           TokenFactorIndex = i;
22375           Ld = cast<LoadSDNode>(St->getValue());
22376         } else
22377           Ops.push_back(ChainVal->getOperand(i));
22378       }
22379     }
22380
22381     if (!Ld || !ISD::isNormalLoad(Ld))
22382       return SDValue();
22383
22384     // If this is not the MMX case, i.e. we are just turning i64 load/store
22385     // into f64 load/store, avoid the transformation if there are multiple
22386     // uses of the loaded value.
22387     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22388       return SDValue();
22389
22390     SDLoc LdDL(Ld);
22391     SDLoc StDL(N);
22392     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22393     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22394     // pair instead.
22395     if (Subtarget->is64Bit() || F64IsLegal) {
22396       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22397       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22398                                   Ld->getPointerInfo(), Ld->isVolatile(),
22399                                   Ld->isNonTemporal(), Ld->isInvariant(),
22400                                   Ld->getAlignment());
22401       SDValue NewChain = NewLd.getValue(1);
22402       if (TokenFactorIndex != -1) {
22403         Ops.push_back(NewChain);
22404         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22405       }
22406       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22407                           St->getPointerInfo(),
22408                           St->isVolatile(), St->isNonTemporal(),
22409                           St->getAlignment());
22410     }
22411
22412     // Otherwise, lower to two pairs of 32-bit loads / stores.
22413     SDValue LoAddr = Ld->getBasePtr();
22414     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22415                                  DAG.getConstant(4, MVT::i32));
22416
22417     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22418                                Ld->getPointerInfo(),
22419                                Ld->isVolatile(), Ld->isNonTemporal(),
22420                                Ld->isInvariant(), Ld->getAlignment());
22421     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22422                                Ld->getPointerInfo().getWithOffset(4),
22423                                Ld->isVolatile(), Ld->isNonTemporal(),
22424                                Ld->isInvariant(),
22425                                MinAlign(Ld->getAlignment(), 4));
22426
22427     SDValue NewChain = LoLd.getValue(1);
22428     if (TokenFactorIndex != -1) {
22429       Ops.push_back(LoLd);
22430       Ops.push_back(HiLd);
22431       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22432     }
22433
22434     LoAddr = St->getBasePtr();
22435     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22436                          DAG.getConstant(4, MVT::i32));
22437
22438     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22439                                 St->getPointerInfo(),
22440                                 St->isVolatile(), St->isNonTemporal(),
22441                                 St->getAlignment());
22442     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22443                                 St->getPointerInfo().getWithOffset(4),
22444                                 St->isVolatile(),
22445                                 St->isNonTemporal(),
22446                                 MinAlign(St->getAlignment(), 4));
22447     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22448   }
22449   return SDValue();
22450 }
22451
22452 /// Return 'true' if this vector operation is "horizontal"
22453 /// and return the operands for the horizontal operation in LHS and RHS.  A
22454 /// horizontal operation performs the binary operation on successive elements
22455 /// of its first operand, then on successive elements of its second operand,
22456 /// returning the resulting values in a vector.  For example, if
22457 ///   A = < float a0, float a1, float a2, float a3 >
22458 /// and
22459 ///   B = < float b0, float b1, float b2, float b3 >
22460 /// then the result of doing a horizontal operation on A and B is
22461 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22462 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22463 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22464 /// set to A, RHS to B, and the routine returns 'true'.
22465 /// Note that the binary operation should have the property that if one of the
22466 /// operands is UNDEF then the result is UNDEF.
22467 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22468   // Look for the following pattern: if
22469   //   A = < float a0, float a1, float a2, float a3 >
22470   //   B = < float b0, float b1, float b2, float b3 >
22471   // and
22472   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22473   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22474   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22475   // which is A horizontal-op B.
22476
22477   // At least one of the operands should be a vector shuffle.
22478   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22479       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22480     return false;
22481
22482   MVT VT = LHS.getSimpleValueType();
22483
22484   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22485          "Unsupported vector type for horizontal add/sub");
22486
22487   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22488   // operate independently on 128-bit lanes.
22489   unsigned NumElts = VT.getVectorNumElements();
22490   unsigned NumLanes = VT.getSizeInBits()/128;
22491   unsigned NumLaneElts = NumElts / NumLanes;
22492   assert((NumLaneElts % 2 == 0) &&
22493          "Vector type should have an even number of elements in each lane");
22494   unsigned HalfLaneElts = NumLaneElts/2;
22495
22496   // View LHS in the form
22497   //   LHS = VECTOR_SHUFFLE A, B, LMask
22498   // If LHS is not a shuffle then pretend it is the shuffle
22499   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22500   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22501   // type VT.
22502   SDValue A, B;
22503   SmallVector<int, 16> LMask(NumElts);
22504   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22505     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22506       A = LHS.getOperand(0);
22507     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22508       B = LHS.getOperand(1);
22509     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22510     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22511   } else {
22512     if (LHS.getOpcode() != ISD::UNDEF)
22513       A = LHS;
22514     for (unsigned i = 0; i != NumElts; ++i)
22515       LMask[i] = i;
22516   }
22517
22518   // Likewise, view RHS in the form
22519   //   RHS = VECTOR_SHUFFLE C, D, RMask
22520   SDValue C, D;
22521   SmallVector<int, 16> RMask(NumElts);
22522   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22523     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22524       C = RHS.getOperand(0);
22525     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22526       D = RHS.getOperand(1);
22527     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22528     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22529   } else {
22530     if (RHS.getOpcode() != ISD::UNDEF)
22531       C = RHS;
22532     for (unsigned i = 0; i != NumElts; ++i)
22533       RMask[i] = i;
22534   }
22535
22536   // Check that the shuffles are both shuffling the same vectors.
22537   if (!(A == C && B == D) && !(A == D && B == C))
22538     return false;
22539
22540   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22541   if (!A.getNode() && !B.getNode())
22542     return false;
22543
22544   // If A and B occur in reverse order in RHS, then "swap" them (which means
22545   // rewriting the mask).
22546   if (A != C)
22547     CommuteVectorShuffleMask(RMask, NumElts);
22548
22549   // At this point LHS and RHS are equivalent to
22550   //   LHS = VECTOR_SHUFFLE A, B, LMask
22551   //   RHS = VECTOR_SHUFFLE A, B, RMask
22552   // Check that the masks correspond to performing a horizontal operation.
22553   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22554     for (unsigned i = 0; i != NumLaneElts; ++i) {
22555       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22556
22557       // Ignore any UNDEF components.
22558       if (LIdx < 0 || RIdx < 0 ||
22559           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22560           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22561         continue;
22562
22563       // Check that successive elements are being operated on.  If not, this is
22564       // not a horizontal operation.
22565       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22566       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22567       if (!(LIdx == Index && RIdx == Index + 1) &&
22568           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22569         return false;
22570     }
22571   }
22572
22573   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22574   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22575   return true;
22576 }
22577
22578 /// Do target-specific dag combines on floating point adds.
22579 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22580                                   const X86Subtarget *Subtarget) {
22581   EVT VT = N->getValueType(0);
22582   SDValue LHS = N->getOperand(0);
22583   SDValue RHS = N->getOperand(1);
22584
22585   // Try to synthesize horizontal adds from adds of shuffles.
22586   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22587        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22588       isHorizontalBinOp(LHS, RHS, true))
22589     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22590   return SDValue();
22591 }
22592
22593 /// Do target-specific dag combines on floating point subs.
22594 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22595                                   const X86Subtarget *Subtarget) {
22596   EVT VT = N->getValueType(0);
22597   SDValue LHS = N->getOperand(0);
22598   SDValue RHS = N->getOperand(1);
22599
22600   // Try to synthesize horizontal subs from subs of shuffles.
22601   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22602        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22603       isHorizontalBinOp(LHS, RHS, false))
22604     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22605   return SDValue();
22606 }
22607
22608 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
22609 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22610   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22611
22612   // F[X]OR(0.0, x) -> x
22613   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22614     if (C->getValueAPF().isPosZero())
22615       return N->getOperand(1);
22616
22617   // F[X]OR(x, 0.0) -> x
22618   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22619     if (C->getValueAPF().isPosZero())
22620       return N->getOperand(0);
22621   return SDValue();
22622 }
22623
22624 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
22625 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22626   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22627
22628   // Only perform optimizations if UnsafeMath is used.
22629   if (!DAG.getTarget().Options.UnsafeFPMath)
22630     return SDValue();
22631
22632   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22633   // into FMINC and FMAXC, which are Commutative operations.
22634   unsigned NewOp = 0;
22635   switch (N->getOpcode()) {
22636     default: llvm_unreachable("unknown opcode");
22637     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22638     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22639   }
22640
22641   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22642                      N->getOperand(0), N->getOperand(1));
22643 }
22644
22645 /// Do target-specific dag combines on X86ISD::FAND nodes.
22646 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22647   // FAND(0.0, x) -> 0.0
22648   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22649     if (C->getValueAPF().isPosZero())
22650       return N->getOperand(0);
22651
22652   // FAND(x, 0.0) -> 0.0
22653   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22654     if (C->getValueAPF().isPosZero())
22655       return N->getOperand(1);
22656   
22657   return SDValue();
22658 }
22659
22660 /// Do target-specific dag combines on X86ISD::FANDN nodes
22661 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22662   // FANDN(0.0, x) -> x
22663   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22664     if (C->getValueAPF().isPosZero())
22665       return N->getOperand(1);
22666
22667   // FANDN(x, 0.0) -> 0.0
22668   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22669     if (C->getValueAPF().isPosZero())
22670       return N->getOperand(1);
22671
22672   return SDValue();
22673 }
22674
22675 static SDValue PerformBTCombine(SDNode *N,
22676                                 SelectionDAG &DAG,
22677                                 TargetLowering::DAGCombinerInfo &DCI) {
22678   // BT ignores high bits in the bit index operand.
22679   SDValue Op1 = N->getOperand(1);
22680   if (Op1.hasOneUse()) {
22681     unsigned BitWidth = Op1.getValueSizeInBits();
22682     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22683     APInt KnownZero, KnownOne;
22684     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22685                                           !DCI.isBeforeLegalizeOps());
22686     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22687     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22688         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22689       DCI.CommitTargetLoweringOpt(TLO);
22690   }
22691   return SDValue();
22692 }
22693
22694 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22695   SDValue Op = N->getOperand(0);
22696   if (Op.getOpcode() == ISD::BITCAST)
22697     Op = Op.getOperand(0);
22698   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22699   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22700       VT.getVectorElementType().getSizeInBits() ==
22701       OpVT.getVectorElementType().getSizeInBits()) {
22702     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22703   }
22704   return SDValue();
22705 }
22706
22707 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22708                                                const X86Subtarget *Subtarget) {
22709   EVT VT = N->getValueType(0);
22710   if (!VT.isVector())
22711     return SDValue();
22712
22713   SDValue N0 = N->getOperand(0);
22714   SDValue N1 = N->getOperand(1);
22715   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22716   SDLoc dl(N);
22717
22718   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22719   // both SSE and AVX2 since there is no sign-extended shift right
22720   // operation on a vector with 64-bit elements.
22721   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22722   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22723   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22724       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22725     SDValue N00 = N0.getOperand(0);
22726
22727     // EXTLOAD has a better solution on AVX2,
22728     // it may be replaced with X86ISD::VSEXT node.
22729     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22730       if (!ISD::isNormalLoad(N00.getNode()))
22731         return SDValue();
22732
22733     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22734         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22735                                   N00, N1);
22736       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22737     }
22738   }
22739   return SDValue();
22740 }
22741
22742 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22743                                   TargetLowering::DAGCombinerInfo &DCI,
22744                                   const X86Subtarget *Subtarget) {
22745   SDValue N0 = N->getOperand(0);
22746   EVT VT = N->getValueType(0);
22747
22748   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
22749   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
22750   // This exposes the sext to the sdivrem lowering, so that it directly extends
22751   // from AH (which we otherwise need to do contortions to access).
22752   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
22753       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
22754     SDLoc dl(N);
22755     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
22756     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
22757                             N0.getOperand(0), N0.getOperand(1));
22758     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
22759     return R.getValue(1);
22760   }
22761
22762   if (!DCI.isBeforeLegalizeOps())
22763     return SDValue();
22764
22765   if (!Subtarget->hasFp256())
22766     return SDValue();
22767
22768   if (VT.isVector() && VT.getSizeInBits() == 256) {
22769     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22770     if (R.getNode())
22771       return R;
22772   }
22773
22774   return SDValue();
22775 }
22776
22777 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22778                                  const X86Subtarget* Subtarget) {
22779   SDLoc dl(N);
22780   EVT VT = N->getValueType(0);
22781
22782   // Let legalize expand this if it isn't a legal type yet.
22783   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22784     return SDValue();
22785
22786   EVT ScalarVT = VT.getScalarType();
22787   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22788       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22789     return SDValue();
22790
22791   SDValue A = N->getOperand(0);
22792   SDValue B = N->getOperand(1);
22793   SDValue C = N->getOperand(2);
22794
22795   bool NegA = (A.getOpcode() == ISD::FNEG);
22796   bool NegB = (B.getOpcode() == ISD::FNEG);
22797   bool NegC = (C.getOpcode() == ISD::FNEG);
22798
22799   // Negative multiplication when NegA xor NegB
22800   bool NegMul = (NegA != NegB);
22801   if (NegA)
22802     A = A.getOperand(0);
22803   if (NegB)
22804     B = B.getOperand(0);
22805   if (NegC)
22806     C = C.getOperand(0);
22807
22808   unsigned Opcode;
22809   if (!NegMul)
22810     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22811   else
22812     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22813
22814   return DAG.getNode(Opcode, dl, VT, A, B, C);
22815 }
22816
22817 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22818                                   TargetLowering::DAGCombinerInfo &DCI,
22819                                   const X86Subtarget *Subtarget) {
22820   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22821   //           (and (i32 x86isd::setcc_carry), 1)
22822   // This eliminates the zext. This transformation is necessary because
22823   // ISD::SETCC is always legalized to i8.
22824   SDLoc dl(N);
22825   SDValue N0 = N->getOperand(0);
22826   EVT VT = N->getValueType(0);
22827
22828   if (N0.getOpcode() == ISD::AND &&
22829       N0.hasOneUse() &&
22830       N0.getOperand(0).hasOneUse()) {
22831     SDValue N00 = N0.getOperand(0);
22832     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22833       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22834       if (!C || C->getZExtValue() != 1)
22835         return SDValue();
22836       return DAG.getNode(ISD::AND, dl, VT,
22837                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22838                                      N00.getOperand(0), N00.getOperand(1)),
22839                          DAG.getConstant(1, VT));
22840     }
22841   }
22842
22843   if (N0.getOpcode() == ISD::TRUNCATE &&
22844       N0.hasOneUse() &&
22845       N0.getOperand(0).hasOneUse()) {
22846     SDValue N00 = N0.getOperand(0);
22847     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22848       return DAG.getNode(ISD::AND, dl, VT,
22849                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22850                                      N00.getOperand(0), N00.getOperand(1)),
22851                          DAG.getConstant(1, VT));
22852     }
22853   }
22854   if (VT.is256BitVector()) {
22855     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22856     if (R.getNode())
22857       return R;
22858   }
22859
22860   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
22861   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
22862   // This exposes the zext to the udivrem lowering, so that it directly extends
22863   // from AH (which we otherwise need to do contortions to access).
22864   if (N0.getOpcode() == ISD::UDIVREM &&
22865       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
22866       (VT == MVT::i32 || VT == MVT::i64)) {
22867     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
22868     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
22869                             N0.getOperand(0), N0.getOperand(1));
22870     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
22871     return R.getValue(1);
22872   }
22873
22874   return SDValue();
22875 }
22876
22877 // Optimize x == -y --> x+y == 0
22878 //          x != -y --> x+y != 0
22879 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22880                                       const X86Subtarget* Subtarget) {
22881   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22882   SDValue LHS = N->getOperand(0);
22883   SDValue RHS = N->getOperand(1);
22884   EVT VT = N->getValueType(0);
22885   SDLoc DL(N);
22886
22887   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22888     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22889       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22890         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22891                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22892         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22893                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22894       }
22895   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22896     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22897       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22898         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22899                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22900         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22901                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22902       }
22903
22904   if (VT.getScalarType() == MVT::i1) {
22905     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22906       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22907     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22908     if (!IsSEXT0 && !IsVZero0)
22909       return SDValue();
22910     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22911       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22912     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22913
22914     if (!IsSEXT1 && !IsVZero1)
22915       return SDValue();
22916
22917     if (IsSEXT0 && IsVZero1) {
22918       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22919       if (CC == ISD::SETEQ)
22920         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22921       return LHS.getOperand(0);
22922     }
22923     if (IsSEXT1 && IsVZero0) {
22924       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22925       if (CC == ISD::SETEQ)
22926         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22927       return RHS.getOperand(0);
22928     }
22929   }
22930
22931   return SDValue();
22932 }
22933
22934 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
22935                                          SelectionDAG &DAG) {
22936   SDLoc dl(Load);
22937   MVT VT = Load->getSimpleValueType(0);
22938   MVT EVT = VT.getVectorElementType();
22939   SDValue Addr = Load->getOperand(1);
22940   SDValue NewAddr = DAG.getNode(
22941       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
22942       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
22943
22944   SDValue NewLoad =
22945       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
22946                   DAG.getMachineFunction().getMachineMemOperand(
22947                       Load->getMemOperand(), 0, EVT.getStoreSize()));
22948   return NewLoad;
22949 }
22950
22951 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22952                                       const X86Subtarget *Subtarget) {
22953   SDLoc dl(N);
22954   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22955   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22956          "X86insertps is only defined for v4x32");
22957
22958   SDValue Ld = N->getOperand(1);
22959   if (MayFoldLoad(Ld)) {
22960     // Extract the countS bits from the immediate so we can get the proper
22961     // address when narrowing the vector load to a specific element.
22962     // When the second source op is a memory address, interps doesn't use
22963     // countS and just gets an f32 from that address.
22964     unsigned DestIndex =
22965         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22966     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22967   } else
22968     return SDValue();
22969
22970   // Create this as a scalar to vector to match the instruction pattern.
22971   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22972   // countS bits are ignored when loading from memory on insertps, which
22973   // means we don't need to explicitly set them to 0.
22974   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22975                      LoadScalarToVector, N->getOperand(2));
22976 }
22977
22978 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
22979   SDValue V0 = N->getOperand(0);
22980   SDValue V1 = N->getOperand(1);
22981   SDLoc DL(N);
22982   EVT VT = N->getValueType(0);
22983
22984   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
22985   // operands and changing the mask to 1. This saves us a bunch of
22986   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
22987   // x86InstrInfo knows how to commute this back after instruction selection
22988   // if it would help register allocation.
22989   
22990   // TODO: If optimizing for size or a processor that doesn't suffer from
22991   // partial register update stalls, this should be transformed into a MOVSD
22992   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
22993
22994   if (VT == MVT::v2f64)
22995     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
22996       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
22997         SDValue NewMask = DAG.getConstant(1, MVT::i8);
22998         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
22999       }
23000
23001   return SDValue();
23002 }
23003
23004 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23005 // as "sbb reg,reg", since it can be extended without zext and produces
23006 // an all-ones bit which is more useful than 0/1 in some cases.
23007 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23008                                MVT VT) {
23009   if (VT == MVT::i8)
23010     return DAG.getNode(ISD::AND, DL, VT,
23011                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23012                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23013                        DAG.getConstant(1, VT));
23014   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23015   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23016                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23017                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23018 }
23019
23020 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23021 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23022                                    TargetLowering::DAGCombinerInfo &DCI,
23023                                    const X86Subtarget *Subtarget) {
23024   SDLoc DL(N);
23025   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23026   SDValue EFLAGS = N->getOperand(1);
23027
23028   if (CC == X86::COND_A) {
23029     // Try to convert COND_A into COND_B in an attempt to facilitate
23030     // materializing "setb reg".
23031     //
23032     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23033     // cannot take an immediate as its first operand.
23034     //
23035     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23036         EFLAGS.getValueType().isInteger() &&
23037         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23038       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23039                                    EFLAGS.getNode()->getVTList(),
23040                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23041       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23042       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23043     }
23044   }
23045
23046   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23047   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23048   // cases.
23049   if (CC == X86::COND_B)
23050     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23051
23052   SDValue Flags;
23053
23054   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23055   if (Flags.getNode()) {
23056     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23057     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23058   }
23059
23060   return SDValue();
23061 }
23062
23063 // Optimize branch condition evaluation.
23064 //
23065 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23066                                     TargetLowering::DAGCombinerInfo &DCI,
23067                                     const X86Subtarget *Subtarget) {
23068   SDLoc DL(N);
23069   SDValue Chain = N->getOperand(0);
23070   SDValue Dest = N->getOperand(1);
23071   SDValue EFLAGS = N->getOperand(3);
23072   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23073
23074   SDValue Flags;
23075
23076   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23077   if (Flags.getNode()) {
23078     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23079     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23080                        Flags);
23081   }
23082
23083   return SDValue();
23084 }
23085
23086 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23087                                                          SelectionDAG &DAG) {
23088   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23089   // optimize away operation when it's from a constant.
23090   //
23091   // The general transformation is:
23092   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23093   //       AND(VECTOR_CMP(x,y), constant2)
23094   //    constant2 = UNARYOP(constant)
23095
23096   // Early exit if this isn't a vector operation, the operand of the
23097   // unary operation isn't a bitwise AND, or if the sizes of the operations
23098   // aren't the same.
23099   EVT VT = N->getValueType(0);
23100   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23101       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23102       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23103     return SDValue();
23104
23105   // Now check that the other operand of the AND is a constant. We could
23106   // make the transformation for non-constant splats as well, but it's unclear
23107   // that would be a benefit as it would not eliminate any operations, just
23108   // perform one more step in scalar code before moving to the vector unit.
23109   if (BuildVectorSDNode *BV =
23110           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23111     // Bail out if the vector isn't a constant.
23112     if (!BV->isConstant())
23113       return SDValue();
23114
23115     // Everything checks out. Build up the new and improved node.
23116     SDLoc DL(N);
23117     EVT IntVT = BV->getValueType(0);
23118     // Create a new constant of the appropriate type for the transformed
23119     // DAG.
23120     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23121     // The AND node needs bitcasts to/from an integer vector type around it.
23122     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23123     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23124                                  N->getOperand(0)->getOperand(0), MaskConst);
23125     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23126     return Res;
23127   }
23128
23129   return SDValue();
23130 }
23131
23132 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23133                                         const X86Subtarget *Subtarget) {
23134   // First try to optimize away the conversion entirely when it's
23135   // conditionally from a constant. Vectors only.
23136   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23137   if (Res != SDValue())
23138     return Res;
23139
23140   // Now move on to more general possibilities.
23141   SDValue Op0 = N->getOperand(0);
23142   EVT InVT = Op0->getValueType(0);
23143
23144   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23145   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23146     SDLoc dl(N);
23147     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23148     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23149     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23150   }
23151
23152   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23153   // a 32-bit target where SSE doesn't support i64->FP operations.
23154   if (Op0.getOpcode() == ISD::LOAD) {
23155     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23156     EVT VT = Ld->getValueType(0);
23157     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23158         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23159         !Subtarget->is64Bit() && VT == MVT::i64) {
23160       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23161           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23162       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23163       return FILDChain;
23164     }
23165   }
23166   return SDValue();
23167 }
23168
23169 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23170 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23171                                  X86TargetLowering::DAGCombinerInfo &DCI) {
23172   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23173   // the result is either zero or one (depending on the input carry bit).
23174   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23175   if (X86::isZeroNode(N->getOperand(0)) &&
23176       X86::isZeroNode(N->getOperand(1)) &&
23177       // We don't have a good way to replace an EFLAGS use, so only do this when
23178       // dead right now.
23179       SDValue(N, 1).use_empty()) {
23180     SDLoc DL(N);
23181     EVT VT = N->getValueType(0);
23182     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23183     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23184                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23185                                            DAG.getConstant(X86::COND_B,MVT::i8),
23186                                            N->getOperand(2)),
23187                                DAG.getConstant(1, VT));
23188     return DCI.CombineTo(N, Res1, CarryOut);
23189   }
23190
23191   return SDValue();
23192 }
23193
23194 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23195 //      (add Y, (setne X, 0)) -> sbb -1, Y
23196 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23197 //      (sub (setne X, 0), Y) -> adc -1, Y
23198 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23199   SDLoc DL(N);
23200
23201   // Look through ZExts.
23202   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23203   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23204     return SDValue();
23205
23206   SDValue SetCC = Ext.getOperand(0);
23207   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23208     return SDValue();
23209
23210   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23211   if (CC != X86::COND_E && CC != X86::COND_NE)
23212     return SDValue();
23213
23214   SDValue Cmp = SetCC.getOperand(1);
23215   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23216       !X86::isZeroNode(Cmp.getOperand(1)) ||
23217       !Cmp.getOperand(0).getValueType().isInteger())
23218     return SDValue();
23219
23220   SDValue CmpOp0 = Cmp.getOperand(0);
23221   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23222                                DAG.getConstant(1, CmpOp0.getValueType()));
23223
23224   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23225   if (CC == X86::COND_NE)
23226     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23227                        DL, OtherVal.getValueType(), OtherVal,
23228                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23229   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23230                      DL, OtherVal.getValueType(), OtherVal,
23231                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23232 }
23233
23234 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23235 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23236                                  const X86Subtarget *Subtarget) {
23237   EVT VT = N->getValueType(0);
23238   SDValue Op0 = N->getOperand(0);
23239   SDValue Op1 = N->getOperand(1);
23240
23241   // Try to synthesize horizontal adds from adds of shuffles.
23242   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23243        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23244       isHorizontalBinOp(Op0, Op1, true))
23245     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23246
23247   return OptimizeConditionalInDecrement(N, DAG);
23248 }
23249
23250 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23251                                  const X86Subtarget *Subtarget) {
23252   SDValue Op0 = N->getOperand(0);
23253   SDValue Op1 = N->getOperand(1);
23254
23255   // X86 can't encode an immediate LHS of a sub. See if we can push the
23256   // negation into a preceding instruction.
23257   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23258     // If the RHS of the sub is a XOR with one use and a constant, invert the
23259     // immediate. Then add one to the LHS of the sub so we can turn
23260     // X-Y -> X+~Y+1, saving one register.
23261     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23262         isa<ConstantSDNode>(Op1.getOperand(1))) {
23263       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23264       EVT VT = Op0.getValueType();
23265       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23266                                    Op1.getOperand(0),
23267                                    DAG.getConstant(~XorC, VT));
23268       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23269                          DAG.getConstant(C->getAPIntValue()+1, VT));
23270     }
23271   }
23272
23273   // Try to synthesize horizontal adds from adds of shuffles.
23274   EVT VT = N->getValueType(0);
23275   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23276        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23277       isHorizontalBinOp(Op0, Op1, true))
23278     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23279
23280   return OptimizeConditionalInDecrement(N, DAG);
23281 }
23282
23283 /// performVZEXTCombine - Performs build vector combines
23284 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23285                                    TargetLowering::DAGCombinerInfo &DCI,
23286                                    const X86Subtarget *Subtarget) {
23287   SDLoc DL(N);
23288   MVT VT = N->getSimpleValueType(0);
23289   SDValue Op = N->getOperand(0);
23290   MVT OpVT = Op.getSimpleValueType();
23291   MVT OpEltVT = OpVT.getVectorElementType();
23292   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23293
23294   // (vzext (bitcast (vzext (x)) -> (vzext x)
23295   SDValue V = Op;
23296   while (V.getOpcode() == ISD::BITCAST)
23297     V = V.getOperand(0);
23298
23299   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23300     MVT InnerVT = V.getSimpleValueType();
23301     MVT InnerEltVT = InnerVT.getVectorElementType();
23302
23303     // If the element sizes match exactly, we can just do one larger vzext. This
23304     // is always an exact type match as vzext operates on integer types.
23305     if (OpEltVT == InnerEltVT) {
23306       assert(OpVT == InnerVT && "Types must match for vzext!");
23307       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23308     }
23309
23310     // The only other way we can combine them is if only a single element of the
23311     // inner vzext is used in the input to the outer vzext.
23312     if (InnerEltVT.getSizeInBits() < InputBits)
23313       return SDValue();
23314
23315     // In this case, the inner vzext is completely dead because we're going to
23316     // only look at bits inside of the low element. Just do the outer vzext on
23317     // a bitcast of the input to the inner.
23318     return DAG.getNode(X86ISD::VZEXT, DL, VT,
23319                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23320   }
23321
23322   // Check if we can bypass extracting and re-inserting an element of an input
23323   // vector. Essentialy:
23324   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23325   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23326       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23327       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23328     SDValue ExtractedV = V.getOperand(0);
23329     SDValue OrigV = ExtractedV.getOperand(0);
23330     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23331       if (ExtractIdx->getZExtValue() == 0) {
23332         MVT OrigVT = OrigV.getSimpleValueType();
23333         // Extract a subvector if necessary...
23334         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23335           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23336           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23337                                     OrigVT.getVectorNumElements() / Ratio);
23338           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23339                               DAG.getIntPtrConstant(0));
23340         }
23341         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23342         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23343       }
23344   }
23345
23346   return SDValue();
23347 }
23348
23349 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23350                                              DAGCombinerInfo &DCI) const {
23351   SelectionDAG &DAG = DCI.DAG;
23352   switch (N->getOpcode()) {
23353   default: break;
23354   case ISD::EXTRACT_VECTOR_ELT:
23355     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23356   case ISD::VSELECT:
23357   case ISD::SELECT:
23358   case X86ISD::SHRUNKBLEND:
23359     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23360   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
23361   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23362   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23363   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23364   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23365   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23366   case ISD::SHL:
23367   case ISD::SRA:
23368   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23369   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23370   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23371   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23372   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23373   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23374   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23375   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
23376   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23377   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23378   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23379   case X86ISD::FXOR:
23380   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23381   case X86ISD::FMIN:
23382   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23383   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23384   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23385   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23386   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23387   case ISD::ANY_EXTEND:
23388   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23389   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23390   case ISD::SIGN_EXTEND_INREG:
23391     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23392   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23393   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23394   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23395   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23396   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23397   case X86ISD::SHUFP:       // Handle all target specific shuffles
23398   case X86ISD::PALIGNR:
23399   case X86ISD::UNPCKH:
23400   case X86ISD::UNPCKL:
23401   case X86ISD::MOVHLPS:
23402   case X86ISD::MOVLHPS:
23403   case X86ISD::PSHUFB:
23404   case X86ISD::PSHUFD:
23405   case X86ISD::PSHUFHW:
23406   case X86ISD::PSHUFLW:
23407   case X86ISD::MOVSS:
23408   case X86ISD::MOVSD:
23409   case X86ISD::VPERMILPI:
23410   case X86ISD::VPERM2X128:
23411   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23412   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23413   case ISD::INTRINSIC_WO_CHAIN:
23414     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23415   case X86ISD::INSERTPS: {
23416     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23417       return PerformINSERTPSCombine(N, DAG, Subtarget);
23418     break;
23419   }
23420   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
23421   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23422   }
23423
23424   return SDValue();
23425 }
23426
23427 /// isTypeDesirableForOp - Return true if the target has native support for
23428 /// the specified value type and it is 'desirable' to use the type for the
23429 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23430 /// instruction encodings are longer and some i16 instructions are slow.
23431 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23432   if (!isTypeLegal(VT))
23433     return false;
23434   if (VT != MVT::i16)
23435     return true;
23436
23437   switch (Opc) {
23438   default:
23439     return true;
23440   case ISD::LOAD:
23441   case ISD::SIGN_EXTEND:
23442   case ISD::ZERO_EXTEND:
23443   case ISD::ANY_EXTEND:
23444   case ISD::SHL:
23445   case ISD::SRL:
23446   case ISD::SUB:
23447   case ISD::ADD:
23448   case ISD::MUL:
23449   case ISD::AND:
23450   case ISD::OR:
23451   case ISD::XOR:
23452     return false;
23453   }
23454 }
23455
23456 /// IsDesirableToPromoteOp - This method query the target whether it is
23457 /// beneficial for dag combiner to promote the specified node. If true, it
23458 /// should return the desired promotion type by reference.
23459 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23460   EVT VT = Op.getValueType();
23461   if (VT != MVT::i16)
23462     return false;
23463
23464   bool Promote = false;
23465   bool Commute = false;
23466   switch (Op.getOpcode()) {
23467   default: break;
23468   case ISD::LOAD: {
23469     LoadSDNode *LD = cast<LoadSDNode>(Op);
23470     // If the non-extending load has a single use and it's not live out, then it
23471     // might be folded.
23472     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23473                                                      Op.hasOneUse()*/) {
23474       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23475              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23476         // The only case where we'd want to promote LOAD (rather then it being
23477         // promoted as an operand is when it's only use is liveout.
23478         if (UI->getOpcode() != ISD::CopyToReg)
23479           return false;
23480       }
23481     }
23482     Promote = true;
23483     break;
23484   }
23485   case ISD::SIGN_EXTEND:
23486   case ISD::ZERO_EXTEND:
23487   case ISD::ANY_EXTEND:
23488     Promote = true;
23489     break;
23490   case ISD::SHL:
23491   case ISD::SRL: {
23492     SDValue N0 = Op.getOperand(0);
23493     // Look out for (store (shl (load), x)).
23494     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23495       return false;
23496     Promote = true;
23497     break;
23498   }
23499   case ISD::ADD:
23500   case ISD::MUL:
23501   case ISD::AND:
23502   case ISD::OR:
23503   case ISD::XOR:
23504     Commute = true;
23505     // fallthrough
23506   case ISD::SUB: {
23507     SDValue N0 = Op.getOperand(0);
23508     SDValue N1 = Op.getOperand(1);
23509     if (!Commute && MayFoldLoad(N1))
23510       return false;
23511     // Avoid disabling potential load folding opportunities.
23512     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23513       return false;
23514     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23515       return false;
23516     Promote = true;
23517   }
23518   }
23519
23520   PVT = MVT::i32;
23521   return Promote;
23522 }
23523
23524 //===----------------------------------------------------------------------===//
23525 //                           X86 Inline Assembly Support
23526 //===----------------------------------------------------------------------===//
23527
23528 namespace {
23529   // Helper to match a string separated by whitespace.
23530   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
23531     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
23532
23533     for (unsigned i = 0, e = args.size(); i != e; ++i) {
23534       StringRef piece(*args[i]);
23535       if (!s.startswith(piece)) // Check if the piece matches.
23536         return false;
23537
23538       s = s.substr(piece.size());
23539       StringRef::size_type pos = s.find_first_not_of(" \t");
23540       if (pos == 0) // We matched a prefix.
23541         return false;
23542
23543       s = s.substr(pos);
23544     }
23545
23546     return s.empty();
23547   }
23548   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
23549 }
23550
23551 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23552
23553   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23554     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23555         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23556         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23557
23558       if (AsmPieces.size() == 3)
23559         return true;
23560       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23561         return true;
23562     }
23563   }
23564   return false;
23565 }
23566
23567 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23568   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23569
23570   std::string AsmStr = IA->getAsmString();
23571
23572   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23573   if (!Ty || Ty->getBitWidth() % 16 != 0)
23574     return false;
23575
23576   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23577   SmallVector<StringRef, 4> AsmPieces;
23578   SplitString(AsmStr, AsmPieces, ";\n");
23579
23580   switch (AsmPieces.size()) {
23581   default: return false;
23582   case 1:
23583     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23584     // we will turn this bswap into something that will be lowered to logical
23585     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23586     // lower so don't worry about this.
23587     // bswap $0
23588     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23589         matchAsm(AsmPieces[0], "bswapl", "$0") ||
23590         matchAsm(AsmPieces[0], "bswapq", "$0") ||
23591         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23592         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23593         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23594       // No need to check constraints, nothing other than the equivalent of
23595       // "=r,0" would be valid here.
23596       return IntrinsicLowering::LowerToByteSwap(CI);
23597     }
23598
23599     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23600     if (CI->getType()->isIntegerTy(16) &&
23601         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23602         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23603          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23604       AsmPieces.clear();
23605       const std::string &ConstraintsStr = IA->getConstraintString();
23606       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23607       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23608       if (clobbersFlagRegisters(AsmPieces))
23609         return IntrinsicLowering::LowerToByteSwap(CI);
23610     }
23611     break;
23612   case 3:
23613     if (CI->getType()->isIntegerTy(32) &&
23614         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23615         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23616         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23617         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23618       AsmPieces.clear();
23619       const std::string &ConstraintsStr = IA->getConstraintString();
23620       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23621       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23622       if (clobbersFlagRegisters(AsmPieces))
23623         return IntrinsicLowering::LowerToByteSwap(CI);
23624     }
23625
23626     if (CI->getType()->isIntegerTy(64)) {
23627       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23628       if (Constraints.size() >= 2 &&
23629           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23630           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23631         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23632         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23633             matchAsm(AsmPieces[1], "bswap", "%edx") &&
23634             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23635           return IntrinsicLowering::LowerToByteSwap(CI);
23636       }
23637     }
23638     break;
23639   }
23640   return false;
23641 }
23642
23643 /// getConstraintType - Given a constraint letter, return the type of
23644 /// constraint it is for this target.
23645 X86TargetLowering::ConstraintType
23646 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23647   if (Constraint.size() == 1) {
23648     switch (Constraint[0]) {
23649     case 'R':
23650     case 'q':
23651     case 'Q':
23652     case 'f':
23653     case 't':
23654     case 'u':
23655     case 'y':
23656     case 'x':
23657     case 'Y':
23658     case 'l':
23659       return C_RegisterClass;
23660     case 'a':
23661     case 'b':
23662     case 'c':
23663     case 'd':
23664     case 'S':
23665     case 'D':
23666     case 'A':
23667       return C_Register;
23668     case 'I':
23669     case 'J':
23670     case 'K':
23671     case 'L':
23672     case 'M':
23673     case 'N':
23674     case 'G':
23675     case 'C':
23676     case 'e':
23677     case 'Z':
23678       return C_Other;
23679     default:
23680       break;
23681     }
23682   }
23683   return TargetLowering::getConstraintType(Constraint);
23684 }
23685
23686 /// Examine constraint type and operand type and determine a weight value.
23687 /// This object must already have been set up with the operand type
23688 /// and the current alternative constraint selected.
23689 TargetLowering::ConstraintWeight
23690   X86TargetLowering::getSingleConstraintMatchWeight(
23691     AsmOperandInfo &info, const char *constraint) const {
23692   ConstraintWeight weight = CW_Invalid;
23693   Value *CallOperandVal = info.CallOperandVal;
23694     // If we don't have a value, we can't do a match,
23695     // but allow it at the lowest weight.
23696   if (!CallOperandVal)
23697     return CW_Default;
23698   Type *type = CallOperandVal->getType();
23699   // Look at the constraint type.
23700   switch (*constraint) {
23701   default:
23702     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23703   case 'R':
23704   case 'q':
23705   case 'Q':
23706   case 'a':
23707   case 'b':
23708   case 'c':
23709   case 'd':
23710   case 'S':
23711   case 'D':
23712   case 'A':
23713     if (CallOperandVal->getType()->isIntegerTy())
23714       weight = CW_SpecificReg;
23715     break;
23716   case 'f':
23717   case 't':
23718   case 'u':
23719     if (type->isFloatingPointTy())
23720       weight = CW_SpecificReg;
23721     break;
23722   case 'y':
23723     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23724       weight = CW_SpecificReg;
23725     break;
23726   case 'x':
23727   case 'Y':
23728     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23729         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23730       weight = CW_Register;
23731     break;
23732   case 'I':
23733     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23734       if (C->getZExtValue() <= 31)
23735         weight = CW_Constant;
23736     }
23737     break;
23738   case 'J':
23739     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23740       if (C->getZExtValue() <= 63)
23741         weight = CW_Constant;
23742     }
23743     break;
23744   case 'K':
23745     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23746       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23747         weight = CW_Constant;
23748     }
23749     break;
23750   case 'L':
23751     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23752       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23753         weight = CW_Constant;
23754     }
23755     break;
23756   case 'M':
23757     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23758       if (C->getZExtValue() <= 3)
23759         weight = CW_Constant;
23760     }
23761     break;
23762   case 'N':
23763     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23764       if (C->getZExtValue() <= 0xff)
23765         weight = CW_Constant;
23766     }
23767     break;
23768   case 'G':
23769   case 'C':
23770     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23771       weight = CW_Constant;
23772     }
23773     break;
23774   case 'e':
23775     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23776       if ((C->getSExtValue() >= -0x80000000LL) &&
23777           (C->getSExtValue() <= 0x7fffffffLL))
23778         weight = CW_Constant;
23779     }
23780     break;
23781   case 'Z':
23782     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23783       if (C->getZExtValue() <= 0xffffffff)
23784         weight = CW_Constant;
23785     }
23786     break;
23787   }
23788   return weight;
23789 }
23790
23791 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23792 /// with another that has more specific requirements based on the type of the
23793 /// corresponding operand.
23794 const char *X86TargetLowering::
23795 LowerXConstraint(EVT ConstraintVT) const {
23796   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23797   // 'f' like normal targets.
23798   if (ConstraintVT.isFloatingPoint()) {
23799     if (Subtarget->hasSSE2())
23800       return "Y";
23801     if (Subtarget->hasSSE1())
23802       return "x";
23803   }
23804
23805   return TargetLowering::LowerXConstraint(ConstraintVT);
23806 }
23807
23808 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23809 /// vector.  If it is invalid, don't add anything to Ops.
23810 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23811                                                      std::string &Constraint,
23812                                                      std::vector<SDValue>&Ops,
23813                                                      SelectionDAG &DAG) const {
23814   SDValue Result;
23815
23816   // Only support length 1 constraints for now.
23817   if (Constraint.length() > 1) return;
23818
23819   char ConstraintLetter = Constraint[0];
23820   switch (ConstraintLetter) {
23821   default: break;
23822   case 'I':
23823     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23824       if (C->getZExtValue() <= 31) {
23825         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23826         break;
23827       }
23828     }
23829     return;
23830   case 'J':
23831     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23832       if (C->getZExtValue() <= 63) {
23833         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23834         break;
23835       }
23836     }
23837     return;
23838   case 'K':
23839     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23840       if (isInt<8>(C->getSExtValue())) {
23841         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23842         break;
23843       }
23844     }
23845     return;
23846   case 'L':
23847     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23848       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
23849           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
23850         Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
23851         break;
23852       }
23853     }
23854     return;
23855   case 'M':
23856     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23857       if (C->getZExtValue() <= 3) {
23858         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23859         break;
23860       }
23861     }
23862     return;
23863   case 'N':
23864     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23865       if (C->getZExtValue() <= 255) {
23866         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23867         break;
23868       }
23869     }
23870     return;
23871   case 'O':
23872     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23873       if (C->getZExtValue() <= 127) {
23874         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23875         break;
23876       }
23877     }
23878     return;
23879   case 'e': {
23880     // 32-bit signed value
23881     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23882       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23883                                            C->getSExtValue())) {
23884         // Widen to 64 bits here to get it sign extended.
23885         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23886         break;
23887       }
23888     // FIXME gcc accepts some relocatable values here too, but only in certain
23889     // memory models; it's complicated.
23890     }
23891     return;
23892   }
23893   case 'Z': {
23894     // 32-bit unsigned value
23895     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23896       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23897                                            C->getZExtValue())) {
23898         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23899         break;
23900       }
23901     }
23902     // FIXME gcc accepts some relocatable values here too, but only in certain
23903     // memory models; it's complicated.
23904     return;
23905   }
23906   case 'i': {
23907     // Literal immediates are always ok.
23908     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23909       // Widen to 64 bits here to get it sign extended.
23910       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23911       break;
23912     }
23913
23914     // In any sort of PIC mode addresses need to be computed at runtime by
23915     // adding in a register or some sort of table lookup.  These can't
23916     // be used as immediates.
23917     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23918       return;
23919
23920     // If we are in non-pic codegen mode, we allow the address of a global (with
23921     // an optional displacement) to be used with 'i'.
23922     GlobalAddressSDNode *GA = nullptr;
23923     int64_t Offset = 0;
23924
23925     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23926     while (1) {
23927       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23928         Offset += GA->getOffset();
23929         break;
23930       } else if (Op.getOpcode() == ISD::ADD) {
23931         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23932           Offset += C->getZExtValue();
23933           Op = Op.getOperand(0);
23934           continue;
23935         }
23936       } else if (Op.getOpcode() == ISD::SUB) {
23937         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23938           Offset += -C->getZExtValue();
23939           Op = Op.getOperand(0);
23940           continue;
23941         }
23942       }
23943
23944       // Otherwise, this isn't something we can handle, reject it.
23945       return;
23946     }
23947
23948     const GlobalValue *GV = GA->getGlobal();
23949     // If we require an extra load to get this address, as in PIC mode, we
23950     // can't accept it.
23951     if (isGlobalStubReference(
23952             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23953       return;
23954
23955     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23956                                         GA->getValueType(0), Offset);
23957     break;
23958   }
23959   }
23960
23961   if (Result.getNode()) {
23962     Ops.push_back(Result);
23963     return;
23964   }
23965   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23966 }
23967
23968 std::pair<unsigned, const TargetRegisterClass*>
23969 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23970                                                 MVT VT) const {
23971   // First, see if this is a constraint that directly corresponds to an LLVM
23972   // register class.
23973   if (Constraint.size() == 1) {
23974     // GCC Constraint Letters
23975     switch (Constraint[0]) {
23976     default: break;
23977       // TODO: Slight differences here in allocation order and leaving
23978       // RIP in the class. Do they matter any more here than they do
23979       // in the normal allocation?
23980     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23981       if (Subtarget->is64Bit()) {
23982         if (VT == MVT::i32 || VT == MVT::f32)
23983           return std::make_pair(0U, &X86::GR32RegClass);
23984         if (VT == MVT::i16)
23985           return std::make_pair(0U, &X86::GR16RegClass);
23986         if (VT == MVT::i8 || VT == MVT::i1)
23987           return std::make_pair(0U, &X86::GR8RegClass);
23988         if (VT == MVT::i64 || VT == MVT::f64)
23989           return std::make_pair(0U, &X86::GR64RegClass);
23990         break;
23991       }
23992       // 32-bit fallthrough
23993     case 'Q':   // Q_REGS
23994       if (VT == MVT::i32 || VT == MVT::f32)
23995         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23996       if (VT == MVT::i16)
23997         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23998       if (VT == MVT::i8 || VT == MVT::i1)
23999         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24000       if (VT == MVT::i64)
24001         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24002       break;
24003     case 'r':   // GENERAL_REGS
24004     case 'l':   // INDEX_REGS
24005       if (VT == MVT::i8 || VT == MVT::i1)
24006         return std::make_pair(0U, &X86::GR8RegClass);
24007       if (VT == MVT::i16)
24008         return std::make_pair(0U, &X86::GR16RegClass);
24009       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24010         return std::make_pair(0U, &X86::GR32RegClass);
24011       return std::make_pair(0U, &X86::GR64RegClass);
24012     case 'R':   // LEGACY_REGS
24013       if (VT == MVT::i8 || VT == MVT::i1)
24014         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24015       if (VT == MVT::i16)
24016         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24017       if (VT == MVT::i32 || !Subtarget->is64Bit())
24018         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24019       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24020     case 'f':  // FP Stack registers.
24021       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24022       // value to the correct fpstack register class.
24023       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24024         return std::make_pair(0U, &X86::RFP32RegClass);
24025       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24026         return std::make_pair(0U, &X86::RFP64RegClass);
24027       return std::make_pair(0U, &X86::RFP80RegClass);
24028     case 'y':   // MMX_REGS if MMX allowed.
24029       if (!Subtarget->hasMMX()) break;
24030       return std::make_pair(0U, &X86::VR64RegClass);
24031     case 'Y':   // SSE_REGS if SSE2 allowed
24032       if (!Subtarget->hasSSE2()) break;
24033       // FALL THROUGH.
24034     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24035       if (!Subtarget->hasSSE1()) break;
24036
24037       switch (VT.SimpleTy) {
24038       default: break;
24039       // Scalar SSE types.
24040       case MVT::f32:
24041       case MVT::i32:
24042         return std::make_pair(0U, &X86::FR32RegClass);
24043       case MVT::f64:
24044       case MVT::i64:
24045         return std::make_pair(0U, &X86::FR64RegClass);
24046       // Vector types.
24047       case MVT::v16i8:
24048       case MVT::v8i16:
24049       case MVT::v4i32:
24050       case MVT::v2i64:
24051       case MVT::v4f32:
24052       case MVT::v2f64:
24053         return std::make_pair(0U, &X86::VR128RegClass);
24054       // AVX types.
24055       case MVT::v32i8:
24056       case MVT::v16i16:
24057       case MVT::v8i32:
24058       case MVT::v4i64:
24059       case MVT::v8f32:
24060       case MVT::v4f64:
24061         return std::make_pair(0U, &X86::VR256RegClass);
24062       case MVT::v8f64:
24063       case MVT::v16f32:
24064       case MVT::v16i32:
24065       case MVT::v8i64:
24066         return std::make_pair(0U, &X86::VR512RegClass);
24067       }
24068       break;
24069     }
24070   }
24071
24072   // Use the default implementation in TargetLowering to convert the register
24073   // constraint into a member of a register class.
24074   std::pair<unsigned, const TargetRegisterClass*> Res;
24075   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
24076
24077   // Not found as a standard register?
24078   if (!Res.second) {
24079     // Map st(0) -> st(7) -> ST0
24080     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24081         tolower(Constraint[1]) == 's' &&
24082         tolower(Constraint[2]) == 't' &&
24083         Constraint[3] == '(' &&
24084         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24085         Constraint[5] == ')' &&
24086         Constraint[6] == '}') {
24087
24088       Res.first = X86::FP0+Constraint[4]-'0';
24089       Res.second = &X86::RFP80RegClass;
24090       return Res;
24091     }
24092
24093     // GCC allows "st(0)" to be called just plain "st".
24094     if (StringRef("{st}").equals_lower(Constraint)) {
24095       Res.first = X86::FP0;
24096       Res.second = &X86::RFP80RegClass;
24097       return Res;
24098     }
24099
24100     // flags -> EFLAGS
24101     if (StringRef("{flags}").equals_lower(Constraint)) {
24102       Res.first = X86::EFLAGS;
24103       Res.second = &X86::CCRRegClass;
24104       return Res;
24105     }
24106
24107     // 'A' means EAX + EDX.
24108     if (Constraint == "A") {
24109       Res.first = X86::EAX;
24110       Res.second = &X86::GR32_ADRegClass;
24111       return Res;
24112     }
24113     return Res;
24114   }
24115
24116   // Otherwise, check to see if this is a register class of the wrong value
24117   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24118   // turn into {ax},{dx}.
24119   if (Res.second->hasType(VT))
24120     return Res;   // Correct type already, nothing to do.
24121
24122   // All of the single-register GCC register classes map their values onto
24123   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24124   // really want an 8-bit or 32-bit register, map to the appropriate register
24125   // class and return the appropriate register.
24126   if (Res.second == &X86::GR16RegClass) {
24127     if (VT == MVT::i8 || VT == MVT::i1) {
24128       unsigned DestReg = 0;
24129       switch (Res.first) {
24130       default: break;
24131       case X86::AX: DestReg = X86::AL; break;
24132       case X86::DX: DestReg = X86::DL; break;
24133       case X86::CX: DestReg = X86::CL; break;
24134       case X86::BX: DestReg = X86::BL; break;
24135       }
24136       if (DestReg) {
24137         Res.first = DestReg;
24138         Res.second = &X86::GR8RegClass;
24139       }
24140     } else if (VT == MVT::i32 || VT == MVT::f32) {
24141       unsigned DestReg = 0;
24142       switch (Res.first) {
24143       default: break;
24144       case X86::AX: DestReg = X86::EAX; break;
24145       case X86::DX: DestReg = X86::EDX; break;
24146       case X86::CX: DestReg = X86::ECX; break;
24147       case X86::BX: DestReg = X86::EBX; break;
24148       case X86::SI: DestReg = X86::ESI; break;
24149       case X86::DI: DestReg = X86::EDI; break;
24150       case X86::BP: DestReg = X86::EBP; break;
24151       case X86::SP: DestReg = X86::ESP; break;
24152       }
24153       if (DestReg) {
24154         Res.first = DestReg;
24155         Res.second = &X86::GR32RegClass;
24156       }
24157     } else if (VT == MVT::i64 || VT == MVT::f64) {
24158       unsigned DestReg = 0;
24159       switch (Res.first) {
24160       default: break;
24161       case X86::AX: DestReg = X86::RAX; break;
24162       case X86::DX: DestReg = X86::RDX; break;
24163       case X86::CX: DestReg = X86::RCX; break;
24164       case X86::BX: DestReg = X86::RBX; break;
24165       case X86::SI: DestReg = X86::RSI; break;
24166       case X86::DI: DestReg = X86::RDI; break;
24167       case X86::BP: DestReg = X86::RBP; break;
24168       case X86::SP: DestReg = X86::RSP; break;
24169       }
24170       if (DestReg) {
24171         Res.first = DestReg;
24172         Res.second = &X86::GR64RegClass;
24173       }
24174     }
24175   } else if (Res.second == &X86::FR32RegClass ||
24176              Res.second == &X86::FR64RegClass ||
24177              Res.second == &X86::VR128RegClass ||
24178              Res.second == &X86::VR256RegClass ||
24179              Res.second == &X86::FR32XRegClass ||
24180              Res.second == &X86::FR64XRegClass ||
24181              Res.second == &X86::VR128XRegClass ||
24182              Res.second == &X86::VR256XRegClass ||
24183              Res.second == &X86::VR512RegClass) {
24184     // Handle references to XMM physical registers that got mapped into the
24185     // wrong class.  This can happen with constraints like {xmm0} where the
24186     // target independent register mapper will just pick the first match it can
24187     // find, ignoring the required type.
24188
24189     if (VT == MVT::f32 || VT == MVT::i32)
24190       Res.second = &X86::FR32RegClass;
24191     else if (VT == MVT::f64 || VT == MVT::i64)
24192       Res.second = &X86::FR64RegClass;
24193     else if (X86::VR128RegClass.hasType(VT))
24194       Res.second = &X86::VR128RegClass;
24195     else if (X86::VR256RegClass.hasType(VT))
24196       Res.second = &X86::VR256RegClass;
24197     else if (X86::VR512RegClass.hasType(VT))
24198       Res.second = &X86::VR512RegClass;
24199   }
24200
24201   return Res;
24202 }
24203
24204 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24205                                             Type *Ty) const {
24206   // Scaling factors are not free at all.
24207   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24208   // will take 2 allocations in the out of order engine instead of 1
24209   // for plain addressing mode, i.e. inst (reg1).
24210   // E.g.,
24211   // vaddps (%rsi,%drx), %ymm0, %ymm1
24212   // Requires two allocations (one for the load, one for the computation)
24213   // whereas:
24214   // vaddps (%rsi), %ymm0, %ymm1
24215   // Requires just 1 allocation, i.e., freeing allocations for other operations
24216   // and having less micro operations to execute.
24217   //
24218   // For some X86 architectures, this is even worse because for instance for
24219   // stores, the complex addressing mode forces the instruction to use the
24220   // "load" ports instead of the dedicated "store" port.
24221   // E.g., on Haswell:
24222   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24223   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24224   if (isLegalAddressingMode(AM, Ty))
24225     // Scale represents reg2 * scale, thus account for 1
24226     // as soon as we use a second register.
24227     return AM.Scale != 0;
24228   return -1;
24229 }
24230
24231 bool X86TargetLowering::isTargetFTOL() const {
24232   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
24233 }