[x86] Add vector @llvm.ctpop intrinsic custom lowering
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallBitVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/VariadicFunction.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
54 #include <bitset>
55 #include <numeric>
56 #include <cctype>
57 using namespace llvm;
58
59 #define DEBUG_TYPE "x86-isel"
60
61 STATISTIC(NumTailCalls, "Number of tail calls");
62
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64     "x86-experimental-vector-widening-legalization", cl::init(false),
65     cl::desc("Enable an experimental vector type legalization through widening "
66              "rather than promotion."),
67     cl::Hidden);
68
69 static cl::opt<bool> ExperimentalVectorShuffleLowering(
70     "x86-experimental-vector-shuffle-lowering", cl::init(true),
71     cl::desc("Enable an experimental vector shuffle lowering code path."),
72     cl::Hidden);
73
74 static cl::opt<int> ReciprocalEstimateRefinementSteps(
75     "x86-recip-refinement-steps", cl::init(1),
76     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
77              "result of the hardware reciprocal estimate instruction."),
78     cl::NotHidden);
79
80 // Forward declarations.
81 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
82                        SDValue V2);
83
84 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
85                                 SelectionDAG &DAG, SDLoc dl,
86                                 unsigned vectorWidth) {
87   assert((vectorWidth == 128 || vectorWidth == 256) &&
88          "Unsupported vector width");
89   EVT VT = Vec.getValueType();
90   EVT ElVT = VT.getVectorElementType();
91   unsigned Factor = VT.getSizeInBits()/vectorWidth;
92   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
93                                   VT.getVectorNumElements()/Factor);
94
95   // Extract from UNDEF is UNDEF.
96   if (Vec.getOpcode() == ISD::UNDEF)
97     return DAG.getUNDEF(ResultVT);
98
99   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
100   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
101
102   // This is the index of the first element of the vectorWidth-bit chunk
103   // we want.
104   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
105                                * ElemsPerChunk);
106
107   // If the input is a buildvector just emit a smaller one.
108   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
109     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
110                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
111                                     ElemsPerChunk));
112
113   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
114   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
115 }
116
117 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
118 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
119 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
120 /// instructions or a simple subregister reference. Idx is an index in the
121 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
122 /// lowering EXTRACT_VECTOR_ELT operations easier.
123 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
124                                    SelectionDAG &DAG, SDLoc dl) {
125   assert((Vec.getValueType().is256BitVector() ||
126           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
127   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
128 }
129
130 /// Generate a DAG to grab 256-bits from a 512-bit vector.
131 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
132                                    SelectionDAG &DAG, SDLoc dl) {
133   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
134   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
135 }
136
137 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
138                                unsigned IdxVal, SelectionDAG &DAG,
139                                SDLoc dl, unsigned vectorWidth) {
140   assert((vectorWidth == 128 || vectorWidth == 256) &&
141          "Unsupported vector width");
142   // Inserting UNDEF is Result
143   if (Vec.getOpcode() == ISD::UNDEF)
144     return Result;
145   EVT VT = Vec.getValueType();
146   EVT ElVT = VT.getVectorElementType();
147   EVT ResultVT = Result.getValueType();
148
149   // Insert the relevant vectorWidth bits.
150   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
151
152   // This is the index of the first element of the vectorWidth-bit chunk
153   // we want.
154   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
155                                * ElemsPerChunk);
156
157   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
158   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
159 }
160
161 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
162 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
163 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
164 /// simple superregister reference.  Idx is an index in the 128 bits
165 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
166 /// lowering INSERT_VECTOR_ELT operations easier.
167 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
168                                   SelectionDAG &DAG,SDLoc dl) {
169   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
170   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
171 }
172
173 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
174                                   SelectionDAG &DAG, SDLoc dl) {
175   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
176   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
177 }
178
179 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
180 /// instructions. This is used because creating CONCAT_VECTOR nodes of
181 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
182 /// large BUILD_VECTORS.
183 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
184                                    unsigned NumElems, SelectionDAG &DAG,
185                                    SDLoc dl) {
186   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
187   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
188 }
189
190 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
191                                    unsigned NumElems, SelectionDAG &DAG,
192                                    SDLoc dl) {
193   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
194   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
195 }
196
197 // FIXME: This should stop caching the target machine as soon as
198 // we can remove resetOperationActions et al.
199 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM)
200     : TargetLowering(TM) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasSSE2();
203   X86ScalarSSEf32 = Subtarget->hasSSE1();
204   TD = getDataLayout();
205
206   resetOperationActions();
207 }
208
209 void X86TargetLowering::resetOperationActions() {
210   const TargetMachine &TM = getTargetMachine();
211   static bool FirstTimeThrough = true;
212
213   // If none of the target options have changed, then we don't need to reset the
214   // operation actions.
215   if (!FirstTimeThrough && TO == TM.Options) return;
216
217   if (!FirstTimeThrough) {
218     // Reinitialize the actions.
219     initActions();
220     FirstTimeThrough = false;
221   }
222
223   TO = TM.Options;
224
225   // Set up the TargetLowering object.
226   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227
228   // X86 is weird. It always uses i8 for shift amounts and setcc results.
229   setBooleanContents(ZeroOrOneBooleanContent);
230   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232
233   // For 64-bit, since we have so many registers, use the ILP scheduler.
234   // For 32-bit, use the register pressure specific scheduling.
235   // For Atom, always use ILP scheduling.
236   if (Subtarget->isAtom())
237     setSchedulingPreference(Sched::ILP);
238   else if (Subtarget->is64Bit())
239     setSchedulingPreference(Sched::ILP);
240   else
241     setSchedulingPreference(Sched::RegPressure);
242   const X86RegisterInfo *RegInfo =
243       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
244   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245
246   // Bypass expensive divides on Atom when compiling with O2.
247   if (TM.getOptLevel() >= CodeGenOpt::Default) {
248     if (Subtarget->hasSlowDivide32())
249       addBypassSlowDiv(32, 8);
250     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
251       addBypassSlowDiv(64, 16);
252   }
253
254   if (Subtarget->isTargetKnownWindowsMSVC()) {
255     // Setup Windows compiler runtime calls.
256     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258     setLibcallName(RTLIB::SREM_I64, "_allrem");
259     setLibcallName(RTLIB::UREM_I64, "_aullrem");
260     setLibcallName(RTLIB::MUL_I64, "_allmul");
261     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266
267     // The _ftol2 runtime function has an unusual calling conv, which
268     // is modeled by a special pseudo-instruction.
269     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
270     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
273   }
274
275   if (Subtarget->isTargetDarwin()) {
276     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277     setUseUnderscoreSetJmp(false);
278     setUseUnderscoreLongJmp(false);
279   } else if (Subtarget->isTargetWindowsGNU()) {
280     // MS runtime is weird: it exports _setjmp, but longjmp!
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(false);
283   } else {
284     setUseUnderscoreSetJmp(true);
285     setUseUnderscoreLongJmp(true);
286   }
287
288   // Set up the register classes.
289   addRegisterClass(MVT::i8, &X86::GR8RegClass);
290   addRegisterClass(MVT::i16, &X86::GR16RegClass);
291   addRegisterClass(MVT::i32, &X86::GR32RegClass);
292   if (Subtarget->is64Bit())
293     addRegisterClass(MVT::i64, &X86::GR64RegClass);
294
295   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296
297   // We don't accept any truncstore of integer registers.
298   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
304
305   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
306
307   // SETOEQ and SETUNE require checking two conditions.
308   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314
315   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316   // operation.
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
318   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
319   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
320
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
323     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
324   } else if (!TM.Options.UseSoftFloat) {
325     // We have an algorithm for SSE2->double, and we turn this into a
326     // 64-bit FILD followed by conditional FADD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
328     // We have an algorithm for SSE2, and we turn this into a 64-bit
329     // FILD for other targets.
330     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
331   }
332
333   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334   // this operation.
335   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
336   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
337
338   if (!TM.Options.UseSoftFloat) {
339     // SSE has no i16 to fp conversion, only i32
340     if (X86ScalarSSEf32) {
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
342       // f32 and f64 cases are Legal, f80 case is not
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     } else {
345       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
346       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
347     }
348   } else {
349     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
350     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
351   }
352
353   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
354   // are Legal, f80 is custom lowered.
355   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
356   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
357
358   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359   // this operation.
360   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
361   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
362
363   if (X86ScalarSSEf32) {
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
365     // f32 and f64 cases are Legal, f80 case is not
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   } else {
368     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
369     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
370   }
371
372   // Handle FP_TO_UINT by promoting the destination to a larger signed
373   // conversion.
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
375   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
376   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
377
378   if (Subtarget->is64Bit()) {
379     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
380     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
381   } else if (!TM.Options.UseSoftFloat) {
382     // Since AVX is a superset of SSE3, only check for SSE here.
383     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384       // Expand FP_TO_UINT into a select.
385       // FIXME: We would like to use a Custom expander here eventually to do
386       // the optimal thing for SSE vs. the default expansion in the legalizer.
387       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
388     else
389       // With SSE3 we can use fisttpll to convert to a signed i64; without
390       // SSE, we're stuck with a fistpll.
391       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
392   }
393
394   if (isTargetFTOL()) {
395     // Use the _ftol2 runtime function, which has a pseudo-instruction
396     // to handle its weird calling convention.
397     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
398   }
399
400   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401   if (!X86ScalarSSEf64) {
402     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
403     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
404     if (Subtarget->is64Bit()) {
405       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
406       // Without SSE, i64->f64 goes through memory.
407       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
408     }
409   }
410
411   // Scalar integer divide and remainder are lowered to use operations that
412   // produce two results, to match the available instructions. This exposes
413   // the two-result form to trivial CSE, which is able to combine x/y and x%y
414   // into a single instruction.
415   //
416   // Scalar integer multiply-high is also lowered to use two-result
417   // operations, to match the available instructions. However, plain multiply
418   // (low) operations are left as Legal, as there are single-result
419   // instructions for this in x86. Using the two-result multiply instructions
420   // when both high and low results are needed must be arranged by dagcombine.
421   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422     MVT VT = IntVTs[i];
423     setOperationAction(ISD::MULHS, VT, Expand);
424     setOperationAction(ISD::MULHU, VT, Expand);
425     setOperationAction(ISD::SDIV, VT, Expand);
426     setOperationAction(ISD::UDIV, VT, Expand);
427     setOperationAction(ISD::SREM, VT, Expand);
428     setOperationAction(ISD::UREM, VT, Expand);
429
430     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431     setOperationAction(ISD::ADDC, VT, Custom);
432     setOperationAction(ISD::ADDE, VT, Custom);
433     setOperationAction(ISD::SUBC, VT, Custom);
434     setOperationAction(ISD::SUBE, VT, Custom);
435   }
436
437   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
438   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
439   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
444   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
445   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
446   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
447   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
448   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
449   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
450   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
451   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
452   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
453   if (Subtarget->is64Bit())
454     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
455   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
456   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
457   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
458   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
459   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
460   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
461   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
462   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
463
464   // Promote the i8 variants and force them on up to i32 which has a shorter
465   // encoding.
466   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
467   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
468   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
469   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
470   if (Subtarget->hasBMI()) {
471     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
472     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
473     if (Subtarget->is64Bit())
474       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
475   } else {
476     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
477     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
478     if (Subtarget->is64Bit())
479       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
480   }
481
482   if (Subtarget->hasLZCNT()) {
483     // When promoting the i8 variants, force them to i32 for a shorter
484     // encoding.
485     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
486     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
488     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
491     if (Subtarget->is64Bit())
492       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
493   } else {
494     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
495     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
496     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
497     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
498     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
500     if (Subtarget->is64Bit()) {
501       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
502       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
503     }
504   }
505
506   // Special handling for half-precision floating point conversions.
507   // If we don't have F16C support, then lower half float conversions
508   // into library calls.
509   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
510     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
511     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
512   }
513
514   // There's never any support for operations beyond MVT::f32.
515   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
516   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
517   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
518   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
519
520   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
521   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
522   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
523   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
524
525   if (Subtarget->hasPOPCNT()) {
526     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
527   } else {
528     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
529     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
530     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
531     if (Subtarget->is64Bit())
532       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
533   }
534
535   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
536
537   if (!Subtarget->hasMOVBE())
538     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
539
540   // These should be promoted to a larger select which is supported.
541   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
542   // X86 wants to expand cmov itself.
543   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
544   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
545   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
546   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
547   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
548   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
549   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
550   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
551   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
552   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
553   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
554   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
555   if (Subtarget->is64Bit()) {
556     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
557     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
558   }
559   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
560   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
561   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
562   // support continuation, user-level threading, and etc.. As a result, no
563   // other SjLj exception interfaces are implemented and please don't build
564   // your own exception handling based on them.
565   // LLVM/Clang supports zero-cost DWARF exception handling.
566   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
567   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
568
569   // Darwin ABI issue.
570   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
571   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
572   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
573   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
574   if (Subtarget->is64Bit())
575     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
576   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
577   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
578   if (Subtarget->is64Bit()) {
579     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
580     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
581     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
582     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
583     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
584   }
585   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
586   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
587   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
588   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
589   if (Subtarget->is64Bit()) {
590     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
591     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
592     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
593   }
594
595   if (Subtarget->hasSSE1())
596     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
597
598   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
599
600   // Expand certain atomics
601   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
602     MVT VT = IntVTs[i];
603     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
604     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
605     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
606   }
607
608   if (Subtarget->hasCmpxchg16b()) {
609     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
610   }
611
612   // FIXME - use subtarget debug flags
613   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
614       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
615     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
616   }
617
618   if (Subtarget->is64Bit()) {
619     setExceptionPointerRegister(X86::RAX);
620     setExceptionSelectorRegister(X86::RDX);
621   } else {
622     setExceptionPointerRegister(X86::EAX);
623     setExceptionSelectorRegister(X86::EDX);
624   }
625   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
626   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
627
628   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
629   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
630
631   setOperationAction(ISD::TRAP, MVT::Other, Legal);
632   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
633
634   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
635   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
636   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
637   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
638     // TargetInfo::X86_64ABIBuiltinVaList
639     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
640     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
641   } else {
642     // TargetInfo::CharPtrBuiltinVaList
643     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
644     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
645   }
646
647   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
648   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
649
650   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
651
652   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
653     // f32 and f64 use SSE.
654     // Set up the FP register classes.
655     addRegisterClass(MVT::f32, &X86::FR32RegClass);
656     addRegisterClass(MVT::f64, &X86::FR64RegClass);
657
658     // Use ANDPD to simulate FABS.
659     setOperationAction(ISD::FABS , MVT::f64, Custom);
660     setOperationAction(ISD::FABS , MVT::f32, Custom);
661
662     // Use XORP to simulate FNEG.
663     setOperationAction(ISD::FNEG , MVT::f64, Custom);
664     setOperationAction(ISD::FNEG , MVT::f32, Custom);
665
666     // Use ANDPD and ORPD to simulate FCOPYSIGN.
667     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
668     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
669
670     // Lower this to FGETSIGNx86 plus an AND.
671     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
672     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
673
674     // We don't support sin/cos/fmod
675     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
676     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
677     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
678     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
679     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
680     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
681
682     // Expand FP immediates into loads from the stack, except for the special
683     // cases we handle.
684     addLegalFPImmediate(APFloat(+0.0)); // xorpd
685     addLegalFPImmediate(APFloat(+0.0f)); // xorps
686   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
687     // Use SSE for f32, x87 for f64.
688     // Set up the FP register classes.
689     addRegisterClass(MVT::f32, &X86::FR32RegClass);
690     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
691
692     // Use ANDPS to simulate FABS.
693     setOperationAction(ISD::FABS , MVT::f32, Custom);
694
695     // Use XORP to simulate FNEG.
696     setOperationAction(ISD::FNEG , MVT::f32, Custom);
697
698     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
699
700     // Use ANDPS and ORPS to simulate FCOPYSIGN.
701     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
702     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
703
704     // We don't support sin/cos/fmod
705     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
706     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
707     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
708
709     // Special cases we handle for FP constants.
710     addLegalFPImmediate(APFloat(+0.0f)); // xorps
711     addLegalFPImmediate(APFloat(+0.0)); // FLD0
712     addLegalFPImmediate(APFloat(+1.0)); // FLD1
713     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
714     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
715
716     if (!TM.Options.UnsafeFPMath) {
717       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
718       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
719       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
720     }
721   } else if (!TM.Options.UseSoftFloat) {
722     // f32 and f64 in x87.
723     // Set up the FP register classes.
724     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
725     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
726
727     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
728     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
729     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
730     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
731
732     if (!TM.Options.UnsafeFPMath) {
733       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
734       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
735       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
736       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
737       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
738       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
739     }
740     addLegalFPImmediate(APFloat(+0.0)); // FLD0
741     addLegalFPImmediate(APFloat(+1.0)); // FLD1
742     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
743     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
744     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
745     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
746     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
747     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
748   }
749
750   // We don't support FMA.
751   setOperationAction(ISD::FMA, MVT::f64, Expand);
752   setOperationAction(ISD::FMA, MVT::f32, Expand);
753
754   // Long double always uses X87.
755   if (!TM.Options.UseSoftFloat) {
756     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
757     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
758     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
759     {
760       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
761       addLegalFPImmediate(TmpFlt);  // FLD0
762       TmpFlt.changeSign();
763       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
764
765       bool ignored;
766       APFloat TmpFlt2(+1.0);
767       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
768                       &ignored);
769       addLegalFPImmediate(TmpFlt2);  // FLD1
770       TmpFlt2.changeSign();
771       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
772     }
773
774     if (!TM.Options.UnsafeFPMath) {
775       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
776       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
777       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
778     }
779
780     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
781     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
782     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
783     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
784     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
785     setOperationAction(ISD::FMA, MVT::f80, Expand);
786   }
787
788   // Always use a library call for pow.
789   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
790   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
791   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
792
793   setOperationAction(ISD::FLOG, MVT::f80, Expand);
794   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
795   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
796   setOperationAction(ISD::FEXP, MVT::f80, Expand);
797   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
798   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
799   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
800
801   // First set operation action for all vector types to either promote
802   // (for widening) or expand (for scalarization). Then we will selectively
803   // turn on ones that can be effectively codegen'd.
804   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
805            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
806     MVT VT = (MVT::SimpleValueType)i;
807     setOperationAction(ISD::ADD , VT, Expand);
808     setOperationAction(ISD::SUB , VT, Expand);
809     setOperationAction(ISD::FADD, VT, Expand);
810     setOperationAction(ISD::FNEG, VT, Expand);
811     setOperationAction(ISD::FSUB, VT, Expand);
812     setOperationAction(ISD::MUL , VT, Expand);
813     setOperationAction(ISD::FMUL, VT, Expand);
814     setOperationAction(ISD::SDIV, VT, Expand);
815     setOperationAction(ISD::UDIV, VT, Expand);
816     setOperationAction(ISD::FDIV, VT, Expand);
817     setOperationAction(ISD::SREM, VT, Expand);
818     setOperationAction(ISD::UREM, VT, Expand);
819     setOperationAction(ISD::LOAD, VT, Expand);
820     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
821     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
822     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
823     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
824     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
825     setOperationAction(ISD::FABS, VT, Expand);
826     setOperationAction(ISD::FSIN, VT, Expand);
827     setOperationAction(ISD::FSINCOS, VT, Expand);
828     setOperationAction(ISD::FCOS, VT, Expand);
829     setOperationAction(ISD::FSINCOS, VT, Expand);
830     setOperationAction(ISD::FREM, VT, Expand);
831     setOperationAction(ISD::FMA,  VT, Expand);
832     setOperationAction(ISD::FPOWI, VT, Expand);
833     setOperationAction(ISD::FSQRT, VT, Expand);
834     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
835     setOperationAction(ISD::FFLOOR, VT, Expand);
836     setOperationAction(ISD::FCEIL, VT, Expand);
837     setOperationAction(ISD::FTRUNC, VT, Expand);
838     setOperationAction(ISD::FRINT, VT, Expand);
839     setOperationAction(ISD::FNEARBYINT, VT, Expand);
840     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
841     setOperationAction(ISD::MULHS, VT, Expand);
842     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
843     setOperationAction(ISD::MULHU, VT, Expand);
844     setOperationAction(ISD::SDIVREM, VT, Expand);
845     setOperationAction(ISD::UDIVREM, VT, Expand);
846     setOperationAction(ISD::FPOW, VT, Expand);
847     setOperationAction(ISD::CTPOP, VT, Expand);
848     setOperationAction(ISD::CTTZ, VT, Expand);
849     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
850     setOperationAction(ISD::CTLZ, VT, Expand);
851     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
852     setOperationAction(ISD::SHL, VT, Expand);
853     setOperationAction(ISD::SRA, VT, Expand);
854     setOperationAction(ISD::SRL, VT, Expand);
855     setOperationAction(ISD::ROTL, VT, Expand);
856     setOperationAction(ISD::ROTR, VT, Expand);
857     setOperationAction(ISD::BSWAP, VT, Expand);
858     setOperationAction(ISD::SETCC, VT, Expand);
859     setOperationAction(ISD::FLOG, VT, Expand);
860     setOperationAction(ISD::FLOG2, VT, Expand);
861     setOperationAction(ISD::FLOG10, VT, Expand);
862     setOperationAction(ISD::FEXP, VT, Expand);
863     setOperationAction(ISD::FEXP2, VT, Expand);
864     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
865     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
866     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
867     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
868     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
869     setOperationAction(ISD::TRUNCATE, VT, Expand);
870     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
871     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
872     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
873     setOperationAction(ISD::VSELECT, VT, Expand);
874     setOperationAction(ISD::SELECT_CC, VT, Expand);
875     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
876              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
877       setTruncStoreAction(VT,
878                           (MVT::SimpleValueType)InnerVT, Expand);
879     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
880     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
881
882     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
883     // we have to deal with them whether we ask for Expansion or not. Setting
884     // Expand causes its own optimisation problems though, so leave them legal.
885     if (VT.getVectorElementType() == MVT::i1)
886       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
887   }
888
889   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
890   // with -msoft-float, disable use of MMX as well.
891   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
892     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
893     // No operations on x86mmx supported, everything uses intrinsics.
894   }
895
896   // MMX-sized vectors (other than x86mmx) are expected to be expanded
897   // into smaller operations.
898   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
899   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
900   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
901   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
902   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
903   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
904   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
905   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
906   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
907   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
908   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
909   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
910   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
911   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
912   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
913   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
914   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
915   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
916   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
917   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
918   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
919   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
920   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
921   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
922   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
923   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
924   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
925   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
926   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
927
928   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
929     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
930
931     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
932     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
933     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
934     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
935     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
936     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
937     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
938     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
939     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
940     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
942     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
943     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
944   }
945
946   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
947     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
948
949     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
950     // registers cannot be used even for integer operations.
951     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
952     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
953     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
954     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
955
956     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
957     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
958     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
959     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
960     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
961     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
962     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
963     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
964     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
965     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
966     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
967     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
968     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
969     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
971     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
972     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
973     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
974     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
975     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
976     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
977     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
978
979     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
980     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
981     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
982     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
983
984     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
985     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
989
990     // Only provide customized ctpop vector bit twiddling for vector types we
991     // know to perform better than using the popcnt instructions on each vector
992     // element. If popcnt isn't supported, always provide the custom version.
993     if (!Subtarget->hasPOPCNT()) {
994       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
995       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
996     }
997
998     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
999     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1000       MVT VT = (MVT::SimpleValueType)i;
1001       // Do not attempt to custom lower non-power-of-2 vectors
1002       if (!isPowerOf2_32(VT.getVectorNumElements()))
1003         continue;
1004       // Do not attempt to custom lower non-128-bit vectors
1005       if (!VT.is128BitVector())
1006         continue;
1007       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1008       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1009       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1010     }
1011
1012     // We support custom legalizing of sext and anyext loads for specific
1013     // memory vector types which we can load as a scalar (or sequence of
1014     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1015     // loads these must work with a single scalar load.
1016     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1017     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1018     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1019     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1020     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1021     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1022     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1025
1026     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1027     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1028     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1029     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1030     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1031     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1032
1033     if (Subtarget->is64Bit()) {
1034       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1035       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1036     }
1037
1038     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1039     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1040       MVT VT = (MVT::SimpleValueType)i;
1041
1042       // Do not attempt to promote non-128-bit vectors
1043       if (!VT.is128BitVector())
1044         continue;
1045
1046       setOperationAction(ISD::AND,    VT, Promote);
1047       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1048       setOperationAction(ISD::OR,     VT, Promote);
1049       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1050       setOperationAction(ISD::XOR,    VT, Promote);
1051       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1052       setOperationAction(ISD::LOAD,   VT, Promote);
1053       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1054       setOperationAction(ISD::SELECT, VT, Promote);
1055       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1056     }
1057
1058     // Custom lower v2i64 and v2f64 selects.
1059     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1060     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1061     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1062     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1063
1064     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1065     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1066
1067     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1068     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1069     // As there is no 64-bit GPR available, we need build a special custom
1070     // sequence to convert from v2i32 to v2f32.
1071     if (!Subtarget->is64Bit())
1072       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1073
1074     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1075     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1076
1077     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1078
1079     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1080     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1081     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1082   }
1083
1084   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1085     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1086     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1087     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1088     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1089     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1090     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1091     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1092     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1093     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1094     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1095
1096     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1099     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1101     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1102     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1103     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1104     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1105     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1106
1107     // FIXME: Do we need to handle scalar-to-vector here?
1108     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1109
1110     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1111     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1112     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1113     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1114     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1115     // There is no BLENDI for byte vectors. We don't need to custom lower
1116     // some vselects for now.
1117     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1118
1119     // SSE41 brings specific instructions for doing vector sign extend even in
1120     // cases where we don't have SRA.
1121     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1122     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1123     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1124
1125     // i8 and i16 vectors are custom because the source register and source
1126     // source memory operand types are not the same width.  f32 vectors are
1127     // custom since the immediate controlling the insert encodes additional
1128     // information.
1129     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1130     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1131     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1132     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1133
1134     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1135     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1136     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1137     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1138
1139     // FIXME: these should be Legal, but that's only for the case where
1140     // the index is constant.  For now custom expand to deal with that.
1141     if (Subtarget->is64Bit()) {
1142       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1143       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1144     }
1145   }
1146
1147   if (Subtarget->hasSSE2()) {
1148     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1149     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1150
1151     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1152     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1153
1154     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1155     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1156
1157     // In the customized shift lowering, the legal cases in AVX2 will be
1158     // recognized.
1159     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1160     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1161
1162     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1163     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1164
1165     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1166   }
1167
1168   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1169     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1170     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1171     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1172     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1173     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1174     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1175
1176     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1177     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1178     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1179
1180     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1181     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1182     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1183     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1184     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1185     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1186     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1187     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1188     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1189     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1190     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1191     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1192
1193     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1194     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1195     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1196     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1197     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1198     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1199     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1200     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1201     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1202     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1203     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1204     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1205
1206     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1207     // even though v8i16 is a legal type.
1208     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1209     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1210     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1211
1212     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1213     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1214     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1215
1216     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1217     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1218
1219     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1220
1221     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1222     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1223
1224     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1225     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1226
1227     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1228     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1229
1230     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1231     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1232     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1233     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1234
1235     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1236     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1237     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1238
1239     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1240     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1241     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1242     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1243
1244     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1245     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1246     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1247     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1248     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1249     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1250     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1251     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1252     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1253     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1254     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1255     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1256
1257     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1258       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1259       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1260       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1261       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1262       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1263       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1264     }
1265
1266     if (Subtarget->hasInt256()) {
1267       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1268       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1269       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1270       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1271
1272       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1273       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1274       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1275       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1276
1277       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1278       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1279       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1280       // Don't lower v32i8 because there is no 128-bit byte mul
1281
1282       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1283       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1284       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1285       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1286
1287       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1288       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1289
1290       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1291       // when we have a 256bit-wide blend with immediate.
1292       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1293
1294       // Only provide customized ctpop vector bit twiddling for vector types we
1295       // know to perform better than using the popcnt instructions on each
1296       // vector element. If popcnt isn't supported, always provide the custom
1297       // version.
1298       if (!Subtarget->hasPOPCNT())
1299         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1300
1301       // Custom CTPOP always performs better on natively supported v8i32
1302       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1303     } else {
1304       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1305       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1306       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1307       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1308
1309       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1310       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1311       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1312       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1313
1314       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1315       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1316       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1317       // Don't lower v32i8 because there is no 128-bit byte mul
1318     }
1319
1320     // In the customized shift lowering, the legal cases in AVX2 will be
1321     // recognized.
1322     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1323     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1324
1325     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1326     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1327
1328     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1329
1330     // Custom lower several nodes for 256-bit types.
1331     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1332              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1333       MVT VT = (MVT::SimpleValueType)i;
1334
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::INSERT_VECTOR_ELT,  VT, Custom);
1351       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1352       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1353       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1354       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1355     }
1356
1357     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1358     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1359       MVT VT = (MVT::SimpleValueType)i;
1360
1361       // Do not attempt to promote non-256-bit vectors
1362       if (!VT.is256BitVector())
1363         continue;
1364
1365       setOperationAction(ISD::AND,    VT, Promote);
1366       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1367       setOperationAction(ISD::OR,     VT, Promote);
1368       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1369       setOperationAction(ISD::XOR,    VT, Promote);
1370       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1371       setOperationAction(ISD::LOAD,   VT, Promote);
1372       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1373       setOperationAction(ISD::SELECT, VT, Promote);
1374       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1375     }
1376   }
1377
1378   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1379     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1380     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1381     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1382     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1383
1384     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1385     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1386     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1387
1388     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1389     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1390     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1391     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1392     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1393     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1394     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1395     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1397     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1398     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1399
1400     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1401     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1402     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1403     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1404     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1405     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1406
1407     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1408     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1409     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1410     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1411     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1412     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1413     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1414     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1415
1416     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1417     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1420     if (Subtarget->is64Bit()) {
1421       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1422       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1423       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1424       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1425     }
1426     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1427     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1428     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1429     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1430     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1431     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1432     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1433     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1434     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1435     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1436     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1437     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1438     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1439     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1440
1441     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1442     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1443     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1444     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1445     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1446     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1447     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1448     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1449     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1450     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1451     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1452     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1453     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1454
1455     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1456     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1457     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1458     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1459     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1460     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1461
1462     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1463     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1464
1465     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1466
1467     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1468     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1469     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1470     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1471     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1472     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1473     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1474     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1475     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1476
1477     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1479
1480     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1482
1483     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1484
1485     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1486     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1487
1488     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1489     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1490
1491     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1492     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1493
1494     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1495     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1496     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1497     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1498     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1499     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1500
1501     if (Subtarget->hasCDI()) {
1502       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1503       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1504     }
1505
1506     // Custom lower several nodes.
1507     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1508              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1509       MVT VT = (MVT::SimpleValueType)i;
1510
1511       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1512       // Extract subvector is special because the value type
1513       // (result) is 256/128-bit but the source is 512-bit wide.
1514       if (VT.is128BitVector() || VT.is256BitVector()) {
1515         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1516       }
1517       if (VT.getVectorElementType() == MVT::i1)
1518         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1519
1520       // Do not attempt to custom lower other non-512-bit vectors
1521       if (!VT.is512BitVector())
1522         continue;
1523
1524       if ( EltSize >= 32) {
1525         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1526         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1527         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1528         setOperationAction(ISD::VSELECT,             VT, Legal);
1529         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1530         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1531         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1532         setOperationAction(ISD::MLOAD,               VT, Legal);
1533         setOperationAction(ISD::MSTORE,              VT, Legal);
1534       }
1535     }
1536     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1537       MVT VT = (MVT::SimpleValueType)i;
1538
1539       // Do not attempt to promote non-256-bit vectors.
1540       if (!VT.is512BitVector())
1541         continue;
1542
1543       setOperationAction(ISD::SELECT, VT, Promote);
1544       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1545     }
1546   }// has  AVX-512
1547
1548   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1549     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1550     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1551
1552     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1553     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1554
1555     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1556     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1557     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1558     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1559     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1560     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1561     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1562     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1563     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1564
1565     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1566       const MVT VT = (MVT::SimpleValueType)i;
1567
1568       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1569
1570       // Do not attempt to promote non-256-bit vectors.
1571       if (!VT.is512BitVector())
1572         continue;
1573
1574       if (EltSize < 32) {
1575         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1576         setOperationAction(ISD::VSELECT,             VT, Legal);
1577       }
1578     }
1579   }
1580
1581   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1582     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1583     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1584
1585     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1586     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1587     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Legal);
1588
1589     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1590     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1591     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1592     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1593     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1594     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1595   }
1596
1597   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1598   // of this type with custom code.
1599   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1600            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1601     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1602                        Custom);
1603   }
1604
1605   // We want to custom lower some of our intrinsics.
1606   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1607   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1608   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1609   if (!Subtarget->is64Bit())
1610     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1611
1612   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1613   // handle type legalization for these operations here.
1614   //
1615   // FIXME: We really should do custom legalization for addition and
1616   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1617   // than generic legalization for 64-bit multiplication-with-overflow, though.
1618   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1619     // Add/Sub/Mul with overflow operations are custom lowered.
1620     MVT VT = IntVTs[i];
1621     setOperationAction(ISD::SADDO, VT, Custom);
1622     setOperationAction(ISD::UADDO, VT, Custom);
1623     setOperationAction(ISD::SSUBO, VT, Custom);
1624     setOperationAction(ISD::USUBO, VT, Custom);
1625     setOperationAction(ISD::SMULO, VT, Custom);
1626     setOperationAction(ISD::UMULO, VT, Custom);
1627   }
1628
1629
1630   if (!Subtarget->is64Bit()) {
1631     // These libcalls are not available in 32-bit.
1632     setLibcallName(RTLIB::SHL_I128, nullptr);
1633     setLibcallName(RTLIB::SRL_I128, nullptr);
1634     setLibcallName(RTLIB::SRA_I128, nullptr);
1635   }
1636
1637   // Combine sin / cos into one node or libcall if possible.
1638   if (Subtarget->hasSinCos()) {
1639     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1640     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1641     if (Subtarget->isTargetDarwin()) {
1642       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1643       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1644       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1645       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1646     }
1647   }
1648
1649   if (Subtarget->isTargetWin64()) {
1650     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1651     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1652     setOperationAction(ISD::SREM, MVT::i128, Custom);
1653     setOperationAction(ISD::UREM, MVT::i128, Custom);
1654     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1655     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1656   }
1657
1658   // We have target-specific dag combine patterns for the following nodes:
1659   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1660   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1661   setTargetDAGCombine(ISD::VSELECT);
1662   setTargetDAGCombine(ISD::SELECT);
1663   setTargetDAGCombine(ISD::SHL);
1664   setTargetDAGCombine(ISD::SRA);
1665   setTargetDAGCombine(ISD::SRL);
1666   setTargetDAGCombine(ISD::OR);
1667   setTargetDAGCombine(ISD::AND);
1668   setTargetDAGCombine(ISD::ADD);
1669   setTargetDAGCombine(ISD::FADD);
1670   setTargetDAGCombine(ISD::FSUB);
1671   setTargetDAGCombine(ISD::FMA);
1672   setTargetDAGCombine(ISD::SUB);
1673   setTargetDAGCombine(ISD::LOAD);
1674   setTargetDAGCombine(ISD::STORE);
1675   setTargetDAGCombine(ISD::ZERO_EXTEND);
1676   setTargetDAGCombine(ISD::ANY_EXTEND);
1677   setTargetDAGCombine(ISD::SIGN_EXTEND);
1678   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1679   setTargetDAGCombine(ISD::TRUNCATE);
1680   setTargetDAGCombine(ISD::SINT_TO_FP);
1681   setTargetDAGCombine(ISD::SETCC);
1682   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1683   setTargetDAGCombine(ISD::BUILD_VECTOR);
1684   if (Subtarget->is64Bit())
1685     setTargetDAGCombine(ISD::MUL);
1686   setTargetDAGCombine(ISD::XOR);
1687
1688   computeRegisterProperties();
1689
1690   // On Darwin, -Os means optimize for size without hurting performance,
1691   // do not reduce the limit.
1692   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1693   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1694   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1695   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1696   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1697   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1698   setPrefLoopAlignment(4); // 2^4 bytes.
1699
1700   // Predictable cmov don't hurt on atom because it's in-order.
1701   PredictableSelectIsExpensive = !Subtarget->isAtom();
1702   EnableExtLdPromotion = true;
1703   setPrefFunctionAlignment(4); // 2^4 bytes.
1704
1705   verifyIntrinsicTables();
1706 }
1707
1708 // This has so far only been implemented for 64-bit MachO.
1709 bool X86TargetLowering::useLoadStackGuardNode() const {
1710   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1711 }
1712
1713 TargetLoweringBase::LegalizeTypeAction
1714 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1715   if (ExperimentalVectorWideningLegalization &&
1716       VT.getVectorNumElements() != 1 &&
1717       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1718     return TypeWidenVector;
1719
1720   return TargetLoweringBase::getPreferredVectorAction(VT);
1721 }
1722
1723 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1724   if (!VT.isVector())
1725     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1726
1727   const unsigned NumElts = VT.getVectorNumElements();
1728   const EVT EltVT = VT.getVectorElementType();
1729   if (VT.is512BitVector()) {
1730     if (Subtarget->hasAVX512())
1731       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1732           EltVT == MVT::f32 || EltVT == MVT::f64)
1733         switch(NumElts) {
1734         case  8: return MVT::v8i1;
1735         case 16: return MVT::v16i1;
1736       }
1737     if (Subtarget->hasBWI())
1738       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1739         switch(NumElts) {
1740         case 32: return MVT::v32i1;
1741         case 64: return MVT::v64i1;
1742       }
1743   }
1744
1745   if (VT.is256BitVector() || VT.is128BitVector()) {
1746     if (Subtarget->hasVLX())
1747       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1748           EltVT == MVT::f32 || EltVT == MVT::f64)
1749         switch(NumElts) {
1750         case 2: return MVT::v2i1;
1751         case 4: return MVT::v4i1;
1752         case 8: return MVT::v8i1;
1753       }
1754     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1755       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1756         switch(NumElts) {
1757         case  8: return MVT::v8i1;
1758         case 16: return MVT::v16i1;
1759         case 32: return MVT::v32i1;
1760       }
1761   }
1762
1763   return VT.changeVectorElementTypeToInteger();
1764 }
1765
1766 /// Helper for getByValTypeAlignment to determine
1767 /// the desired ByVal argument alignment.
1768 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1769   if (MaxAlign == 16)
1770     return;
1771   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1772     if (VTy->getBitWidth() == 128)
1773       MaxAlign = 16;
1774   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1775     unsigned EltAlign = 0;
1776     getMaxByValAlign(ATy->getElementType(), EltAlign);
1777     if (EltAlign > MaxAlign)
1778       MaxAlign = EltAlign;
1779   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1780     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1781       unsigned EltAlign = 0;
1782       getMaxByValAlign(STy->getElementType(i), EltAlign);
1783       if (EltAlign > MaxAlign)
1784         MaxAlign = EltAlign;
1785       if (MaxAlign == 16)
1786         break;
1787     }
1788   }
1789 }
1790
1791 /// Return the desired alignment for ByVal aggregate
1792 /// function arguments in the caller parameter area. For X86, aggregates
1793 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1794 /// are at 4-byte boundaries.
1795 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1796   if (Subtarget->is64Bit()) {
1797     // Max of 8 and alignment of type.
1798     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1799     if (TyAlign > 8)
1800       return TyAlign;
1801     return 8;
1802   }
1803
1804   unsigned Align = 4;
1805   if (Subtarget->hasSSE1())
1806     getMaxByValAlign(Ty, Align);
1807   return Align;
1808 }
1809
1810 /// Returns the target specific optimal type for load
1811 /// and store operations as a result of memset, memcpy, and memmove
1812 /// lowering. If DstAlign is zero that means it's safe to destination
1813 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1814 /// means there isn't a need to check it against alignment requirement,
1815 /// probably because the source does not need to be loaded. If 'IsMemset' is
1816 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1817 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1818 /// source is constant so it does not need to be loaded.
1819 /// It returns EVT::Other if the type should be determined using generic
1820 /// target-independent logic.
1821 EVT
1822 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1823                                        unsigned DstAlign, unsigned SrcAlign,
1824                                        bool IsMemset, bool ZeroMemset,
1825                                        bool MemcpyStrSrc,
1826                                        MachineFunction &MF) const {
1827   const Function *F = MF.getFunction();
1828   if ((!IsMemset || ZeroMemset) &&
1829       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1830                                        Attribute::NoImplicitFloat)) {
1831     if (Size >= 16 &&
1832         (Subtarget->isUnalignedMemAccessFast() ||
1833          ((DstAlign == 0 || DstAlign >= 16) &&
1834           (SrcAlign == 0 || SrcAlign >= 16)))) {
1835       if (Size >= 32) {
1836         if (Subtarget->hasInt256())
1837           return MVT::v8i32;
1838         if (Subtarget->hasFp256())
1839           return MVT::v8f32;
1840       }
1841       if (Subtarget->hasSSE2())
1842         return MVT::v4i32;
1843       if (Subtarget->hasSSE1())
1844         return MVT::v4f32;
1845     } else if (!MemcpyStrSrc && Size >= 8 &&
1846                !Subtarget->is64Bit() &&
1847                Subtarget->hasSSE2()) {
1848       // Do not use f64 to lower memcpy if source is string constant. It's
1849       // better to use i32 to avoid the loads.
1850       return MVT::f64;
1851     }
1852   }
1853   if (Subtarget->is64Bit() && Size >= 8)
1854     return MVT::i64;
1855   return MVT::i32;
1856 }
1857
1858 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1859   if (VT == MVT::f32)
1860     return X86ScalarSSEf32;
1861   else if (VT == MVT::f64)
1862     return X86ScalarSSEf64;
1863   return true;
1864 }
1865
1866 bool
1867 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1868                                                   unsigned,
1869                                                   unsigned,
1870                                                   bool *Fast) const {
1871   if (Fast)
1872     *Fast = Subtarget->isUnalignedMemAccessFast();
1873   return true;
1874 }
1875
1876 /// Return the entry encoding for a jump table in the
1877 /// current function.  The returned value is a member of the
1878 /// MachineJumpTableInfo::JTEntryKind enum.
1879 unsigned X86TargetLowering::getJumpTableEncoding() const {
1880   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1881   // symbol.
1882   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1883       Subtarget->isPICStyleGOT())
1884     return MachineJumpTableInfo::EK_Custom32;
1885
1886   // Otherwise, use the normal jump table encoding heuristics.
1887   return TargetLowering::getJumpTableEncoding();
1888 }
1889
1890 const MCExpr *
1891 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1892                                              const MachineBasicBlock *MBB,
1893                                              unsigned uid,MCContext &Ctx) const{
1894   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1895          Subtarget->isPICStyleGOT());
1896   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1897   // entries.
1898   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1899                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1900 }
1901
1902 /// Returns relocation base for the given PIC jumptable.
1903 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1904                                                     SelectionDAG &DAG) const {
1905   if (!Subtarget->is64Bit())
1906     // This doesn't have SDLoc associated with it, but is not really the
1907     // same as a Register.
1908     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1909   return Table;
1910 }
1911
1912 /// This returns the relocation base for the given PIC jumptable,
1913 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1914 const MCExpr *X86TargetLowering::
1915 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1916                              MCContext &Ctx) const {
1917   // X86-64 uses RIP relative addressing based on the jump table label.
1918   if (Subtarget->isPICStyleRIPRel())
1919     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1920
1921   // Otherwise, the reference is relative to the PIC base.
1922   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1923 }
1924
1925 // FIXME: Why this routine is here? Move to RegInfo!
1926 std::pair<const TargetRegisterClass*, uint8_t>
1927 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1928   const TargetRegisterClass *RRC = nullptr;
1929   uint8_t Cost = 1;
1930   switch (VT.SimpleTy) {
1931   default:
1932     return TargetLowering::findRepresentativeClass(VT);
1933   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1934     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1935     break;
1936   case MVT::x86mmx:
1937     RRC = &X86::VR64RegClass;
1938     break;
1939   case MVT::f32: case MVT::f64:
1940   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1941   case MVT::v4f32: case MVT::v2f64:
1942   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1943   case MVT::v4f64:
1944     RRC = &X86::VR128RegClass;
1945     break;
1946   }
1947   return std::make_pair(RRC, Cost);
1948 }
1949
1950 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1951                                                unsigned &Offset) const {
1952   if (!Subtarget->isTargetLinux())
1953     return false;
1954
1955   if (Subtarget->is64Bit()) {
1956     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1957     Offset = 0x28;
1958     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1959       AddressSpace = 256;
1960     else
1961       AddressSpace = 257;
1962   } else {
1963     // %gs:0x14 on i386
1964     Offset = 0x14;
1965     AddressSpace = 256;
1966   }
1967   return true;
1968 }
1969
1970 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1971                                             unsigned DestAS) const {
1972   assert(SrcAS != DestAS && "Expected different address spaces!");
1973
1974   return SrcAS < 256 && DestAS < 256;
1975 }
1976
1977 //===----------------------------------------------------------------------===//
1978 //               Return Value Calling Convention Implementation
1979 //===----------------------------------------------------------------------===//
1980
1981 #include "X86GenCallingConv.inc"
1982
1983 bool
1984 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1985                                   MachineFunction &MF, bool isVarArg,
1986                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1987                         LLVMContext &Context) const {
1988   SmallVector<CCValAssign, 16> RVLocs;
1989   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1990   return CCInfo.CheckReturn(Outs, RetCC_X86);
1991 }
1992
1993 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1994   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1995   return ScratchRegs;
1996 }
1997
1998 SDValue
1999 X86TargetLowering::LowerReturn(SDValue Chain,
2000                                CallingConv::ID CallConv, bool isVarArg,
2001                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2002                                const SmallVectorImpl<SDValue> &OutVals,
2003                                SDLoc dl, SelectionDAG &DAG) const {
2004   MachineFunction &MF = DAG.getMachineFunction();
2005   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2006
2007   SmallVector<CCValAssign, 16> RVLocs;
2008   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2009   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2010
2011   SDValue Flag;
2012   SmallVector<SDValue, 6> RetOps;
2013   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2014   // Operand #1 = Bytes To Pop
2015   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2016                    MVT::i16));
2017
2018   // Copy the result values into the output registers.
2019   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2020     CCValAssign &VA = RVLocs[i];
2021     assert(VA.isRegLoc() && "Can only return in registers!");
2022     SDValue ValToCopy = OutVals[i];
2023     EVT ValVT = ValToCopy.getValueType();
2024
2025     // Promote values to the appropriate types.
2026     if (VA.getLocInfo() == CCValAssign::SExt)
2027       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2028     else if (VA.getLocInfo() == CCValAssign::ZExt)
2029       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2030     else if (VA.getLocInfo() == CCValAssign::AExt)
2031       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2032     else if (VA.getLocInfo() == CCValAssign::BCvt)
2033       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2034
2035     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2036            "Unexpected FP-extend for return value.");
2037
2038     // If this is x86-64, and we disabled SSE, we can't return FP values,
2039     // or SSE or MMX vectors.
2040     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2041          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2042           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2043       report_fatal_error("SSE register return with SSE disabled");
2044     }
2045     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2046     // llvm-gcc has never done it right and no one has noticed, so this
2047     // should be OK for now.
2048     if (ValVT == MVT::f64 &&
2049         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2050       report_fatal_error("SSE2 register return with SSE2 disabled");
2051
2052     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2053     // the RET instruction and handled by the FP Stackifier.
2054     if (VA.getLocReg() == X86::FP0 ||
2055         VA.getLocReg() == X86::FP1) {
2056       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2057       // change the value to the FP stack register class.
2058       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2059         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2060       RetOps.push_back(ValToCopy);
2061       // Don't emit a copytoreg.
2062       continue;
2063     }
2064
2065     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2066     // which is returned in RAX / RDX.
2067     if (Subtarget->is64Bit()) {
2068       if (ValVT == MVT::x86mmx) {
2069         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2070           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2071           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2072                                   ValToCopy);
2073           // If we don't have SSE2 available, convert to v4f32 so the generated
2074           // register is legal.
2075           if (!Subtarget->hasSSE2())
2076             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2077         }
2078       }
2079     }
2080
2081     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2082     Flag = Chain.getValue(1);
2083     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2084   }
2085
2086   // The x86-64 ABIs require that for returning structs by value we copy
2087   // the sret argument into %rax/%eax (depending on ABI) for the return.
2088   // Win32 requires us to put the sret argument to %eax as well.
2089   // We saved the argument into a virtual register in the entry block,
2090   // so now we copy the value out and into %rax/%eax.
2091   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2092       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2093     MachineFunction &MF = DAG.getMachineFunction();
2094     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2095     unsigned Reg = FuncInfo->getSRetReturnReg();
2096     assert(Reg &&
2097            "SRetReturnReg should have been set in LowerFormalArguments().");
2098     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2099
2100     unsigned RetValReg
2101         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2102           X86::RAX : X86::EAX;
2103     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2104     Flag = Chain.getValue(1);
2105
2106     // RAX/EAX now acts like a return value.
2107     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2108   }
2109
2110   RetOps[0] = Chain;  // Update chain.
2111
2112   // Add the flag if we have it.
2113   if (Flag.getNode())
2114     RetOps.push_back(Flag);
2115
2116   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2117 }
2118
2119 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2120   if (N->getNumValues() != 1)
2121     return false;
2122   if (!N->hasNUsesOfValue(1, 0))
2123     return false;
2124
2125   SDValue TCChain = Chain;
2126   SDNode *Copy = *N->use_begin();
2127   if (Copy->getOpcode() == ISD::CopyToReg) {
2128     // If the copy has a glue operand, we conservatively assume it isn't safe to
2129     // perform a tail call.
2130     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2131       return false;
2132     TCChain = Copy->getOperand(0);
2133   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2134     return false;
2135
2136   bool HasRet = false;
2137   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2138        UI != UE; ++UI) {
2139     if (UI->getOpcode() != X86ISD::RET_FLAG)
2140       return false;
2141     // If we are returning more than one value, we can definitely
2142     // not make a tail call see PR19530
2143     if (UI->getNumOperands() > 4)
2144       return false;
2145     if (UI->getNumOperands() == 4 &&
2146         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2147       return false;
2148     HasRet = true;
2149   }
2150
2151   if (!HasRet)
2152     return false;
2153
2154   Chain = TCChain;
2155   return true;
2156 }
2157
2158 EVT
2159 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2160                                             ISD::NodeType ExtendKind) const {
2161   MVT ReturnMVT;
2162   // TODO: Is this also valid on 32-bit?
2163   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2164     ReturnMVT = MVT::i8;
2165   else
2166     ReturnMVT = MVT::i32;
2167
2168   EVT MinVT = getRegisterType(Context, ReturnMVT);
2169   return VT.bitsLT(MinVT) ? MinVT : VT;
2170 }
2171
2172 /// Lower the result values of a call into the
2173 /// appropriate copies out of appropriate physical registers.
2174 ///
2175 SDValue
2176 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2177                                    CallingConv::ID CallConv, bool isVarArg,
2178                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2179                                    SDLoc dl, SelectionDAG &DAG,
2180                                    SmallVectorImpl<SDValue> &InVals) const {
2181
2182   // Assign locations to each value returned by this call.
2183   SmallVector<CCValAssign, 16> RVLocs;
2184   bool Is64Bit = Subtarget->is64Bit();
2185   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2186                  *DAG.getContext());
2187   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2188
2189   // Copy all of the result registers out of their specified physreg.
2190   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2191     CCValAssign &VA = RVLocs[i];
2192     EVT CopyVT = VA.getValVT();
2193
2194     // If this is x86-64, and we disabled SSE, we can't return FP values
2195     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2196         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2197       report_fatal_error("SSE register return with SSE disabled");
2198     }
2199
2200     // If we prefer to use the value in xmm registers, copy it out as f80 and
2201     // use a truncate to move it from fp stack reg to xmm reg.
2202     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2203         isScalarFPTypeInSSEReg(VA.getValVT()))
2204       CopyVT = MVT::f80;
2205
2206     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2207                                CopyVT, InFlag).getValue(1);
2208     SDValue Val = Chain.getValue(0);
2209
2210     if (CopyVT != VA.getValVT())
2211       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2212                         // This truncation won't change the value.
2213                         DAG.getIntPtrConstant(1));
2214
2215     InFlag = Chain.getValue(2);
2216     InVals.push_back(Val);
2217   }
2218
2219   return Chain;
2220 }
2221
2222 //===----------------------------------------------------------------------===//
2223 //                C & StdCall & Fast Calling Convention implementation
2224 //===----------------------------------------------------------------------===//
2225 //  StdCall calling convention seems to be standard for many Windows' API
2226 //  routines and around. It differs from C calling convention just a little:
2227 //  callee should clean up the stack, not caller. Symbols should be also
2228 //  decorated in some fancy way :) It doesn't support any vector arguments.
2229 //  For info on fast calling convention see Fast Calling Convention (tail call)
2230 //  implementation LowerX86_32FastCCCallTo.
2231
2232 /// CallIsStructReturn - Determines whether a call uses struct return
2233 /// semantics.
2234 enum StructReturnType {
2235   NotStructReturn,
2236   RegStructReturn,
2237   StackStructReturn
2238 };
2239 static StructReturnType
2240 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2241   if (Outs.empty())
2242     return NotStructReturn;
2243
2244   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2245   if (!Flags.isSRet())
2246     return NotStructReturn;
2247   if (Flags.isInReg())
2248     return RegStructReturn;
2249   return StackStructReturn;
2250 }
2251
2252 /// Determines whether a function uses struct return semantics.
2253 static StructReturnType
2254 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2255   if (Ins.empty())
2256     return NotStructReturn;
2257
2258   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2259   if (!Flags.isSRet())
2260     return NotStructReturn;
2261   if (Flags.isInReg())
2262     return RegStructReturn;
2263   return StackStructReturn;
2264 }
2265
2266 /// Make a copy of an aggregate at address specified by "Src" to address
2267 /// "Dst" with size and alignment information specified by the specific
2268 /// parameter attribute. The copy will be passed as a byval function parameter.
2269 static SDValue
2270 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2271                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2272                           SDLoc dl) {
2273   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2274
2275   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2276                        /*isVolatile*/false, /*AlwaysInline=*/true,
2277                        MachinePointerInfo(), MachinePointerInfo());
2278 }
2279
2280 /// Return true if the calling convention is one that
2281 /// supports tail call optimization.
2282 static bool IsTailCallConvention(CallingConv::ID CC) {
2283   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2284           CC == CallingConv::HiPE);
2285 }
2286
2287 /// \brief Return true if the calling convention is a C calling convention.
2288 static bool IsCCallConvention(CallingConv::ID CC) {
2289   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2290           CC == CallingConv::X86_64_SysV);
2291 }
2292
2293 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2294   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2295     return false;
2296
2297   CallSite CS(CI);
2298   CallingConv::ID CalleeCC = CS.getCallingConv();
2299   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2300     return false;
2301
2302   return true;
2303 }
2304
2305 /// Return true if the function is being made into
2306 /// a tailcall target by changing its ABI.
2307 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2308                                    bool GuaranteedTailCallOpt) {
2309   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2310 }
2311
2312 SDValue
2313 X86TargetLowering::LowerMemArgument(SDValue Chain,
2314                                     CallingConv::ID CallConv,
2315                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2316                                     SDLoc dl, SelectionDAG &DAG,
2317                                     const CCValAssign &VA,
2318                                     MachineFrameInfo *MFI,
2319                                     unsigned i) const {
2320   // Create the nodes corresponding to a load from this parameter slot.
2321   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2322   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2323       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2324   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2325   EVT ValVT;
2326
2327   // If value is passed by pointer we have address passed instead of the value
2328   // itself.
2329   if (VA.getLocInfo() == CCValAssign::Indirect)
2330     ValVT = VA.getLocVT();
2331   else
2332     ValVT = VA.getValVT();
2333
2334   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2335   // changed with more analysis.
2336   // In case of tail call optimization mark all arguments mutable. Since they
2337   // could be overwritten by lowering of arguments in case of a tail call.
2338   if (Flags.isByVal()) {
2339     unsigned Bytes = Flags.getByValSize();
2340     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2341     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2342     return DAG.getFrameIndex(FI, getPointerTy());
2343   } else {
2344     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2345                                     VA.getLocMemOffset(), isImmutable);
2346     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2347     return DAG.getLoad(ValVT, dl, Chain, FIN,
2348                        MachinePointerInfo::getFixedStack(FI),
2349                        false, false, false, 0);
2350   }
2351 }
2352
2353 // FIXME: Get this from tablegen.
2354 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2355                                                 const X86Subtarget *Subtarget) {
2356   assert(Subtarget->is64Bit());
2357
2358   if (Subtarget->isCallingConvWin64(CallConv)) {
2359     static const MCPhysReg GPR64ArgRegsWin64[] = {
2360       X86::RCX, X86::RDX, X86::R8,  X86::R9
2361     };
2362     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2363   }
2364
2365   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2366     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2367   };
2368   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2369 }
2370
2371 // FIXME: Get this from tablegen.
2372 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2373                                                 CallingConv::ID CallConv,
2374                                                 const X86Subtarget *Subtarget) {
2375   assert(Subtarget->is64Bit());
2376   if (Subtarget->isCallingConvWin64(CallConv)) {
2377     // The XMM registers which might contain var arg parameters are shadowed
2378     // in their paired GPR.  So we only need to save the GPR to their home
2379     // slots.
2380     // TODO: __vectorcall will change this.
2381     return None;
2382   }
2383
2384   const Function *Fn = MF.getFunction();
2385   bool NoImplicitFloatOps = Fn->getAttributes().
2386       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2387   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2388          "SSE register cannot be used when SSE is disabled!");
2389   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2390       !Subtarget->hasSSE1())
2391     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2392     // registers.
2393     return None;
2394
2395   static const MCPhysReg XMMArgRegs64Bit[] = {
2396     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2397     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2398   };
2399   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2400 }
2401
2402 SDValue
2403 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2404                                         CallingConv::ID CallConv,
2405                                         bool isVarArg,
2406                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2407                                         SDLoc dl,
2408                                         SelectionDAG &DAG,
2409                                         SmallVectorImpl<SDValue> &InVals)
2410                                           const {
2411   MachineFunction &MF = DAG.getMachineFunction();
2412   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2413
2414   const Function* Fn = MF.getFunction();
2415   if (Fn->hasExternalLinkage() &&
2416       Subtarget->isTargetCygMing() &&
2417       Fn->getName() == "main")
2418     FuncInfo->setForceFramePointer(true);
2419
2420   MachineFrameInfo *MFI = MF.getFrameInfo();
2421   bool Is64Bit = Subtarget->is64Bit();
2422   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2423
2424   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2425          "Var args not supported with calling convention fastcc, ghc or hipe");
2426
2427   // Assign locations to all of the incoming arguments.
2428   SmallVector<CCValAssign, 16> ArgLocs;
2429   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2430
2431   // Allocate shadow area for Win64
2432   if (IsWin64)
2433     CCInfo.AllocateStack(32, 8);
2434
2435   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2436
2437   unsigned LastVal = ~0U;
2438   SDValue ArgValue;
2439   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2440     CCValAssign &VA = ArgLocs[i];
2441     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2442     // places.
2443     assert(VA.getValNo() != LastVal &&
2444            "Don't support value assigned to multiple locs yet");
2445     (void)LastVal;
2446     LastVal = VA.getValNo();
2447
2448     if (VA.isRegLoc()) {
2449       EVT RegVT = VA.getLocVT();
2450       const TargetRegisterClass *RC;
2451       if (RegVT == MVT::i32)
2452         RC = &X86::GR32RegClass;
2453       else if (Is64Bit && RegVT == MVT::i64)
2454         RC = &X86::GR64RegClass;
2455       else if (RegVT == MVT::f32)
2456         RC = &X86::FR32RegClass;
2457       else if (RegVT == MVT::f64)
2458         RC = &X86::FR64RegClass;
2459       else if (RegVT.is512BitVector())
2460         RC = &X86::VR512RegClass;
2461       else if (RegVT.is256BitVector())
2462         RC = &X86::VR256RegClass;
2463       else if (RegVT.is128BitVector())
2464         RC = &X86::VR128RegClass;
2465       else if (RegVT == MVT::x86mmx)
2466         RC = &X86::VR64RegClass;
2467       else if (RegVT == MVT::i1)
2468         RC = &X86::VK1RegClass;
2469       else if (RegVT == MVT::v8i1)
2470         RC = &X86::VK8RegClass;
2471       else if (RegVT == MVT::v16i1)
2472         RC = &X86::VK16RegClass;
2473       else if (RegVT == MVT::v32i1)
2474         RC = &X86::VK32RegClass;
2475       else if (RegVT == MVT::v64i1)
2476         RC = &X86::VK64RegClass;
2477       else
2478         llvm_unreachable("Unknown argument type!");
2479
2480       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2481       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2482
2483       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2484       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2485       // right size.
2486       if (VA.getLocInfo() == CCValAssign::SExt)
2487         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2488                                DAG.getValueType(VA.getValVT()));
2489       else if (VA.getLocInfo() == CCValAssign::ZExt)
2490         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2491                                DAG.getValueType(VA.getValVT()));
2492       else if (VA.getLocInfo() == CCValAssign::BCvt)
2493         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2494
2495       if (VA.isExtInLoc()) {
2496         // Handle MMX values passed in XMM regs.
2497         if (RegVT.isVector())
2498           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2499         else
2500           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2501       }
2502     } else {
2503       assert(VA.isMemLoc());
2504       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2505     }
2506
2507     // If value is passed via pointer - do a load.
2508     if (VA.getLocInfo() == CCValAssign::Indirect)
2509       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2510                              MachinePointerInfo(), false, false, false, 0);
2511
2512     InVals.push_back(ArgValue);
2513   }
2514
2515   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2516     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2517       // The x86-64 ABIs require that for returning structs by value we copy
2518       // the sret argument into %rax/%eax (depending on ABI) for the return.
2519       // Win32 requires us to put the sret argument to %eax as well.
2520       // Save the argument into a virtual register so that we can access it
2521       // from the return points.
2522       if (Ins[i].Flags.isSRet()) {
2523         unsigned Reg = FuncInfo->getSRetReturnReg();
2524         if (!Reg) {
2525           MVT PtrTy = getPointerTy();
2526           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2527           FuncInfo->setSRetReturnReg(Reg);
2528         }
2529         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2530         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2531         break;
2532       }
2533     }
2534   }
2535
2536   unsigned StackSize = CCInfo.getNextStackOffset();
2537   // Align stack specially for tail calls.
2538   if (FuncIsMadeTailCallSafe(CallConv,
2539                              MF.getTarget().Options.GuaranteedTailCallOpt))
2540     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2541
2542   // If the function takes variable number of arguments, make a frame index for
2543   // the start of the first vararg value... for expansion of llvm.va_start. We
2544   // can skip this if there are no va_start calls.
2545   if (MFI->hasVAStart() &&
2546       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2547                    CallConv != CallingConv::X86_ThisCall))) {
2548     FuncInfo->setVarArgsFrameIndex(
2549         MFI->CreateFixedObject(1, StackSize, true));
2550   }
2551
2552   // 64-bit calling conventions support varargs and register parameters, so we
2553   // have to do extra work to spill them in the prologue or forward them to
2554   // musttail calls.
2555   if (Is64Bit && isVarArg &&
2556       (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2557     // Find the first unallocated argument registers.
2558     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2559     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2560     unsigned NumIntRegs =
2561         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2562     unsigned NumXMMRegs =
2563         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2564     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2565            "SSE register cannot be used when SSE is disabled!");
2566
2567     // Gather all the live in physical registers.
2568     SmallVector<SDValue, 6> LiveGPRs;
2569     SmallVector<SDValue, 8> LiveXMMRegs;
2570     SDValue ALVal;
2571     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2572       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2573       LiveGPRs.push_back(
2574           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2575     }
2576     if (!ArgXMMs.empty()) {
2577       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2578       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2579       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2580         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2581         LiveXMMRegs.push_back(
2582             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2583       }
2584     }
2585
2586     // Store them to the va_list returned by va_start.
2587     if (MFI->hasVAStart()) {
2588       if (IsWin64) {
2589         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2590         // Get to the caller-allocated home save location.  Add 8 to account
2591         // for the return address.
2592         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2593         FuncInfo->setRegSaveFrameIndex(
2594           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2595         // Fixup to set vararg frame on shadow area (4 x i64).
2596         if (NumIntRegs < 4)
2597           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2598       } else {
2599         // For X86-64, if there are vararg parameters that are passed via
2600         // registers, then we must store them to their spots on the stack so
2601         // they may be loaded by deferencing the result of va_next.
2602         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2603         FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2604         FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2605             ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2606       }
2607
2608       // Store the integer parameter registers.
2609       SmallVector<SDValue, 8> MemOps;
2610       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2611                                         getPointerTy());
2612       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2613       for (SDValue Val : LiveGPRs) {
2614         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2615                                   DAG.getIntPtrConstant(Offset));
2616         SDValue Store =
2617           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2618                        MachinePointerInfo::getFixedStack(
2619                          FuncInfo->getRegSaveFrameIndex(), Offset),
2620                        false, false, 0);
2621         MemOps.push_back(Store);
2622         Offset += 8;
2623       }
2624
2625       if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2626         // Now store the XMM (fp + vector) parameter registers.
2627         SmallVector<SDValue, 12> SaveXMMOps;
2628         SaveXMMOps.push_back(Chain);
2629         SaveXMMOps.push_back(ALVal);
2630         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2631                                FuncInfo->getRegSaveFrameIndex()));
2632         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2633                                FuncInfo->getVarArgsFPOffset()));
2634         SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2635                           LiveXMMRegs.end());
2636         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2637                                      MVT::Other, SaveXMMOps));
2638       }
2639
2640       if (!MemOps.empty())
2641         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2642     } else {
2643       // Add all GPRs, al, and XMMs to the list of forwards.  We will add then
2644       // to the liveout set on a musttail call.
2645       assert(MFI->hasMustTailInVarArgFunc());
2646       auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2647       typedef X86MachineFunctionInfo::Forward Forward;
2648
2649       for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2650         unsigned VReg =
2651             MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2652         Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2653         Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2654       }
2655
2656       if (!ArgXMMs.empty()) {
2657         unsigned ALVReg =
2658             MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2659         Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2660         Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2661
2662         for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2663           unsigned VReg =
2664               MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2665           Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2666           Forwards.push_back(
2667               Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2668         }
2669       }
2670     }
2671   }
2672
2673   // Some CCs need callee pop.
2674   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2675                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2676     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2677   } else {
2678     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2679     // If this is an sret function, the return should pop the hidden pointer.
2680     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2681         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2682         argsAreStructReturn(Ins) == StackStructReturn)
2683       FuncInfo->setBytesToPopOnReturn(4);
2684   }
2685
2686   if (!Is64Bit) {
2687     // RegSaveFrameIndex is X86-64 only.
2688     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2689     if (CallConv == CallingConv::X86_FastCall ||
2690         CallConv == CallingConv::X86_ThisCall)
2691       // fastcc functions can't have varargs.
2692       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2693   }
2694
2695   FuncInfo->setArgumentStackSize(StackSize);
2696
2697   return Chain;
2698 }
2699
2700 SDValue
2701 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2702                                     SDValue StackPtr, SDValue Arg,
2703                                     SDLoc dl, SelectionDAG &DAG,
2704                                     const CCValAssign &VA,
2705                                     ISD::ArgFlagsTy Flags) const {
2706   unsigned LocMemOffset = VA.getLocMemOffset();
2707   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2708   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2709   if (Flags.isByVal())
2710     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2711
2712   return DAG.getStore(Chain, dl, Arg, PtrOff,
2713                       MachinePointerInfo::getStack(LocMemOffset),
2714                       false, false, 0);
2715 }
2716
2717 /// Emit a load of return address if tail call
2718 /// optimization is performed and it is required.
2719 SDValue
2720 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2721                                            SDValue &OutRetAddr, SDValue Chain,
2722                                            bool IsTailCall, bool Is64Bit,
2723                                            int FPDiff, SDLoc dl) const {
2724   // Adjust the Return address stack slot.
2725   EVT VT = getPointerTy();
2726   OutRetAddr = getReturnAddressFrameIndex(DAG);
2727
2728   // Load the "old" Return address.
2729   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2730                            false, false, false, 0);
2731   return SDValue(OutRetAddr.getNode(), 1);
2732 }
2733
2734 /// Emit a store of the return address if tail call
2735 /// optimization is performed and it is required (FPDiff!=0).
2736 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2737                                         SDValue Chain, SDValue RetAddrFrIdx,
2738                                         EVT PtrVT, unsigned SlotSize,
2739                                         int FPDiff, SDLoc dl) {
2740   // Store the return address to the appropriate stack slot.
2741   if (!FPDiff) return Chain;
2742   // Calculate the new stack slot for the return address.
2743   int NewReturnAddrFI =
2744     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2745                                          false);
2746   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2747   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2748                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2749                        false, false, 0);
2750   return Chain;
2751 }
2752
2753 SDValue
2754 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2755                              SmallVectorImpl<SDValue> &InVals) const {
2756   SelectionDAG &DAG                     = CLI.DAG;
2757   SDLoc &dl                             = CLI.DL;
2758   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2759   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2760   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2761   SDValue Chain                         = CLI.Chain;
2762   SDValue Callee                        = CLI.Callee;
2763   CallingConv::ID CallConv              = CLI.CallConv;
2764   bool &isTailCall                      = CLI.IsTailCall;
2765   bool isVarArg                         = CLI.IsVarArg;
2766
2767   MachineFunction &MF = DAG.getMachineFunction();
2768   bool Is64Bit        = Subtarget->is64Bit();
2769   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2770   StructReturnType SR = callIsStructReturn(Outs);
2771   bool IsSibcall      = false;
2772   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2773
2774   if (MF.getTarget().Options.DisableTailCalls)
2775     isTailCall = false;
2776
2777   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2778   if (IsMustTail) {
2779     // Force this to be a tail call.  The verifier rules are enough to ensure
2780     // that we can lower this successfully without moving the return address
2781     // around.
2782     isTailCall = true;
2783   } else if (isTailCall) {
2784     // Check if it's really possible to do a tail call.
2785     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2786                     isVarArg, SR != NotStructReturn,
2787                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2788                     Outs, OutVals, Ins, DAG);
2789
2790     // Sibcalls are automatically detected tailcalls which do not require
2791     // ABI changes.
2792     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2793       IsSibcall = true;
2794
2795     if (isTailCall)
2796       ++NumTailCalls;
2797   }
2798
2799   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2800          "Var args not supported with calling convention fastcc, ghc or hipe");
2801
2802   // Analyze operands of the call, assigning locations to each operand.
2803   SmallVector<CCValAssign, 16> ArgLocs;
2804   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2805
2806   // Allocate shadow area for Win64
2807   if (IsWin64)
2808     CCInfo.AllocateStack(32, 8);
2809
2810   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2811
2812   // Get a count of how many bytes are to be pushed on the stack.
2813   unsigned NumBytes = CCInfo.getNextStackOffset();
2814   if (IsSibcall)
2815     // This is a sibcall. The memory operands are available in caller's
2816     // own caller's stack.
2817     NumBytes = 0;
2818   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2819            IsTailCallConvention(CallConv))
2820     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2821
2822   int FPDiff = 0;
2823   if (isTailCall && !IsSibcall && !IsMustTail) {
2824     // Lower arguments at fp - stackoffset + fpdiff.
2825     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2826
2827     FPDiff = NumBytesCallerPushed - NumBytes;
2828
2829     // Set the delta of movement of the returnaddr stackslot.
2830     // But only set if delta is greater than previous delta.
2831     if (FPDiff < X86Info->getTCReturnAddrDelta())
2832       X86Info->setTCReturnAddrDelta(FPDiff);
2833   }
2834
2835   unsigned NumBytesToPush = NumBytes;
2836   unsigned NumBytesToPop = NumBytes;
2837
2838   // If we have an inalloca argument, all stack space has already been allocated
2839   // for us and be right at the top of the stack.  We don't support multiple
2840   // arguments passed in memory when using inalloca.
2841   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2842     NumBytesToPush = 0;
2843     if (!ArgLocs.back().isMemLoc())
2844       report_fatal_error("cannot use inalloca attribute on a register "
2845                          "parameter");
2846     if (ArgLocs.back().getLocMemOffset() != 0)
2847       report_fatal_error("any parameter with the inalloca attribute must be "
2848                          "the only memory argument");
2849   }
2850
2851   if (!IsSibcall)
2852     Chain = DAG.getCALLSEQ_START(
2853         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2854
2855   SDValue RetAddrFrIdx;
2856   // Load return address for tail calls.
2857   if (isTailCall && FPDiff)
2858     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2859                                     Is64Bit, FPDiff, dl);
2860
2861   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2862   SmallVector<SDValue, 8> MemOpChains;
2863   SDValue StackPtr;
2864
2865   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2866   // of tail call optimization arguments are handle later.
2867   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2868       DAG.getSubtarget().getRegisterInfo());
2869   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2870     // Skip inalloca arguments, they have already been written.
2871     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2872     if (Flags.isInAlloca())
2873       continue;
2874
2875     CCValAssign &VA = ArgLocs[i];
2876     EVT RegVT = VA.getLocVT();
2877     SDValue Arg = OutVals[i];
2878     bool isByVal = Flags.isByVal();
2879
2880     // Promote the value if needed.
2881     switch (VA.getLocInfo()) {
2882     default: llvm_unreachable("Unknown loc info!");
2883     case CCValAssign::Full: break;
2884     case CCValAssign::SExt:
2885       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2886       break;
2887     case CCValAssign::ZExt:
2888       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2889       break;
2890     case CCValAssign::AExt:
2891       if (RegVT.is128BitVector()) {
2892         // Special case: passing MMX values in XMM registers.
2893         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2894         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2895         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2896       } else
2897         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2898       break;
2899     case CCValAssign::BCvt:
2900       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2901       break;
2902     case CCValAssign::Indirect: {
2903       // Store the argument.
2904       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2905       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2906       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2907                            MachinePointerInfo::getFixedStack(FI),
2908                            false, false, 0);
2909       Arg = SpillSlot;
2910       break;
2911     }
2912     }
2913
2914     if (VA.isRegLoc()) {
2915       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2916       if (isVarArg && IsWin64) {
2917         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2918         // shadow reg if callee is a varargs function.
2919         unsigned ShadowReg = 0;
2920         switch (VA.getLocReg()) {
2921         case X86::XMM0: ShadowReg = X86::RCX; break;
2922         case X86::XMM1: ShadowReg = X86::RDX; break;
2923         case X86::XMM2: ShadowReg = X86::R8; break;
2924         case X86::XMM3: ShadowReg = X86::R9; break;
2925         }
2926         if (ShadowReg)
2927           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2928       }
2929     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2930       assert(VA.isMemLoc());
2931       if (!StackPtr.getNode())
2932         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2933                                       getPointerTy());
2934       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2935                                              dl, DAG, VA, Flags));
2936     }
2937   }
2938
2939   if (!MemOpChains.empty())
2940     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2941
2942   if (Subtarget->isPICStyleGOT()) {
2943     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2944     // GOT pointer.
2945     if (!isTailCall) {
2946       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2947                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2948     } else {
2949       // If we are tail calling and generating PIC/GOT style code load the
2950       // address of the callee into ECX. The value in ecx is used as target of
2951       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2952       // for tail calls on PIC/GOT architectures. Normally we would just put the
2953       // address of GOT into ebx and then call target@PLT. But for tail calls
2954       // ebx would be restored (since ebx is callee saved) before jumping to the
2955       // target@PLT.
2956
2957       // Note: The actual moving to ECX is done further down.
2958       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2959       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2960           !G->getGlobal()->hasProtectedVisibility())
2961         Callee = LowerGlobalAddress(Callee, DAG);
2962       else if (isa<ExternalSymbolSDNode>(Callee))
2963         Callee = LowerExternalSymbol(Callee, DAG);
2964     }
2965   }
2966
2967   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2968     // From AMD64 ABI document:
2969     // For calls that may call functions that use varargs or stdargs
2970     // (prototype-less calls or calls to functions containing ellipsis (...) in
2971     // the declaration) %al is used as hidden argument to specify the number
2972     // of SSE registers used. The contents of %al do not need to match exactly
2973     // the number of registers, but must be an ubound on the number of SSE
2974     // registers used and is in the range 0 - 8 inclusive.
2975
2976     // Count the number of XMM registers allocated.
2977     static const MCPhysReg XMMArgRegs[] = {
2978       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2979       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2980     };
2981     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2982     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2983            && "SSE registers cannot be used when SSE is disabled");
2984
2985     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2986                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2987   }
2988
2989   if (Is64Bit && isVarArg && IsMustTail) {
2990     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2991     for (const auto &F : Forwards) {
2992       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2993       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2994     }
2995   }
2996
2997   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2998   // don't need this because the eligibility check rejects calls that require
2999   // shuffling arguments passed in memory.
3000   if (!IsSibcall && isTailCall) {
3001     // Force all the incoming stack arguments to be loaded from the stack
3002     // before any new outgoing arguments are stored to the stack, because the
3003     // outgoing stack slots may alias the incoming argument stack slots, and
3004     // the alias isn't otherwise explicit. This is slightly more conservative
3005     // than necessary, because it means that each store effectively depends
3006     // on every argument instead of just those arguments it would clobber.
3007     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3008
3009     SmallVector<SDValue, 8> MemOpChains2;
3010     SDValue FIN;
3011     int FI = 0;
3012     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3013       CCValAssign &VA = ArgLocs[i];
3014       if (VA.isRegLoc())
3015         continue;
3016       assert(VA.isMemLoc());
3017       SDValue Arg = OutVals[i];
3018       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3019       // Skip inalloca arguments.  They don't require any work.
3020       if (Flags.isInAlloca())
3021         continue;
3022       // Create frame index.
3023       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3024       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3025       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3026       FIN = DAG.getFrameIndex(FI, getPointerTy());
3027
3028       if (Flags.isByVal()) {
3029         // Copy relative to framepointer.
3030         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3031         if (!StackPtr.getNode())
3032           StackPtr = DAG.getCopyFromReg(Chain, dl,
3033                                         RegInfo->getStackRegister(),
3034                                         getPointerTy());
3035         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3036
3037         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3038                                                          ArgChain,
3039                                                          Flags, DAG, dl));
3040       } else {
3041         // Store relative to framepointer.
3042         MemOpChains2.push_back(
3043           DAG.getStore(ArgChain, dl, Arg, FIN,
3044                        MachinePointerInfo::getFixedStack(FI),
3045                        false, false, 0));
3046       }
3047     }
3048
3049     if (!MemOpChains2.empty())
3050       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3051
3052     // Store the return address to the appropriate stack slot.
3053     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3054                                      getPointerTy(), RegInfo->getSlotSize(),
3055                                      FPDiff, dl);
3056   }
3057
3058   // Build a sequence of copy-to-reg nodes chained together with token chain
3059   // and flag operands which copy the outgoing args into registers.
3060   SDValue InFlag;
3061   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3062     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3063                              RegsToPass[i].second, InFlag);
3064     InFlag = Chain.getValue(1);
3065   }
3066
3067   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3068     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3069     // In the 64-bit large code model, we have to make all calls
3070     // through a register, since the call instruction's 32-bit
3071     // pc-relative offset may not be large enough to hold the whole
3072     // address.
3073   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3074     // If the callee is a GlobalAddress node (quite common, every direct call
3075     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3076     // it.
3077
3078     // We should use extra load for direct calls to dllimported functions in
3079     // non-JIT mode.
3080     const GlobalValue *GV = G->getGlobal();
3081     if (!GV->hasDLLImportStorageClass()) {
3082       unsigned char OpFlags = 0;
3083       bool ExtraLoad = false;
3084       unsigned WrapperKind = ISD::DELETED_NODE;
3085
3086       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3087       // external symbols most go through the PLT in PIC mode.  If the symbol
3088       // has hidden or protected visibility, or if it is static or local, then
3089       // we don't need to use the PLT - we can directly call it.
3090       if (Subtarget->isTargetELF() &&
3091           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3092           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3093         OpFlags = X86II::MO_PLT;
3094       } else if (Subtarget->isPICStyleStubAny() &&
3095                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3096                  (!Subtarget->getTargetTriple().isMacOSX() ||
3097                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3098         // PC-relative references to external symbols should go through $stub,
3099         // unless we're building with the leopard linker or later, which
3100         // automatically synthesizes these stubs.
3101         OpFlags = X86II::MO_DARWIN_STUB;
3102       } else if (Subtarget->isPICStyleRIPRel() &&
3103                  isa<Function>(GV) &&
3104                  cast<Function>(GV)->getAttributes().
3105                    hasAttribute(AttributeSet::FunctionIndex,
3106                                 Attribute::NonLazyBind)) {
3107         // If the function is marked as non-lazy, generate an indirect call
3108         // which loads from the GOT directly. This avoids runtime overhead
3109         // at the cost of eager binding (and one extra byte of encoding).
3110         OpFlags = X86II::MO_GOTPCREL;
3111         WrapperKind = X86ISD::WrapperRIP;
3112         ExtraLoad = true;
3113       }
3114
3115       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3116                                           G->getOffset(), OpFlags);
3117
3118       // Add a wrapper if needed.
3119       if (WrapperKind != ISD::DELETED_NODE)
3120         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3121       // Add extra indirection if needed.
3122       if (ExtraLoad)
3123         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3124                              MachinePointerInfo::getGOT(),
3125                              false, false, false, 0);
3126     }
3127   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3128     unsigned char OpFlags = 0;
3129
3130     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3131     // external symbols should go through the PLT.
3132     if (Subtarget->isTargetELF() &&
3133         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3134       OpFlags = X86II::MO_PLT;
3135     } else if (Subtarget->isPICStyleStubAny() &&
3136                (!Subtarget->getTargetTriple().isMacOSX() ||
3137                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3138       // PC-relative references to external symbols should go through $stub,
3139       // unless we're building with the leopard linker or later, which
3140       // automatically synthesizes these stubs.
3141       OpFlags = X86II::MO_DARWIN_STUB;
3142     }
3143
3144     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3145                                          OpFlags);
3146   } else if (Subtarget->isTarget64BitILP32() && Callee->getValueType(0) == MVT::i32) {
3147     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3148     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3149   }
3150
3151   // Returns a chain & a flag for retval copy to use.
3152   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3153   SmallVector<SDValue, 8> Ops;
3154
3155   if (!IsSibcall && isTailCall) {
3156     Chain = DAG.getCALLSEQ_END(Chain,
3157                                DAG.getIntPtrConstant(NumBytesToPop, true),
3158                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3159     InFlag = Chain.getValue(1);
3160   }
3161
3162   Ops.push_back(Chain);
3163   Ops.push_back(Callee);
3164
3165   if (isTailCall)
3166     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3167
3168   // Add argument registers to the end of the list so that they are known live
3169   // into the call.
3170   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3171     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3172                                   RegsToPass[i].second.getValueType()));
3173
3174   // Add a register mask operand representing the call-preserved registers.
3175   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3176   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3177   assert(Mask && "Missing call preserved mask for calling convention");
3178   Ops.push_back(DAG.getRegisterMask(Mask));
3179
3180   if (InFlag.getNode())
3181     Ops.push_back(InFlag);
3182
3183   if (isTailCall) {
3184     // We used to do:
3185     //// If this is the first return lowered for this function, add the regs
3186     //// to the liveout set for the function.
3187     // This isn't right, although it's probably harmless on x86; liveouts
3188     // should be computed from returns not tail calls.  Consider a void
3189     // function making a tail call to a function returning int.
3190     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3191   }
3192
3193   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3194   InFlag = Chain.getValue(1);
3195
3196   // Create the CALLSEQ_END node.
3197   unsigned NumBytesForCalleeToPop;
3198   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3199                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3200     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3201   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3202            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3203            SR == StackStructReturn)
3204     // If this is a call to a struct-return function, the callee
3205     // pops the hidden struct pointer, so we have to push it back.
3206     // This is common for Darwin/X86, Linux & Mingw32 targets.
3207     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3208     NumBytesForCalleeToPop = 4;
3209   else
3210     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3211
3212   // Returns a flag for retval copy to use.
3213   if (!IsSibcall) {
3214     Chain = DAG.getCALLSEQ_END(Chain,
3215                                DAG.getIntPtrConstant(NumBytesToPop, true),
3216                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3217                                                      true),
3218                                InFlag, dl);
3219     InFlag = Chain.getValue(1);
3220   }
3221
3222   // Handle result values, copying them out of physregs into vregs that we
3223   // return.
3224   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3225                          Ins, dl, DAG, InVals);
3226 }
3227
3228 //===----------------------------------------------------------------------===//
3229 //                Fast Calling Convention (tail call) implementation
3230 //===----------------------------------------------------------------------===//
3231
3232 //  Like std call, callee cleans arguments, convention except that ECX is
3233 //  reserved for storing the tail called function address. Only 2 registers are
3234 //  free for argument passing (inreg). Tail call optimization is performed
3235 //  provided:
3236 //                * tailcallopt is enabled
3237 //                * caller/callee are fastcc
3238 //  On X86_64 architecture with GOT-style position independent code only local
3239 //  (within module) calls are supported at the moment.
3240 //  To keep the stack aligned according to platform abi the function
3241 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3242 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3243 //  If a tail called function callee has more arguments than the caller the
3244 //  caller needs to make sure that there is room to move the RETADDR to. This is
3245 //  achieved by reserving an area the size of the argument delta right after the
3246 //  original RETADDR, but before the saved framepointer or the spilled registers
3247 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3248 //  stack layout:
3249 //    arg1
3250 //    arg2
3251 //    RETADDR
3252 //    [ new RETADDR
3253 //      move area ]
3254 //    (possible EBP)
3255 //    ESI
3256 //    EDI
3257 //    local1 ..
3258
3259 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3260 /// for a 16 byte align requirement.
3261 unsigned
3262 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3263                                                SelectionDAG& DAG) const {
3264   MachineFunction &MF = DAG.getMachineFunction();
3265   const TargetMachine &TM = MF.getTarget();
3266   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3267       TM.getSubtargetImpl()->getRegisterInfo());
3268   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3269   unsigned StackAlignment = TFI.getStackAlignment();
3270   uint64_t AlignMask = StackAlignment - 1;
3271   int64_t Offset = StackSize;
3272   unsigned SlotSize = RegInfo->getSlotSize();
3273   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3274     // Number smaller than 12 so just add the difference.
3275     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3276   } else {
3277     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3278     Offset = ((~AlignMask) & Offset) + StackAlignment +
3279       (StackAlignment-SlotSize);
3280   }
3281   return Offset;
3282 }
3283
3284 /// MatchingStackOffset - Return true if the given stack call argument is
3285 /// already available in the same position (relatively) of the caller's
3286 /// incoming argument stack.
3287 static
3288 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3289                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3290                          const X86InstrInfo *TII) {
3291   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3292   int FI = INT_MAX;
3293   if (Arg.getOpcode() == ISD::CopyFromReg) {
3294     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3295     if (!TargetRegisterInfo::isVirtualRegister(VR))
3296       return false;
3297     MachineInstr *Def = MRI->getVRegDef(VR);
3298     if (!Def)
3299       return false;
3300     if (!Flags.isByVal()) {
3301       if (!TII->isLoadFromStackSlot(Def, FI))
3302         return false;
3303     } else {
3304       unsigned Opcode = Def->getOpcode();
3305       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3306           Def->getOperand(1).isFI()) {
3307         FI = Def->getOperand(1).getIndex();
3308         Bytes = Flags.getByValSize();
3309       } else
3310         return false;
3311     }
3312   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3313     if (Flags.isByVal())
3314       // ByVal argument is passed in as a pointer but it's now being
3315       // dereferenced. e.g.
3316       // define @foo(%struct.X* %A) {
3317       //   tail call @bar(%struct.X* byval %A)
3318       // }
3319       return false;
3320     SDValue Ptr = Ld->getBasePtr();
3321     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3322     if (!FINode)
3323       return false;
3324     FI = FINode->getIndex();
3325   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3326     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3327     FI = FINode->getIndex();
3328     Bytes = Flags.getByValSize();
3329   } else
3330     return false;
3331
3332   assert(FI != INT_MAX);
3333   if (!MFI->isFixedObjectIndex(FI))
3334     return false;
3335   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3336 }
3337
3338 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3339 /// for tail call optimization. Targets which want to do tail call
3340 /// optimization should implement this function.
3341 bool
3342 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3343                                                      CallingConv::ID CalleeCC,
3344                                                      bool isVarArg,
3345                                                      bool isCalleeStructRet,
3346                                                      bool isCallerStructRet,
3347                                                      Type *RetTy,
3348                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3349                                     const SmallVectorImpl<SDValue> &OutVals,
3350                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3351                                                      SelectionDAG &DAG) const {
3352   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3353     return false;
3354
3355   // If -tailcallopt is specified, make fastcc functions tail-callable.
3356   const MachineFunction &MF = DAG.getMachineFunction();
3357   const Function *CallerF = MF.getFunction();
3358
3359   // If the function return type is x86_fp80 and the callee return type is not,
3360   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3361   // perform a tailcall optimization here.
3362   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3363     return false;
3364
3365   CallingConv::ID CallerCC = CallerF->getCallingConv();
3366   bool CCMatch = CallerCC == CalleeCC;
3367   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3368   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3369
3370   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3371     if (IsTailCallConvention(CalleeCC) && CCMatch)
3372       return true;
3373     return false;
3374   }
3375
3376   // Look for obvious safe cases to perform tail call optimization that do not
3377   // require ABI changes. This is what gcc calls sibcall.
3378
3379   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3380   // emit a special epilogue.
3381   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3382       DAG.getSubtarget().getRegisterInfo());
3383   if (RegInfo->needsStackRealignment(MF))
3384     return false;
3385
3386   // Also avoid sibcall optimization if either caller or callee uses struct
3387   // return semantics.
3388   if (isCalleeStructRet || isCallerStructRet)
3389     return false;
3390
3391   // An stdcall/thiscall caller is expected to clean up its arguments; the
3392   // callee isn't going to do that.
3393   // FIXME: this is more restrictive than needed. We could produce a tailcall
3394   // when the stack adjustment matches. For example, with a thiscall that takes
3395   // only one argument.
3396   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3397                    CallerCC == CallingConv::X86_ThisCall))
3398     return false;
3399
3400   // Do not sibcall optimize vararg calls unless all arguments are passed via
3401   // registers.
3402   if (isVarArg && !Outs.empty()) {
3403
3404     // Optimizing for varargs on Win64 is unlikely to be safe without
3405     // additional testing.
3406     if (IsCalleeWin64 || IsCallerWin64)
3407       return false;
3408
3409     SmallVector<CCValAssign, 16> ArgLocs;
3410     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3411                    *DAG.getContext());
3412
3413     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3414     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3415       if (!ArgLocs[i].isRegLoc())
3416         return false;
3417   }
3418
3419   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3420   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3421   // this into a sibcall.
3422   bool Unused = false;
3423   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3424     if (!Ins[i].Used) {
3425       Unused = true;
3426       break;
3427     }
3428   }
3429   if (Unused) {
3430     SmallVector<CCValAssign, 16> RVLocs;
3431     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3432                    *DAG.getContext());
3433     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3434     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3435       CCValAssign &VA = RVLocs[i];
3436       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3437         return false;
3438     }
3439   }
3440
3441   // If the calling conventions do not match, then we'd better make sure the
3442   // results are returned in the same way as what the caller expects.
3443   if (!CCMatch) {
3444     SmallVector<CCValAssign, 16> RVLocs1;
3445     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3446                     *DAG.getContext());
3447     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3448
3449     SmallVector<CCValAssign, 16> RVLocs2;
3450     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3451                     *DAG.getContext());
3452     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3453
3454     if (RVLocs1.size() != RVLocs2.size())
3455       return false;
3456     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3457       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3458         return false;
3459       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3460         return false;
3461       if (RVLocs1[i].isRegLoc()) {
3462         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3463           return false;
3464       } else {
3465         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3466           return false;
3467       }
3468     }
3469   }
3470
3471   // If the callee takes no arguments then go on to check the results of the
3472   // call.
3473   if (!Outs.empty()) {
3474     // Check if stack adjustment is needed. For now, do not do this if any
3475     // argument is passed on the stack.
3476     SmallVector<CCValAssign, 16> ArgLocs;
3477     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3478                    *DAG.getContext());
3479
3480     // Allocate shadow area for Win64
3481     if (IsCalleeWin64)
3482       CCInfo.AllocateStack(32, 8);
3483
3484     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3485     if (CCInfo.getNextStackOffset()) {
3486       MachineFunction &MF = DAG.getMachineFunction();
3487       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3488         return false;
3489
3490       // Check if the arguments are already laid out in the right way as
3491       // the caller's fixed stack objects.
3492       MachineFrameInfo *MFI = MF.getFrameInfo();
3493       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3494       const X86InstrInfo *TII =
3495           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3496       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3497         CCValAssign &VA = ArgLocs[i];
3498         SDValue Arg = OutVals[i];
3499         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3500         if (VA.getLocInfo() == CCValAssign::Indirect)
3501           return false;
3502         if (!VA.isRegLoc()) {
3503           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3504                                    MFI, MRI, TII))
3505             return false;
3506         }
3507       }
3508     }
3509
3510     // If the tailcall address may be in a register, then make sure it's
3511     // possible to register allocate for it. In 32-bit, the call address can
3512     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3513     // callee-saved registers are restored. These happen to be the same
3514     // registers used to pass 'inreg' arguments so watch out for those.
3515     if (!Subtarget->is64Bit() &&
3516         ((!isa<GlobalAddressSDNode>(Callee) &&
3517           !isa<ExternalSymbolSDNode>(Callee)) ||
3518          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3519       unsigned NumInRegs = 0;
3520       // In PIC we need an extra register to formulate the address computation
3521       // for the callee.
3522       unsigned MaxInRegs =
3523         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3524
3525       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3526         CCValAssign &VA = ArgLocs[i];
3527         if (!VA.isRegLoc())
3528           continue;
3529         unsigned Reg = VA.getLocReg();
3530         switch (Reg) {
3531         default: break;
3532         case X86::EAX: case X86::EDX: case X86::ECX:
3533           if (++NumInRegs == MaxInRegs)
3534             return false;
3535           break;
3536         }
3537       }
3538     }
3539   }
3540
3541   return true;
3542 }
3543
3544 FastISel *
3545 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3546                                   const TargetLibraryInfo *libInfo) const {
3547   return X86::createFastISel(funcInfo, libInfo);
3548 }
3549
3550 //===----------------------------------------------------------------------===//
3551 //                           Other Lowering Hooks
3552 //===----------------------------------------------------------------------===//
3553
3554 static bool MayFoldLoad(SDValue Op) {
3555   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3556 }
3557
3558 static bool MayFoldIntoStore(SDValue Op) {
3559   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3560 }
3561
3562 static bool isTargetShuffle(unsigned Opcode) {
3563   switch(Opcode) {
3564   default: return false;
3565   case X86ISD::BLENDI:
3566   case X86ISD::PSHUFB:
3567   case X86ISD::PSHUFD:
3568   case X86ISD::PSHUFHW:
3569   case X86ISD::PSHUFLW:
3570   case X86ISD::SHUFP:
3571   case X86ISD::PALIGNR:
3572   case X86ISD::MOVLHPS:
3573   case X86ISD::MOVLHPD:
3574   case X86ISD::MOVHLPS:
3575   case X86ISD::MOVLPS:
3576   case X86ISD::MOVLPD:
3577   case X86ISD::MOVSHDUP:
3578   case X86ISD::MOVSLDUP:
3579   case X86ISD::MOVDDUP:
3580   case X86ISD::MOVSS:
3581   case X86ISD::MOVSD:
3582   case X86ISD::UNPCKL:
3583   case X86ISD::UNPCKH:
3584   case X86ISD::VPERMILPI:
3585   case X86ISD::VPERM2X128:
3586   case X86ISD::VPERMI:
3587     return true;
3588   }
3589 }
3590
3591 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3592                                     SDValue V1, SelectionDAG &DAG) {
3593   switch(Opc) {
3594   default: llvm_unreachable("Unknown x86 shuffle node");
3595   case X86ISD::MOVSHDUP:
3596   case X86ISD::MOVSLDUP:
3597   case X86ISD::MOVDDUP:
3598     return DAG.getNode(Opc, dl, VT, V1);
3599   }
3600 }
3601
3602 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3603                                     SDValue V1, unsigned TargetMask,
3604                                     SelectionDAG &DAG) {
3605   switch(Opc) {
3606   default: llvm_unreachable("Unknown x86 shuffle node");
3607   case X86ISD::PSHUFD:
3608   case X86ISD::PSHUFHW:
3609   case X86ISD::PSHUFLW:
3610   case X86ISD::VPERMILPI:
3611   case X86ISD::VPERMI:
3612     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3613   }
3614 }
3615
3616 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3617                                     SDValue V1, SDValue V2, unsigned TargetMask,
3618                                     SelectionDAG &DAG) {
3619   switch(Opc) {
3620   default: llvm_unreachable("Unknown x86 shuffle node");
3621   case X86ISD::PALIGNR:
3622   case X86ISD::VALIGN:
3623   case X86ISD::SHUFP:
3624   case X86ISD::VPERM2X128:
3625     return DAG.getNode(Opc, dl, VT, V1, V2,
3626                        DAG.getConstant(TargetMask, MVT::i8));
3627   }
3628 }
3629
3630 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3631                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3632   switch(Opc) {
3633   default: llvm_unreachable("Unknown x86 shuffle node");
3634   case X86ISD::MOVLHPS:
3635   case X86ISD::MOVLHPD:
3636   case X86ISD::MOVHLPS:
3637   case X86ISD::MOVLPS:
3638   case X86ISD::MOVLPD:
3639   case X86ISD::MOVSS:
3640   case X86ISD::MOVSD:
3641   case X86ISD::UNPCKL:
3642   case X86ISD::UNPCKH:
3643     return DAG.getNode(Opc, dl, VT, V1, V2);
3644   }
3645 }
3646
3647 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3648   MachineFunction &MF = DAG.getMachineFunction();
3649   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3650       DAG.getSubtarget().getRegisterInfo());
3651   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3652   int ReturnAddrIndex = FuncInfo->getRAIndex();
3653
3654   if (ReturnAddrIndex == 0) {
3655     // Set up a frame object for the return address.
3656     unsigned SlotSize = RegInfo->getSlotSize();
3657     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3658                                                            -(int64_t)SlotSize,
3659                                                            false);
3660     FuncInfo->setRAIndex(ReturnAddrIndex);
3661   }
3662
3663   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3664 }
3665
3666 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3667                                        bool hasSymbolicDisplacement) {
3668   // Offset should fit into 32 bit immediate field.
3669   if (!isInt<32>(Offset))
3670     return false;
3671
3672   // If we don't have a symbolic displacement - we don't have any extra
3673   // restrictions.
3674   if (!hasSymbolicDisplacement)
3675     return true;
3676
3677   // FIXME: Some tweaks might be needed for medium code model.
3678   if (M != CodeModel::Small && M != CodeModel::Kernel)
3679     return false;
3680
3681   // For small code model we assume that latest object is 16MB before end of 31
3682   // bits boundary. We may also accept pretty large negative constants knowing
3683   // that all objects are in the positive half of address space.
3684   if (M == CodeModel::Small && Offset < 16*1024*1024)
3685     return true;
3686
3687   // For kernel code model we know that all object resist in the negative half
3688   // of 32bits address space. We may not accept negative offsets, since they may
3689   // be just off and we may accept pretty large positive ones.
3690   if (M == CodeModel::Kernel && Offset >= 0)
3691     return true;
3692
3693   return false;
3694 }
3695
3696 /// isCalleePop - Determines whether the callee is required to pop its
3697 /// own arguments. Callee pop is necessary to support tail calls.
3698 bool X86::isCalleePop(CallingConv::ID CallingConv,
3699                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3700   switch (CallingConv) {
3701   default:
3702     return false;
3703   case CallingConv::X86_StdCall:
3704   case CallingConv::X86_FastCall:
3705   case CallingConv::X86_ThisCall:
3706     return !is64Bit;
3707   case CallingConv::Fast:
3708   case CallingConv::GHC:
3709   case CallingConv::HiPE:
3710     if (IsVarArg)
3711       return false;
3712     return TailCallOpt;
3713   }
3714 }
3715
3716 /// \brief Return true if the condition is an unsigned comparison operation.
3717 static bool isX86CCUnsigned(unsigned X86CC) {
3718   switch (X86CC) {
3719   default: llvm_unreachable("Invalid integer condition!");
3720   case X86::COND_E:     return true;
3721   case X86::COND_G:     return false;
3722   case X86::COND_GE:    return false;
3723   case X86::COND_L:     return false;
3724   case X86::COND_LE:    return false;
3725   case X86::COND_NE:    return true;
3726   case X86::COND_B:     return true;
3727   case X86::COND_A:     return true;
3728   case X86::COND_BE:    return true;
3729   case X86::COND_AE:    return true;
3730   }
3731   llvm_unreachable("covered switch fell through?!");
3732 }
3733
3734 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3735 /// specific condition code, returning the condition code and the LHS/RHS of the
3736 /// comparison to make.
3737 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3738                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3739   if (!isFP) {
3740     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3741       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3742         // X > -1   -> X == 0, jump !sign.
3743         RHS = DAG.getConstant(0, RHS.getValueType());
3744         return X86::COND_NS;
3745       }
3746       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3747         // X < 0   -> X == 0, jump on sign.
3748         return X86::COND_S;
3749       }
3750       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3751         // X < 1   -> X <= 0
3752         RHS = DAG.getConstant(0, RHS.getValueType());
3753         return X86::COND_LE;
3754       }
3755     }
3756
3757     switch (SetCCOpcode) {
3758     default: llvm_unreachable("Invalid integer condition!");
3759     case ISD::SETEQ:  return X86::COND_E;
3760     case ISD::SETGT:  return X86::COND_G;
3761     case ISD::SETGE:  return X86::COND_GE;
3762     case ISD::SETLT:  return X86::COND_L;
3763     case ISD::SETLE:  return X86::COND_LE;
3764     case ISD::SETNE:  return X86::COND_NE;
3765     case ISD::SETULT: return X86::COND_B;
3766     case ISD::SETUGT: return X86::COND_A;
3767     case ISD::SETULE: return X86::COND_BE;
3768     case ISD::SETUGE: return X86::COND_AE;
3769     }
3770   }
3771
3772   // First determine if it is required or is profitable to flip the operands.
3773
3774   // If LHS is a foldable load, but RHS is not, flip the condition.
3775   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3776       !ISD::isNON_EXTLoad(RHS.getNode())) {
3777     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3778     std::swap(LHS, RHS);
3779   }
3780
3781   switch (SetCCOpcode) {
3782   default: break;
3783   case ISD::SETOLT:
3784   case ISD::SETOLE:
3785   case ISD::SETUGT:
3786   case ISD::SETUGE:
3787     std::swap(LHS, RHS);
3788     break;
3789   }
3790
3791   // On a floating point condition, the flags are set as follows:
3792   // ZF  PF  CF   op
3793   //  0 | 0 | 0 | X > Y
3794   //  0 | 0 | 1 | X < Y
3795   //  1 | 0 | 0 | X == Y
3796   //  1 | 1 | 1 | unordered
3797   switch (SetCCOpcode) {
3798   default: llvm_unreachable("Condcode should be pre-legalized away");
3799   case ISD::SETUEQ:
3800   case ISD::SETEQ:   return X86::COND_E;
3801   case ISD::SETOLT:              // flipped
3802   case ISD::SETOGT:
3803   case ISD::SETGT:   return X86::COND_A;
3804   case ISD::SETOLE:              // flipped
3805   case ISD::SETOGE:
3806   case ISD::SETGE:   return X86::COND_AE;
3807   case ISD::SETUGT:              // flipped
3808   case ISD::SETULT:
3809   case ISD::SETLT:   return X86::COND_B;
3810   case ISD::SETUGE:              // flipped
3811   case ISD::SETULE:
3812   case ISD::SETLE:   return X86::COND_BE;
3813   case ISD::SETONE:
3814   case ISD::SETNE:   return X86::COND_NE;
3815   case ISD::SETUO:   return X86::COND_P;
3816   case ISD::SETO:    return X86::COND_NP;
3817   case ISD::SETOEQ:
3818   case ISD::SETUNE:  return X86::COND_INVALID;
3819   }
3820 }
3821
3822 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3823 /// code. Current x86 isa includes the following FP cmov instructions:
3824 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3825 static bool hasFPCMov(unsigned X86CC) {
3826   switch (X86CC) {
3827   default:
3828     return false;
3829   case X86::COND_B:
3830   case X86::COND_BE:
3831   case X86::COND_E:
3832   case X86::COND_P:
3833   case X86::COND_A:
3834   case X86::COND_AE:
3835   case X86::COND_NE:
3836   case X86::COND_NP:
3837     return true;
3838   }
3839 }
3840
3841 /// isFPImmLegal - Returns true if the target can instruction select the
3842 /// specified FP immediate natively. If false, the legalizer will
3843 /// materialize the FP immediate as a load from a constant pool.
3844 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3845   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3846     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3847       return true;
3848   }
3849   return false;
3850 }
3851
3852 /// \brief Returns true if it is beneficial to convert a load of a constant
3853 /// to just the constant itself.
3854 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3855                                                           Type *Ty) const {
3856   assert(Ty->isIntegerTy());
3857
3858   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3859   if (BitSize == 0 || BitSize > 64)
3860     return false;
3861   return true;
3862 }
3863
3864 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, 
3865                                                 unsigned Index) const {
3866   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3867     return false;
3868
3869   return (Index == 0 || Index == ResVT.getVectorNumElements());
3870 }
3871
3872 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3873 /// the specified range (L, H].
3874 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3875   return (Val < 0) || (Val >= Low && Val < Hi);
3876 }
3877
3878 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3879 /// specified value.
3880 static bool isUndefOrEqual(int Val, int CmpVal) {
3881   return (Val < 0 || Val == CmpVal);
3882 }
3883
3884 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3885 /// from position Pos and ending in Pos+Size, falls within the specified
3886 /// sequential range (L, L+Pos]. or is undef.
3887 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3888                                        unsigned Pos, unsigned Size, int Low) {
3889   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3890     if (!isUndefOrEqual(Mask[i], Low))
3891       return false;
3892   return true;
3893 }
3894
3895 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3896 /// is suitable for input to PSHUFD. That is, it doesn't reference the other
3897 /// operand - by default will match for first operand.
3898 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT,
3899                          bool TestSecondOperand = false) {
3900   if (VT != MVT::v4f32 && VT != MVT::v4i32 &&
3901       VT != MVT::v2f64 && VT != MVT::v2i64)
3902     return false;
3903
3904   unsigned NumElems = VT.getVectorNumElements();
3905   unsigned Lo = TestSecondOperand ? NumElems : 0;
3906   unsigned Hi = Lo + NumElems;
3907
3908   for (unsigned i = 0; i < NumElems; ++i)
3909     if (!isUndefOrInRange(Mask[i], (int)Lo, (int)Hi))
3910       return false;
3911
3912   return true;
3913 }
3914
3915 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3916 /// is suitable for input to PSHUFHW.
3917 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3918   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3919     return false;
3920
3921   // Lower quadword copied in order or undef.
3922   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3923     return false;
3924
3925   // Upper quadword shuffled.
3926   for (unsigned i = 4; i != 8; ++i)
3927     if (!isUndefOrInRange(Mask[i], 4, 8))
3928       return false;
3929
3930   if (VT == MVT::v16i16) {
3931     // Lower quadword copied in order or undef.
3932     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3933       return false;
3934
3935     // Upper quadword shuffled.
3936     for (unsigned i = 12; i != 16; ++i)
3937       if (!isUndefOrInRange(Mask[i], 12, 16))
3938         return false;
3939   }
3940
3941   return true;
3942 }
3943
3944 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3945 /// is suitable for input to PSHUFLW.
3946 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3947   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3948     return false;
3949
3950   // Upper quadword copied in order.
3951   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3952     return false;
3953
3954   // Lower quadword shuffled.
3955   for (unsigned i = 0; i != 4; ++i)
3956     if (!isUndefOrInRange(Mask[i], 0, 4))
3957       return false;
3958
3959   if (VT == MVT::v16i16) {
3960     // Upper quadword copied in order.
3961     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3962       return false;
3963
3964     // Lower quadword shuffled.
3965     for (unsigned i = 8; i != 12; ++i)
3966       if (!isUndefOrInRange(Mask[i], 8, 12))
3967         return false;
3968   }
3969
3970   return true;
3971 }
3972
3973 /// \brief Return true if the mask specifies a shuffle of elements that is
3974 /// suitable for input to intralane (palignr) or interlane (valign) vector
3975 /// right-shift.
3976 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3977   unsigned NumElts = VT.getVectorNumElements();
3978   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3979   unsigned NumLaneElts = NumElts/NumLanes;
3980
3981   // Do not handle 64-bit element shuffles with palignr.
3982   if (NumLaneElts == 2)
3983     return false;
3984
3985   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3986     unsigned i;
3987     for (i = 0; i != NumLaneElts; ++i) {
3988       if (Mask[i+l] >= 0)
3989         break;
3990     }
3991
3992     // Lane is all undef, go to next lane
3993     if (i == NumLaneElts)
3994       continue;
3995
3996     int Start = Mask[i+l];
3997
3998     // Make sure its in this lane in one of the sources
3999     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
4000         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
4001       return false;
4002
4003     // If not lane 0, then we must match lane 0
4004     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
4005       return false;
4006
4007     // Correct second source to be contiguous with first source
4008     if (Start >= (int)NumElts)
4009       Start -= NumElts - NumLaneElts;
4010
4011     // Make sure we're shifting in the right direction.
4012     if (Start <= (int)(i+l))
4013       return false;
4014
4015     Start -= i;
4016
4017     // Check the rest of the elements to see if they are consecutive.
4018     for (++i; i != NumLaneElts; ++i) {
4019       int Idx = Mask[i+l];
4020
4021       // Make sure its in this lane
4022       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
4023           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
4024         return false;
4025
4026       // If not lane 0, then we must match lane 0
4027       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
4028         return false;
4029
4030       if (Idx >= (int)NumElts)
4031         Idx -= NumElts - NumLaneElts;
4032
4033       if (!isUndefOrEqual(Idx, Start+i))
4034         return false;
4035
4036     }
4037   }
4038
4039   return true;
4040 }
4041
4042 /// \brief Return true if the node specifies a shuffle of elements that is
4043 /// suitable for input to PALIGNR.
4044 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4045                           const X86Subtarget *Subtarget) {
4046   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4047       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4048       VT.is512BitVector())
4049     // FIXME: Add AVX512BW.
4050     return false;
4051
4052   return isAlignrMask(Mask, VT, false);
4053 }
4054
4055 /// \brief Return true if the node specifies a shuffle of elements that is
4056 /// suitable for input to VALIGN.
4057 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4058                           const X86Subtarget *Subtarget) {
4059   // FIXME: Add AVX512VL.
4060   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4061     return false;
4062   return isAlignrMask(Mask, VT, true);
4063 }
4064
4065 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4066 /// the two vector operands have swapped position.
4067 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4068                                      unsigned NumElems) {
4069   for (unsigned i = 0; i != NumElems; ++i) {
4070     int idx = Mask[i];
4071     if (idx < 0)
4072       continue;
4073     else if (idx < (int)NumElems)
4074       Mask[i] = idx + NumElems;
4075     else
4076       Mask[i] = idx - NumElems;
4077   }
4078 }
4079
4080 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4081 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4082 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4083 /// reverse of what x86 shuffles want.
4084 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4085
4086   unsigned NumElems = VT.getVectorNumElements();
4087   unsigned NumLanes = VT.getSizeInBits()/128;
4088   unsigned NumLaneElems = NumElems/NumLanes;
4089
4090   if (NumLaneElems != 2 && NumLaneElems != 4)
4091     return false;
4092
4093   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4094   bool symetricMaskRequired =
4095     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4096
4097   // VSHUFPSY divides the resulting vector into 4 chunks.
4098   // The sources are also splitted into 4 chunks, and each destination
4099   // chunk must come from a different source chunk.
4100   //
4101   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4102   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4103   //
4104   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4105   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4106   //
4107   // VSHUFPDY divides the resulting vector into 4 chunks.
4108   // The sources are also splitted into 4 chunks, and each destination
4109   // chunk must come from a different source chunk.
4110   //
4111   //  SRC1 =>      X3       X2       X1       X0
4112   //  SRC2 =>      Y3       Y2       Y1       Y0
4113   //
4114   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4115   //
4116   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4117   unsigned HalfLaneElems = NumLaneElems/2;
4118   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4119     for (unsigned i = 0; i != NumLaneElems; ++i) {
4120       int Idx = Mask[i+l];
4121       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4122       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4123         return false;
4124       // For VSHUFPSY, the mask of the second half must be the same as the
4125       // first but with the appropriate offsets. This works in the same way as
4126       // VPERMILPS works with masks.
4127       if (!symetricMaskRequired || Idx < 0)
4128         continue;
4129       if (MaskVal[i] < 0) {
4130         MaskVal[i] = Idx - l;
4131         continue;
4132       }
4133       if ((signed)(Idx - l) != MaskVal[i])
4134         return false;
4135     }
4136   }
4137
4138   return true;
4139 }
4140
4141 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4142 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4143 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4144   if (!VT.is128BitVector())
4145     return false;
4146
4147   unsigned NumElems = VT.getVectorNumElements();
4148
4149   if (NumElems != 4)
4150     return false;
4151
4152   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4153   return isUndefOrEqual(Mask[0], 6) &&
4154          isUndefOrEqual(Mask[1], 7) &&
4155          isUndefOrEqual(Mask[2], 2) &&
4156          isUndefOrEqual(Mask[3], 3);
4157 }
4158
4159 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4160 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4161 /// <2, 3, 2, 3>
4162 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4163   if (!VT.is128BitVector())
4164     return false;
4165
4166   unsigned NumElems = VT.getVectorNumElements();
4167
4168   if (NumElems != 4)
4169     return false;
4170
4171   return isUndefOrEqual(Mask[0], 2) &&
4172          isUndefOrEqual(Mask[1], 3) &&
4173          isUndefOrEqual(Mask[2], 2) &&
4174          isUndefOrEqual(Mask[3], 3);
4175 }
4176
4177 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4178 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4179 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4180   if (!VT.is128BitVector())
4181     return false;
4182
4183   unsigned NumElems = VT.getVectorNumElements();
4184
4185   if (NumElems != 2 && NumElems != 4)
4186     return false;
4187
4188   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4189     if (!isUndefOrEqual(Mask[i], i + NumElems))
4190       return false;
4191
4192   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4193     if (!isUndefOrEqual(Mask[i], i))
4194       return false;
4195
4196   return true;
4197 }
4198
4199 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4200 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4201 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4202   if (!VT.is128BitVector())
4203     return false;
4204
4205   unsigned NumElems = VT.getVectorNumElements();
4206
4207   if (NumElems != 2 && NumElems != 4)
4208     return false;
4209
4210   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4211     if (!isUndefOrEqual(Mask[i], i))
4212       return false;
4213
4214   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4215     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4216       return false;
4217
4218   return true;
4219 }
4220
4221 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4222 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4223 /// i. e: If all but one element come from the same vector.
4224 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4225   // TODO: Deal with AVX's VINSERTPS
4226   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4227     return false;
4228
4229   unsigned CorrectPosV1 = 0;
4230   unsigned CorrectPosV2 = 0;
4231   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4232     if (Mask[i] == -1) {
4233       ++CorrectPosV1;
4234       ++CorrectPosV2;
4235       continue;
4236     }
4237
4238     if (Mask[i] == i)
4239       ++CorrectPosV1;
4240     else if (Mask[i] == i + 4)
4241       ++CorrectPosV2;
4242   }
4243
4244   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4245     // We have 3 elements (undefs count as elements from any vector) from one
4246     // vector, and one from another.
4247     return true;
4248
4249   return false;
4250 }
4251
4252 //
4253 // Some special combinations that can be optimized.
4254 //
4255 static
4256 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4257                                SelectionDAG &DAG) {
4258   MVT VT = SVOp->getSimpleValueType(0);
4259   SDLoc dl(SVOp);
4260
4261   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4262     return SDValue();
4263
4264   ArrayRef<int> Mask = SVOp->getMask();
4265
4266   // These are the special masks that may be optimized.
4267   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4268   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4269   bool MatchEvenMask = true;
4270   bool MatchOddMask  = true;
4271   for (int i=0; i<8; ++i) {
4272     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4273       MatchEvenMask = false;
4274     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4275       MatchOddMask = false;
4276   }
4277
4278   if (!MatchEvenMask && !MatchOddMask)
4279     return SDValue();
4280
4281   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4282
4283   SDValue Op0 = SVOp->getOperand(0);
4284   SDValue Op1 = SVOp->getOperand(1);
4285
4286   if (MatchEvenMask) {
4287     // Shift the second operand right to 32 bits.
4288     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4289     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4290   } else {
4291     // Shift the first operand left to 32 bits.
4292     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4293     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4294   }
4295   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4296   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4297 }
4298
4299 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4300 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4301 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4302                          bool HasInt256, bool V2IsSplat = false) {
4303
4304   assert(VT.getSizeInBits() >= 128 &&
4305          "Unsupported vector type for unpckl");
4306
4307   unsigned NumElts = VT.getVectorNumElements();
4308   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4309       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4310     return false;
4311
4312   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4313          "Unsupported vector type for unpckh");
4314
4315   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4316   unsigned NumLanes = VT.getSizeInBits()/128;
4317   unsigned NumLaneElts = NumElts/NumLanes;
4318
4319   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4320     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4321       int BitI  = Mask[l+i];
4322       int BitI1 = Mask[l+i+1];
4323       if (!isUndefOrEqual(BitI, j))
4324         return false;
4325       if (V2IsSplat) {
4326         if (!isUndefOrEqual(BitI1, NumElts))
4327           return false;
4328       } else {
4329         if (!isUndefOrEqual(BitI1, j + NumElts))
4330           return false;
4331       }
4332     }
4333   }
4334
4335   return true;
4336 }
4337
4338 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4339 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4340 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4341                          bool HasInt256, bool V2IsSplat = false) {
4342   assert(VT.getSizeInBits() >= 128 &&
4343          "Unsupported vector type for unpckh");
4344
4345   unsigned NumElts = VT.getVectorNumElements();
4346   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4347       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4348     return false;
4349
4350   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4351          "Unsupported vector type for unpckh");
4352
4353   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4354   unsigned NumLanes = VT.getSizeInBits()/128;
4355   unsigned NumLaneElts = NumElts/NumLanes;
4356
4357   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4358     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4359       int BitI  = Mask[l+i];
4360       int BitI1 = Mask[l+i+1];
4361       if (!isUndefOrEqual(BitI, j))
4362         return false;
4363       if (V2IsSplat) {
4364         if (isUndefOrEqual(BitI1, NumElts))
4365           return false;
4366       } else {
4367         if (!isUndefOrEqual(BitI1, j+NumElts))
4368           return false;
4369       }
4370     }
4371   }
4372   return true;
4373 }
4374
4375 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4376 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4377 /// <0, 0, 1, 1>
4378 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4379   unsigned NumElts = VT.getVectorNumElements();
4380   bool Is256BitVec = VT.is256BitVector();
4381
4382   if (VT.is512BitVector())
4383     return false;
4384   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4385          "Unsupported vector type for unpckh");
4386
4387   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4388       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4389     return false;
4390
4391   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4392   // FIXME: Need a better way to get rid of this, there's no latency difference
4393   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4394   // the former later. We should also remove the "_undef" special mask.
4395   if (NumElts == 4 && Is256BitVec)
4396     return false;
4397
4398   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4399   // independently on 128-bit lanes.
4400   unsigned NumLanes = VT.getSizeInBits()/128;
4401   unsigned NumLaneElts = NumElts/NumLanes;
4402
4403   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4404     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4405       int BitI  = Mask[l+i];
4406       int BitI1 = Mask[l+i+1];
4407
4408       if (!isUndefOrEqual(BitI, j))
4409         return false;
4410       if (!isUndefOrEqual(BitI1, j))
4411         return false;
4412     }
4413   }
4414
4415   return true;
4416 }
4417
4418 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4419 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4420 /// <2, 2, 3, 3>
4421 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4422   unsigned NumElts = VT.getVectorNumElements();
4423
4424   if (VT.is512BitVector())
4425     return false;
4426
4427   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4428          "Unsupported vector type for unpckh");
4429
4430   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4431       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4432     return false;
4433
4434   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4435   // independently on 128-bit lanes.
4436   unsigned NumLanes = VT.getSizeInBits()/128;
4437   unsigned NumLaneElts = NumElts/NumLanes;
4438
4439   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4440     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4441       int BitI  = Mask[l+i];
4442       int BitI1 = Mask[l+i+1];
4443       if (!isUndefOrEqual(BitI, j))
4444         return false;
4445       if (!isUndefOrEqual(BitI1, j))
4446         return false;
4447     }
4448   }
4449   return true;
4450 }
4451
4452 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4453 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4454 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4455   if (!VT.is512BitVector())
4456     return false;
4457
4458   unsigned NumElts = VT.getVectorNumElements();
4459   unsigned HalfSize = NumElts/2;
4460   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4461     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4462       *Imm = 1;
4463       return true;
4464     }
4465   }
4466   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4467     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4468       *Imm = 0;
4469       return true;
4470     }
4471   }
4472   return false;
4473 }
4474
4475 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4476 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4477 /// MOVSD, and MOVD, i.e. setting the lowest element.
4478 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4479   if (VT.getVectorElementType().getSizeInBits() < 32)
4480     return false;
4481   if (!VT.is128BitVector())
4482     return false;
4483
4484   unsigned NumElts = VT.getVectorNumElements();
4485
4486   if (!isUndefOrEqual(Mask[0], NumElts))
4487     return false;
4488
4489   for (unsigned i = 1; i != NumElts; ++i)
4490     if (!isUndefOrEqual(Mask[i], i))
4491       return false;
4492
4493   return true;
4494 }
4495
4496 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4497 /// as permutations between 128-bit chunks or halves. As an example: this
4498 /// shuffle bellow:
4499 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4500 /// The first half comes from the second half of V1 and the second half from the
4501 /// the second half of V2.
4502 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4503   if (!HasFp256 || !VT.is256BitVector())
4504     return false;
4505
4506   // The shuffle result is divided into half A and half B. In total the two
4507   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4508   // B must come from C, D, E or F.
4509   unsigned HalfSize = VT.getVectorNumElements()/2;
4510   bool MatchA = false, MatchB = false;
4511
4512   // Check if A comes from one of C, D, E, F.
4513   for (unsigned Half = 0; Half != 4; ++Half) {
4514     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4515       MatchA = true;
4516       break;
4517     }
4518   }
4519
4520   // Check if B comes from one of C, D, E, F.
4521   for (unsigned Half = 0; Half != 4; ++Half) {
4522     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4523       MatchB = true;
4524       break;
4525     }
4526   }
4527
4528   return MatchA && MatchB;
4529 }
4530
4531 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4532 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4533 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4534   MVT VT = SVOp->getSimpleValueType(0);
4535
4536   unsigned HalfSize = VT.getVectorNumElements()/2;
4537
4538   unsigned FstHalf = 0, SndHalf = 0;
4539   for (unsigned i = 0; i < HalfSize; ++i) {
4540     if (SVOp->getMaskElt(i) > 0) {
4541       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4542       break;
4543     }
4544   }
4545   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4546     if (SVOp->getMaskElt(i) > 0) {
4547       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4548       break;
4549     }
4550   }
4551
4552   return (FstHalf | (SndHalf << 4));
4553 }
4554
4555 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4556 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4557   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4558   if (EltSize < 32)
4559     return false;
4560
4561   unsigned NumElts = VT.getVectorNumElements();
4562   Imm8 = 0;
4563   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4564     for (unsigned i = 0; i != NumElts; ++i) {
4565       if (Mask[i] < 0)
4566         continue;
4567       Imm8 |= Mask[i] << (i*2);
4568     }
4569     return true;
4570   }
4571
4572   unsigned LaneSize = 4;
4573   SmallVector<int, 4> MaskVal(LaneSize, -1);
4574
4575   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4576     for (unsigned i = 0; i != LaneSize; ++i) {
4577       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4578         return false;
4579       if (Mask[i+l] < 0)
4580         continue;
4581       if (MaskVal[i] < 0) {
4582         MaskVal[i] = Mask[i+l] - l;
4583         Imm8 |= MaskVal[i] << (i*2);
4584         continue;
4585       }
4586       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4587         return false;
4588     }
4589   }
4590   return true;
4591 }
4592
4593 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4594 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4595 /// Note that VPERMIL mask matching is different depending whether theunderlying
4596 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4597 /// to the same elements of the low, but to the higher half of the source.
4598 /// In VPERMILPD the two lanes could be shuffled independently of each other
4599 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4600 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4601   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4602   if (VT.getSizeInBits() < 256 || EltSize < 32)
4603     return false;
4604   bool symetricMaskRequired = (EltSize == 32);
4605   unsigned NumElts = VT.getVectorNumElements();
4606
4607   unsigned NumLanes = VT.getSizeInBits()/128;
4608   unsigned LaneSize = NumElts/NumLanes;
4609   // 2 or 4 elements in one lane
4610
4611   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4612   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4613     for (unsigned i = 0; i != LaneSize; ++i) {
4614       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4615         return false;
4616       if (symetricMaskRequired) {
4617         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4618           ExpectedMaskVal[i] = Mask[i+l] - l;
4619           continue;
4620         }
4621         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4622           return false;
4623       }
4624     }
4625   }
4626   return true;
4627 }
4628
4629 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4630 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4631 /// element of vector 2 and the other elements to come from vector 1 in order.
4632 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4633                                bool V2IsSplat = false, bool V2IsUndef = false) {
4634   if (!VT.is128BitVector())
4635     return false;
4636
4637   unsigned NumOps = VT.getVectorNumElements();
4638   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4639     return false;
4640
4641   if (!isUndefOrEqual(Mask[0], 0))
4642     return false;
4643
4644   for (unsigned i = 1; i != NumOps; ++i)
4645     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4646           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4647           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4648       return false;
4649
4650   return true;
4651 }
4652
4653 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4654 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4655 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4656 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4657                            const X86Subtarget *Subtarget) {
4658   if (!Subtarget->hasSSE3())
4659     return false;
4660
4661   unsigned NumElems = VT.getVectorNumElements();
4662
4663   if ((VT.is128BitVector() && NumElems != 4) ||
4664       (VT.is256BitVector() && NumElems != 8) ||
4665       (VT.is512BitVector() && NumElems != 16))
4666     return false;
4667
4668   // "i+1" is the value the indexed mask element must have
4669   for (unsigned i = 0; i != NumElems; i += 2)
4670     if (!isUndefOrEqual(Mask[i], i+1) ||
4671         !isUndefOrEqual(Mask[i+1], i+1))
4672       return false;
4673
4674   return true;
4675 }
4676
4677 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4678 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4679 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4680 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4681                            const X86Subtarget *Subtarget) {
4682   if (!Subtarget->hasSSE3())
4683     return false;
4684
4685   unsigned NumElems = VT.getVectorNumElements();
4686
4687   if ((VT.is128BitVector() && NumElems != 4) ||
4688       (VT.is256BitVector() && NumElems != 8) ||
4689       (VT.is512BitVector() && NumElems != 16))
4690     return false;
4691
4692   // "i" is the value the indexed mask element must have
4693   for (unsigned i = 0; i != NumElems; i += 2)
4694     if (!isUndefOrEqual(Mask[i], i) ||
4695         !isUndefOrEqual(Mask[i+1], i))
4696       return false;
4697
4698   return true;
4699 }
4700
4701 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4702 /// specifies a shuffle of elements that is suitable for input to 256-bit
4703 /// version of MOVDDUP.
4704 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4705   if (!HasFp256 || !VT.is256BitVector())
4706     return false;
4707
4708   unsigned NumElts = VT.getVectorNumElements();
4709   if (NumElts != 4)
4710     return false;
4711
4712   for (unsigned i = 0; i != NumElts/2; ++i)
4713     if (!isUndefOrEqual(Mask[i], 0))
4714       return false;
4715   for (unsigned i = NumElts/2; i != NumElts; ++i)
4716     if (!isUndefOrEqual(Mask[i], NumElts/2))
4717       return false;
4718   return true;
4719 }
4720
4721 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4722 /// specifies a shuffle of elements that is suitable for input to 128-bit
4723 /// version of MOVDDUP.
4724 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4725   if (!VT.is128BitVector())
4726     return false;
4727
4728   unsigned e = VT.getVectorNumElements() / 2;
4729   for (unsigned i = 0; i != e; ++i)
4730     if (!isUndefOrEqual(Mask[i], i))
4731       return false;
4732   for (unsigned i = 0; i != e; ++i)
4733     if (!isUndefOrEqual(Mask[e+i], i))
4734       return false;
4735   return true;
4736 }
4737
4738 /// isVEXTRACTIndex - Return true if the specified
4739 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4740 /// suitable for instruction that extract 128 or 256 bit vectors
4741 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4742   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4743   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4744     return false;
4745
4746   // The index should be aligned on a vecWidth-bit boundary.
4747   uint64_t Index =
4748     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4749
4750   MVT VT = N->getSimpleValueType(0);
4751   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4752   bool Result = (Index * ElSize) % vecWidth == 0;
4753
4754   return Result;
4755 }
4756
4757 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4758 /// operand specifies a subvector insert that is suitable for input to
4759 /// insertion of 128 or 256-bit subvectors
4760 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4761   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4762   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4763     return false;
4764   // The index should be aligned on a vecWidth-bit boundary.
4765   uint64_t Index =
4766     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4767
4768   MVT VT = N->getSimpleValueType(0);
4769   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4770   bool Result = (Index * ElSize) % vecWidth == 0;
4771
4772   return Result;
4773 }
4774
4775 bool X86::isVINSERT128Index(SDNode *N) {
4776   return isVINSERTIndex(N, 128);
4777 }
4778
4779 bool X86::isVINSERT256Index(SDNode *N) {
4780   return isVINSERTIndex(N, 256);
4781 }
4782
4783 bool X86::isVEXTRACT128Index(SDNode *N) {
4784   return isVEXTRACTIndex(N, 128);
4785 }
4786
4787 bool X86::isVEXTRACT256Index(SDNode *N) {
4788   return isVEXTRACTIndex(N, 256);
4789 }
4790
4791 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4792 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4793 /// Handles 128-bit and 256-bit.
4794 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4795   MVT VT = N->getSimpleValueType(0);
4796
4797   assert((VT.getSizeInBits() >= 128) &&
4798          "Unsupported vector type for PSHUF/SHUFP");
4799
4800   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4801   // independently on 128-bit lanes.
4802   unsigned NumElts = VT.getVectorNumElements();
4803   unsigned NumLanes = VT.getSizeInBits()/128;
4804   unsigned NumLaneElts = NumElts/NumLanes;
4805
4806   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4807          "Only supports 2, 4 or 8 elements per lane");
4808
4809   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4810   unsigned Mask = 0;
4811   for (unsigned i = 0; i != NumElts; ++i) {
4812     int Elt = N->getMaskElt(i);
4813     if (Elt < 0) continue;
4814     Elt &= NumLaneElts - 1;
4815     unsigned ShAmt = (i << Shift) % 8;
4816     Mask |= Elt << ShAmt;
4817   }
4818
4819   return Mask;
4820 }
4821
4822 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4823 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4824 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4825   MVT VT = N->getSimpleValueType(0);
4826
4827   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4828          "Unsupported vector type for PSHUFHW");
4829
4830   unsigned NumElts = VT.getVectorNumElements();
4831
4832   unsigned Mask = 0;
4833   for (unsigned l = 0; l != NumElts; l += 8) {
4834     // 8 nodes per lane, but we only care about the last 4.
4835     for (unsigned i = 0; i < 4; ++i) {
4836       int Elt = N->getMaskElt(l+i+4);
4837       if (Elt < 0) continue;
4838       Elt &= 0x3; // only 2-bits.
4839       Mask |= Elt << (i * 2);
4840     }
4841   }
4842
4843   return Mask;
4844 }
4845
4846 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4847 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4848 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4849   MVT VT = N->getSimpleValueType(0);
4850
4851   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4852          "Unsupported vector type for PSHUFHW");
4853
4854   unsigned NumElts = VT.getVectorNumElements();
4855
4856   unsigned Mask = 0;
4857   for (unsigned l = 0; l != NumElts; l += 8) {
4858     // 8 nodes per lane, but we only care about the first 4.
4859     for (unsigned i = 0; i < 4; ++i) {
4860       int Elt = N->getMaskElt(l+i);
4861       if (Elt < 0) continue;
4862       Elt &= 0x3; // only 2-bits
4863       Mask |= Elt << (i * 2);
4864     }
4865   }
4866
4867   return Mask;
4868 }
4869
4870 /// \brief Return the appropriate immediate to shuffle the specified
4871 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4872 /// VALIGN (if Interlane is true) instructions.
4873 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4874                                            bool InterLane) {
4875   MVT VT = SVOp->getSimpleValueType(0);
4876   unsigned EltSize = InterLane ? 1 :
4877     VT.getVectorElementType().getSizeInBits() >> 3;
4878
4879   unsigned NumElts = VT.getVectorNumElements();
4880   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4881   unsigned NumLaneElts = NumElts/NumLanes;
4882
4883   int Val = 0;
4884   unsigned i;
4885   for (i = 0; i != NumElts; ++i) {
4886     Val = SVOp->getMaskElt(i);
4887     if (Val >= 0)
4888       break;
4889   }
4890   if (Val >= (int)NumElts)
4891     Val -= NumElts - NumLaneElts;
4892
4893   assert(Val - i > 0 && "PALIGNR imm should be positive");
4894   return (Val - i) * EltSize;
4895 }
4896
4897 /// \brief Return the appropriate immediate to shuffle the specified
4898 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4899 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4900   return getShuffleAlignrImmediate(SVOp, false);
4901 }
4902
4903 /// \brief Return the appropriate immediate to shuffle the specified
4904 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4905 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4906   return getShuffleAlignrImmediate(SVOp, true);
4907 }
4908
4909
4910 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4911   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4912   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4913     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4914
4915   uint64_t Index =
4916     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4917
4918   MVT VecVT = N->getOperand(0).getSimpleValueType();
4919   MVT ElVT = VecVT.getVectorElementType();
4920
4921   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4922   return Index / NumElemsPerChunk;
4923 }
4924
4925 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4926   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4927   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4928     llvm_unreachable("Illegal insert subvector for VINSERT");
4929
4930   uint64_t Index =
4931     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4932
4933   MVT VecVT = N->getSimpleValueType(0);
4934   MVT ElVT = VecVT.getVectorElementType();
4935
4936   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4937   return Index / NumElemsPerChunk;
4938 }
4939
4940 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4941 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4942 /// and VINSERTI128 instructions.
4943 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4944   return getExtractVEXTRACTImmediate(N, 128);
4945 }
4946
4947 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4948 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4949 /// and VINSERTI64x4 instructions.
4950 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4951   return getExtractVEXTRACTImmediate(N, 256);
4952 }
4953
4954 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4955 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4956 /// and VINSERTI128 instructions.
4957 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4958   return getInsertVINSERTImmediate(N, 128);
4959 }
4960
4961 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4962 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4963 /// and VINSERTI64x4 instructions.
4964 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4965   return getInsertVINSERTImmediate(N, 256);
4966 }
4967
4968 /// isZero - Returns true if Elt is a constant integer zero
4969 static bool isZero(SDValue V) {
4970   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4971   return C && C->isNullValue();
4972 }
4973
4974 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4975 /// constant +0.0.
4976 bool X86::isZeroNode(SDValue Elt) {
4977   if (isZero(Elt))
4978     return true;
4979   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4980     return CFP->getValueAPF().isPosZero();
4981   return false;
4982 }
4983
4984 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4985 /// match movhlps. The lower half elements should come from upper half of
4986 /// V1 (and in order), and the upper half elements should come from the upper
4987 /// half of V2 (and in order).
4988 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4989   if (!VT.is128BitVector())
4990     return false;
4991   if (VT.getVectorNumElements() != 4)
4992     return false;
4993   for (unsigned i = 0, e = 2; i != e; ++i)
4994     if (!isUndefOrEqual(Mask[i], i+2))
4995       return false;
4996   for (unsigned i = 2; i != 4; ++i)
4997     if (!isUndefOrEqual(Mask[i], i+4))
4998       return false;
4999   return true;
5000 }
5001
5002 /// isScalarLoadToVector - Returns true if the node is a scalar load that
5003 /// is promoted to a vector. It also returns the LoadSDNode by reference if
5004 /// required.
5005 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
5006   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
5007     return false;
5008   N = N->getOperand(0).getNode();
5009   if (!ISD::isNON_EXTLoad(N))
5010     return false;
5011   if (LD)
5012     *LD = cast<LoadSDNode>(N);
5013   return true;
5014 }
5015
5016 // Test whether the given value is a vector value which will be legalized
5017 // into a load.
5018 static bool WillBeConstantPoolLoad(SDNode *N) {
5019   if (N->getOpcode() != ISD::BUILD_VECTOR)
5020     return false;
5021
5022   // Check for any non-constant elements.
5023   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5024     switch (N->getOperand(i).getNode()->getOpcode()) {
5025     case ISD::UNDEF:
5026     case ISD::ConstantFP:
5027     case ISD::Constant:
5028       break;
5029     default:
5030       return false;
5031     }
5032
5033   // Vectors of all-zeros and all-ones are materialized with special
5034   // instructions rather than being loaded.
5035   return !ISD::isBuildVectorAllZeros(N) &&
5036          !ISD::isBuildVectorAllOnes(N);
5037 }
5038
5039 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5040 /// match movlp{s|d}. The lower half elements should come from lower half of
5041 /// V1 (and in order), and the upper half elements should come from the upper
5042 /// half of V2 (and in order). And since V1 will become the source of the
5043 /// MOVLP, it must be either a vector load or a scalar load to vector.
5044 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5045                                ArrayRef<int> Mask, MVT VT) {
5046   if (!VT.is128BitVector())
5047     return false;
5048
5049   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5050     return false;
5051   // Is V2 is a vector load, don't do this transformation. We will try to use
5052   // load folding shufps op.
5053   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5054     return false;
5055
5056   unsigned NumElems = VT.getVectorNumElements();
5057
5058   if (NumElems != 2 && NumElems != 4)
5059     return false;
5060   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5061     if (!isUndefOrEqual(Mask[i], i))
5062       return false;
5063   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5064     if (!isUndefOrEqual(Mask[i], i+NumElems))
5065       return false;
5066   return true;
5067 }
5068
5069 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5070 /// to an zero vector.
5071 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5072 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5073   SDValue V1 = N->getOperand(0);
5074   SDValue V2 = N->getOperand(1);
5075   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5076   for (unsigned i = 0; i != NumElems; ++i) {
5077     int Idx = N->getMaskElt(i);
5078     if (Idx >= (int)NumElems) {
5079       unsigned Opc = V2.getOpcode();
5080       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5081         continue;
5082       if (Opc != ISD::BUILD_VECTOR ||
5083           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5084         return false;
5085     } else if (Idx >= 0) {
5086       unsigned Opc = V1.getOpcode();
5087       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5088         continue;
5089       if (Opc != ISD::BUILD_VECTOR ||
5090           !X86::isZeroNode(V1.getOperand(Idx)))
5091         return false;
5092     }
5093   }
5094   return true;
5095 }
5096
5097 /// getZeroVector - Returns a vector of specified type with all zero elements.
5098 ///
5099 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5100                              SelectionDAG &DAG, SDLoc dl) {
5101   assert(VT.isVector() && "Expected a vector type");
5102
5103   // Always build SSE zero vectors as <4 x i32> bitcasted
5104   // to their dest type. This ensures they get CSE'd.
5105   SDValue Vec;
5106   if (VT.is128BitVector()) {  // SSE
5107     if (Subtarget->hasSSE2()) {  // SSE2
5108       SDValue Cst = DAG.getConstant(0, MVT::i32);
5109       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5110     } else { // SSE1
5111       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5112       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5113     }
5114   } else if (VT.is256BitVector()) { // AVX
5115     if (Subtarget->hasInt256()) { // AVX2
5116       SDValue Cst = DAG.getConstant(0, MVT::i32);
5117       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5118       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5119     } else {
5120       // 256-bit logic and arithmetic instructions in AVX are all
5121       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5122       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5123       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5124       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5125     }
5126   } else if (VT.is512BitVector()) { // AVX-512
5127       SDValue Cst = DAG.getConstant(0, MVT::i32);
5128       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5129                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5130       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5131   } else if (VT.getScalarType() == MVT::i1) {
5132     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5133     SDValue Cst = DAG.getConstant(0, MVT::i1);
5134     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5135     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5136   } else
5137     llvm_unreachable("Unexpected vector type");
5138
5139   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5140 }
5141
5142 /// getOnesVector - Returns a vector of specified type with all bits set.
5143 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5144 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5145 /// Then bitcast to their original type, ensuring they get CSE'd.
5146 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5147                              SDLoc dl) {
5148   assert(VT.isVector() && "Expected a vector type");
5149
5150   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
5151   SDValue Vec;
5152   if (VT.is256BitVector()) {
5153     if (HasInt256) { // AVX2
5154       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5155       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5156     } else { // AVX
5157       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5158       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5159     }
5160   } else if (VT.is128BitVector()) {
5161     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5162   } else
5163     llvm_unreachable("Unexpected vector type");
5164
5165   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5166 }
5167
5168 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5169 /// that point to V2 points to its first element.
5170 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5171   for (unsigned i = 0; i != NumElems; ++i) {
5172     if (Mask[i] > (int)NumElems) {
5173       Mask[i] = NumElems;
5174     }
5175   }
5176 }
5177
5178 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5179 /// operation of specified width.
5180 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5181                        SDValue V2) {
5182   unsigned NumElems = VT.getVectorNumElements();
5183   SmallVector<int, 8> Mask;
5184   Mask.push_back(NumElems);
5185   for (unsigned i = 1; i != NumElems; ++i)
5186     Mask.push_back(i);
5187   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5188 }
5189
5190 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5191 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5192                           SDValue V2) {
5193   unsigned NumElems = VT.getVectorNumElements();
5194   SmallVector<int, 8> Mask;
5195   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5196     Mask.push_back(i);
5197     Mask.push_back(i + NumElems);
5198   }
5199   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5200 }
5201
5202 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5203 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5204                           SDValue V2) {
5205   unsigned NumElems = VT.getVectorNumElements();
5206   SmallVector<int, 8> Mask;
5207   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5208     Mask.push_back(i + Half);
5209     Mask.push_back(i + NumElems + Half);
5210   }
5211   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5212 }
5213
5214 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5215 // a generic shuffle instruction because the target has no such instructions.
5216 // Generate shuffles which repeat i16 and i8 several times until they can be
5217 // represented by v4f32 and then be manipulated by target suported shuffles.
5218 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5219   MVT VT = V.getSimpleValueType();
5220   int NumElems = VT.getVectorNumElements();
5221   SDLoc dl(V);
5222
5223   while (NumElems > 4) {
5224     if (EltNo < NumElems/2) {
5225       V = getUnpackl(DAG, dl, VT, V, V);
5226     } else {
5227       V = getUnpackh(DAG, dl, VT, V, V);
5228       EltNo -= NumElems/2;
5229     }
5230     NumElems >>= 1;
5231   }
5232   return V;
5233 }
5234
5235 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5236 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5237   MVT VT = V.getSimpleValueType();
5238   SDLoc dl(V);
5239
5240   if (VT.is128BitVector()) {
5241     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5242     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5243     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5244                              &SplatMask[0]);
5245   } else if (VT.is256BitVector()) {
5246     // To use VPERMILPS to splat scalars, the second half of indicies must
5247     // refer to the higher part, which is a duplication of the lower one,
5248     // because VPERMILPS can only handle in-lane permutations.
5249     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5250                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5251
5252     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5253     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5254                              &SplatMask[0]);
5255   } else
5256     llvm_unreachable("Vector size not supported");
5257
5258   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5259 }
5260
5261 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5262 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5263   MVT SrcVT = SV->getSimpleValueType(0);
5264   SDValue V1 = SV->getOperand(0);
5265   SDLoc dl(SV);
5266
5267   int EltNo = SV->getSplatIndex();
5268   int NumElems = SrcVT.getVectorNumElements();
5269   bool Is256BitVec = SrcVT.is256BitVector();
5270
5271   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5272          "Unknown how to promote splat for type");
5273
5274   // Extract the 128-bit part containing the splat element and update
5275   // the splat element index when it refers to the higher register.
5276   if (Is256BitVec) {
5277     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5278     if (EltNo >= NumElems/2)
5279       EltNo -= NumElems/2;
5280   }
5281
5282   // All i16 and i8 vector types can't be used directly by a generic shuffle
5283   // instruction because the target has no such instruction. Generate shuffles
5284   // which repeat i16 and i8 several times until they fit in i32, and then can
5285   // be manipulated by target suported shuffles.
5286   MVT EltVT = SrcVT.getVectorElementType();
5287   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5288     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5289
5290   // Recreate the 256-bit vector and place the same 128-bit vector
5291   // into the low and high part. This is necessary because we want
5292   // to use VPERM* to shuffle the vectors
5293   if (Is256BitVec) {
5294     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5295   }
5296
5297   return getLegalSplat(DAG, V1, EltNo);
5298 }
5299
5300 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5301 /// vector of zero or undef vector.  This produces a shuffle where the low
5302 /// element of V2 is swizzled into the zero/undef vector, landing at element
5303 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5304 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5305                                            bool IsZero,
5306                                            const X86Subtarget *Subtarget,
5307                                            SelectionDAG &DAG) {
5308   MVT VT = V2.getSimpleValueType();
5309   SDValue V1 = IsZero
5310     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5311   unsigned NumElems = VT.getVectorNumElements();
5312   SmallVector<int, 16> MaskVec;
5313   for (unsigned i = 0; i != NumElems; ++i)
5314     // If this is the insertion idx, put the low elt of V2 here.
5315     MaskVec.push_back(i == Idx ? NumElems : i);
5316   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5317 }
5318
5319 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5320 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5321 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5322 /// shuffles which use a single input multiple times, and in those cases it will
5323 /// adjust the mask to only have indices within that single input.
5324 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5325                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5326   unsigned NumElems = VT.getVectorNumElements();
5327   SDValue ImmN;
5328
5329   IsUnary = false;
5330   bool IsFakeUnary = false;
5331   switch(N->getOpcode()) {
5332   case X86ISD::BLENDI:
5333     ImmN = N->getOperand(N->getNumOperands()-1);
5334     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5335     break;
5336   case X86ISD::SHUFP:
5337     ImmN = N->getOperand(N->getNumOperands()-1);
5338     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5339     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5340     break;
5341   case X86ISD::UNPCKH:
5342     DecodeUNPCKHMask(VT, Mask);
5343     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5344     break;
5345   case X86ISD::UNPCKL:
5346     DecodeUNPCKLMask(VT, Mask);
5347     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5348     break;
5349   case X86ISD::MOVHLPS:
5350     DecodeMOVHLPSMask(NumElems, Mask);
5351     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5352     break;
5353   case X86ISD::MOVLHPS:
5354     DecodeMOVLHPSMask(NumElems, Mask);
5355     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5356     break;
5357   case X86ISD::PALIGNR:
5358     ImmN = N->getOperand(N->getNumOperands()-1);
5359     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5360     break;
5361   case X86ISD::PSHUFD:
5362   case X86ISD::VPERMILPI:
5363     ImmN = N->getOperand(N->getNumOperands()-1);
5364     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5365     IsUnary = true;
5366     break;
5367   case X86ISD::PSHUFHW:
5368     ImmN = N->getOperand(N->getNumOperands()-1);
5369     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5370     IsUnary = true;
5371     break;
5372   case X86ISD::PSHUFLW:
5373     ImmN = N->getOperand(N->getNumOperands()-1);
5374     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5375     IsUnary = true;
5376     break;
5377   case X86ISD::PSHUFB: {
5378     IsUnary = true;
5379     SDValue MaskNode = N->getOperand(1);
5380     while (MaskNode->getOpcode() == ISD::BITCAST)
5381       MaskNode = MaskNode->getOperand(0);
5382
5383     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5384       // If we have a build-vector, then things are easy.
5385       EVT VT = MaskNode.getValueType();
5386       assert(VT.isVector() &&
5387              "Can't produce a non-vector with a build_vector!");
5388       if (!VT.isInteger())
5389         return false;
5390
5391       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5392
5393       SmallVector<uint64_t, 32> RawMask;
5394       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5395         SDValue Op = MaskNode->getOperand(i);
5396         if (Op->getOpcode() == ISD::UNDEF) {
5397           RawMask.push_back((uint64_t)SM_SentinelUndef);
5398           continue;
5399         }
5400         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5401         if (!CN)
5402           return false;
5403         APInt MaskElement = CN->getAPIntValue();
5404
5405         // We now have to decode the element which could be any integer size and
5406         // extract each byte of it.
5407         for (int j = 0; j < NumBytesPerElement; ++j) {
5408           // Note that this is x86 and so always little endian: the low byte is
5409           // the first byte of the mask.
5410           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5411           MaskElement = MaskElement.lshr(8);
5412         }
5413       }
5414       DecodePSHUFBMask(RawMask, Mask);
5415       break;
5416     }
5417
5418     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5419     if (!MaskLoad)
5420       return false;
5421
5422     SDValue Ptr = MaskLoad->getBasePtr();
5423     if (Ptr->getOpcode() == X86ISD::Wrapper)
5424       Ptr = Ptr->getOperand(0);
5425
5426     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5427     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5428       return false;
5429
5430     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5431       // FIXME: Support AVX-512 here.
5432       Type *Ty = C->getType();
5433       if (!Ty->isVectorTy() || (Ty->getVectorNumElements() != 16 &&
5434                                 Ty->getVectorNumElements() != 32))
5435         return false;
5436
5437       DecodePSHUFBMask(C, Mask);
5438       break;
5439     }
5440
5441     return false;
5442   }
5443   case X86ISD::VPERMI:
5444     ImmN = N->getOperand(N->getNumOperands()-1);
5445     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5446     IsUnary = true;
5447     break;
5448   case X86ISD::MOVSS:
5449   case X86ISD::MOVSD: {
5450     // The index 0 always comes from the first element of the second source,
5451     // this is why MOVSS and MOVSD are used in the first place. The other
5452     // elements come from the other positions of the first source vector
5453     Mask.push_back(NumElems);
5454     for (unsigned i = 1; i != NumElems; ++i) {
5455       Mask.push_back(i);
5456     }
5457     break;
5458   }
5459   case X86ISD::VPERM2X128:
5460     ImmN = N->getOperand(N->getNumOperands()-1);
5461     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5462     if (Mask.empty()) return false;
5463     break;
5464   case X86ISD::MOVSLDUP:
5465     DecodeMOVSLDUPMask(VT, Mask);
5466     break;
5467   case X86ISD::MOVSHDUP:
5468     DecodeMOVSHDUPMask(VT, Mask);
5469     break;
5470   case X86ISD::MOVDDUP:
5471   case X86ISD::MOVLHPD:
5472   case X86ISD::MOVLPD:
5473   case X86ISD::MOVLPS:
5474     // Not yet implemented
5475     return false;
5476   default: llvm_unreachable("unknown target shuffle node");
5477   }
5478
5479   // If we have a fake unary shuffle, the shuffle mask is spread across two
5480   // inputs that are actually the same node. Re-map the mask to always point
5481   // into the first input.
5482   if (IsFakeUnary)
5483     for (int &M : Mask)
5484       if (M >= (int)Mask.size())
5485         M -= Mask.size();
5486
5487   return true;
5488 }
5489
5490 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5491 /// element of the result of the vector shuffle.
5492 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5493                                    unsigned Depth) {
5494   if (Depth == 6)
5495     return SDValue();  // Limit search depth.
5496
5497   SDValue V = SDValue(N, 0);
5498   EVT VT = V.getValueType();
5499   unsigned Opcode = V.getOpcode();
5500
5501   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5502   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5503     int Elt = SV->getMaskElt(Index);
5504
5505     if (Elt < 0)
5506       return DAG.getUNDEF(VT.getVectorElementType());
5507
5508     unsigned NumElems = VT.getVectorNumElements();
5509     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5510                                          : SV->getOperand(1);
5511     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5512   }
5513
5514   // Recurse into target specific vector shuffles to find scalars.
5515   if (isTargetShuffle(Opcode)) {
5516     MVT ShufVT = V.getSimpleValueType();
5517     unsigned NumElems = ShufVT.getVectorNumElements();
5518     SmallVector<int, 16> ShuffleMask;
5519     bool IsUnary;
5520
5521     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5522       return SDValue();
5523
5524     int Elt = ShuffleMask[Index];
5525     if (Elt < 0)
5526       return DAG.getUNDEF(ShufVT.getVectorElementType());
5527
5528     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5529                                          : N->getOperand(1);
5530     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5531                                Depth+1);
5532   }
5533
5534   // Actual nodes that may contain scalar elements
5535   if (Opcode == ISD::BITCAST) {
5536     V = V.getOperand(0);
5537     EVT SrcVT = V.getValueType();
5538     unsigned NumElems = VT.getVectorNumElements();
5539
5540     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5541       return SDValue();
5542   }
5543
5544   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5545     return (Index == 0) ? V.getOperand(0)
5546                         : DAG.getUNDEF(VT.getVectorElementType());
5547
5548   if (V.getOpcode() == ISD::BUILD_VECTOR)
5549     return V.getOperand(Index);
5550
5551   return SDValue();
5552 }
5553
5554 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5555 /// shuffle operation which come from a consecutively from a zero. The
5556 /// search can start in two different directions, from left or right.
5557 /// We count undefs as zeros until PreferredNum is reached.
5558 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5559                                          unsigned NumElems, bool ZerosFromLeft,
5560                                          SelectionDAG &DAG,
5561                                          unsigned PreferredNum = -1U) {
5562   unsigned NumZeros = 0;
5563   for (unsigned i = 0; i != NumElems; ++i) {
5564     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5565     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5566     if (!Elt.getNode())
5567       break;
5568
5569     if (X86::isZeroNode(Elt))
5570       ++NumZeros;
5571     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5572       NumZeros = std::min(NumZeros + 1, PreferredNum);
5573     else
5574       break;
5575   }
5576
5577   return NumZeros;
5578 }
5579
5580 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5581 /// correspond consecutively to elements from one of the vector operands,
5582 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5583 static
5584 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5585                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5586                               unsigned NumElems, unsigned &OpNum) {
5587   bool SeenV1 = false;
5588   bool SeenV2 = false;
5589
5590   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5591     int Idx = SVOp->getMaskElt(i);
5592     // Ignore undef indicies
5593     if (Idx < 0)
5594       continue;
5595
5596     if (Idx < (int)NumElems)
5597       SeenV1 = true;
5598     else
5599       SeenV2 = true;
5600
5601     // Only accept consecutive elements from the same vector
5602     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5603       return false;
5604   }
5605
5606   OpNum = SeenV1 ? 0 : 1;
5607   return true;
5608 }
5609
5610 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5611 /// logical left shift of a vector.
5612 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5613                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5614   unsigned NumElems =
5615     SVOp->getSimpleValueType(0).getVectorNumElements();
5616   unsigned NumZeros = getNumOfConsecutiveZeros(
5617       SVOp, NumElems, false /* check zeros from right */, DAG,
5618       SVOp->getMaskElt(0));
5619   unsigned OpSrc;
5620
5621   if (!NumZeros)
5622     return false;
5623
5624   // Considering the elements in the mask that are not consecutive zeros,
5625   // check if they consecutively come from only one of the source vectors.
5626   //
5627   //               V1 = {X, A, B, C}     0
5628   //                         \  \  \    /
5629   //   vector_shuffle V1, V2 <1, 2, 3, X>
5630   //
5631   if (!isShuffleMaskConsecutive(SVOp,
5632             0,                   // Mask Start Index
5633             NumElems-NumZeros,   // Mask End Index(exclusive)
5634             NumZeros,            // Where to start looking in the src vector
5635             NumElems,            // Number of elements in vector
5636             OpSrc))              // Which source operand ?
5637     return false;
5638
5639   isLeft = false;
5640   ShAmt = NumZeros;
5641   ShVal = SVOp->getOperand(OpSrc);
5642   return true;
5643 }
5644
5645 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5646 /// logical left shift of a vector.
5647 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5648                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5649   unsigned NumElems =
5650     SVOp->getSimpleValueType(0).getVectorNumElements();
5651   unsigned NumZeros = getNumOfConsecutiveZeros(
5652       SVOp, NumElems, true /* check zeros from left */, DAG,
5653       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5654   unsigned OpSrc;
5655
5656   if (!NumZeros)
5657     return false;
5658
5659   // Considering the elements in the mask that are not consecutive zeros,
5660   // check if they consecutively come from only one of the source vectors.
5661   //
5662   //                           0    { A, B, X, X } = V2
5663   //                          / \    /  /
5664   //   vector_shuffle V1, V2 <X, X, 4, 5>
5665   //
5666   if (!isShuffleMaskConsecutive(SVOp,
5667             NumZeros,     // Mask Start Index
5668             NumElems,     // Mask End Index(exclusive)
5669             0,            // Where to start looking in the src vector
5670             NumElems,     // Number of elements in vector
5671             OpSrc))       // Which source operand ?
5672     return false;
5673
5674   isLeft = true;
5675   ShAmt = NumZeros;
5676   ShVal = SVOp->getOperand(OpSrc);
5677   return true;
5678 }
5679
5680 /// isVectorShift - Returns true if the shuffle can be implemented as a
5681 /// logical left or right shift of a vector.
5682 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5683                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5684   // Although the logic below support any bitwidth size, there are no
5685   // shift instructions which handle more than 128-bit vectors.
5686   if (!SVOp->getSimpleValueType(0).is128BitVector())
5687     return false;
5688
5689   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5690       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5691     return true;
5692
5693   return false;
5694 }
5695
5696 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5697 ///
5698 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5699                                        unsigned NumNonZero, unsigned NumZero,
5700                                        SelectionDAG &DAG,
5701                                        const X86Subtarget* Subtarget,
5702                                        const TargetLowering &TLI) {
5703   if (NumNonZero > 8)
5704     return SDValue();
5705
5706   SDLoc dl(Op);
5707   SDValue V;
5708   bool First = true;
5709   for (unsigned i = 0; i < 16; ++i) {
5710     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5711     if (ThisIsNonZero && First) {
5712       if (NumZero)
5713         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5714       else
5715         V = DAG.getUNDEF(MVT::v8i16);
5716       First = false;
5717     }
5718
5719     if ((i & 1) != 0) {
5720       SDValue ThisElt, LastElt;
5721       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5722       if (LastIsNonZero) {
5723         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5724                               MVT::i16, Op.getOperand(i-1));
5725       }
5726       if (ThisIsNonZero) {
5727         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5728         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5729                               ThisElt, DAG.getConstant(8, MVT::i8));
5730         if (LastIsNonZero)
5731           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5732       } else
5733         ThisElt = LastElt;
5734
5735       if (ThisElt.getNode())
5736         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5737                         DAG.getIntPtrConstant(i/2));
5738     }
5739   }
5740
5741   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5742 }
5743
5744 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5745 ///
5746 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5747                                      unsigned NumNonZero, unsigned NumZero,
5748                                      SelectionDAG &DAG,
5749                                      const X86Subtarget* Subtarget,
5750                                      const TargetLowering &TLI) {
5751   if (NumNonZero > 4)
5752     return SDValue();
5753
5754   SDLoc dl(Op);
5755   SDValue V;
5756   bool First = true;
5757   for (unsigned i = 0; i < 8; ++i) {
5758     bool isNonZero = (NonZeros & (1 << i)) != 0;
5759     if (isNonZero) {
5760       if (First) {
5761         if (NumZero)
5762           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5763         else
5764           V = DAG.getUNDEF(MVT::v8i16);
5765         First = false;
5766       }
5767       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5768                       MVT::v8i16, V, Op.getOperand(i),
5769                       DAG.getIntPtrConstant(i));
5770     }
5771   }
5772
5773   return V;
5774 }
5775
5776 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5777 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5778                                      const X86Subtarget *Subtarget,
5779                                      const TargetLowering &TLI) {
5780   // Find all zeroable elements.
5781   bool Zeroable[4];
5782   for (int i=0; i < 4; ++i) {
5783     SDValue Elt = Op->getOperand(i);
5784     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5785   }
5786   assert(std::count_if(&Zeroable[0], &Zeroable[4],
5787                        [](bool M) { return !M; }) > 1 &&
5788          "We expect at least two non-zero elements!");
5789
5790   // We only know how to deal with build_vector nodes where elements are either
5791   // zeroable or extract_vector_elt with constant index.
5792   SDValue FirstNonZero;
5793   unsigned FirstNonZeroIdx;
5794   for (unsigned i=0; i < 4; ++i) {
5795     if (Zeroable[i])
5796       continue;
5797     SDValue Elt = Op->getOperand(i);
5798     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5799         !isa<ConstantSDNode>(Elt.getOperand(1)))
5800       return SDValue();
5801     // Make sure that this node is extracting from a 128-bit vector.
5802     MVT VT = Elt.getOperand(0).getSimpleValueType();
5803     if (!VT.is128BitVector())
5804       return SDValue();
5805     if (!FirstNonZero.getNode()) {
5806       FirstNonZero = Elt;
5807       FirstNonZeroIdx = i;
5808     }
5809   }
5810
5811   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5812   SDValue V1 = FirstNonZero.getOperand(0);
5813   MVT VT = V1.getSimpleValueType();
5814
5815   // See if this build_vector can be lowered as a blend with zero.
5816   SDValue Elt;
5817   unsigned EltMaskIdx, EltIdx;
5818   int Mask[4];
5819   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5820     if (Zeroable[EltIdx]) {
5821       // The zero vector will be on the right hand side.
5822       Mask[EltIdx] = EltIdx+4;
5823       continue;
5824     }
5825
5826     Elt = Op->getOperand(EltIdx);
5827     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5828     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5829     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5830       break;
5831     Mask[EltIdx] = EltIdx;
5832   }
5833
5834   if (EltIdx == 4) {
5835     // Let the shuffle legalizer deal with blend operations.
5836     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5837     if (V1.getSimpleValueType() != VT)
5838       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5839     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5840   }
5841
5842   // See if we can lower this build_vector to a INSERTPS.
5843   if (!Subtarget->hasSSE41())
5844     return SDValue();
5845
5846   SDValue V2 = Elt.getOperand(0);
5847   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5848     V1 = SDValue();
5849
5850   bool CanFold = true;
5851   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5852     if (Zeroable[i])
5853       continue;
5854
5855     SDValue Current = Op->getOperand(i);
5856     SDValue SrcVector = Current->getOperand(0);
5857     if (!V1.getNode())
5858       V1 = SrcVector;
5859     CanFold = SrcVector == V1 &&
5860       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5861   }
5862
5863   if (!CanFold)
5864     return SDValue();
5865
5866   assert(V1.getNode() && "Expected at least two non-zero elements!");
5867   if (V1.getSimpleValueType() != MVT::v4f32)
5868     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5869   if (V2.getSimpleValueType() != MVT::v4f32)
5870     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5871
5872   // Ok, we can emit an INSERTPS instruction.
5873   unsigned ZMask = 0;
5874   for (int i = 0; i < 4; ++i)
5875     if (Zeroable[i])
5876       ZMask |= 1 << i;
5877
5878   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5879   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5880   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
5881                                DAG.getIntPtrConstant(InsertPSMask));
5882   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
5883 }
5884
5885 /// getVShift - Return a vector logical shift node.
5886 ///
5887 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5888                          unsigned NumBits, SelectionDAG &DAG,
5889                          const TargetLowering &TLI, SDLoc dl) {
5890   assert(VT.is128BitVector() && "Unknown type for VShift");
5891   EVT ShVT = MVT::v2i64;
5892   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5893   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5894   return DAG.getNode(ISD::BITCAST, dl, VT,
5895                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5896                              DAG.getConstant(NumBits,
5897                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5898 }
5899
5900 static SDValue
5901 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5902
5903   // Check if the scalar load can be widened into a vector load. And if
5904   // the address is "base + cst" see if the cst can be "absorbed" into
5905   // the shuffle mask.
5906   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5907     SDValue Ptr = LD->getBasePtr();
5908     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5909       return SDValue();
5910     EVT PVT = LD->getValueType(0);
5911     if (PVT != MVT::i32 && PVT != MVT::f32)
5912       return SDValue();
5913
5914     int FI = -1;
5915     int64_t Offset = 0;
5916     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5917       FI = FINode->getIndex();
5918       Offset = 0;
5919     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5920                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5921       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5922       Offset = Ptr.getConstantOperandVal(1);
5923       Ptr = Ptr.getOperand(0);
5924     } else {
5925       return SDValue();
5926     }
5927
5928     // FIXME: 256-bit vector instructions don't require a strict alignment,
5929     // improve this code to support it better.
5930     unsigned RequiredAlign = VT.getSizeInBits()/8;
5931     SDValue Chain = LD->getChain();
5932     // Make sure the stack object alignment is at least 16 or 32.
5933     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5934     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5935       if (MFI->isFixedObjectIndex(FI)) {
5936         // Can't change the alignment. FIXME: It's possible to compute
5937         // the exact stack offset and reference FI + adjust offset instead.
5938         // If someone *really* cares about this. That's the way to implement it.
5939         return SDValue();
5940       } else {
5941         MFI->setObjectAlignment(FI, RequiredAlign);
5942       }
5943     }
5944
5945     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5946     // Ptr + (Offset & ~15).
5947     if (Offset < 0)
5948       return SDValue();
5949     if ((Offset % RequiredAlign) & 3)
5950       return SDValue();
5951     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5952     if (StartOffset)
5953       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5954                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5955
5956     int EltNo = (Offset - StartOffset) >> 2;
5957     unsigned NumElems = VT.getVectorNumElements();
5958
5959     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5960     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5961                              LD->getPointerInfo().getWithOffset(StartOffset),
5962                              false, false, false, 0);
5963
5964     SmallVector<int, 8> Mask;
5965     for (unsigned i = 0; i != NumElems; ++i)
5966       Mask.push_back(EltNo);
5967
5968     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5969   }
5970
5971   return SDValue();
5972 }
5973
5974 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5975 /// vector of type 'VT', see if the elements can be replaced by a single large
5976 /// load which has the same value as a build_vector whose operands are 'elts'.
5977 ///
5978 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5979 ///
5980 /// FIXME: we'd also like to handle the case where the last elements are zero
5981 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5982 /// There's even a handy isZeroNode for that purpose.
5983 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5984                                         SDLoc &DL, SelectionDAG &DAG,
5985                                         bool isAfterLegalize) {
5986   EVT EltVT = VT.getVectorElementType();
5987   unsigned NumElems = Elts.size();
5988
5989   LoadSDNode *LDBase = nullptr;
5990   unsigned LastLoadedElt = -1U;
5991
5992   // For each element in the initializer, see if we've found a load or an undef.
5993   // If we don't find an initial load element, or later load elements are
5994   // non-consecutive, bail out.
5995   for (unsigned i = 0; i < NumElems; ++i) {
5996     SDValue Elt = Elts[i];
5997
5998     if (!Elt.getNode() ||
5999         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
6000       return SDValue();
6001     if (!LDBase) {
6002       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
6003         return SDValue();
6004       LDBase = cast<LoadSDNode>(Elt.getNode());
6005       LastLoadedElt = i;
6006       continue;
6007     }
6008     if (Elt.getOpcode() == ISD::UNDEF)
6009       continue;
6010
6011     LoadSDNode *LD = cast<LoadSDNode>(Elt);
6012     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
6013       return SDValue();
6014     LastLoadedElt = i;
6015   }
6016
6017   // If we have found an entire vector of loads and undefs, then return a large
6018   // load of the entire vector width starting at the base pointer.  If we found
6019   // consecutive loads for the low half, generate a vzext_load node.
6020   if (LastLoadedElt == NumElems - 1) {
6021
6022     if (isAfterLegalize &&
6023         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
6024       return SDValue();
6025
6026     SDValue NewLd = SDValue();
6027
6028     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
6029       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6030                           LDBase->getPointerInfo(),
6031                           LDBase->isVolatile(), LDBase->isNonTemporal(),
6032                           LDBase->isInvariant(), 0);
6033     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6034                         LDBase->getPointerInfo(),
6035                         LDBase->isVolatile(), LDBase->isNonTemporal(),
6036                         LDBase->isInvariant(), LDBase->getAlignment());
6037
6038     if (LDBase->hasAnyUseOfValue(1)) {
6039       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6040                                      SDValue(LDBase, 1),
6041                                      SDValue(NewLd.getNode(), 1));
6042       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6043       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6044                              SDValue(NewLd.getNode(), 1));
6045     }
6046
6047     return NewLd;
6048   }
6049   
6050   //TODO: The code below fires only for for loading the low v2i32 / v2f32
6051   //of a v4i32 / v4f32. It's probably worth generalizing.
6052   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
6053       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
6054     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
6055     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
6056     SDValue ResNode =
6057         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
6058                                 LDBase->getPointerInfo(),
6059                                 LDBase->getAlignment(),
6060                                 false/*isVolatile*/, true/*ReadMem*/,
6061                                 false/*WriteMem*/);
6062
6063     // Make sure the newly-created LOAD is in the same position as LDBase in
6064     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
6065     // update uses of LDBase's output chain to use the TokenFactor.
6066     if (LDBase->hasAnyUseOfValue(1)) {
6067       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6068                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
6069       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6070       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6071                              SDValue(ResNode.getNode(), 1));
6072     }
6073
6074     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
6075   }
6076   return SDValue();
6077 }
6078
6079 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6080 /// to generate a splat value for the following cases:
6081 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6082 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6083 /// a scalar load, or a constant.
6084 /// The VBROADCAST node is returned when a pattern is found,
6085 /// or SDValue() otherwise.
6086 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6087                                     SelectionDAG &DAG) {
6088   // VBROADCAST requires AVX.
6089   // TODO: Splats could be generated for non-AVX CPUs using SSE
6090   // instructions, but there's less potential gain for only 128-bit vectors.
6091   if (!Subtarget->hasAVX())
6092     return SDValue();
6093
6094   MVT VT = Op.getSimpleValueType();
6095   SDLoc dl(Op);
6096
6097   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6098          "Unsupported vector type for broadcast.");
6099
6100   SDValue Ld;
6101   bool ConstSplatVal;
6102
6103   switch (Op.getOpcode()) {
6104     default:
6105       // Unknown pattern found.
6106       return SDValue();
6107
6108     case ISD::BUILD_VECTOR: {
6109       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6110       BitVector UndefElements;
6111       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6112
6113       // We need a splat of a single value to use broadcast, and it doesn't
6114       // make any sense if the value is only in one element of the vector.
6115       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6116         return SDValue();
6117
6118       Ld = Splat;
6119       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6120                        Ld.getOpcode() == ISD::ConstantFP);
6121
6122       // Make sure that all of the users of a non-constant load are from the
6123       // BUILD_VECTOR node.
6124       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6125         return SDValue();
6126       break;
6127     }
6128
6129     case ISD::VECTOR_SHUFFLE: {
6130       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6131
6132       // Shuffles must have a splat mask where the first element is
6133       // broadcasted.
6134       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6135         return SDValue();
6136
6137       SDValue Sc = Op.getOperand(0);
6138       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6139           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6140
6141         if (!Subtarget->hasInt256())
6142           return SDValue();
6143
6144         // Use the register form of the broadcast instruction available on AVX2.
6145         if (VT.getSizeInBits() >= 256)
6146           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6147         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6148       }
6149
6150       Ld = Sc.getOperand(0);
6151       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6152                        Ld.getOpcode() == ISD::ConstantFP);
6153
6154       // The scalar_to_vector node and the suspected
6155       // load node must have exactly one user.
6156       // Constants may have multiple users.
6157
6158       // AVX-512 has register version of the broadcast
6159       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6160         Ld.getValueType().getSizeInBits() >= 32;
6161       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6162           !hasRegVer))
6163         return SDValue();
6164       break;
6165     }
6166   }
6167
6168   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6169   bool IsGE256 = (VT.getSizeInBits() >= 256);
6170
6171   // When optimizing for size, generate up to 5 extra bytes for a broadcast
6172   // instruction to save 8 or more bytes of constant pool data.
6173   // TODO: If multiple splats are generated to load the same constant,
6174   // it may be detrimental to overall size. There needs to be a way to detect
6175   // that condition to know if this is truly a size win.
6176   const Function *F = DAG.getMachineFunction().getFunction();
6177   bool OptForSize = F->getAttributes().
6178     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6179
6180   // Handle broadcasting a single constant scalar from the constant pool
6181   // into a vector.
6182   // On Sandybridge (no AVX2), it is still better to load a constant vector
6183   // from the constant pool and not to broadcast it from a scalar.
6184   // But override that restriction when optimizing for size.
6185   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
6186   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
6187     EVT CVT = Ld.getValueType();
6188     assert(!CVT.isVector() && "Must not broadcast a vector type");
6189
6190     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
6191     // For size optimization, also splat v2f64 and v2i64, and for size opt
6192     // with AVX2, also splat i8 and i16.
6193     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
6194     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6195         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
6196       const Constant *C = nullptr;
6197       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6198         C = CI->getConstantIntValue();
6199       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6200         C = CF->getConstantFPValue();
6201
6202       assert(C && "Invalid constant type");
6203
6204       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6205       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6206       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6207       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6208                        MachinePointerInfo::getConstantPool(),
6209                        false, false, false, Alignment);
6210
6211       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6212     }
6213   }
6214
6215   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6216
6217   // Handle AVX2 in-register broadcasts.
6218   if (!IsLoad && Subtarget->hasInt256() &&
6219       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6220     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6221
6222   // The scalar source must be a normal load.
6223   if (!IsLoad)
6224     return SDValue();
6225
6226   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6227       (Subtarget->hasVLX() && ScalarSize == 64))
6228     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6229
6230   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6231   // double since there is no vbroadcastsd xmm
6232   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6233     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6234       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6235   }
6236
6237   // Unsupported broadcast.
6238   return SDValue();
6239 }
6240
6241 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6242 /// underlying vector and index.
6243 ///
6244 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6245 /// index.
6246 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6247                                          SDValue ExtIdx) {
6248   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6249   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6250     return Idx;
6251
6252   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6253   // lowered this:
6254   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6255   // to:
6256   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6257   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6258   //                           undef)
6259   //                       Constant<0>)
6260   // In this case the vector is the extract_subvector expression and the index
6261   // is 2, as specified by the shuffle.
6262   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6263   SDValue ShuffleVec = SVOp->getOperand(0);
6264   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6265   assert(ShuffleVecVT.getVectorElementType() ==
6266          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6267
6268   int ShuffleIdx = SVOp->getMaskElt(Idx);
6269   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6270     ExtractedFromVec = ShuffleVec;
6271     return ShuffleIdx;
6272   }
6273   return Idx;
6274 }
6275
6276 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6277   MVT VT = Op.getSimpleValueType();
6278
6279   // Skip if insert_vec_elt is not supported.
6280   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6281   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6282     return SDValue();
6283
6284   SDLoc DL(Op);
6285   unsigned NumElems = Op.getNumOperands();
6286
6287   SDValue VecIn1;
6288   SDValue VecIn2;
6289   SmallVector<unsigned, 4> InsertIndices;
6290   SmallVector<int, 8> Mask(NumElems, -1);
6291
6292   for (unsigned i = 0; i != NumElems; ++i) {
6293     unsigned Opc = Op.getOperand(i).getOpcode();
6294
6295     if (Opc == ISD::UNDEF)
6296       continue;
6297
6298     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6299       // Quit if more than 1 elements need inserting.
6300       if (InsertIndices.size() > 1)
6301         return SDValue();
6302
6303       InsertIndices.push_back(i);
6304       continue;
6305     }
6306
6307     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6308     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6309     // Quit if non-constant index.
6310     if (!isa<ConstantSDNode>(ExtIdx))
6311       return SDValue();
6312     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6313
6314     // Quit if extracted from vector of different type.
6315     if (ExtractedFromVec.getValueType() != VT)
6316       return SDValue();
6317
6318     if (!VecIn1.getNode())
6319       VecIn1 = ExtractedFromVec;
6320     else if (VecIn1 != ExtractedFromVec) {
6321       if (!VecIn2.getNode())
6322         VecIn2 = ExtractedFromVec;
6323       else if (VecIn2 != ExtractedFromVec)
6324         // Quit if more than 2 vectors to shuffle
6325         return SDValue();
6326     }
6327
6328     if (ExtractedFromVec == VecIn1)
6329       Mask[i] = Idx;
6330     else if (ExtractedFromVec == VecIn2)
6331       Mask[i] = Idx + NumElems;
6332   }
6333
6334   if (!VecIn1.getNode())
6335     return SDValue();
6336
6337   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6338   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6339   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6340     unsigned Idx = InsertIndices[i];
6341     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6342                      DAG.getIntPtrConstant(Idx));
6343   }
6344
6345   return NV;
6346 }
6347
6348 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6349 SDValue
6350 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6351
6352   MVT VT = Op.getSimpleValueType();
6353   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6354          "Unexpected type in LowerBUILD_VECTORvXi1!");
6355
6356   SDLoc dl(Op);
6357   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6358     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6359     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6360     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6361   }
6362
6363   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6364     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6365     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6366     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6367   }
6368
6369   bool AllContants = true;
6370   uint64_t Immediate = 0;
6371   int NonConstIdx = -1;
6372   bool IsSplat = true;
6373   unsigned NumNonConsts = 0;
6374   unsigned NumConsts = 0;
6375   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6376     SDValue In = Op.getOperand(idx);
6377     if (In.getOpcode() == ISD::UNDEF)
6378       continue;
6379     if (!isa<ConstantSDNode>(In)) {
6380       AllContants = false;
6381       NonConstIdx = idx;
6382       NumNonConsts++;
6383     } else {
6384       NumConsts++;
6385       if (cast<ConstantSDNode>(In)->getZExtValue())
6386       Immediate |= (1ULL << idx);
6387     }
6388     if (In != Op.getOperand(0))
6389       IsSplat = false;
6390   }
6391
6392   if (AllContants) {
6393     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6394       DAG.getConstant(Immediate, MVT::i16));
6395     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6396                        DAG.getIntPtrConstant(0));
6397   }
6398
6399   if (NumNonConsts == 1 && NonConstIdx != 0) {
6400     SDValue DstVec;
6401     if (NumConsts) {
6402       SDValue VecAsImm = DAG.getConstant(Immediate,
6403                                          MVT::getIntegerVT(VT.getSizeInBits()));
6404       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6405     }
6406     else
6407       DstVec = DAG.getUNDEF(VT);
6408     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6409                        Op.getOperand(NonConstIdx),
6410                        DAG.getIntPtrConstant(NonConstIdx));
6411   }
6412   if (!IsSplat && (NonConstIdx != 0))
6413     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6414   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6415   SDValue Select;
6416   if (IsSplat)
6417     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6418                           DAG.getConstant(-1, SelectVT),
6419                           DAG.getConstant(0, SelectVT));
6420   else
6421     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6422                          DAG.getConstant((Immediate | 1), SelectVT),
6423                          DAG.getConstant(Immediate, SelectVT));
6424   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6425 }
6426
6427 /// \brief Return true if \p N implements a horizontal binop and return the
6428 /// operands for the horizontal binop into V0 and V1.
6429 ///
6430 /// This is a helper function of PerformBUILD_VECTORCombine.
6431 /// This function checks that the build_vector \p N in input implements a
6432 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6433 /// operation to match.
6434 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6435 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6436 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6437 /// arithmetic sub.
6438 ///
6439 /// This function only analyzes elements of \p N whose indices are
6440 /// in range [BaseIdx, LastIdx).
6441 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6442                               SelectionDAG &DAG,
6443                               unsigned BaseIdx, unsigned LastIdx,
6444                               SDValue &V0, SDValue &V1) {
6445   EVT VT = N->getValueType(0);
6446
6447   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6448   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6449          "Invalid Vector in input!");
6450
6451   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6452   bool CanFold = true;
6453   unsigned ExpectedVExtractIdx = BaseIdx;
6454   unsigned NumElts = LastIdx - BaseIdx;
6455   V0 = DAG.getUNDEF(VT);
6456   V1 = DAG.getUNDEF(VT);
6457
6458   // Check if N implements a horizontal binop.
6459   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6460     SDValue Op = N->getOperand(i + BaseIdx);
6461
6462     // Skip UNDEFs.
6463     if (Op->getOpcode() == ISD::UNDEF) {
6464       // Update the expected vector extract index.
6465       if (i * 2 == NumElts)
6466         ExpectedVExtractIdx = BaseIdx;
6467       ExpectedVExtractIdx += 2;
6468       continue;
6469     }
6470
6471     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6472
6473     if (!CanFold)
6474       break;
6475
6476     SDValue Op0 = Op.getOperand(0);
6477     SDValue Op1 = Op.getOperand(1);
6478
6479     // Try to match the following pattern:
6480     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6481     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6482         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6483         Op0.getOperand(0) == Op1.getOperand(0) &&
6484         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6485         isa<ConstantSDNode>(Op1.getOperand(1)));
6486     if (!CanFold)
6487       break;
6488
6489     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6490     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6491
6492     if (i * 2 < NumElts) {
6493       if (V0.getOpcode() == ISD::UNDEF)
6494         V0 = Op0.getOperand(0);
6495     } else {
6496       if (V1.getOpcode() == ISD::UNDEF)
6497         V1 = Op0.getOperand(0);
6498       if (i * 2 == NumElts)
6499         ExpectedVExtractIdx = BaseIdx;
6500     }
6501
6502     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6503     if (I0 == ExpectedVExtractIdx)
6504       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6505     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6506       // Try to match the following dag sequence:
6507       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6508       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6509     } else
6510       CanFold = false;
6511
6512     ExpectedVExtractIdx += 2;
6513   }
6514
6515   return CanFold;
6516 }
6517
6518 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6519 /// a concat_vector.
6520 ///
6521 /// This is a helper function of PerformBUILD_VECTORCombine.
6522 /// This function expects two 256-bit vectors called V0 and V1.
6523 /// At first, each vector is split into two separate 128-bit vectors.
6524 /// Then, the resulting 128-bit vectors are used to implement two
6525 /// horizontal binary operations.
6526 ///
6527 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6528 ///
6529 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6530 /// the two new horizontal binop.
6531 /// When Mode is set, the first horizontal binop dag node would take as input
6532 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6533 /// horizontal binop dag node would take as input the lower 128-bit of V1
6534 /// and the upper 128-bit of V1.
6535 ///   Example:
6536 ///     HADD V0_LO, V0_HI
6537 ///     HADD V1_LO, V1_HI
6538 ///
6539 /// Otherwise, the first horizontal binop dag node takes as input the lower
6540 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6541 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6542 ///   Example:
6543 ///     HADD V0_LO, V1_LO
6544 ///     HADD V0_HI, V1_HI
6545 ///
6546 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6547 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6548 /// the upper 128-bits of the result.
6549 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6550                                      SDLoc DL, SelectionDAG &DAG,
6551                                      unsigned X86Opcode, bool Mode,
6552                                      bool isUndefLO, bool isUndefHI) {
6553   EVT VT = V0.getValueType();
6554   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6555          "Invalid nodes in input!");
6556
6557   unsigned NumElts = VT.getVectorNumElements();
6558   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6559   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6560   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6561   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6562   EVT NewVT = V0_LO.getValueType();
6563
6564   SDValue LO = DAG.getUNDEF(NewVT);
6565   SDValue HI = DAG.getUNDEF(NewVT);
6566
6567   if (Mode) {
6568     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6569     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6570       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6571     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6572       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6573   } else {
6574     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6575     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6576                        V1_LO->getOpcode() != ISD::UNDEF))
6577       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6578
6579     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6580                        V1_HI->getOpcode() != ISD::UNDEF))
6581       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6582   }
6583
6584   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6585 }
6586
6587 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6588 /// sequence of 'vadd + vsub + blendi'.
6589 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6590                            const X86Subtarget *Subtarget) {
6591   SDLoc DL(BV);
6592   EVT VT = BV->getValueType(0);
6593   unsigned NumElts = VT.getVectorNumElements();
6594   SDValue InVec0 = DAG.getUNDEF(VT);
6595   SDValue InVec1 = DAG.getUNDEF(VT);
6596
6597   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6598           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6599
6600   // Odd-numbered elements in the input build vector are obtained from
6601   // adding two integer/float elements.
6602   // Even-numbered elements in the input build vector are obtained from
6603   // subtracting two integer/float elements.
6604   unsigned ExpectedOpcode = ISD::FSUB;
6605   unsigned NextExpectedOpcode = ISD::FADD;
6606   bool AddFound = false;
6607   bool SubFound = false;
6608
6609   for (unsigned i = 0, e = NumElts; i != e; i++) {
6610     SDValue Op = BV->getOperand(i);
6611
6612     // Skip 'undef' values.
6613     unsigned Opcode = Op.getOpcode();
6614     if (Opcode == ISD::UNDEF) {
6615       std::swap(ExpectedOpcode, NextExpectedOpcode);
6616       continue;
6617     }
6618
6619     // Early exit if we found an unexpected opcode.
6620     if (Opcode != ExpectedOpcode)
6621       return SDValue();
6622
6623     SDValue Op0 = Op.getOperand(0);
6624     SDValue Op1 = Op.getOperand(1);
6625
6626     // Try to match the following pattern:
6627     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6628     // Early exit if we cannot match that sequence.
6629     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6630         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6631         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6632         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6633         Op0.getOperand(1) != Op1.getOperand(1))
6634       return SDValue();
6635
6636     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6637     if (I0 != i)
6638       return SDValue();
6639
6640     // We found a valid add/sub node. Update the information accordingly.
6641     if (i & 1)
6642       AddFound = true;
6643     else
6644       SubFound = true;
6645
6646     // Update InVec0 and InVec1.
6647     if (InVec0.getOpcode() == ISD::UNDEF)
6648       InVec0 = Op0.getOperand(0);
6649     if (InVec1.getOpcode() == ISD::UNDEF)
6650       InVec1 = Op1.getOperand(0);
6651
6652     // Make sure that operands in input to each add/sub node always
6653     // come from a same pair of vectors.
6654     if (InVec0 != Op0.getOperand(0)) {
6655       if (ExpectedOpcode == ISD::FSUB)
6656         return SDValue();
6657
6658       // FADD is commutable. Try to commute the operands
6659       // and then test again.
6660       std::swap(Op0, Op1);
6661       if (InVec0 != Op0.getOperand(0))
6662         return SDValue();
6663     }
6664
6665     if (InVec1 != Op1.getOperand(0))
6666       return SDValue();
6667
6668     // Update the pair of expected opcodes.
6669     std::swap(ExpectedOpcode, NextExpectedOpcode);
6670   }
6671
6672   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6673   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6674       InVec1.getOpcode() != ISD::UNDEF)
6675     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6676
6677   return SDValue();
6678 }
6679
6680 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6681                                           const X86Subtarget *Subtarget) {
6682   SDLoc DL(N);
6683   EVT VT = N->getValueType(0);
6684   unsigned NumElts = VT.getVectorNumElements();
6685   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6686   SDValue InVec0, InVec1;
6687
6688   // Try to match an ADDSUB.
6689   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6690       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6691     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6692     if (Value.getNode())
6693       return Value;
6694   }
6695
6696   // Try to match horizontal ADD/SUB.
6697   unsigned NumUndefsLO = 0;
6698   unsigned NumUndefsHI = 0;
6699   unsigned Half = NumElts/2;
6700
6701   // Count the number of UNDEF operands in the build_vector in input.
6702   for (unsigned i = 0, e = Half; i != e; ++i)
6703     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6704       NumUndefsLO++;
6705
6706   for (unsigned i = Half, e = NumElts; i != e; ++i)
6707     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6708       NumUndefsHI++;
6709
6710   // Early exit if this is either a build_vector of all UNDEFs or all the
6711   // operands but one are UNDEF.
6712   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6713     return SDValue();
6714
6715   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6716     // Try to match an SSE3 float HADD/HSUB.
6717     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6718       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6719
6720     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6721       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6722   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6723     // Try to match an SSSE3 integer HADD/HSUB.
6724     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6725       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6726
6727     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6728       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6729   }
6730
6731   if (!Subtarget->hasAVX())
6732     return SDValue();
6733
6734   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6735     // Try to match an AVX horizontal add/sub of packed single/double
6736     // precision floating point values from 256-bit vectors.
6737     SDValue InVec2, InVec3;
6738     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6739         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6740         ((InVec0.getOpcode() == ISD::UNDEF ||
6741           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6742         ((InVec1.getOpcode() == ISD::UNDEF ||
6743           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6744       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6745
6746     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6747         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6748         ((InVec0.getOpcode() == ISD::UNDEF ||
6749           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6750         ((InVec1.getOpcode() == ISD::UNDEF ||
6751           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6752       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6753   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6754     // Try to match an AVX2 horizontal add/sub of signed integers.
6755     SDValue InVec2, InVec3;
6756     unsigned X86Opcode;
6757     bool CanFold = true;
6758
6759     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6760         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6761         ((InVec0.getOpcode() == ISD::UNDEF ||
6762           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6763         ((InVec1.getOpcode() == ISD::UNDEF ||
6764           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6765       X86Opcode = X86ISD::HADD;
6766     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6767         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6768         ((InVec0.getOpcode() == ISD::UNDEF ||
6769           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6770         ((InVec1.getOpcode() == ISD::UNDEF ||
6771           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6772       X86Opcode = X86ISD::HSUB;
6773     else
6774       CanFold = false;
6775
6776     if (CanFold) {
6777       // Fold this build_vector into a single horizontal add/sub.
6778       // Do this only if the target has AVX2.
6779       if (Subtarget->hasAVX2())
6780         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6781
6782       // Do not try to expand this build_vector into a pair of horizontal
6783       // add/sub if we can emit a pair of scalar add/sub.
6784       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6785         return SDValue();
6786
6787       // Convert this build_vector into a pair of horizontal binop followed by
6788       // a concat vector.
6789       bool isUndefLO = NumUndefsLO == Half;
6790       bool isUndefHI = NumUndefsHI == Half;
6791       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6792                                    isUndefLO, isUndefHI);
6793     }
6794   }
6795
6796   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6797        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6798     unsigned X86Opcode;
6799     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6800       X86Opcode = X86ISD::HADD;
6801     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6802       X86Opcode = X86ISD::HSUB;
6803     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6804       X86Opcode = X86ISD::FHADD;
6805     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6806       X86Opcode = X86ISD::FHSUB;
6807     else
6808       return SDValue();
6809
6810     // Don't try to expand this build_vector into a pair of horizontal add/sub
6811     // if we can simply emit a pair of scalar add/sub.
6812     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6813       return SDValue();
6814
6815     // Convert this build_vector into two horizontal add/sub followed by
6816     // a concat vector.
6817     bool isUndefLO = NumUndefsLO == Half;
6818     bool isUndefHI = NumUndefsHI == Half;
6819     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6820                                  isUndefLO, isUndefHI);
6821   }
6822
6823   return SDValue();
6824 }
6825
6826 SDValue
6827 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6828   SDLoc dl(Op);
6829
6830   MVT VT = Op.getSimpleValueType();
6831   MVT ExtVT = VT.getVectorElementType();
6832   unsigned NumElems = Op.getNumOperands();
6833
6834   // Generate vectors for predicate vectors.
6835   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6836     return LowerBUILD_VECTORvXi1(Op, DAG);
6837
6838   // Vectors containing all zeros can be matched by pxor and xorps later
6839   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6840     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6841     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6842     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6843       return Op;
6844
6845     return getZeroVector(VT, Subtarget, DAG, dl);
6846   }
6847
6848   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6849   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6850   // vpcmpeqd on 256-bit vectors.
6851   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6852     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6853       return Op;
6854
6855     if (!VT.is512BitVector())
6856       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6857   }
6858
6859   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6860   if (Broadcast.getNode())
6861     return Broadcast;
6862
6863   unsigned EVTBits = ExtVT.getSizeInBits();
6864
6865   unsigned NumZero  = 0;
6866   unsigned NumNonZero = 0;
6867   unsigned NonZeros = 0;
6868   bool IsAllConstants = true;
6869   SmallSet<SDValue, 8> Values;
6870   for (unsigned i = 0; i < NumElems; ++i) {
6871     SDValue Elt = Op.getOperand(i);
6872     if (Elt.getOpcode() == ISD::UNDEF)
6873       continue;
6874     Values.insert(Elt);
6875     if (Elt.getOpcode() != ISD::Constant &&
6876         Elt.getOpcode() != ISD::ConstantFP)
6877       IsAllConstants = false;
6878     if (X86::isZeroNode(Elt))
6879       NumZero++;
6880     else {
6881       NonZeros |= (1 << i);
6882       NumNonZero++;
6883     }
6884   }
6885
6886   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6887   if (NumNonZero == 0)
6888     return DAG.getUNDEF(VT);
6889
6890   // Special case for single non-zero, non-undef, element.
6891   if (NumNonZero == 1) {
6892     unsigned Idx = countTrailingZeros(NonZeros);
6893     SDValue Item = Op.getOperand(Idx);
6894
6895     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6896     // the value are obviously zero, truncate the value to i32 and do the
6897     // insertion that way.  Only do this if the value is non-constant or if the
6898     // value is a constant being inserted into element 0.  It is cheaper to do
6899     // a constant pool load than it is to do a movd + shuffle.
6900     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6901         (!IsAllConstants || Idx == 0)) {
6902       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6903         // Handle SSE only.
6904         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6905         EVT VecVT = MVT::v4i32;
6906         unsigned VecElts = 4;
6907
6908         // Truncate the value (which may itself be a constant) to i32, and
6909         // convert it to a vector with movd (S2V+shuffle to zero extend).
6910         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6911         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6912
6913         // If using the new shuffle lowering, just directly insert this.
6914         if (ExperimentalVectorShuffleLowering)
6915           return DAG.getNode(
6916               ISD::BITCAST, dl, VT,
6917               getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6918
6919         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6920
6921         // Now we have our 32-bit value zero extended in the low element of
6922         // a vector.  If Idx != 0, swizzle it into place.
6923         if (Idx != 0) {
6924           SmallVector<int, 4> Mask;
6925           Mask.push_back(Idx);
6926           for (unsigned i = 1; i != VecElts; ++i)
6927             Mask.push_back(i);
6928           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6929                                       &Mask[0]);
6930         }
6931         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6932       }
6933     }
6934
6935     // If we have a constant or non-constant insertion into the low element of
6936     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6937     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6938     // depending on what the source datatype is.
6939     if (Idx == 0) {
6940       if (NumZero == 0)
6941         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6942
6943       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6944           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6945         if (VT.is256BitVector() || VT.is512BitVector()) {
6946           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6947           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6948                              Item, DAG.getIntPtrConstant(0));
6949         }
6950         assert(VT.is128BitVector() && "Expected an SSE value type!");
6951         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6952         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6953         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6954       }
6955
6956       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6957         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6958         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6959         if (VT.is256BitVector()) {
6960           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6961           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6962         } else {
6963           assert(VT.is128BitVector() && "Expected an SSE value type!");
6964           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6965         }
6966         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6967       }
6968     }
6969
6970     // Is it a vector logical left shift?
6971     if (NumElems == 2 && Idx == 1 &&
6972         X86::isZeroNode(Op.getOperand(0)) &&
6973         !X86::isZeroNode(Op.getOperand(1))) {
6974       unsigned NumBits = VT.getSizeInBits();
6975       return getVShift(true, VT,
6976                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6977                                    VT, Op.getOperand(1)),
6978                        NumBits/2, DAG, *this, dl);
6979     }
6980
6981     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6982       return SDValue();
6983
6984     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6985     // is a non-constant being inserted into an element other than the low one,
6986     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6987     // movd/movss) to move this into the low element, then shuffle it into
6988     // place.
6989     if (EVTBits == 32) {
6990       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6991
6992       // If using the new shuffle lowering, just directly insert this.
6993       if (ExperimentalVectorShuffleLowering)
6994         return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6995
6996       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6997       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6998       SmallVector<int, 8> MaskVec;
6999       for (unsigned i = 0; i != NumElems; ++i)
7000         MaskVec.push_back(i == Idx ? 0 : 1);
7001       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
7002     }
7003   }
7004
7005   // Splat is obviously ok. Let legalizer expand it to a shuffle.
7006   if (Values.size() == 1) {
7007     if (EVTBits == 32) {
7008       // Instead of a shuffle like this:
7009       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
7010       // Check if it's possible to issue this instead.
7011       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
7012       unsigned Idx = countTrailingZeros(NonZeros);
7013       SDValue Item = Op.getOperand(Idx);
7014       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
7015         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
7016     }
7017     return SDValue();
7018   }
7019
7020   // A vector full of immediates; various special cases are already
7021   // handled, so this is best done with a single constant-pool load.
7022   if (IsAllConstants)
7023     return SDValue();
7024
7025   // For AVX-length vectors, see if we can use a vector load to get all of the
7026   // elements, otherwise build the individual 128-bit pieces and use
7027   // shuffles to put them in place.
7028   if (VT.is256BitVector() || VT.is512BitVector()) {
7029     SmallVector<SDValue, 64> V;
7030     for (unsigned i = 0; i != NumElems; ++i)
7031       V.push_back(Op.getOperand(i));
7032
7033     // Check for a build vector of consecutive loads.
7034     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
7035       return LD;
7036     
7037     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
7038
7039     // Build both the lower and upper subvector.
7040     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7041                                 makeArrayRef(&V[0], NumElems/2));
7042     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7043                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
7044
7045     // Recreate the wider vector with the lower and upper part.
7046     if (VT.is256BitVector())
7047       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7048     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7049   }
7050
7051   // Let legalizer expand 2-wide build_vectors.
7052   if (EVTBits == 64) {
7053     if (NumNonZero == 1) {
7054       // One half is zero or undef.
7055       unsigned Idx = countTrailingZeros(NonZeros);
7056       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
7057                                  Op.getOperand(Idx));
7058       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
7059     }
7060     return SDValue();
7061   }
7062
7063   // If element VT is < 32 bits, convert it to inserts into a zero vector.
7064   if (EVTBits == 8 && NumElems == 16) {
7065     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
7066                                         Subtarget, *this);
7067     if (V.getNode()) return V;
7068   }
7069
7070   if (EVTBits == 16 && NumElems == 8) {
7071     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
7072                                       Subtarget, *this);
7073     if (V.getNode()) return V;
7074   }
7075
7076   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
7077   if (EVTBits == 32 && NumElems == 4) {
7078     SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
7079     if (V.getNode())
7080       return V;
7081   }
7082
7083   // If element VT is == 32 bits, turn it into a number of shuffles.
7084   SmallVector<SDValue, 8> V(NumElems);
7085   if (NumElems == 4 && NumZero > 0) {
7086     for (unsigned i = 0; i < 4; ++i) {
7087       bool isZero = !(NonZeros & (1 << i));
7088       if (isZero)
7089         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7090       else
7091         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7092     }
7093
7094     for (unsigned i = 0; i < 2; ++i) {
7095       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7096         default: break;
7097         case 0:
7098           V[i] = V[i*2];  // Must be a zero vector.
7099           break;
7100         case 1:
7101           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7102           break;
7103         case 2:
7104           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7105           break;
7106         case 3:
7107           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7108           break;
7109       }
7110     }
7111
7112     bool Reverse1 = (NonZeros & 0x3) == 2;
7113     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7114     int MaskVec[] = {
7115       Reverse1 ? 1 : 0,
7116       Reverse1 ? 0 : 1,
7117       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7118       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7119     };
7120     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7121   }
7122
7123   if (Values.size() > 1 && VT.is128BitVector()) {
7124     // Check for a build vector of consecutive loads.
7125     for (unsigned i = 0; i < NumElems; ++i)
7126       V[i] = Op.getOperand(i);
7127
7128     // Check for elements which are consecutive loads.
7129     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7130     if (LD.getNode())
7131       return LD;
7132
7133     // Check for a build vector from mostly shuffle plus few inserting.
7134     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7135     if (Sh.getNode())
7136       return Sh;
7137
7138     // For SSE 4.1, use insertps to put the high elements into the low element.
7139     if (getSubtarget()->hasSSE41()) {
7140       SDValue Result;
7141       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7142         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7143       else
7144         Result = DAG.getUNDEF(VT);
7145
7146       for (unsigned i = 1; i < NumElems; ++i) {
7147         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7148         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7149                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7150       }
7151       return Result;
7152     }
7153
7154     // Otherwise, expand into a number of unpckl*, start by extending each of
7155     // our (non-undef) elements to the full vector width with the element in the
7156     // bottom slot of the vector (which generates no code for SSE).
7157     for (unsigned i = 0; i < NumElems; ++i) {
7158       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7159         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7160       else
7161         V[i] = DAG.getUNDEF(VT);
7162     }
7163
7164     // Next, we iteratively mix elements, e.g. for v4f32:
7165     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7166     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7167     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7168     unsigned EltStride = NumElems >> 1;
7169     while (EltStride != 0) {
7170       for (unsigned i = 0; i < EltStride; ++i) {
7171         // If V[i+EltStride] is undef and this is the first round of mixing,
7172         // then it is safe to just drop this shuffle: V[i] is already in the
7173         // right place, the one element (since it's the first round) being
7174         // inserted as undef can be dropped.  This isn't safe for successive
7175         // rounds because they will permute elements within both vectors.
7176         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7177             EltStride == NumElems/2)
7178           continue;
7179
7180         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7181       }
7182       EltStride >>= 1;
7183     }
7184     return V[0];
7185   }
7186   return SDValue();
7187 }
7188
7189 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7190 // to create 256-bit vectors from two other 128-bit ones.
7191 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7192   SDLoc dl(Op);
7193   MVT ResVT = Op.getSimpleValueType();
7194
7195   assert((ResVT.is256BitVector() ||
7196           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7197
7198   SDValue V1 = Op.getOperand(0);
7199   SDValue V2 = Op.getOperand(1);
7200   unsigned NumElems = ResVT.getVectorNumElements();
7201   if(ResVT.is256BitVector())
7202     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7203
7204   if (Op.getNumOperands() == 4) {
7205     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7206                                 ResVT.getVectorNumElements()/2);
7207     SDValue V3 = Op.getOperand(2);
7208     SDValue V4 = Op.getOperand(3);
7209     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7210       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7211   }
7212   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7213 }
7214
7215 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7216   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7217   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7218          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7219           Op.getNumOperands() == 4)));
7220
7221   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7222   // from two other 128-bit ones.
7223
7224   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7225   return LowerAVXCONCAT_VECTORS(Op, DAG);
7226 }
7227
7228
7229 //===----------------------------------------------------------------------===//
7230 // Vector shuffle lowering
7231 //
7232 // This is an experimental code path for lowering vector shuffles on x86. It is
7233 // designed to handle arbitrary vector shuffles and blends, gracefully
7234 // degrading performance as necessary. It works hard to recognize idiomatic
7235 // shuffles and lower them to optimal instruction patterns without leaving
7236 // a framework that allows reasonably efficient handling of all vector shuffle
7237 // patterns.
7238 //===----------------------------------------------------------------------===//
7239
7240 /// \brief Tiny helper function to identify a no-op mask.
7241 ///
7242 /// This is a somewhat boring predicate function. It checks whether the mask
7243 /// array input, which is assumed to be a single-input shuffle mask of the kind
7244 /// used by the X86 shuffle instructions (not a fully general
7245 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7246 /// in-place shuffle are 'no-op's.
7247 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7248   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7249     if (Mask[i] != -1 && Mask[i] != i)
7250       return false;
7251   return true;
7252 }
7253
7254 /// \brief Helper function to classify a mask as a single-input mask.
7255 ///
7256 /// This isn't a generic single-input test because in the vector shuffle
7257 /// lowering we canonicalize single inputs to be the first input operand. This
7258 /// means we can more quickly test for a single input by only checking whether
7259 /// an input from the second operand exists. We also assume that the size of
7260 /// mask corresponds to the size of the input vectors which isn't true in the
7261 /// fully general case.
7262 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7263   for (int M : Mask)
7264     if (M >= (int)Mask.size())
7265       return false;
7266   return true;
7267 }
7268
7269 /// \brief Test whether there are elements crossing 128-bit lanes in this
7270 /// shuffle mask.
7271 ///
7272 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
7273 /// and we routinely test for these.
7274 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
7275   int LaneSize = 128 / VT.getScalarSizeInBits();
7276   int Size = Mask.size();
7277   for (int i = 0; i < Size; ++i)
7278     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
7279       return true;
7280   return false;
7281 }
7282
7283 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
7284 ///
7285 /// This checks a shuffle mask to see if it is performing the same
7286 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
7287 /// that it is also not lane-crossing. It may however involve a blend from the
7288 /// same lane of a second vector.
7289 ///
7290 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
7291 /// non-trivial to compute in the face of undef lanes. The representation is
7292 /// *not* suitable for use with existing 128-bit shuffles as it will contain
7293 /// entries from both V1 and V2 inputs to the wider mask.
7294 static bool
7295 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
7296                                 SmallVectorImpl<int> &RepeatedMask) {
7297   int LaneSize = 128 / VT.getScalarSizeInBits();
7298   RepeatedMask.resize(LaneSize, -1);
7299   int Size = Mask.size();
7300   for (int i = 0; i < Size; ++i) {
7301     if (Mask[i] < 0)
7302       continue;
7303     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
7304       // This entry crosses lanes, so there is no way to model this shuffle.
7305       return false;
7306
7307     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
7308     if (RepeatedMask[i % LaneSize] == -1)
7309       // This is the first non-undef entry in this slot of a 128-bit lane.
7310       RepeatedMask[i % LaneSize] =
7311           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
7312     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
7313       // Found a mismatch with the repeated mask.
7314       return false;
7315   }
7316   return true;
7317 }
7318
7319 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7320 // 2013 will allow us to use it as a non-type template parameter.
7321 namespace {
7322
7323 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7324 ///
7325 /// See its documentation for details.
7326 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7327   if (Mask.size() != Args.size())
7328     return false;
7329   for (int i = 0, e = Mask.size(); i < e; ++i) {
7330     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7331     if (Mask[i] != -1 && Mask[i] != *Args[i])
7332       return false;
7333   }
7334   return true;
7335 }
7336
7337 } // namespace
7338
7339 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7340 /// arguments.
7341 ///
7342 /// This is a fast way to test a shuffle mask against a fixed pattern:
7343 ///
7344 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7345 ///
7346 /// It returns true if the mask is exactly as wide as the argument list, and
7347 /// each element of the mask is either -1 (signifying undef) or the value given
7348 /// in the argument.
7349 static const VariadicFunction1<
7350     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7351
7352 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7353 ///
7354 /// This helper function produces an 8-bit shuffle immediate corresponding to
7355 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7356 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7357 /// example.
7358 ///
7359 /// NB: We rely heavily on "undef" masks preserving the input lane.
7360 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7361                                           SelectionDAG &DAG) {
7362   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7363   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7364   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7365   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7366   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7367
7368   unsigned Imm = 0;
7369   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7370   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7371   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7372   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7373   return DAG.getConstant(Imm, MVT::i8);
7374 }
7375
7376 /// \brief Try to emit a blend instruction for a shuffle.
7377 ///
7378 /// This doesn't do any checks for the availability of instructions for blending
7379 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7380 /// be matched in the backend with the type given. What it does check for is
7381 /// that the shuffle mask is in fact a blend.
7382 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7383                                          SDValue V2, ArrayRef<int> Mask,
7384                                          const X86Subtarget *Subtarget,
7385                                          SelectionDAG &DAG) {
7386
7387   unsigned BlendMask = 0;
7388   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7389     if (Mask[i] >= Size) {
7390       if (Mask[i] != i + Size)
7391         return SDValue(); // Shuffled V2 input!
7392       BlendMask |= 1u << i;
7393       continue;
7394     }
7395     if (Mask[i] >= 0 && Mask[i] != i)
7396       return SDValue(); // Shuffled V1 input!
7397   }
7398   switch (VT.SimpleTy) {
7399   case MVT::v2f64:
7400   case MVT::v4f32:
7401   case MVT::v4f64:
7402   case MVT::v8f32:
7403     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7404                        DAG.getConstant(BlendMask, MVT::i8));
7405
7406   case MVT::v4i64:
7407   case MVT::v8i32:
7408     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7409     // FALLTHROUGH
7410   case MVT::v2i64:
7411   case MVT::v4i32:
7412     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7413     // that instruction.
7414     if (Subtarget->hasAVX2()) {
7415       // Scale the blend by the number of 32-bit dwords per element.
7416       int Scale =  VT.getScalarSizeInBits() / 32;
7417       BlendMask = 0;
7418       for (int i = 0, Size = Mask.size(); i < Size; ++i)
7419         if (Mask[i] >= Size)
7420           for (int j = 0; j < Scale; ++j)
7421             BlendMask |= 1u << (i * Scale + j);
7422
7423       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7424       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
7425       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
7426       return DAG.getNode(ISD::BITCAST, DL, VT,
7427                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7428                                      DAG.getConstant(BlendMask, MVT::i8)));
7429     }
7430     // FALLTHROUGH
7431   case MVT::v8i16: {
7432     // For integer shuffles we need to expand the mask and cast the inputs to
7433     // v8i16s prior to blending.
7434     int Scale = 8 / VT.getVectorNumElements();
7435     BlendMask = 0;
7436     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7437       if (Mask[i] >= Size)
7438         for (int j = 0; j < Scale; ++j)
7439           BlendMask |= 1u << (i * Scale + j);
7440
7441     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
7442     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
7443     return DAG.getNode(ISD::BITCAST, DL, VT,
7444                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7445                                    DAG.getConstant(BlendMask, MVT::i8)));
7446   }
7447
7448   case MVT::v16i16: {
7449     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7450     SmallVector<int, 8> RepeatedMask;
7451     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7452       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7453       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7454       BlendMask = 0;
7455       for (int i = 0; i < 8; ++i)
7456         if (RepeatedMask[i] >= 16)
7457           BlendMask |= 1u << i;
7458       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7459                          DAG.getConstant(BlendMask, MVT::i8));
7460     }
7461   }
7462     // FALLTHROUGH
7463   case MVT::v32i8: {
7464     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7465     // Scale the blend by the number of bytes per element.
7466     int Scale =  VT.getScalarSizeInBits() / 8;
7467     assert(Mask.size() * Scale == 32 && "Not a 256-bit vector!");
7468
7469     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7470     // mix of LLVM's code generator and the x86 backend. We tell the code
7471     // generator that boolean values in the elements of an x86 vector register
7472     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7473     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7474     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7475     // of the element (the remaining are ignored) and 0 in that high bit would
7476     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7477     // the LLVM model for boolean values in vector elements gets the relevant
7478     // bit set, it is set backwards and over constrained relative to x86's
7479     // actual model.
7480     SDValue VSELECTMask[32];
7481     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7482       for (int j = 0; j < Scale; ++j)
7483         VSELECTMask[Scale * i + j] =
7484             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7485                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8);
7486
7487     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1);
7488     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V2);
7489     return DAG.getNode(
7490         ISD::BITCAST, DL, VT,
7491         DAG.getNode(ISD::VSELECT, DL, MVT::v32i8,
7492                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, VSELECTMask),
7493                     V1, V2));
7494   }
7495
7496   default:
7497     llvm_unreachable("Not a supported integer vector type!");
7498   }
7499 }
7500
7501 /// \brief Generic routine to lower a shuffle and blend as a decomposed set of
7502 /// unblended shuffles followed by an unshuffled blend.
7503 ///
7504 /// This matches the extremely common pattern for handling combined
7505 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7506 /// operations.
7507 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7508                                                           SDValue V1,
7509                                                           SDValue V2,
7510                                                           ArrayRef<int> Mask,
7511                                                           SelectionDAG &DAG) {
7512   // Shuffle the input elements into the desired positions in V1 and V2 and
7513   // blend them together.
7514   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7515   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7516   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7517   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7518     if (Mask[i] >= 0 && Mask[i] < Size) {
7519       V1Mask[i] = Mask[i];
7520       BlendMask[i] = i;
7521     } else if (Mask[i] >= Size) {
7522       V2Mask[i] = Mask[i] - Size;
7523       BlendMask[i] = i + Size;
7524     }
7525
7526   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7527   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7528   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7529 }
7530
7531 /// \brief Try to lower a vector shuffle as a byte rotation.
7532 ///
7533 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7534 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7535 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7536 /// try to generically lower a vector shuffle through such an pattern. It
7537 /// does not check for the profitability of lowering either as PALIGNR or
7538 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7539 /// This matches shuffle vectors that look like:
7540 ///
7541 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7542 ///
7543 /// Essentially it concatenates V1 and V2, shifts right by some number of
7544 /// elements, and takes the low elements as the result. Note that while this is
7545 /// specified as a *right shift* because x86 is little-endian, it is a *left
7546 /// rotate* of the vector lanes.
7547 ///
7548 /// Note that this only handles 128-bit vector widths currently.
7549 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7550                                               SDValue V2,
7551                                               ArrayRef<int> Mask,
7552                                               const X86Subtarget *Subtarget,
7553                                               SelectionDAG &DAG) {
7554   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7555
7556   // We need to detect various ways of spelling a rotation:
7557   //   [11, 12, 13, 14, 15,  0,  1,  2]
7558   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7559   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7560   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7561   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7562   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7563   int Rotation = 0;
7564   SDValue Lo, Hi;
7565   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7566     if (Mask[i] == -1)
7567       continue;
7568     assert(Mask[i] >= 0 && "Only -1 is a valid negative mask element!");
7569
7570     // Based on the mod-Size value of this mask element determine where
7571     // a rotated vector would have started.
7572     int StartIdx = i - (Mask[i] % Size);
7573     if (StartIdx == 0)
7574       // The identity rotation isn't interesting, stop.
7575       return SDValue();
7576
7577     // If we found the tail of a vector the rotation must be the missing
7578     // front. If we found the head of a vector, it must be how much of the head.
7579     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
7580
7581     if (Rotation == 0)
7582       Rotation = CandidateRotation;
7583     else if (Rotation != CandidateRotation)
7584       // The rotations don't match, so we can't match this mask.
7585       return SDValue();
7586
7587     // Compute which value this mask is pointing at.
7588     SDValue MaskV = Mask[i] < Size ? V1 : V2;
7589
7590     // Compute which of the two target values this index should be assigned to.
7591     // This reflects whether the high elements are remaining or the low elements
7592     // are remaining.
7593     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7594
7595     // Either set up this value if we've not encountered it before, or check
7596     // that it remains consistent.
7597     if (!TargetV)
7598       TargetV = MaskV;
7599     else if (TargetV != MaskV)
7600       // This may be a rotation, but it pulls from the inputs in some
7601       // unsupported interleaving.
7602       return SDValue();
7603   }
7604
7605   // Check that we successfully analyzed the mask, and normalize the results.
7606   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7607   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7608   if (!Lo)
7609     Lo = Hi;
7610   else if (!Hi)
7611     Hi = Lo;
7612
7613   assert(VT.getSizeInBits() == 128 &&
7614          "Rotate-based lowering only supports 128-bit lowering!");
7615   assert(Mask.size() <= 16 &&
7616          "Can shuffle at most 16 bytes in a 128-bit vector!");
7617
7618   // The actual rotate instruction rotates bytes, so we need to scale the
7619   // rotation based on how many bytes are in the vector.
7620   int Scale = 16 / Mask.size();
7621
7622   // SSSE3 targets can use the palignr instruction
7623   if (Subtarget->hasSSSE3()) {
7624     // Cast the inputs to v16i8 to match PALIGNR.
7625     Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Lo);
7626     Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Hi);
7627
7628     return DAG.getNode(ISD::BITCAST, DL, VT,
7629                        DAG.getNode(X86ISD::PALIGNR, DL, MVT::v16i8, Hi, Lo,
7630                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
7631   }
7632
7633   // Default SSE2 implementation
7634   int LoByteShift = 16 - Rotation * Scale;
7635   int HiByteShift = Rotation * Scale;
7636
7637   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7638   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
7639   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
7640
7641   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7642                                 DAG.getConstant(8 * LoByteShift, MVT::i8));
7643   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7644                                 DAG.getConstant(8 * HiByteShift, MVT::i8));
7645   return DAG.getNode(ISD::BITCAST, DL, VT,
7646                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7647 }
7648
7649 /// \brief Compute whether each element of a shuffle is zeroable.
7650 ///
7651 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7652 /// Either it is an undef element in the shuffle mask, the element of the input
7653 /// referenced is undef, or the element of the input referenced is known to be
7654 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7655 /// as many lanes with this technique as possible to simplify the remaining
7656 /// shuffle.
7657 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
7658                                                      SDValue V1, SDValue V2) {
7659   SmallBitVector Zeroable(Mask.size(), false);
7660
7661   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7662   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7663
7664   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7665     int M = Mask[i];
7666     // Handle the easy cases.
7667     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7668       Zeroable[i] = true;
7669       continue;
7670     }
7671
7672     // If this is an index into a build_vector node, dig out the input value and
7673     // use it.
7674     SDValue V = M < Size ? V1 : V2;
7675     if (V.getOpcode() != ISD::BUILD_VECTOR)
7676       continue;
7677
7678     SDValue Input = V.getOperand(M % Size);
7679     // The UNDEF opcode check really should be dead code here, but not quite
7680     // worth asserting on (it isn't invalid, just unexpected).
7681     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
7682       Zeroable[i] = true;
7683   }
7684
7685   return Zeroable;
7686 }
7687
7688 /// \brief Try to lower a vector shuffle as a byte shift (shifts in zeros).
7689 ///
7690 /// Attempts to match a shuffle mask against the PSRLDQ and PSLLDQ SSE2
7691 /// byte-shift instructions. The mask must consist of a shifted sequential
7692 /// shuffle from one of the input vectors and zeroable elements for the
7693 /// remaining 'shifted in' elements.
7694 ///
7695 /// Note that this only handles 128-bit vector widths currently.
7696 static SDValue lowerVectorShuffleAsByteShift(SDLoc DL, MVT VT, SDValue V1,
7697                                              SDValue V2, ArrayRef<int> Mask,
7698                                              SelectionDAG &DAG) {
7699   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7700
7701   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7702
7703   int Size = Mask.size();
7704   int Scale = 16 / Size;
7705
7706   auto isSequential = [](int Base, int StartIndex, int EndIndex, int MaskOffset,
7707                          ArrayRef<int> Mask) {
7708     for (int i = StartIndex; i < EndIndex; i++) {
7709       if (Mask[i] < 0)
7710         continue;
7711       if (i + Base != Mask[i] - MaskOffset)
7712         return false;
7713     }
7714     return true;
7715   };
7716
7717   for (int Shift = 1; Shift < Size; Shift++) {
7718     int ByteShift = Shift * Scale;
7719
7720     // PSRLDQ : (little-endian) right byte shift
7721     // [ 5,  6,  7, zz, zz, zz, zz, zz]
7722     // [ -1, 5,  6,  7, zz, zz, zz, zz]
7723     // [  1, 2, -1, -1, -1, -1, zz, zz]
7724     bool ZeroableRight = true;
7725     for (int i = Size - Shift; i < Size; i++) {
7726       ZeroableRight &= Zeroable[i];
7727     }
7728
7729     if (ZeroableRight) {
7730       bool ValidShiftRight1 = isSequential(Shift, 0, Size - Shift, 0, Mask);
7731       bool ValidShiftRight2 = isSequential(Shift, 0, Size - Shift, Size, Mask);
7732
7733       if (ValidShiftRight1 || ValidShiftRight2) {
7734         // Cast the inputs to v2i64 to match PSRLDQ.
7735         SDValue &TargetV = ValidShiftRight1 ? V1 : V2;
7736         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7737         SDValue Shifted = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, V,
7738                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7739         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7740       }
7741     }
7742
7743     // PSLLDQ : (little-endian) left byte shift
7744     // [ zz,  0,  1,  2,  3,  4,  5,  6]
7745     // [ zz, zz, -1, -1,  2,  3,  4, -1]
7746     // [ zz, zz, zz, zz, zz, zz, -1,  1]
7747     bool ZeroableLeft = true;
7748     for (int i = 0; i < Shift; i++) {
7749       ZeroableLeft &= Zeroable[i];
7750     }
7751
7752     if (ZeroableLeft) {
7753       bool ValidShiftLeft1 = isSequential(-Shift, Shift, Size, 0, Mask);
7754       bool ValidShiftLeft2 = isSequential(-Shift, Shift, Size, Size, Mask);
7755
7756       if (ValidShiftLeft1 || ValidShiftLeft2) {
7757         // Cast the inputs to v2i64 to match PSLLDQ.
7758         SDValue &TargetV = ValidShiftLeft1 ? V1 : V2;
7759         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7760         SDValue Shifted = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, V,
7761                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7762         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7763       }
7764     }
7765   }
7766
7767   return SDValue();
7768 }
7769
7770 /// \brief Lower a vector shuffle as a zero or any extension.
7771 ///
7772 /// Given a specific number of elements, element bit width, and extension
7773 /// stride, produce either a zero or any extension based on the available
7774 /// features of the subtarget.
7775 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7776     SDLoc DL, MVT VT, int NumElements, int Scale, bool AnyExt, SDValue InputV,
7777     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7778   assert(Scale > 1 && "Need a scale to extend.");
7779   int EltBits = VT.getSizeInBits() / NumElements;
7780   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7781          "Only 8, 16, and 32 bit elements can be extended.");
7782   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7783
7784   // Found a valid zext mask! Try various lowering strategies based on the
7785   // input type and available ISA extensions.
7786   if (Subtarget->hasSSE41()) {
7787     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7788     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7789                                  NumElements / Scale);
7790     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7791     return DAG.getNode(ISD::BITCAST, DL, VT,
7792                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7793   }
7794
7795   // For any extends we can cheat for larger element sizes and use shuffle
7796   // instructions that can fold with a load and/or copy.
7797   if (AnyExt && EltBits == 32) {
7798     int PSHUFDMask[4] = {0, -1, 1, -1};
7799     return DAG.getNode(
7800         ISD::BITCAST, DL, VT,
7801         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7802                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7803                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7804   }
7805   if (AnyExt && EltBits == 16 && Scale > 2) {
7806     int PSHUFDMask[4] = {0, -1, 0, -1};
7807     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7808                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7809                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
7810     int PSHUFHWMask[4] = {1, -1, -1, -1};
7811     return DAG.getNode(
7812         ISD::BITCAST, DL, VT,
7813         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7814                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
7815                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
7816   }
7817
7818   // If this would require more than 2 unpack instructions to expand, use
7819   // pshufb when available. We can only use more than 2 unpack instructions
7820   // when zero extending i8 elements which also makes it easier to use pshufb.
7821   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7822     assert(NumElements == 16 && "Unexpected byte vector width!");
7823     SDValue PSHUFBMask[16];
7824     for (int i = 0; i < 16; ++i)
7825       PSHUFBMask[i] =
7826           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
7827     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
7828     return DAG.getNode(ISD::BITCAST, DL, VT,
7829                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7830                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
7831                                                MVT::v16i8, PSHUFBMask)));
7832   }
7833
7834   // Otherwise emit a sequence of unpacks.
7835   do {
7836     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7837     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7838                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7839     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7840     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7841     Scale /= 2;
7842     EltBits *= 2;
7843     NumElements /= 2;
7844   } while (Scale > 1);
7845   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
7846 }
7847
7848 /// \brief Try to lower a vector shuffle as a zero extension on any micrarch.
7849 ///
7850 /// This routine will try to do everything in its power to cleverly lower
7851 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7852 /// check for the profitability of this lowering,  it tries to aggressively
7853 /// match this pattern. It will use all of the micro-architectural details it
7854 /// can to emit an efficient lowering. It handles both blends with all-zero
7855 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7856 /// masking out later).
7857 ///
7858 /// The reason we have dedicated lowering for zext-style shuffles is that they
7859 /// are both incredibly common and often quite performance sensitive.
7860 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7861     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7862     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7863   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7864
7865   int Bits = VT.getSizeInBits();
7866   int NumElements = Mask.size();
7867
7868   // Define a helper function to check a particular ext-scale and lower to it if
7869   // valid.
7870   auto Lower = [&](int Scale) -> SDValue {
7871     SDValue InputV;
7872     bool AnyExt = true;
7873     for (int i = 0; i < NumElements; ++i) {
7874       if (Mask[i] == -1)
7875         continue; // Valid anywhere but doesn't tell us anything.
7876       if (i % Scale != 0) {
7877         // Each of the extend elements needs to be zeroable.
7878         if (!Zeroable[i])
7879           return SDValue();
7880
7881         // We no lorger are in the anyext case.
7882         AnyExt = false;
7883         continue;
7884       }
7885
7886       // Each of the base elements needs to be consecutive indices into the
7887       // same input vector.
7888       SDValue V = Mask[i] < NumElements ? V1 : V2;
7889       if (!InputV)
7890         InputV = V;
7891       else if (InputV != V)
7892         return SDValue(); // Flip-flopping inputs.
7893
7894       if (Mask[i] % NumElements != i / Scale)
7895         return SDValue(); // Non-consecutive strided elemenst.
7896     }
7897
7898     // If we fail to find an input, we have a zero-shuffle which should always
7899     // have already been handled.
7900     // FIXME: Maybe handle this here in case during blending we end up with one?
7901     if (!InputV)
7902       return SDValue();
7903
7904     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7905         DL, VT, NumElements, Scale, AnyExt, InputV, Subtarget, DAG);
7906   };
7907
7908   // The widest scale possible for extending is to a 64-bit integer.
7909   assert(Bits % 64 == 0 &&
7910          "The number of bits in a vector must be divisible by 64 on x86!");
7911   int NumExtElements = Bits / 64;
7912
7913   // Each iteration, try extending the elements half as much, but into twice as
7914   // many elements.
7915   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7916     assert(NumElements % NumExtElements == 0 &&
7917            "The input vector size must be divisble by the extended size.");
7918     if (SDValue V = Lower(NumElements / NumExtElements))
7919       return V;
7920   }
7921
7922   // No viable ext lowering found.
7923   return SDValue();
7924 }
7925
7926 /// \brief Try to get a scalar value for a specific element of a vector.
7927 ///
7928 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7929 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7930                                               SelectionDAG &DAG) {
7931   MVT VT = V.getSimpleValueType();
7932   MVT EltVT = VT.getVectorElementType();
7933   while (V.getOpcode() == ISD::BITCAST)
7934     V = V.getOperand(0);
7935   // If the bitcasts shift the element size, we can't extract an equivalent
7936   // element from it.
7937   MVT NewVT = V.getSimpleValueType();
7938   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7939     return SDValue();
7940
7941   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7942       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
7943     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
7944
7945   return SDValue();
7946 }
7947
7948 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7949 ///
7950 /// This is particularly important because the set of instructions varies
7951 /// significantly based on whether the operand is a load or not.
7952 static bool isShuffleFoldableLoad(SDValue V) {
7953   while (V.getOpcode() == ISD::BITCAST)
7954     V = V.getOperand(0);
7955
7956   return ISD::isNON_EXTLoad(V.getNode());
7957 }
7958
7959 /// \brief Try to lower insertion of a single element into a zero vector.
7960 ///
7961 /// This is a common pattern that we have especially efficient patterns to lower
7962 /// across all subtarget feature sets.
7963 static SDValue lowerVectorShuffleAsElementInsertion(
7964     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7965     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7966   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7967   MVT ExtVT = VT;
7968   MVT EltVT = VT.getVectorElementType();
7969
7970   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7971                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7972                 Mask.begin();
7973   bool IsV1Zeroable = true;
7974   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7975     if (i != V2Index && !Zeroable[i]) {
7976       IsV1Zeroable = false;
7977       break;
7978     }
7979
7980   // Check for a single input from a SCALAR_TO_VECTOR node.
7981   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7982   // all the smarts here sunk into that routine. However, the current
7983   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7984   // vector shuffle lowering is dead.
7985   if (SDValue V2S = getScalarValueForVectorElement(
7986           V2, Mask[V2Index] - Mask.size(), DAG)) {
7987     // We need to zext the scalar if it is smaller than an i32.
7988     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7989     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7990       // Using zext to expand a narrow element won't work for non-zero
7991       // insertions.
7992       if (!IsV1Zeroable)
7993         return SDValue();
7994
7995       // Zero-extend directly to i32.
7996       ExtVT = MVT::v4i32;
7997       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7998     }
7999     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
8000   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
8001              EltVT == MVT::i16) {
8002     // Either not inserting from the low element of the input or the input
8003     // element size is too small to use VZEXT_MOVL to clear the high bits.
8004     return SDValue();
8005   }
8006
8007   if (!IsV1Zeroable) {
8008     // If V1 can't be treated as a zero vector we have fewer options to lower
8009     // this. We can't support integer vectors or non-zero targets cheaply, and
8010     // the V1 elements can't be permuted in any way.
8011     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8012     if (!VT.isFloatingPoint() || V2Index != 0)
8013       return SDValue();
8014     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8015     V1Mask[V2Index] = -1;
8016     if (!isNoopShuffleMask(V1Mask))
8017       return SDValue();
8018     // This is essentially a special case blend operation, but if we have
8019     // general purpose blend operations, they are always faster. Bail and let
8020     // the rest of the lowering handle these as blends.
8021     if (Subtarget->hasSSE41())
8022       return SDValue();
8023
8024     // Otherwise, use MOVSD or MOVSS.
8025     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8026            "Only two types of floating point element types to handle!");
8027     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8028                        ExtVT, V1, V2);
8029   }
8030
8031   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8032   if (ExtVT != VT)
8033     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8034
8035   if (V2Index != 0) {
8036     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8037     // the desired position. Otherwise it is more efficient to do a vector
8038     // shift left. We know that we can do a vector shift left because all
8039     // the inputs are zero.
8040     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8041       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8042       V2Shuffle[V2Index] = 0;
8043       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8044     } else {
8045       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
8046       V2 = DAG.getNode(
8047           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8048           DAG.getConstant(
8049               V2Index * EltVT.getSizeInBits(),
8050               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
8051       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8052     }
8053   }
8054   return V2;
8055 }
8056
8057 /// \brief Try to lower broadcast of a single element.
8058 ///
8059 /// For convenience, this code also bundles all of the subtarget feature set
8060 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8061 /// a convenient way to factor it out.
8062 static SDValue lowerVectorShuffleAsBroadcast(MVT VT, SDLoc DL, SDValue V,
8063                                              ArrayRef<int> Mask,
8064                                              const X86Subtarget *Subtarget,
8065                                              SelectionDAG &DAG) {
8066   if (!Subtarget->hasAVX())
8067     return SDValue();
8068   if (VT.isInteger() && !Subtarget->hasAVX2())
8069     return SDValue();
8070
8071   // Check that the mask is a broadcast.
8072   int BroadcastIdx = -1;
8073   for (int M : Mask)
8074     if (M >= 0 && BroadcastIdx == -1)
8075       BroadcastIdx = M;
8076     else if (M >= 0 && M != BroadcastIdx)
8077       return SDValue();
8078
8079   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8080                                             "a sorted mask where the broadcast "
8081                                             "comes from V1.");
8082
8083   // Go up the chain of (vector) values to try and find a scalar load that
8084   // we can combine with the broadcast.
8085   for (;;) {
8086     switch (V.getOpcode()) {
8087     case ISD::CONCAT_VECTORS: {
8088       int OperandSize = Mask.size() / V.getNumOperands();
8089       V = V.getOperand(BroadcastIdx / OperandSize);
8090       BroadcastIdx %= OperandSize;
8091       continue;
8092     }
8093
8094     case ISD::INSERT_SUBVECTOR: {
8095       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8096       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8097       if (!ConstantIdx)
8098         break;
8099
8100       int BeginIdx = (int)ConstantIdx->getZExtValue();
8101       int EndIdx =
8102           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
8103       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8104         BroadcastIdx -= BeginIdx;
8105         V = VInner;
8106       } else {
8107         V = VOuter;
8108       }
8109       continue;
8110     }
8111     }
8112     break;
8113   }
8114
8115   // Check if this is a broadcast of a scalar. We special case lowering
8116   // for scalars so that we can more effectively fold with loads.
8117   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8118       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8119     V = V.getOperand(BroadcastIdx);
8120
8121     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
8122     // AVX2.
8123     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8124       return SDValue();
8125   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8126     // We can't broadcast from a vector register w/o AVX2, and we can only
8127     // broadcast from the zero-element of a vector register.
8128     return SDValue();
8129   }
8130
8131   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8132 }
8133
8134 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8135 ///
8136 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8137 /// support for floating point shuffles but not integer shuffles. These
8138 /// instructions will incur a domain crossing penalty on some chips though so
8139 /// it is better to avoid lowering through this for integer vectors where
8140 /// possible.
8141 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8142                                        const X86Subtarget *Subtarget,
8143                                        SelectionDAG &DAG) {
8144   SDLoc DL(Op);
8145   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8146   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8147   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8148   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8149   ArrayRef<int> Mask = SVOp->getMask();
8150   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8151
8152   if (isSingleInputShuffleMask(Mask)) {
8153     // Straight shuffle of a single input vector. Simulate this by using the
8154     // single input as both of the "inputs" to this instruction..
8155     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8156
8157     if (Subtarget->hasAVX()) {
8158       // If we have AVX, we can use VPERMILPS which will allow folding a load
8159       // into the shuffle.
8160       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8161                          DAG.getConstant(SHUFPDMask, MVT::i8));
8162     }
8163
8164     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
8165                        DAG.getConstant(SHUFPDMask, MVT::i8));
8166   }
8167   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8168   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8169
8170   // Use dedicated unpack instructions for masks that match their pattern.
8171   if (isShuffleEquivalent(Mask, 0, 2))
8172     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8173   if (isShuffleEquivalent(Mask, 1, 3))
8174     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8175
8176   // If we have a single input, insert that into V1 if we can do so cheaply.
8177   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8178     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8179             MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
8180       return Insertion;
8181     // Try inverting the insertion since for v2 masks it is easy to do and we
8182     // can't reliably sort the mask one way or the other.
8183     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8184                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8185     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8186             MVT::v2f64, DL, V2, V1, InverseMask, Subtarget, DAG))
8187       return Insertion;
8188   }
8189
8190   // Try to use one of the special instruction patterns to handle two common
8191   // blend patterns if a zero-blend above didn't work.
8192   if (isShuffleEquivalent(Mask, 0, 3) || isShuffleEquivalent(Mask, 1, 3))
8193     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8194       // We can either use a special instruction to load over the low double or
8195       // to move just the low double.
8196       return DAG.getNode(
8197           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8198           DL, MVT::v2f64, V2,
8199           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8200
8201   if (Subtarget->hasSSE41())
8202     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8203                                                   Subtarget, DAG))
8204       return Blend;
8205
8206   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8207   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
8208                      DAG.getConstant(SHUFPDMask, MVT::i8));
8209 }
8210
8211 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8212 ///
8213 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8214 /// the integer unit to minimize domain crossing penalties. However, for blends
8215 /// it falls back to the floating point shuffle operation with appropriate bit
8216 /// casting.
8217 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8218                                        const X86Subtarget *Subtarget,
8219                                        SelectionDAG &DAG) {
8220   SDLoc DL(Op);
8221   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8222   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8223   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8224   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8225   ArrayRef<int> Mask = SVOp->getMask();
8226   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8227
8228   if (isSingleInputShuffleMask(Mask)) {
8229     // Check for being able to broadcast a single element.
8230     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v2i64, DL, V1,
8231                                                           Mask, Subtarget, DAG))
8232       return Broadcast;
8233
8234     // Straight shuffle of a single input vector. For everything from SSE2
8235     // onward this has a single fast instruction with no scary immediates.
8236     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8237     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
8238     int WidenedMask[4] = {
8239         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8240         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8241     return DAG.getNode(
8242         ISD::BITCAST, DL, MVT::v2i64,
8243         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
8244                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
8245   }
8246
8247   // Try to use byte shift instructions.
8248   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8249           DL, MVT::v2i64, V1, V2, Mask, DAG))
8250     return Shift;
8251
8252   // If we have a single input from V2 insert that into V1 if we can do so
8253   // cheaply.
8254   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8255     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8256             MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
8257       return Insertion;
8258     // Try inverting the insertion since for v2 masks it is easy to do and we
8259     // can't reliably sort the mask one way or the other.
8260     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8261                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8262     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8263             MVT::v2i64, DL, V2, V1, InverseMask, Subtarget, DAG))
8264       return Insertion;
8265   }
8266
8267   // Use dedicated unpack instructions for masks that match their pattern.
8268   if (isShuffleEquivalent(Mask, 0, 2))
8269     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8270   if (isShuffleEquivalent(Mask, 1, 3))
8271     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8272
8273   if (Subtarget->hasSSE41())
8274     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8275                                                   Subtarget, DAG))
8276       return Blend;
8277
8278   // Try to use byte rotation instructions.
8279   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8280   if (Subtarget->hasSSSE3())
8281     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8282             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8283       return Rotate;
8284
8285   // We implement this with SHUFPD which is pretty lame because it will likely
8286   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8287   // However, all the alternatives are still more cycles and newer chips don't
8288   // have this problem. It would be really nice if x86 had better shuffles here.
8289   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
8290   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
8291   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
8292                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8293 }
8294
8295 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8296 ///
8297 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8298 /// It makes no assumptions about whether this is the *best* lowering, it simply
8299 /// uses it.
8300 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8301                                             ArrayRef<int> Mask, SDValue V1,
8302                                             SDValue V2, SelectionDAG &DAG) {
8303   SDValue LowV = V1, HighV = V2;
8304   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8305
8306   int NumV2Elements =
8307       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8308
8309   if (NumV2Elements == 1) {
8310     int V2Index =
8311         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8312         Mask.begin();
8313
8314     // Compute the index adjacent to V2Index and in the same half by toggling
8315     // the low bit.
8316     int V2AdjIndex = V2Index ^ 1;
8317
8318     if (Mask[V2AdjIndex] == -1) {
8319       // Handles all the cases where we have a single V2 element and an undef.
8320       // This will only ever happen in the high lanes because we commute the
8321       // vector otherwise.
8322       if (V2Index < 2)
8323         std::swap(LowV, HighV);
8324       NewMask[V2Index] -= 4;
8325     } else {
8326       // Handle the case where the V2 element ends up adjacent to a V1 element.
8327       // To make this work, blend them together as the first step.
8328       int V1Index = V2AdjIndex;
8329       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8330       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8331                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8332
8333       // Now proceed to reconstruct the final blend as we have the necessary
8334       // high or low half formed.
8335       if (V2Index < 2) {
8336         LowV = V2;
8337         HighV = V1;
8338       } else {
8339         HighV = V2;
8340       }
8341       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8342       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8343     }
8344   } else if (NumV2Elements == 2) {
8345     if (Mask[0] < 4 && Mask[1] < 4) {
8346       // Handle the easy case where we have V1 in the low lanes and V2 in the
8347       // high lanes.
8348       NewMask[2] -= 4;
8349       NewMask[3] -= 4;
8350     } else if (Mask[2] < 4 && Mask[3] < 4) {
8351       // We also handle the reversed case because this utility may get called
8352       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8353       // arrange things in the right direction.
8354       NewMask[0] -= 4;
8355       NewMask[1] -= 4;
8356       HighV = V1;
8357       LowV = V2;
8358     } else {
8359       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8360       // trying to place elements directly, just blend them and set up the final
8361       // shuffle to place them.
8362
8363       // The first two blend mask elements are for V1, the second two are for
8364       // V2.
8365       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8366                           Mask[2] < 4 ? Mask[2] : Mask[3],
8367                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8368                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8369       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8370                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8371
8372       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8373       // a blend.
8374       LowV = HighV = V1;
8375       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8376       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8377       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8378       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8379     }
8380   }
8381   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8382                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
8383 }
8384
8385 /// \brief Lower 4-lane 32-bit floating point shuffles.
8386 ///
8387 /// Uses instructions exclusively from the floating point unit to minimize
8388 /// domain crossing penalties, as these are sufficient to implement all v4f32
8389 /// shuffles.
8390 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8391                                        const X86Subtarget *Subtarget,
8392                                        SelectionDAG &DAG) {
8393   SDLoc DL(Op);
8394   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8395   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8396   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8397   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8398   ArrayRef<int> Mask = SVOp->getMask();
8399   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8400
8401   int NumV2Elements =
8402       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8403
8404   if (NumV2Elements == 0) {
8405     // Check for being able to broadcast a single element.
8406     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f32, DL, V1,
8407                                                           Mask, Subtarget, DAG))
8408       return Broadcast;
8409
8410     if (Subtarget->hasAVX()) {
8411       // If we have AVX, we can use VPERMILPS which will allow folding a load
8412       // into the shuffle.
8413       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8414                          getV4X86ShuffleImm8ForMask(Mask, DAG));
8415     }
8416
8417     // Otherwise, use a straight shuffle of a single input vector. We pass the
8418     // input vector to both operands to simulate this with a SHUFPS.
8419     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8420                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8421   }
8422
8423   // Use dedicated unpack instructions for masks that match their pattern.
8424   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8425     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8426   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8427     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8428
8429   // There are special ways we can lower some single-element blends. However, we
8430   // have custom ways we can lower more complex single-element blends below that
8431   // we defer to if both this and BLENDPS fail to match, so restrict this to
8432   // when the V2 input is targeting element 0 of the mask -- that is the fast
8433   // case here.
8434   if (NumV2Elements == 1 && Mask[0] >= 4)
8435     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
8436                                                          Mask, Subtarget, DAG))
8437       return V;
8438
8439   if (Subtarget->hasSSE41())
8440     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8441                                                   Subtarget, DAG))
8442       return Blend;
8443
8444   // Check for whether we can use INSERTPS to perform the blend. We only use
8445   // INSERTPS when the V1 elements are already in the correct locations
8446   // because otherwise we can just always use two SHUFPS instructions which
8447   // are much smaller to encode than a SHUFPS and an INSERTPS.
8448   if (NumV2Elements == 1 && Subtarget->hasSSE41()) {
8449     int V2Index =
8450         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8451         Mask.begin();
8452
8453     // When using INSERTPS we can zero any lane of the destination. Collect
8454     // the zero inputs into a mask and drop them from the lanes of V1 which
8455     // actually need to be present as inputs to the INSERTPS.
8456     SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8457
8458     // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
8459     bool InsertNeedsShuffle = false;
8460     unsigned ZMask = 0;
8461     for (int i = 0; i < 4; ++i)
8462       if (i != V2Index) {
8463         if (Zeroable[i]) {
8464           ZMask |= 1 << i;
8465         } else if (Mask[i] != i) {
8466           InsertNeedsShuffle = true;
8467           break;
8468         }
8469       }
8470
8471     // We don't want to use INSERTPS or other insertion techniques if it will
8472     // require shuffling anyways.
8473     if (!InsertNeedsShuffle) {
8474       // If all of V1 is zeroable, replace it with undef.
8475       if ((ZMask | 1 << V2Index) == 0xF)
8476         V1 = DAG.getUNDEF(MVT::v4f32);
8477
8478       unsigned InsertPSMask = (Mask[V2Index] - 4) << 6 | V2Index << 4 | ZMask;
8479       assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8480
8481       // Insert the V2 element into the desired position.
8482       return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8483                          DAG.getConstant(InsertPSMask, MVT::i8));
8484     }
8485   }
8486
8487   // Otherwise fall back to a SHUFPS lowering strategy.
8488   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8489 }
8490
8491 /// \brief Lower 4-lane i32 vector shuffles.
8492 ///
8493 /// We try to handle these with integer-domain shuffles where we can, but for
8494 /// blends we use the floating point domain blend instructions.
8495 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8496                                        const X86Subtarget *Subtarget,
8497                                        SelectionDAG &DAG) {
8498   SDLoc DL(Op);
8499   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8500   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8501   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8502   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8503   ArrayRef<int> Mask = SVOp->getMask();
8504   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8505
8506   // Whenever we can lower this as a zext, that instruction is strictly faster
8507   // than any alternative. It also allows us to fold memory operands into the
8508   // shuffle in many cases.
8509   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8510                                                          Mask, Subtarget, DAG))
8511     return ZExt;
8512
8513   int NumV2Elements =
8514       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8515
8516   if (NumV2Elements == 0) {
8517     // Check for being able to broadcast a single element.
8518     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i32, DL, V1,
8519                                                           Mask, Subtarget, DAG))
8520       return Broadcast;
8521
8522     // Straight shuffle of a single input vector. For everything from SSE2
8523     // onward this has a single fast instruction with no scary immediates.
8524     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8525     // but we aren't actually going to use the UNPCK instruction because doing
8526     // so prevents folding a load into this instruction or making a copy.
8527     const int UnpackLoMask[] = {0, 0, 1, 1};
8528     const int UnpackHiMask[] = {2, 2, 3, 3};
8529     if (isShuffleEquivalent(Mask, 0, 0, 1, 1))
8530       Mask = UnpackLoMask;
8531     else if (isShuffleEquivalent(Mask, 2, 2, 3, 3))
8532       Mask = UnpackHiMask;
8533
8534     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8535                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8536   }
8537
8538   // Try to use byte shift instructions.
8539   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8540           DL, MVT::v4i32, V1, V2, Mask, DAG))
8541     return Shift;
8542
8543   // There are special ways we can lower some single-element blends.
8544   if (NumV2Elements == 1)
8545     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
8546                                                          Mask, Subtarget, DAG))
8547       return V;
8548
8549   // Use dedicated unpack instructions for masks that match their pattern.
8550   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8551     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8552   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8553     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8554
8555   if (Subtarget->hasSSE41())
8556     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8557                                                   Subtarget, DAG))
8558       return Blend;
8559
8560   // Try to use byte rotation instructions.
8561   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8562   if (Subtarget->hasSSSE3())
8563     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8564             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8565       return Rotate;
8566
8567   // We implement this with SHUFPS because it can blend from two vectors.
8568   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8569   // up the inputs, bypassing domain shift penalties that we would encur if we
8570   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8571   // relevant.
8572   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
8573                      DAG.getVectorShuffle(
8574                          MVT::v4f32, DL,
8575                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
8576                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
8577 }
8578
8579 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8580 /// shuffle lowering, and the most complex part.
8581 ///
8582 /// The lowering strategy is to try to form pairs of input lanes which are
8583 /// targeted at the same half of the final vector, and then use a dword shuffle
8584 /// to place them onto the right half, and finally unpack the paired lanes into
8585 /// their final position.
8586 ///
8587 /// The exact breakdown of how to form these dword pairs and align them on the
8588 /// correct sides is really tricky. See the comments within the function for
8589 /// more of the details.
8590 static SDValue lowerV8I16SingleInputVectorShuffle(
8591     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
8592     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8593   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8594   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8595   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8596
8597   SmallVector<int, 4> LoInputs;
8598   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8599                [](int M) { return M >= 0; });
8600   std::sort(LoInputs.begin(), LoInputs.end());
8601   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8602   SmallVector<int, 4> HiInputs;
8603   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8604                [](int M) { return M >= 0; });
8605   std::sort(HiInputs.begin(), HiInputs.end());
8606   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8607   int NumLToL =
8608       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8609   int NumHToL = LoInputs.size() - NumLToL;
8610   int NumLToH =
8611       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8612   int NumHToH = HiInputs.size() - NumLToH;
8613   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8614   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8615   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8616   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8617
8618   // Check for being able to broadcast a single element.
8619   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i16, DL, V,
8620                                                         Mask, Subtarget, DAG))
8621     return Broadcast;
8622
8623   // Try to use byte shift instructions.
8624   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8625           DL, MVT::v8i16, V, V, Mask, DAG))
8626     return Shift;
8627
8628   // Use dedicated unpack instructions for masks that match their pattern.
8629   if (isShuffleEquivalent(Mask, 0, 0, 1, 1, 2, 2, 3, 3))
8630     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
8631   if (isShuffleEquivalent(Mask, 4, 4, 5, 5, 6, 6, 7, 7))
8632     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
8633
8634   // Try to use byte rotation instructions.
8635   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8636           DL, MVT::v8i16, V, V, Mask, Subtarget, DAG))
8637     return Rotate;
8638
8639   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8640   // such inputs we can swap two of the dwords across the half mark and end up
8641   // with <=2 inputs to each half in each half. Once there, we can fall through
8642   // to the generic code below. For example:
8643   //
8644   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8645   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8646   //
8647   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8648   // and an existing 2-into-2 on the other half. In this case we may have to
8649   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8650   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8651   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8652   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8653   // half than the one we target for fixing) will be fixed when we re-enter this
8654   // path. We will also combine away any sequence of PSHUFD instructions that
8655   // result into a single instruction. Here is an example of the tricky case:
8656   //
8657   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8658   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8659   //
8660   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8661   //
8662   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8663   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8664   //
8665   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8666   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8667   //
8668   // The result is fine to be handled by the generic logic.
8669   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8670                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8671                           int AOffset, int BOffset) {
8672     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8673            "Must call this with A having 3 or 1 inputs from the A half.");
8674     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8675            "Must call this with B having 1 or 3 inputs from the B half.");
8676     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8677            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8678
8679     // Compute the index of dword with only one word among the three inputs in
8680     // a half by taking the sum of the half with three inputs and subtracting
8681     // the sum of the actual three inputs. The difference is the remaining
8682     // slot.
8683     int ADWord, BDWord;
8684     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8685     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8686     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8687     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8688     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8689     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8690     int TripleNonInputIdx =
8691         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8692     TripleDWord = TripleNonInputIdx / 2;
8693
8694     // We use xor with one to compute the adjacent DWord to whichever one the
8695     // OneInput is in.
8696     OneInputDWord = (OneInput / 2) ^ 1;
8697
8698     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8699     // and BToA inputs. If there is also such a problem with the BToB and AToB
8700     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8701     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8702     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8703     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8704       // Compute how many inputs will be flipped by swapping these DWords. We
8705       // need
8706       // to balance this to ensure we don't form a 3-1 shuffle in the other
8707       // half.
8708       int NumFlippedAToBInputs =
8709           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8710           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8711       int NumFlippedBToBInputs =
8712           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8713           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8714       if ((NumFlippedAToBInputs == 1 &&
8715            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8716           (NumFlippedBToBInputs == 1 &&
8717            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8718         // We choose whether to fix the A half or B half based on whether that
8719         // half has zero flipped inputs. At zero, we may not be able to fix it
8720         // with that half. We also bias towards fixing the B half because that
8721         // will more commonly be the high half, and we have to bias one way.
8722         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8723                                                        ArrayRef<int> Inputs) {
8724           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8725           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8726                                          PinnedIdx ^ 1) != Inputs.end();
8727           // Determine whether the free index is in the flipped dword or the
8728           // unflipped dword based on where the pinned index is. We use this bit
8729           // in an xor to conditionally select the adjacent dword.
8730           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8731           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8732                                              FixFreeIdx) != Inputs.end();
8733           if (IsFixIdxInput == IsFixFreeIdxInput)
8734             FixFreeIdx += 1;
8735           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8736                                         FixFreeIdx) != Inputs.end();
8737           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8738                  "We need to be changing the number of flipped inputs!");
8739           int PSHUFHalfMask[] = {0, 1, 2, 3};
8740           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8741           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8742                           MVT::v8i16, V,
8743                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
8744
8745           for (int &M : Mask)
8746             if (M != -1 && M == FixIdx)
8747               M = FixFreeIdx;
8748             else if (M != -1 && M == FixFreeIdx)
8749               M = FixIdx;
8750         };
8751         if (NumFlippedBToBInputs != 0) {
8752           int BPinnedIdx =
8753               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8754           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8755         } else {
8756           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8757           int APinnedIdx =
8758               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8759           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8760         }
8761       }
8762     }
8763
8764     int PSHUFDMask[] = {0, 1, 2, 3};
8765     PSHUFDMask[ADWord] = BDWord;
8766     PSHUFDMask[BDWord] = ADWord;
8767     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8768                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8769                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8770                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8771
8772     // Adjust the mask to match the new locations of A and B.
8773     for (int &M : Mask)
8774       if (M != -1 && M/2 == ADWord)
8775         M = 2 * BDWord + M % 2;
8776       else if (M != -1 && M/2 == BDWord)
8777         M = 2 * ADWord + M % 2;
8778
8779     // Recurse back into this routine to re-compute state now that this isn't
8780     // a 3 and 1 problem.
8781     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8782                                 Mask);
8783   };
8784   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8785     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8786   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8787     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8788
8789   // At this point there are at most two inputs to the low and high halves from
8790   // each half. That means the inputs can always be grouped into dwords and
8791   // those dwords can then be moved to the correct half with a dword shuffle.
8792   // We use at most one low and one high word shuffle to collect these paired
8793   // inputs into dwords, and finally a dword shuffle to place them.
8794   int PSHUFLMask[4] = {-1, -1, -1, -1};
8795   int PSHUFHMask[4] = {-1, -1, -1, -1};
8796   int PSHUFDMask[4] = {-1, -1, -1, -1};
8797
8798   // First fix the masks for all the inputs that are staying in their
8799   // original halves. This will then dictate the targets of the cross-half
8800   // shuffles.
8801   auto fixInPlaceInputs =
8802       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8803                     MutableArrayRef<int> SourceHalfMask,
8804                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8805     if (InPlaceInputs.empty())
8806       return;
8807     if (InPlaceInputs.size() == 1) {
8808       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8809           InPlaceInputs[0] - HalfOffset;
8810       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8811       return;
8812     }
8813     if (IncomingInputs.empty()) {
8814       // Just fix all of the in place inputs.
8815       for (int Input : InPlaceInputs) {
8816         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8817         PSHUFDMask[Input / 2] = Input / 2;
8818       }
8819       return;
8820     }
8821
8822     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8823     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8824         InPlaceInputs[0] - HalfOffset;
8825     // Put the second input next to the first so that they are packed into
8826     // a dword. We find the adjacent index by toggling the low bit.
8827     int AdjIndex = InPlaceInputs[0] ^ 1;
8828     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8829     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8830     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8831   };
8832   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8833   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8834
8835   // Now gather the cross-half inputs and place them into a free dword of
8836   // their target half.
8837   // FIXME: This operation could almost certainly be simplified dramatically to
8838   // look more like the 3-1 fixing operation.
8839   auto moveInputsToRightHalf = [&PSHUFDMask](
8840       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8841       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8842       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8843       int DestOffset) {
8844     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8845       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8846     };
8847     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8848                                                int Word) {
8849       int LowWord = Word & ~1;
8850       int HighWord = Word | 1;
8851       return isWordClobbered(SourceHalfMask, LowWord) ||
8852              isWordClobbered(SourceHalfMask, HighWord);
8853     };
8854
8855     if (IncomingInputs.empty())
8856       return;
8857
8858     if (ExistingInputs.empty()) {
8859       // Map any dwords with inputs from them into the right half.
8860       for (int Input : IncomingInputs) {
8861         // If the source half mask maps over the inputs, turn those into
8862         // swaps and use the swapped lane.
8863         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8864           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8865             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8866                 Input - SourceOffset;
8867             // We have to swap the uses in our half mask in one sweep.
8868             for (int &M : HalfMask)
8869               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8870                 M = Input;
8871               else if (M == Input)
8872                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8873           } else {
8874             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8875                        Input - SourceOffset &&
8876                    "Previous placement doesn't match!");
8877           }
8878           // Note that this correctly re-maps both when we do a swap and when
8879           // we observe the other side of the swap above. We rely on that to
8880           // avoid swapping the members of the input list directly.
8881           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8882         }
8883
8884         // Map the input's dword into the correct half.
8885         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8886           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8887         else
8888           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8889                      Input / 2 &&
8890                  "Previous placement doesn't match!");
8891       }
8892
8893       // And just directly shift any other-half mask elements to be same-half
8894       // as we will have mirrored the dword containing the element into the
8895       // same position within that half.
8896       for (int &M : HalfMask)
8897         if (M >= SourceOffset && M < SourceOffset + 4) {
8898           M = M - SourceOffset + DestOffset;
8899           assert(M >= 0 && "This should never wrap below zero!");
8900         }
8901       return;
8902     }
8903
8904     // Ensure we have the input in a viable dword of its current half. This
8905     // is particularly tricky because the original position may be clobbered
8906     // by inputs being moved and *staying* in that half.
8907     if (IncomingInputs.size() == 1) {
8908       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8909         int InputFixed = std::find(std::begin(SourceHalfMask),
8910                                    std::end(SourceHalfMask), -1) -
8911                          std::begin(SourceHalfMask) + SourceOffset;
8912         SourceHalfMask[InputFixed - SourceOffset] =
8913             IncomingInputs[0] - SourceOffset;
8914         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8915                      InputFixed);
8916         IncomingInputs[0] = InputFixed;
8917       }
8918     } else if (IncomingInputs.size() == 2) {
8919       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8920           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8921         // We have two non-adjacent or clobbered inputs we need to extract from
8922         // the source half. To do this, we need to map them into some adjacent
8923         // dword slot in the source mask.
8924         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8925                               IncomingInputs[1] - SourceOffset};
8926
8927         // If there is a free slot in the source half mask adjacent to one of
8928         // the inputs, place the other input in it. We use (Index XOR 1) to
8929         // compute an adjacent index.
8930         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8931             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8932           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8933           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8934           InputsFixed[1] = InputsFixed[0] ^ 1;
8935         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8936                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8937           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8938           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8939           InputsFixed[0] = InputsFixed[1] ^ 1;
8940         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8941                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8942           // The two inputs are in the same DWord but it is clobbered and the
8943           // adjacent DWord isn't used at all. Move both inputs to the free
8944           // slot.
8945           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8946           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8947           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8948           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8949         } else {
8950           // The only way we hit this point is if there is no clobbering
8951           // (because there are no off-half inputs to this half) and there is no
8952           // free slot adjacent to one of the inputs. In this case, we have to
8953           // swap an input with a non-input.
8954           for (int i = 0; i < 4; ++i)
8955             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8956                    "We can't handle any clobbers here!");
8957           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8958                  "Cannot have adjacent inputs here!");
8959
8960           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8961           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8962
8963           // We also have to update the final source mask in this case because
8964           // it may need to undo the above swap.
8965           for (int &M : FinalSourceHalfMask)
8966             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8967               M = InputsFixed[1] + SourceOffset;
8968             else if (M == InputsFixed[1] + SourceOffset)
8969               M = (InputsFixed[0] ^ 1) + SourceOffset;
8970
8971           InputsFixed[1] = InputsFixed[0] ^ 1;
8972         }
8973
8974         // Point everything at the fixed inputs.
8975         for (int &M : HalfMask)
8976           if (M == IncomingInputs[0])
8977             M = InputsFixed[0] + SourceOffset;
8978           else if (M == IncomingInputs[1])
8979             M = InputsFixed[1] + SourceOffset;
8980
8981         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8982         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8983       }
8984     } else {
8985       llvm_unreachable("Unhandled input size!");
8986     }
8987
8988     // Now hoist the DWord down to the right half.
8989     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8990     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8991     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8992     for (int &M : HalfMask)
8993       for (int Input : IncomingInputs)
8994         if (M == Input)
8995           M = FreeDWord * 2 + Input % 2;
8996   };
8997   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8998                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8999   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9000                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9001
9002   // Now enact all the shuffles we've computed to move the inputs into their
9003   // target half.
9004   if (!isNoopShuffleMask(PSHUFLMask))
9005     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
9006                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
9007   if (!isNoopShuffleMask(PSHUFHMask))
9008     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
9009                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
9010   if (!isNoopShuffleMask(PSHUFDMask))
9011     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9012                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
9013                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
9014                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9015
9016   // At this point, each half should contain all its inputs, and we can then
9017   // just shuffle them into their final position.
9018   assert(std::count_if(LoMask.begin(), LoMask.end(),
9019                        [](int M) { return M >= 4; }) == 0 &&
9020          "Failed to lift all the high half inputs to the low mask!");
9021   assert(std::count_if(HiMask.begin(), HiMask.end(),
9022                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9023          "Failed to lift all the low half inputs to the high mask!");
9024
9025   // Do a half shuffle for the low mask.
9026   if (!isNoopShuffleMask(LoMask))
9027     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
9028                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
9029
9030   // Do a half shuffle with the high mask after shifting its values down.
9031   for (int &M : HiMask)
9032     if (M >= 0)
9033       M -= 4;
9034   if (!isNoopShuffleMask(HiMask))
9035     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
9036                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
9037
9038   return V;
9039 }
9040
9041 /// \brief Detect whether the mask pattern should be lowered through
9042 /// interleaving.
9043 ///
9044 /// This essentially tests whether viewing the mask as an interleaving of two
9045 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
9046 /// lowering it through interleaving is a significantly better strategy.
9047 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
9048   int NumEvenInputs[2] = {0, 0};
9049   int NumOddInputs[2] = {0, 0};
9050   int NumLoInputs[2] = {0, 0};
9051   int NumHiInputs[2] = {0, 0};
9052   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9053     if (Mask[i] < 0)
9054       continue;
9055
9056     int InputIdx = Mask[i] >= Size;
9057
9058     if (i < Size / 2)
9059       ++NumLoInputs[InputIdx];
9060     else
9061       ++NumHiInputs[InputIdx];
9062
9063     if ((i % 2) == 0)
9064       ++NumEvenInputs[InputIdx];
9065     else
9066       ++NumOddInputs[InputIdx];
9067   }
9068
9069   // The minimum number of cross-input results for both the interleaved and
9070   // split cases. If interleaving results in fewer cross-input results, return
9071   // true.
9072   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
9073                                     NumEvenInputs[0] + NumOddInputs[1]);
9074   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
9075                               NumLoInputs[0] + NumHiInputs[1]);
9076   return InterleavedCrosses < SplitCrosses;
9077 }
9078
9079 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
9080 ///
9081 /// This strategy only works when the inputs from each vector fit into a single
9082 /// half of that vector, and generally there are not so many inputs as to leave
9083 /// the in-place shuffles required highly constrained (and thus expensive). It
9084 /// shifts all the inputs into a single side of both input vectors and then
9085 /// uses an unpack to interleave these inputs in a single vector. At that
9086 /// point, we will fall back on the generic single input shuffle lowering.
9087 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
9088                                                  SDValue V2,
9089                                                  MutableArrayRef<int> Mask,
9090                                                  const X86Subtarget *Subtarget,
9091                                                  SelectionDAG &DAG) {
9092   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9093   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9094   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
9095   for (int i = 0; i < 8; ++i)
9096     if (Mask[i] >= 0 && Mask[i] < 4)
9097       LoV1Inputs.push_back(i);
9098     else if (Mask[i] >= 4 && Mask[i] < 8)
9099       HiV1Inputs.push_back(i);
9100     else if (Mask[i] >= 8 && Mask[i] < 12)
9101       LoV2Inputs.push_back(i);
9102     else if (Mask[i] >= 12)
9103       HiV2Inputs.push_back(i);
9104
9105   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
9106   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
9107   (void)NumV1Inputs;
9108   (void)NumV2Inputs;
9109   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
9110   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
9111   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
9112
9113   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
9114                      HiV1Inputs.size() + HiV2Inputs.size();
9115
9116   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
9117                               ArrayRef<int> HiInputs, bool MoveToLo,
9118                               int MaskOffset) {
9119     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
9120     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
9121     if (BadInputs.empty())
9122       return V;
9123
9124     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9125     int MoveOffset = MoveToLo ? 0 : 4;
9126
9127     if (GoodInputs.empty()) {
9128       for (int BadInput : BadInputs) {
9129         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
9130         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
9131       }
9132     } else {
9133       if (GoodInputs.size() == 2) {
9134         // If the low inputs are spread across two dwords, pack them into
9135         // a single dword.
9136         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
9137         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
9138         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
9139         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
9140       } else {
9141         // Otherwise pin the good inputs.
9142         for (int GoodInput : GoodInputs)
9143           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
9144       }
9145
9146       if (BadInputs.size() == 2) {
9147         // If we have two bad inputs then there may be either one or two good
9148         // inputs fixed in place. Find a fixed input, and then find the *other*
9149         // two adjacent indices by using modular arithmetic.
9150         int GoodMaskIdx =
9151             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
9152                          [](int M) { return M >= 0; }) -
9153             std::begin(MoveMask);
9154         int MoveMaskIdx =
9155             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
9156         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
9157         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
9158         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9159         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
9160         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9161         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
9162       } else {
9163         assert(BadInputs.size() == 1 && "All sizes handled");
9164         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
9165                                     std::end(MoveMask), -1) -
9166                           std::begin(MoveMask);
9167         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9168         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9169       }
9170     }
9171
9172     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
9173                                 MoveMask);
9174   };
9175   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
9176                         /*MaskOffset*/ 0);
9177   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
9178                         /*MaskOffset*/ 8);
9179
9180   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
9181   // cross-half traffic in the final shuffle.
9182
9183   // Munge the mask to be a single-input mask after the unpack merges the
9184   // results.
9185   for (int &M : Mask)
9186     if (M != -1)
9187       M = 2 * (M % 4) + (M / 8);
9188
9189   return DAG.getVectorShuffle(
9190       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
9191                                   DL, MVT::v8i16, V1, V2),
9192       DAG.getUNDEF(MVT::v8i16), Mask);
9193 }
9194
9195 /// \brief Generic lowering of 8-lane i16 shuffles.
9196 ///
9197 /// This handles both single-input shuffles and combined shuffle/blends with
9198 /// two inputs. The single input shuffles are immediately delegated to
9199 /// a dedicated lowering routine.
9200 ///
9201 /// The blends are lowered in one of three fundamental ways. If there are few
9202 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9203 /// of the input is significantly cheaper when lowered as an interleaving of
9204 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9205 /// halves of the inputs separately (making them have relatively few inputs)
9206 /// and then concatenate them.
9207 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9208                                        const X86Subtarget *Subtarget,
9209                                        SelectionDAG &DAG) {
9210   SDLoc DL(Op);
9211   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9212   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9213   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9214   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9215   ArrayRef<int> OrigMask = SVOp->getMask();
9216   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9217                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9218   MutableArrayRef<int> Mask(MaskStorage);
9219
9220   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9221
9222   // Whenever we can lower this as a zext, that instruction is strictly faster
9223   // than any alternative.
9224   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9225           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9226     return ZExt;
9227
9228   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9229   auto isV2 = [](int M) { return M >= 8; };
9230
9231   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
9232   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9233
9234   if (NumV2Inputs == 0)
9235     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
9236
9237   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
9238                             "to be V1-input shuffles.");
9239
9240   // Try to use byte shift instructions.
9241   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9242           DL, MVT::v8i16, V1, V2, Mask, DAG))
9243     return Shift;
9244
9245   // There are special ways we can lower some single-element blends.
9246   if (NumV2Inputs == 1)
9247     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
9248                                                          Mask, Subtarget, DAG))
9249       return V;
9250
9251   // Use dedicated unpack instructions for masks that match their pattern.
9252   if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 2, 10, 3, 11))
9253     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9254   if (isShuffleEquivalent(Mask, 4, 12, 5, 13, 6, 14, 7, 15))
9255     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9256
9257   if (Subtarget->hasSSE41())
9258     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9259                                                   Subtarget, DAG))
9260       return Blend;
9261
9262   // Try to use byte rotation instructions.
9263   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9264           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9265     return Rotate;
9266
9267   if (NumV1Inputs + NumV2Inputs <= 4)
9268     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
9269
9270   // Check whether an interleaving lowering is likely to be more efficient.
9271   // This isn't perfect but it is a strong heuristic that tends to work well on
9272   // the kinds of shuffles that show up in practice.
9273   //
9274   // FIXME: Handle 1x, 2x, and 4x interleaving.
9275   if (shouldLowerAsInterleaving(Mask)) {
9276     // FIXME: Figure out whether we should pack these into the low or high
9277     // halves.
9278
9279     int EMask[8], OMask[8];
9280     for (int i = 0; i < 4; ++i) {
9281       EMask[i] = Mask[2*i];
9282       OMask[i] = Mask[2*i + 1];
9283       EMask[i + 4] = -1;
9284       OMask[i + 4] = -1;
9285     }
9286
9287     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
9288     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
9289
9290     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
9291   }
9292
9293   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9294   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9295
9296   for (int i = 0; i < 4; ++i) {
9297     LoBlendMask[i] = Mask[i];
9298     HiBlendMask[i] = Mask[i + 4];
9299   }
9300
9301   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9302   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9303   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
9304   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
9305
9306   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9307                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
9308 }
9309
9310 /// \brief Check whether a compaction lowering can be done by dropping even
9311 /// elements and compute how many times even elements must be dropped.
9312 ///
9313 /// This handles shuffles which take every Nth element where N is a power of
9314 /// two. Example shuffle masks:
9315 ///
9316 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9317 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9318 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9319 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9320 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9321 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9322 ///
9323 /// Any of these lanes can of course be undef.
9324 ///
9325 /// This routine only supports N <= 3.
9326 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9327 /// for larger N.
9328 ///
9329 /// \returns N above, or the number of times even elements must be dropped if
9330 /// there is such a number. Otherwise returns zero.
9331 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9332   // Figure out whether we're looping over two inputs or just one.
9333   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9334
9335   // The modulus for the shuffle vector entries is based on whether this is
9336   // a single input or not.
9337   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9338   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9339          "We should only be called with masks with a power-of-2 size!");
9340
9341   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9342
9343   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9344   // and 2^3 simultaneously. This is because we may have ambiguity with
9345   // partially undef inputs.
9346   bool ViableForN[3] = {true, true, true};
9347
9348   for (int i = 0, e = Mask.size(); i < e; ++i) {
9349     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9350     // want.
9351     if (Mask[i] == -1)
9352       continue;
9353
9354     bool IsAnyViable = false;
9355     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9356       if (ViableForN[j]) {
9357         uint64_t N = j + 1;
9358
9359         // The shuffle mask must be equal to (i * 2^N) % M.
9360         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9361           IsAnyViable = true;
9362         else
9363           ViableForN[j] = false;
9364       }
9365     // Early exit if we exhaust the possible powers of two.
9366     if (!IsAnyViable)
9367       break;
9368   }
9369
9370   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9371     if (ViableForN[j])
9372       return j + 1;
9373
9374   // Return 0 as there is no viable power of two.
9375   return 0;
9376 }
9377
9378 /// \brief Generic lowering of v16i8 shuffles.
9379 ///
9380 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9381 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9382 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9383 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9384 /// back together.
9385 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9386                                        const X86Subtarget *Subtarget,
9387                                        SelectionDAG &DAG) {
9388   SDLoc DL(Op);
9389   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9390   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9391   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9392   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9393   ArrayRef<int> OrigMask = SVOp->getMask();
9394   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9395
9396   // Try to use byte shift instructions.
9397   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9398           DL, MVT::v16i8, V1, V2, OrigMask, DAG))
9399     return Shift;
9400
9401   // Try to use byte rotation instructions.
9402   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9403           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9404     return Rotate;
9405
9406   // Try to use a zext lowering.
9407   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9408           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9409     return ZExt;
9410
9411   int MaskStorage[16] = {
9412       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
9413       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
9414       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
9415       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
9416   MutableArrayRef<int> Mask(MaskStorage);
9417   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
9418   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
9419
9420   int NumV2Elements =
9421       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9422
9423   // For single-input shuffles, there are some nicer lowering tricks we can use.
9424   if (NumV2Elements == 0) {
9425     // Check for being able to broadcast a single element.
9426     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i8, DL, V1,
9427                                                           Mask, Subtarget, DAG))
9428       return Broadcast;
9429
9430     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9431     // Notably, this handles splat and partial-splat shuffles more efficiently.
9432     // However, it only makes sense if the pre-duplication shuffle simplifies
9433     // things significantly. Currently, this means we need to be able to
9434     // express the pre-duplication shuffle as an i16 shuffle.
9435     //
9436     // FIXME: We should check for other patterns which can be widened into an
9437     // i16 shuffle as well.
9438     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9439       for (int i = 0; i < 16; i += 2)
9440         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9441           return false;
9442
9443       return true;
9444     };
9445     auto tryToWidenViaDuplication = [&]() -> SDValue {
9446       if (!canWidenViaDuplication(Mask))
9447         return SDValue();
9448       SmallVector<int, 4> LoInputs;
9449       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9450                    [](int M) { return M >= 0 && M < 8; });
9451       std::sort(LoInputs.begin(), LoInputs.end());
9452       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9453                      LoInputs.end());
9454       SmallVector<int, 4> HiInputs;
9455       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9456                    [](int M) { return M >= 8; });
9457       std::sort(HiInputs.begin(), HiInputs.end());
9458       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9459                      HiInputs.end());
9460
9461       bool TargetLo = LoInputs.size() >= HiInputs.size();
9462       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9463       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9464
9465       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9466       SmallDenseMap<int, int, 8> LaneMap;
9467       for (int I : InPlaceInputs) {
9468         PreDupI16Shuffle[I/2] = I/2;
9469         LaneMap[I] = I;
9470       }
9471       int j = TargetLo ? 0 : 4, je = j + 4;
9472       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9473         // Check if j is already a shuffle of this input. This happens when
9474         // there are two adjacent bytes after we move the low one.
9475         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9476           // If we haven't yet mapped the input, search for a slot into which
9477           // we can map it.
9478           while (j < je && PreDupI16Shuffle[j] != -1)
9479             ++j;
9480
9481           if (j == je)
9482             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9483             return SDValue();
9484
9485           // Map this input with the i16 shuffle.
9486           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9487         }
9488
9489         // Update the lane map based on the mapping we ended up with.
9490         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9491       }
9492       V1 = DAG.getNode(
9493           ISD::BITCAST, DL, MVT::v16i8,
9494           DAG.getVectorShuffle(MVT::v8i16, DL,
9495                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9496                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9497
9498       // Unpack the bytes to form the i16s that will be shuffled into place.
9499       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9500                        MVT::v16i8, V1, V1);
9501
9502       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9503       for (int i = 0; i < 16; ++i)
9504         if (Mask[i] != -1) {
9505           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9506           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9507           if (PostDupI16Shuffle[i / 2] == -1)
9508             PostDupI16Shuffle[i / 2] = MappedMask;
9509           else
9510             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9511                    "Conflicting entrties in the original shuffle!");
9512         }
9513       return DAG.getNode(
9514           ISD::BITCAST, DL, MVT::v16i8,
9515           DAG.getVectorShuffle(MVT::v8i16, DL,
9516                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9517                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9518     };
9519     if (SDValue V = tryToWidenViaDuplication())
9520       return V;
9521   }
9522
9523   // Check whether an interleaving lowering is likely to be more efficient.
9524   // This isn't perfect but it is a strong heuristic that tends to work well on
9525   // the kinds of shuffles that show up in practice.
9526   //
9527   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
9528   if (shouldLowerAsInterleaving(Mask)) {
9529     int NumLoHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9530       return (M >= 0 && M < 8) || (M >= 16 && M < 24);
9531     });
9532     int NumHiHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9533       return (M >= 8 && M < 16) || M >= 24;
9534     });
9535     int EMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9536                      -1, -1, -1, -1, -1, -1, -1, -1};
9537     int OMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9538                      -1, -1, -1, -1, -1, -1, -1, -1};
9539     bool UnpackLo = NumLoHalf >= NumHiHalf;
9540     MutableArrayRef<int> TargetEMask(UnpackLo ? EMask : EMask + 8, 8);
9541     MutableArrayRef<int> TargetOMask(UnpackLo ? OMask : OMask + 8, 8);
9542     for (int i = 0; i < 8; ++i) {
9543       TargetEMask[i] = Mask[2 * i];
9544       TargetOMask[i] = Mask[2 * i + 1];
9545     }
9546
9547     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
9548     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
9549
9550     return DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9551                        MVT::v16i8, Evens, Odds);
9552   }
9553
9554   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9555   // with PSHUFB. It is important to do this before we attempt to generate any
9556   // blends but after all of the single-input lowerings. If the single input
9557   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9558   // want to preserve that and we can DAG combine any longer sequences into
9559   // a PSHUFB in the end. But once we start blending from multiple inputs,
9560   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9561   // and there are *very* few patterns that would actually be faster than the
9562   // PSHUFB approach because of its ability to zero lanes.
9563   //
9564   // FIXME: The only exceptions to the above are blends which are exact
9565   // interleavings with direct instructions supporting them. We currently don't
9566   // handle those well here.
9567   if (Subtarget->hasSSSE3()) {
9568     SDValue V1Mask[16];
9569     SDValue V2Mask[16];
9570     for (int i = 0; i < 16; ++i)
9571       if (Mask[i] == -1) {
9572         V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9573       } else {
9574         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
9575         V2Mask[i] =
9576             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
9577       }
9578     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
9579                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9580     if (isSingleInputShuffleMask(Mask))
9581       return V1; // Single inputs are easy.
9582
9583     // Otherwise, blend the two.
9584     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
9585                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9586     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9587   }
9588
9589   // There are special ways we can lower some single-element blends.
9590   if (NumV2Elements == 1)
9591     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
9592                                                          Mask, Subtarget, DAG))
9593       return V;
9594
9595   // Check whether a compaction lowering can be done. This handles shuffles
9596   // which take every Nth element for some even N. See the helper function for
9597   // details.
9598   //
9599   // We special case these as they can be particularly efficiently handled with
9600   // the PACKUSB instruction on x86 and they show up in common patterns of
9601   // rearranging bytes to truncate wide elements.
9602   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9603     // NumEvenDrops is the power of two stride of the elements. Another way of
9604     // thinking about it is that we need to drop the even elements this many
9605     // times to get the original input.
9606     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9607
9608     // First we need to zero all the dropped bytes.
9609     assert(NumEvenDrops <= 3 &&
9610            "No support for dropping even elements more than 3 times.");
9611     // We use the mask type to pick which bytes are preserved based on how many
9612     // elements are dropped.
9613     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9614     SDValue ByteClearMask =
9615         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
9616                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
9617     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9618     if (!IsSingleInput)
9619       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9620
9621     // Now pack things back together.
9622     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
9623     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
9624     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9625     for (int i = 1; i < NumEvenDrops; ++i) {
9626       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
9627       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9628     }
9629
9630     return Result;
9631   }
9632
9633   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9634   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9635   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9636   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9637
9638   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
9639                             MutableArrayRef<int> V1HalfBlendMask,
9640                             MutableArrayRef<int> V2HalfBlendMask) {
9641     for (int i = 0; i < 8; ++i)
9642       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
9643         V1HalfBlendMask[i] = HalfMask[i];
9644         HalfMask[i] = i;
9645       } else if (HalfMask[i] >= 16) {
9646         V2HalfBlendMask[i] = HalfMask[i] - 16;
9647         HalfMask[i] = i + 8;
9648       }
9649   };
9650   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
9651   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
9652
9653   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9654
9655   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
9656                              MutableArrayRef<int> HiBlendMask) {
9657     SDValue V1, V2;
9658     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9659     // them out and avoid using UNPCK{L,H} to extract the elements of V as
9660     // i16s.
9661     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
9662                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
9663         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
9664                      [](int M) { return M >= 0 && M % 2 == 1; })) {
9665       // Use a mask to drop the high bytes.
9666       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
9667       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
9668                        DAG.getConstant(0x00FF, MVT::v8i16));
9669
9670       // This will be a single vector shuffle instead of a blend so nuke V2.
9671       V2 = DAG.getUNDEF(MVT::v8i16);
9672
9673       // Squash the masks to point directly into V1.
9674       for (int &M : LoBlendMask)
9675         if (M >= 0)
9676           M /= 2;
9677       for (int &M : HiBlendMask)
9678         if (M >= 0)
9679           M /= 2;
9680     } else {
9681       // Otherwise just unpack the low half of V into V1 and the high half into
9682       // V2 so that we can blend them as i16s.
9683       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9684                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9685       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9686                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9687     }
9688
9689     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9690     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9691     return std::make_pair(BlendedLo, BlendedHi);
9692   };
9693   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
9694   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
9695   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
9696
9697   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
9698   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
9699
9700   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9701 }
9702
9703 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9704 ///
9705 /// This routine breaks down the specific type of 128-bit shuffle and
9706 /// dispatches to the lowering routines accordingly.
9707 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9708                                         MVT VT, const X86Subtarget *Subtarget,
9709                                         SelectionDAG &DAG) {
9710   switch (VT.SimpleTy) {
9711   case MVT::v2i64:
9712     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9713   case MVT::v2f64:
9714     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9715   case MVT::v4i32:
9716     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9717   case MVT::v4f32:
9718     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9719   case MVT::v8i16:
9720     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9721   case MVT::v16i8:
9722     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9723
9724   default:
9725     llvm_unreachable("Unimplemented!");
9726   }
9727 }
9728
9729 /// \brief Helper function to test whether a shuffle mask could be
9730 /// simplified by widening the elements being shuffled.
9731 ///
9732 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9733 /// leaves it in an unspecified state.
9734 ///
9735 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9736 /// shuffle masks. The latter have the special property of a '-2' representing
9737 /// a zero-ed lane of a vector.
9738 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9739                                     SmallVectorImpl<int> &WidenedMask) {
9740   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9741     // If both elements are undef, its trivial.
9742     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9743       WidenedMask.push_back(SM_SentinelUndef);
9744       continue;
9745     }
9746
9747     // Check for an undef mask and a mask value properly aligned to fit with
9748     // a pair of values. If we find such a case, use the non-undef mask's value.
9749     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9750       WidenedMask.push_back(Mask[i + 1] / 2);
9751       continue;
9752     }
9753     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9754       WidenedMask.push_back(Mask[i] / 2);
9755       continue;
9756     }
9757
9758     // When zeroing, we need to spread the zeroing across both lanes to widen.
9759     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9760       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9761           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9762         WidenedMask.push_back(SM_SentinelZero);
9763         continue;
9764       }
9765       return false;
9766     }
9767
9768     // Finally check if the two mask values are adjacent and aligned with
9769     // a pair.
9770     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9771       WidenedMask.push_back(Mask[i] / 2);
9772       continue;
9773     }
9774
9775     // Otherwise we can't safely widen the elements used in this shuffle.
9776     return false;
9777   }
9778   assert(WidenedMask.size() == Mask.size() / 2 &&
9779          "Incorrect size of mask after widening the elements!");
9780
9781   return true;
9782 }
9783
9784 /// \brief Generic routine to split ector shuffle into half-sized shuffles.
9785 ///
9786 /// This routine just extracts two subvectors, shuffles them independently, and
9787 /// then concatenates them back together. This should work effectively with all
9788 /// AVX vector shuffle types.
9789 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9790                                           SDValue V2, ArrayRef<int> Mask,
9791                                           SelectionDAG &DAG) {
9792   assert(VT.getSizeInBits() >= 256 &&
9793          "Only for 256-bit or wider vector shuffles!");
9794   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9795   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9796
9797   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9798   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9799
9800   int NumElements = VT.getVectorNumElements();
9801   int SplitNumElements = NumElements / 2;
9802   MVT ScalarVT = VT.getScalarType();
9803   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9804
9805   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9806                              DAG.getIntPtrConstant(0));
9807   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9808                              DAG.getIntPtrConstant(SplitNumElements));
9809   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9810                              DAG.getIntPtrConstant(0));
9811   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9812                              DAG.getIntPtrConstant(SplitNumElements));
9813
9814   // Now create two 4-way blends of these half-width vectors.
9815   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9816     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9817     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9818     for (int i = 0; i < SplitNumElements; ++i) {
9819       int M = HalfMask[i];
9820       if (M >= NumElements) {
9821         if (M >= NumElements + SplitNumElements)
9822           UseHiV2 = true;
9823         else
9824           UseLoV2 = true;
9825         V2BlendMask.push_back(M - NumElements);
9826         V1BlendMask.push_back(-1);
9827         BlendMask.push_back(SplitNumElements + i);
9828       } else if (M >= 0) {
9829         if (M >= SplitNumElements)
9830           UseHiV1 = true;
9831         else
9832           UseLoV1 = true;
9833         V2BlendMask.push_back(-1);
9834         V1BlendMask.push_back(M);
9835         BlendMask.push_back(i);
9836       } else {
9837         V2BlendMask.push_back(-1);
9838         V1BlendMask.push_back(-1);
9839         BlendMask.push_back(-1);
9840       }
9841     }
9842
9843     // Because the lowering happens after all combining takes place, we need to
9844     // manually combine these blend masks as much as possible so that we create
9845     // a minimal number of high-level vector shuffle nodes.
9846
9847     // First try just blending the halves of V1 or V2.
9848     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9849       return DAG.getUNDEF(SplitVT);
9850     if (!UseLoV2 && !UseHiV2)
9851       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9852     if (!UseLoV1 && !UseHiV1)
9853       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9854
9855     SDValue V1Blend, V2Blend;
9856     if (UseLoV1 && UseHiV1) {
9857       V1Blend =
9858         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9859     } else {
9860       // We only use half of V1 so map the usage down into the final blend mask.
9861       V1Blend = UseLoV1 ? LoV1 : HiV1;
9862       for (int i = 0; i < SplitNumElements; ++i)
9863         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9864           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9865     }
9866     if (UseLoV2 && UseHiV2) {
9867       V2Blend =
9868         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9869     } else {
9870       // We only use half of V2 so map the usage down into the final blend mask.
9871       V2Blend = UseLoV2 ? LoV2 : HiV2;
9872       for (int i = 0; i < SplitNumElements; ++i)
9873         if (BlendMask[i] >= SplitNumElements)
9874           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9875     }
9876     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9877   };
9878   SDValue Lo = HalfBlend(LoMask);
9879   SDValue Hi = HalfBlend(HiMask);
9880   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9881 }
9882
9883 /// \brief Either split a vector in halves or decompose the shuffles and the
9884 /// blend.
9885 ///
9886 /// This is provided as a good fallback for many lowerings of non-single-input
9887 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9888 /// between splitting the shuffle into 128-bit components and stitching those
9889 /// back together vs. extracting the single-input shuffles and blending those
9890 /// results.
9891 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9892                                                 SDValue V2, ArrayRef<int> Mask,
9893                                                 SelectionDAG &DAG) {
9894   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9895                                             "lower single-input shuffles as it "
9896                                             "could then recurse on itself.");
9897   int Size = Mask.size();
9898
9899   // If this can be modeled as a broadcast of two elements followed by a blend,
9900   // prefer that lowering. This is especially important because broadcasts can
9901   // often fold with memory operands.
9902   auto DoBothBroadcast = [&] {
9903     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9904     for (int M : Mask)
9905       if (M >= Size) {
9906         if (V2BroadcastIdx == -1)
9907           V2BroadcastIdx = M - Size;
9908         else if (M - Size != V2BroadcastIdx)
9909           return false;
9910       } else if (M >= 0) {
9911         if (V1BroadcastIdx == -1)
9912           V1BroadcastIdx = M;
9913         else if (M != V1BroadcastIdx)
9914           return false;
9915       }
9916     return true;
9917   };
9918   if (DoBothBroadcast())
9919     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9920                                                       DAG);
9921
9922   // If the inputs all stem from a single 128-bit lane of each input, then we
9923   // split them rather than blending because the split will decompose to
9924   // unusually few instructions.
9925   int LaneCount = VT.getSizeInBits() / 128;
9926   int LaneSize = Size / LaneCount;
9927   SmallBitVector LaneInputs[2];
9928   LaneInputs[0].resize(LaneCount, false);
9929   LaneInputs[1].resize(LaneCount, false);
9930   for (int i = 0; i < Size; ++i)
9931     if (Mask[i] >= 0)
9932       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9933   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9934     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9935
9936   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9937   // that the decomposed single-input shuffles don't end up here.
9938   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9939 }
9940
9941 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9942 /// a permutation and blend of those lanes.
9943 ///
9944 /// This essentially blends the out-of-lane inputs to each lane into the lane
9945 /// from a permuted copy of the vector. This lowering strategy results in four
9946 /// instructions in the worst case for a single-input cross lane shuffle which
9947 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9948 /// of. Special cases for each particular shuffle pattern should be handled
9949 /// prior to trying this lowering.
9950 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9951                                                        SDValue V1, SDValue V2,
9952                                                        ArrayRef<int> Mask,
9953                                                        SelectionDAG &DAG) {
9954   // FIXME: This should probably be generalized for 512-bit vectors as well.
9955   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9956   int LaneSize = Mask.size() / 2;
9957
9958   // If there are only inputs from one 128-bit lane, splitting will in fact be
9959   // less expensive. The flags track wether the given lane contains an element
9960   // that crosses to another lane.
9961   bool LaneCrossing[2] = {false, false};
9962   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9963     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9964       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9965   if (!LaneCrossing[0] || !LaneCrossing[1])
9966     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9967
9968   if (isSingleInputShuffleMask(Mask)) {
9969     SmallVector<int, 32> FlippedBlendMask;
9970     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9971       FlippedBlendMask.push_back(
9972           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9973                                   ? Mask[i]
9974                                   : Mask[i] % LaneSize +
9975                                         (i / LaneSize) * LaneSize + Size));
9976
9977     // Flip the vector, and blend the results which should now be in-lane. The
9978     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9979     // 5 for the high source. The value 3 selects the high half of source 2 and
9980     // the value 2 selects the low half of source 2. We only use source 2 to
9981     // allow folding it into a memory operand.
9982     unsigned PERMMask = 3 | 2 << 4;
9983     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9984                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9985     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9986   }
9987
9988   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9989   // will be handled by the above logic and a blend of the results, much like
9990   // other patterns in AVX.
9991   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9992 }
9993
9994 /// \brief Handle lowering 2-lane 128-bit shuffles.
9995 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9996                                         SDValue V2, ArrayRef<int> Mask,
9997                                         const X86Subtarget *Subtarget,
9998                                         SelectionDAG &DAG) {
9999   // Blends are faster and handle all the non-lane-crossing cases.
10000   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10001                                                 Subtarget, DAG))
10002     return Blend;
10003
10004   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10005                                VT.getVectorNumElements() / 2);
10006   // Check for patterns which can be matched with a single insert of a 128-bit
10007   // subvector.
10008   if (isShuffleEquivalent(Mask, 0, 1, 0, 1) ||
10009       isShuffleEquivalent(Mask, 0, 1, 4, 5)) {
10010     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10011                               DAG.getIntPtrConstant(0));
10012     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10013                               Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
10014     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10015   }
10016   if (isShuffleEquivalent(Mask, 0, 1, 6, 7)) {
10017     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10018                               DAG.getIntPtrConstant(0));
10019     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
10020                               DAG.getIntPtrConstant(2));
10021     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10022   }
10023
10024   // Otherwise form a 128-bit permutation.
10025   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
10026   unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
10027   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10028                      DAG.getConstant(PermMask, MVT::i8));
10029 }
10030
10031 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10032 /// shuffling each lane.
10033 ///
10034 /// This will only succeed when the result of fixing the 128-bit lanes results
10035 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10036 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10037 /// the lane crosses early and then use simpler shuffles within each lane.
10038 ///
10039 /// FIXME: It might be worthwhile at some point to support this without
10040 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10041 /// in x86 only floating point has interesting non-repeating shuffles, and even
10042 /// those are still *marginally* more expensive.
10043 static SDValue lowerVectorShuffleByMerging128BitLanes(
10044     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10045     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10046   assert(!isSingleInputShuffleMask(Mask) &&
10047          "This is only useful with multiple inputs.");
10048
10049   int Size = Mask.size();
10050   int LaneSize = 128 / VT.getScalarSizeInBits();
10051   int NumLanes = Size / LaneSize;
10052   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10053
10054   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10055   // check whether the in-128-bit lane shuffles share a repeating pattern.
10056   SmallVector<int, 4> Lanes;
10057   Lanes.resize(NumLanes, -1);
10058   SmallVector<int, 4> InLaneMask;
10059   InLaneMask.resize(LaneSize, -1);
10060   for (int i = 0; i < Size; ++i) {
10061     if (Mask[i] < 0)
10062       continue;
10063
10064     int j = i / LaneSize;
10065
10066     if (Lanes[j] < 0) {
10067       // First entry we've seen for this lane.
10068       Lanes[j] = Mask[i] / LaneSize;
10069     } else if (Lanes[j] != Mask[i] / LaneSize) {
10070       // This doesn't match the lane selected previously!
10071       return SDValue();
10072     }
10073
10074     // Check that within each lane we have a consistent shuffle mask.
10075     int k = i % LaneSize;
10076     if (InLaneMask[k] < 0) {
10077       InLaneMask[k] = Mask[i] % LaneSize;
10078     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10079       // This doesn't fit a repeating in-lane mask.
10080       return SDValue();
10081     }
10082   }
10083
10084   // First shuffle the lanes into place.
10085   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10086                                 VT.getSizeInBits() / 64);
10087   SmallVector<int, 8> LaneMask;
10088   LaneMask.resize(NumLanes * 2, -1);
10089   for (int i = 0; i < NumLanes; ++i)
10090     if (Lanes[i] >= 0) {
10091       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10092       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10093     }
10094
10095   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
10096   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
10097   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10098
10099   // Cast it back to the type we actually want.
10100   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
10101
10102   // Now do a simple shuffle that isn't lane crossing.
10103   SmallVector<int, 8> NewMask;
10104   NewMask.resize(Size, -1);
10105   for (int i = 0; i < Size; ++i)
10106     if (Mask[i] >= 0)
10107       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10108   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10109          "Must not introduce lane crosses at this point!");
10110
10111   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10112 }
10113
10114 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10115 /// given mask.
10116 ///
10117 /// This returns true if the elements from a particular input are already in the
10118 /// slot required by the given mask and require no permutation.
10119 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10120   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10121   int Size = Mask.size();
10122   for (int i = 0; i < Size; ++i)
10123     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10124       return false;
10125
10126   return true;
10127 }
10128
10129 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10130 ///
10131 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10132 /// isn't available.
10133 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10134                                        const X86Subtarget *Subtarget,
10135                                        SelectionDAG &DAG) {
10136   SDLoc DL(Op);
10137   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10138   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10139   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10140   ArrayRef<int> Mask = SVOp->getMask();
10141   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10142
10143   SmallVector<int, 4> WidenedMask;
10144   if (canWidenShuffleElements(Mask, WidenedMask))
10145     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10146                                     DAG);
10147
10148   if (isSingleInputShuffleMask(Mask)) {
10149     // Check for being able to broadcast a single element.
10150     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f64, DL, V1,
10151                                                           Mask, Subtarget, DAG))
10152       return Broadcast;
10153
10154     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10155       // Non-half-crossing single input shuffles can be lowerid with an
10156       // interleaved permutation.
10157       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10158                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10159       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10160                          DAG.getConstant(VPERMILPMask, MVT::i8));
10161     }
10162
10163     // With AVX2 we have direct support for this permutation.
10164     if (Subtarget->hasAVX2())
10165       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10166                          getV4X86ShuffleImm8ForMask(Mask, DAG));
10167
10168     // Otherwise, fall back.
10169     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10170                                                    DAG);
10171   }
10172
10173   // X86 has dedicated unpack instructions that can handle specific blend
10174   // operations: UNPCKH and UNPCKL.
10175   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10176     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10177   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10178     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10179
10180   // If we have a single input to the zero element, insert that into V1 if we
10181   // can do so cheaply.
10182   int NumV2Elements =
10183       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
10184   if (NumV2Elements == 1 && Mask[0] >= 4)
10185     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10186             MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
10187       return Insertion;
10188
10189   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10190                                                 Subtarget, DAG))
10191     return Blend;
10192
10193   // Check if the blend happens to exactly fit that of SHUFPD.
10194   if ((Mask[0] == -1 || Mask[0] < 2) &&
10195       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
10196       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
10197       (Mask[3] == -1 || Mask[3] >= 6)) {
10198     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
10199                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
10200     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
10201                        DAG.getConstant(SHUFPDMask, MVT::i8));
10202   }
10203   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
10204       (Mask[1] == -1 || Mask[1] < 2) &&
10205       (Mask[2] == -1 || Mask[2] >= 6) &&
10206       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
10207     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
10208                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
10209     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
10210                        DAG.getConstant(SHUFPDMask, MVT::i8));
10211   }
10212
10213   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10214   // shuffle. However, if we have AVX2 and either inputs are already in place,
10215   // we will be able to shuffle even across lanes the other input in a single
10216   // instruction so skip this pattern.
10217   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10218                                  isShuffleMaskInputInPlace(1, Mask))))
10219     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10220             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10221       return Result;
10222
10223   // If we have AVX2 then we always want to lower with a blend because an v4 we
10224   // can fully permute the elements.
10225   if (Subtarget->hasAVX2())
10226     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10227                                                       Mask, DAG);
10228
10229   // Otherwise fall back on generic lowering.
10230   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10231 }
10232
10233 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10234 ///
10235 /// This routine is only called when we have AVX2 and thus a reasonable
10236 /// instruction set for v4i64 shuffling..
10237 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10238                                        const X86Subtarget *Subtarget,
10239                                        SelectionDAG &DAG) {
10240   SDLoc DL(Op);
10241   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10242   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10243   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10244   ArrayRef<int> Mask = SVOp->getMask();
10245   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10246   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10247
10248   SmallVector<int, 4> WidenedMask;
10249   if (canWidenShuffleElements(Mask, WidenedMask))
10250     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10251                                     DAG);
10252
10253   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10254                                                 Subtarget, DAG))
10255     return Blend;
10256
10257   // Check for being able to broadcast a single element.
10258   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i64, DL, V1,
10259                                                         Mask, Subtarget, DAG))
10260     return Broadcast;
10261
10262   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10263   // use lower latency instructions that will operate on both 128-bit lanes.
10264   SmallVector<int, 2> RepeatedMask;
10265   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10266     if (isSingleInputShuffleMask(Mask)) {
10267       int PSHUFDMask[] = {-1, -1, -1, -1};
10268       for (int i = 0; i < 2; ++i)
10269         if (RepeatedMask[i] >= 0) {
10270           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10271           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10272         }
10273       return DAG.getNode(
10274           ISD::BITCAST, DL, MVT::v4i64,
10275           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10276                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
10277                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
10278     }
10279
10280     // Use dedicated unpack instructions for masks that match their pattern.
10281     if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10282       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10283     if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10284       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10285   }
10286
10287   // AVX2 provides a direct instruction for permuting a single input across
10288   // lanes.
10289   if (isSingleInputShuffleMask(Mask))
10290     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10291                        getV4X86ShuffleImm8ForMask(Mask, DAG));
10292
10293   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10294   // shuffle. However, if we have AVX2 and either inputs are already in place,
10295   // we will be able to shuffle even across lanes the other input in a single
10296   // instruction so skip this pattern.
10297   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10298                                  isShuffleMaskInputInPlace(1, Mask))))
10299     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10300             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10301       return Result;
10302
10303   // Otherwise fall back on generic blend lowering.
10304   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10305                                                     Mask, DAG);
10306 }
10307
10308 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10309 ///
10310 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10311 /// isn't available.
10312 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10313                                        const X86Subtarget *Subtarget,
10314                                        SelectionDAG &DAG) {
10315   SDLoc DL(Op);
10316   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10317   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10318   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10319   ArrayRef<int> Mask = SVOp->getMask();
10320   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10321
10322   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10323                                                 Subtarget, DAG))
10324     return Blend;
10325
10326   // Check for being able to broadcast a single element.
10327   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8f32, DL, V1,
10328                                                         Mask, Subtarget, DAG))
10329     return Broadcast;
10330
10331   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10332   // options to efficiently lower the shuffle.
10333   SmallVector<int, 4> RepeatedMask;
10334   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10335     assert(RepeatedMask.size() == 4 &&
10336            "Repeated masks must be half the mask width!");
10337     if (isSingleInputShuffleMask(Mask))
10338       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10339                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10340
10341     // Use dedicated unpack instructions for masks that match their pattern.
10342     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10343       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10344     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10345       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10346
10347     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10348     // have already handled any direct blends. We also need to squash the
10349     // repeated mask into a simulated v4f32 mask.
10350     for (int i = 0; i < 4; ++i)
10351       if (RepeatedMask[i] >= 8)
10352         RepeatedMask[i] -= 4;
10353     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10354   }
10355
10356   // If we have a single input shuffle with different shuffle patterns in the
10357   // two 128-bit lanes use the variable mask to VPERMILPS.
10358   if (isSingleInputShuffleMask(Mask)) {
10359     SDValue VPermMask[8];
10360     for (int i = 0; i < 8; ++i)
10361       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10362                                  : DAG.getConstant(Mask[i], MVT::i32);
10363     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10364       return DAG.getNode(
10365           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10366           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10367
10368     if (Subtarget->hasAVX2())
10369       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
10370                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
10371                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
10372                                                  MVT::v8i32, VPermMask)),
10373                          V1);
10374
10375     // Otherwise, fall back.
10376     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10377                                                    DAG);
10378   }
10379
10380   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10381   // shuffle.
10382   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10383           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10384     return Result;
10385
10386   // If we have AVX2 then we always want to lower with a blend because at v8 we
10387   // can fully permute the elements.
10388   if (Subtarget->hasAVX2())
10389     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10390                                                       Mask, DAG);
10391
10392   // Otherwise fall back on generic lowering.
10393   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10394 }
10395
10396 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10397 ///
10398 /// This routine is only called when we have AVX2 and thus a reasonable
10399 /// instruction set for v8i32 shuffling..
10400 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10401                                        const X86Subtarget *Subtarget,
10402                                        SelectionDAG &DAG) {
10403   SDLoc DL(Op);
10404   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10405   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10406   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10407   ArrayRef<int> Mask = SVOp->getMask();
10408   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10409   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10410
10411   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10412                                                 Subtarget, DAG))
10413     return Blend;
10414
10415   // Check for being able to broadcast a single element.
10416   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i32, DL, V1,
10417                                                         Mask, Subtarget, DAG))
10418     return Broadcast;
10419
10420   // If the shuffle mask is repeated in each 128-bit lane we can use more
10421   // efficient instructions that mirror the shuffles across the two 128-bit
10422   // lanes.
10423   SmallVector<int, 4> RepeatedMask;
10424   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10425     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10426     if (isSingleInputShuffleMask(Mask))
10427       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10428                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10429
10430     // Use dedicated unpack instructions for masks that match their pattern.
10431     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10432       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10433     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10434       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10435   }
10436
10437   // If the shuffle patterns aren't repeated but it is a single input, directly
10438   // generate a cross-lane VPERMD instruction.
10439   if (isSingleInputShuffleMask(Mask)) {
10440     SDValue VPermMask[8];
10441     for (int i = 0; i < 8; ++i)
10442       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10443                                  : DAG.getConstant(Mask[i], MVT::i32);
10444     return DAG.getNode(
10445         X86ISD::VPERMV, DL, MVT::v8i32,
10446         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10447   }
10448
10449   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10450   // shuffle.
10451   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10452           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10453     return Result;
10454
10455   // Otherwise fall back on generic blend lowering.
10456   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10457                                                     Mask, DAG);
10458 }
10459
10460 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10461 ///
10462 /// This routine is only called when we have AVX2 and thus a reasonable
10463 /// instruction set for v16i16 shuffling..
10464 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10465                                         const X86Subtarget *Subtarget,
10466                                         SelectionDAG &DAG) {
10467   SDLoc DL(Op);
10468   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10469   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10470   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10471   ArrayRef<int> Mask = SVOp->getMask();
10472   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10473   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10474
10475   // Check for being able to broadcast a single element.
10476   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i16, DL, V1,
10477                                                         Mask, Subtarget, DAG))
10478     return Broadcast;
10479
10480   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10481                                                 Subtarget, DAG))
10482     return Blend;
10483
10484   // Use dedicated unpack instructions for masks that match their pattern.
10485   if (isShuffleEquivalent(Mask,
10486                           // First 128-bit lane:
10487                           0, 16, 1, 17, 2, 18, 3, 19,
10488                           // Second 128-bit lane:
10489                           8, 24, 9, 25, 10, 26, 11, 27))
10490     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10491   if (isShuffleEquivalent(Mask,
10492                           // First 128-bit lane:
10493                           4, 20, 5, 21, 6, 22, 7, 23,
10494                           // Second 128-bit lane:
10495                           12, 28, 13, 29, 14, 30, 15, 31))
10496     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10497
10498   if (isSingleInputShuffleMask(Mask)) {
10499     // There are no generalized cross-lane shuffle operations available on i16
10500     // element types.
10501     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10502       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10503                                                      Mask, DAG);
10504
10505     SDValue PSHUFBMask[32];
10506     for (int i = 0; i < 16; ++i) {
10507       if (Mask[i] == -1) {
10508         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10509         continue;
10510       }
10511
10512       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10513       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10514       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
10515       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
10516     }
10517     return DAG.getNode(
10518         ISD::BITCAST, DL, MVT::v16i16,
10519         DAG.getNode(
10520             X86ISD::PSHUFB, DL, MVT::v32i8,
10521             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
10522             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
10523   }
10524
10525   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10526   // shuffle.
10527   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10528           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10529     return Result;
10530
10531   // Otherwise fall back on generic lowering.
10532   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10533 }
10534
10535 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10536 ///
10537 /// This routine is only called when we have AVX2 and thus a reasonable
10538 /// instruction set for v32i8 shuffling..
10539 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10540                                        const X86Subtarget *Subtarget,
10541                                        SelectionDAG &DAG) {
10542   SDLoc DL(Op);
10543   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10544   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10545   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10546   ArrayRef<int> Mask = SVOp->getMask();
10547   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10548   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10549
10550   // Check for being able to broadcast a single element.
10551   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v32i8, DL, V1,
10552                                                         Mask, Subtarget, DAG))
10553     return Broadcast;
10554
10555   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10556                                                 Subtarget, DAG))
10557     return Blend;
10558
10559   // Use dedicated unpack instructions for masks that match their pattern.
10560   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10561   // 256-bit lanes.
10562   if (isShuffleEquivalent(
10563           Mask,
10564           // First 128-bit lane:
10565           0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10566           // Second 128-bit lane:
10567           16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55))
10568     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10569   if (isShuffleEquivalent(
10570           Mask,
10571           // First 128-bit lane:
10572           8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10573           // Second 128-bit lane:
10574           24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63))
10575     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10576
10577   if (isSingleInputShuffleMask(Mask)) {
10578     // There are no generalized cross-lane shuffle operations available on i8
10579     // element types.
10580     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10581       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10582                                                      Mask, DAG);
10583
10584     SDValue PSHUFBMask[32];
10585     for (int i = 0; i < 32; ++i)
10586       PSHUFBMask[i] =
10587           Mask[i] < 0
10588               ? DAG.getUNDEF(MVT::i8)
10589               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
10590
10591     return DAG.getNode(
10592         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10593         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10594   }
10595
10596   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10597   // shuffle.
10598   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10599           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10600     return Result;
10601
10602   // Otherwise fall back on generic lowering.
10603   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10604 }
10605
10606 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10607 ///
10608 /// This routine either breaks down the specific type of a 256-bit x86 vector
10609 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10610 /// together based on the available instructions.
10611 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10612                                         MVT VT, const X86Subtarget *Subtarget,
10613                                         SelectionDAG &DAG) {
10614   SDLoc DL(Op);
10615   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10616   ArrayRef<int> Mask = SVOp->getMask();
10617
10618   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10619   // check for those subtargets here and avoid much of the subtarget querying in
10620   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10621   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10622   // floating point types there eventually, just immediately cast everything to
10623   // a float and operate entirely in that domain.
10624   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10625     int ElementBits = VT.getScalarSizeInBits();
10626     if (ElementBits < 32)
10627       // No floating point type available, decompose into 128-bit vectors.
10628       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10629
10630     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10631                                 VT.getVectorNumElements());
10632     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10633     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10634     return DAG.getNode(ISD::BITCAST, DL, VT,
10635                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10636   }
10637
10638   switch (VT.SimpleTy) {
10639   case MVT::v4f64:
10640     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10641   case MVT::v4i64:
10642     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10643   case MVT::v8f32:
10644     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10645   case MVT::v8i32:
10646     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10647   case MVT::v16i16:
10648     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10649   case MVT::v32i8:
10650     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10651
10652   default:
10653     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10654   }
10655 }
10656
10657 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10658 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10659                                        const X86Subtarget *Subtarget,
10660                                        SelectionDAG &DAG) {
10661   SDLoc DL(Op);
10662   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10663   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10664   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10665   ArrayRef<int> Mask = SVOp->getMask();
10666   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10667
10668   // FIXME: Implement direct support for this type!
10669   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10670 }
10671
10672 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10673 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10674                                        const X86Subtarget *Subtarget,
10675                                        SelectionDAG &DAG) {
10676   SDLoc DL(Op);
10677   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10678   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10679   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10680   ArrayRef<int> Mask = SVOp->getMask();
10681   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10682
10683   // FIXME: Implement direct support for this type!
10684   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10685 }
10686
10687 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10688 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10689                                        const X86Subtarget *Subtarget,
10690                                        SelectionDAG &DAG) {
10691   SDLoc DL(Op);
10692   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10693   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10694   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10695   ArrayRef<int> Mask = SVOp->getMask();
10696   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10697
10698   // FIXME: Implement direct support for this type!
10699   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10700 }
10701
10702 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10703 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10704                                        const X86Subtarget *Subtarget,
10705                                        SelectionDAG &DAG) {
10706   SDLoc DL(Op);
10707   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10708   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10709   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10710   ArrayRef<int> Mask = SVOp->getMask();
10711   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10712
10713   // FIXME: Implement direct support for this type!
10714   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10715 }
10716
10717 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10718 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10719                                         const X86Subtarget *Subtarget,
10720                                         SelectionDAG &DAG) {
10721   SDLoc DL(Op);
10722   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10723   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10724   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10725   ArrayRef<int> Mask = SVOp->getMask();
10726   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10727   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10728
10729   // FIXME: Implement direct support for this type!
10730   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10731 }
10732
10733 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10734 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10735                                        const X86Subtarget *Subtarget,
10736                                        SelectionDAG &DAG) {
10737   SDLoc DL(Op);
10738   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10739   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10740   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10741   ArrayRef<int> Mask = SVOp->getMask();
10742   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10743   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10744
10745   // FIXME: Implement direct support for this type!
10746   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10747 }
10748
10749 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10750 ///
10751 /// This routine either breaks down the specific type of a 512-bit x86 vector
10752 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10753 /// together based on the available instructions.
10754 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10755                                         MVT VT, const X86Subtarget *Subtarget,
10756                                         SelectionDAG &DAG) {
10757   SDLoc DL(Op);
10758   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10759   ArrayRef<int> Mask = SVOp->getMask();
10760   assert(Subtarget->hasAVX512() &&
10761          "Cannot lower 512-bit vectors w/ basic ISA!");
10762
10763   // Check for being able to broadcast a single element.
10764   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(VT.SimpleTy, DL, V1,
10765                                                         Mask, Subtarget, DAG))
10766     return Broadcast;
10767
10768   // Dispatch to each element type for lowering. If we don't have supprot for
10769   // specific element type shuffles at 512 bits, immediately split them and
10770   // lower them. Each lowering routine of a given type is allowed to assume that
10771   // the requisite ISA extensions for that element type are available.
10772   switch (VT.SimpleTy) {
10773   case MVT::v8f64:
10774     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10775   case MVT::v16f32:
10776     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10777   case MVT::v8i64:
10778     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10779   case MVT::v16i32:
10780     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10781   case MVT::v32i16:
10782     if (Subtarget->hasBWI())
10783       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10784     break;
10785   case MVT::v64i8:
10786     if (Subtarget->hasBWI())
10787       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10788     break;
10789
10790   default:
10791     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10792   }
10793
10794   // Otherwise fall back on splitting.
10795   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10796 }
10797
10798 /// \brief Top-level lowering for x86 vector shuffles.
10799 ///
10800 /// This handles decomposition, canonicalization, and lowering of all x86
10801 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10802 /// above in helper routines. The canonicalization attempts to widen shuffles
10803 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10804 /// s.t. only one of the two inputs needs to be tested, etc.
10805 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10806                                   SelectionDAG &DAG) {
10807   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10808   ArrayRef<int> Mask = SVOp->getMask();
10809   SDValue V1 = Op.getOperand(0);
10810   SDValue V2 = Op.getOperand(1);
10811   MVT VT = Op.getSimpleValueType();
10812   int NumElements = VT.getVectorNumElements();
10813   SDLoc dl(Op);
10814
10815   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10816
10817   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10818   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10819   if (V1IsUndef && V2IsUndef)
10820     return DAG.getUNDEF(VT);
10821
10822   // When we create a shuffle node we put the UNDEF node to second operand,
10823   // but in some cases the first operand may be transformed to UNDEF.
10824   // In this case we should just commute the node.
10825   if (V1IsUndef)
10826     return DAG.getCommutedVectorShuffle(*SVOp);
10827
10828   // Check for non-undef masks pointing at an undef vector and make the masks
10829   // undef as well. This makes it easier to match the shuffle based solely on
10830   // the mask.
10831   if (V2IsUndef)
10832     for (int M : Mask)
10833       if (M >= NumElements) {
10834         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10835         for (int &M : NewMask)
10836           if (M >= NumElements)
10837             M = -1;
10838         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10839       }
10840
10841   // Try to collapse shuffles into using a vector type with fewer elements but
10842   // wider element types. We cap this to not form integers or floating point
10843   // elements wider than 64 bits, but it might be interesting to form i128
10844   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10845   SmallVector<int, 16> WidenedMask;
10846   if (VT.getScalarSizeInBits() < 64 &&
10847       canWidenShuffleElements(Mask, WidenedMask)) {
10848     MVT NewEltVT = VT.isFloatingPoint()
10849                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10850                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10851     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10852     // Make sure that the new vector type is legal. For example, v2f64 isn't
10853     // legal on SSE1.
10854     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10855       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10856       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10857       return DAG.getNode(ISD::BITCAST, dl, VT,
10858                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10859     }
10860   }
10861
10862   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10863   for (int M : SVOp->getMask())
10864     if (M < 0)
10865       ++NumUndefElements;
10866     else if (M < NumElements)
10867       ++NumV1Elements;
10868     else
10869       ++NumV2Elements;
10870
10871   // Commute the shuffle as needed such that more elements come from V1 than
10872   // V2. This allows us to match the shuffle pattern strictly on how many
10873   // elements come from V1 without handling the symmetric cases.
10874   if (NumV2Elements > NumV1Elements)
10875     return DAG.getCommutedVectorShuffle(*SVOp);
10876
10877   // When the number of V1 and V2 elements are the same, try to minimize the
10878   // number of uses of V2 in the low half of the vector. When that is tied,
10879   // ensure that the sum of indices for V1 is equal to or lower than the sum
10880   // indices for V2. When those are equal, try to ensure that the number of odd
10881   // indices for V1 is lower than the number of odd indices for V2.
10882   if (NumV1Elements == NumV2Elements) {
10883     int LowV1Elements = 0, LowV2Elements = 0;
10884     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10885       if (M >= NumElements)
10886         ++LowV2Elements;
10887       else if (M >= 0)
10888         ++LowV1Elements;
10889     if (LowV2Elements > LowV1Elements) {
10890       return DAG.getCommutedVectorShuffle(*SVOp);
10891     } else if (LowV2Elements == LowV1Elements) {
10892       int SumV1Indices = 0, SumV2Indices = 0;
10893       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10894         if (SVOp->getMask()[i] >= NumElements)
10895           SumV2Indices += i;
10896         else if (SVOp->getMask()[i] >= 0)
10897           SumV1Indices += i;
10898       if (SumV2Indices < SumV1Indices) {
10899         return DAG.getCommutedVectorShuffle(*SVOp);
10900       } else if (SumV2Indices == SumV1Indices) {
10901         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10902         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10903           if (SVOp->getMask()[i] >= NumElements)
10904             NumV2OddIndices += i % 2;
10905           else if (SVOp->getMask()[i] >= 0)
10906             NumV1OddIndices += i % 2;
10907         if (NumV2OddIndices < NumV1OddIndices)
10908           return DAG.getCommutedVectorShuffle(*SVOp);
10909       }
10910     }
10911   }
10912
10913   // For each vector width, delegate to a specialized lowering routine.
10914   if (VT.getSizeInBits() == 128)
10915     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10916
10917   if (VT.getSizeInBits() == 256)
10918     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10919
10920   // Force AVX-512 vectors to be scalarized for now.
10921   // FIXME: Implement AVX-512 support!
10922   if (VT.getSizeInBits() == 512)
10923     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10924
10925   llvm_unreachable("Unimplemented!");
10926 }
10927
10928
10929 //===----------------------------------------------------------------------===//
10930 // Legacy vector shuffle lowering
10931 //
10932 // This code is the legacy code handling vector shuffles until the above
10933 // replaces its functionality and performance.
10934 //===----------------------------------------------------------------------===//
10935
10936 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
10937                         bool hasInt256, unsigned *MaskOut = nullptr) {
10938   MVT EltVT = VT.getVectorElementType();
10939
10940   // There is no blend with immediate in AVX-512.
10941   if (VT.is512BitVector())
10942     return false;
10943
10944   if (!hasSSE41 || EltVT == MVT::i8)
10945     return false;
10946   if (!hasInt256 && VT == MVT::v16i16)
10947     return false;
10948
10949   unsigned MaskValue = 0;
10950   unsigned NumElems = VT.getVectorNumElements();
10951   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10952   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10953   unsigned NumElemsInLane = NumElems / NumLanes;
10954
10955   // Blend for v16i16 should be symetric for the both lanes.
10956   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10957
10958     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
10959     int EltIdx = MaskVals[i];
10960
10961     if ((EltIdx < 0 || EltIdx == (int)i) &&
10962         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
10963       continue;
10964
10965     if (((unsigned)EltIdx == (i + NumElems)) &&
10966         (SndLaneEltIdx < 0 ||
10967          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
10968       MaskValue |= (1 << i);
10969     else
10970       return false;
10971   }
10972
10973   if (MaskOut)
10974     *MaskOut = MaskValue;
10975   return true;
10976 }
10977
10978 // Try to lower a shuffle node into a simple blend instruction.
10979 // This function assumes isBlendMask returns true for this
10980 // SuffleVectorSDNode
10981 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
10982                                           unsigned MaskValue,
10983                                           const X86Subtarget *Subtarget,
10984                                           SelectionDAG &DAG) {
10985   MVT VT = SVOp->getSimpleValueType(0);
10986   MVT EltVT = VT.getVectorElementType();
10987   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
10988                      Subtarget->hasInt256() && "Trying to lower a "
10989                                                "VECTOR_SHUFFLE to a Blend but "
10990                                                "with the wrong mask"));
10991   SDValue V1 = SVOp->getOperand(0);
10992   SDValue V2 = SVOp->getOperand(1);
10993   SDLoc dl(SVOp);
10994   unsigned NumElems = VT.getVectorNumElements();
10995
10996   // Convert i32 vectors to floating point if it is not AVX2.
10997   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10998   MVT BlendVT = VT;
10999   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
11000     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
11001                                NumElems);
11002     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
11003     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
11004   }
11005
11006   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
11007                             DAG.getConstant(MaskValue, MVT::i32));
11008   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
11009 }
11010
11011 /// In vector type \p VT, return true if the element at index \p InputIdx
11012 /// falls on a different 128-bit lane than \p OutputIdx.
11013 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
11014                                      unsigned OutputIdx) {
11015   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
11016   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
11017 }
11018
11019 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
11020 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
11021 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
11022 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
11023 /// zero.
11024 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
11025                          SelectionDAG &DAG) {
11026   MVT VT = V1.getSimpleValueType();
11027   assert(VT.is128BitVector() || VT.is256BitVector());
11028
11029   MVT EltVT = VT.getVectorElementType();
11030   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
11031   unsigned NumElts = VT.getVectorNumElements();
11032
11033   SmallVector<SDValue, 32> PshufbMask;
11034   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
11035     int InputIdx = MaskVals[OutputIdx];
11036     unsigned InputByteIdx;
11037
11038     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
11039       InputByteIdx = 0x80;
11040     else {
11041       // Cross lane is not allowed.
11042       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
11043         return SDValue();
11044       InputByteIdx = InputIdx * EltSizeInBytes;
11045       // Index is an byte offset within the 128-bit lane.
11046       InputByteIdx &= 0xf;
11047     }
11048
11049     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
11050       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
11051       if (InputByteIdx != 0x80)
11052         ++InputByteIdx;
11053     }
11054   }
11055
11056   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
11057   if (ShufVT != VT)
11058     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
11059   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
11060                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
11061 }
11062
11063 // v8i16 shuffles - Prefer shuffles in the following order:
11064 // 1. [all]   pshuflw, pshufhw, optional move
11065 // 2. [ssse3] 1 x pshufb
11066 // 3. [ssse3] 2 x pshufb + 1 x por
11067 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
11068 static SDValue
11069 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
11070                          SelectionDAG &DAG) {
11071   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11072   SDValue V1 = SVOp->getOperand(0);
11073   SDValue V2 = SVOp->getOperand(1);
11074   SDLoc dl(SVOp);
11075   SmallVector<int, 8> MaskVals;
11076
11077   // Determine if more than 1 of the words in each of the low and high quadwords
11078   // of the result come from the same quadword of one of the two inputs.  Undef
11079   // mask values count as coming from any quadword, for better codegen.
11080   //
11081   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
11082   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
11083   unsigned LoQuad[] = { 0, 0, 0, 0 };
11084   unsigned HiQuad[] = { 0, 0, 0, 0 };
11085   // Indices of quads used.
11086   std::bitset<4> InputQuads;
11087   for (unsigned i = 0; i < 8; ++i) {
11088     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
11089     int EltIdx = SVOp->getMaskElt(i);
11090     MaskVals.push_back(EltIdx);
11091     if (EltIdx < 0) {
11092       ++Quad[0];
11093       ++Quad[1];
11094       ++Quad[2];
11095       ++Quad[3];
11096       continue;
11097     }
11098     ++Quad[EltIdx / 4];
11099     InputQuads.set(EltIdx / 4);
11100   }
11101
11102   int BestLoQuad = -1;
11103   unsigned MaxQuad = 1;
11104   for (unsigned i = 0; i < 4; ++i) {
11105     if (LoQuad[i] > MaxQuad) {
11106       BestLoQuad = i;
11107       MaxQuad = LoQuad[i];
11108     }
11109   }
11110
11111   int BestHiQuad = -1;
11112   MaxQuad = 1;
11113   for (unsigned i = 0; i < 4; ++i) {
11114     if (HiQuad[i] > MaxQuad) {
11115       BestHiQuad = i;
11116       MaxQuad = HiQuad[i];
11117     }
11118   }
11119
11120   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
11121   // of the two input vectors, shuffle them into one input vector so only a
11122   // single pshufb instruction is necessary. If there are more than 2 input
11123   // quads, disable the next transformation since it does not help SSSE3.
11124   bool V1Used = InputQuads[0] || InputQuads[1];
11125   bool V2Used = InputQuads[2] || InputQuads[3];
11126   if (Subtarget->hasSSSE3()) {
11127     if (InputQuads.count() == 2 && V1Used && V2Used) {
11128       BestLoQuad = InputQuads[0] ? 0 : 1;
11129       BestHiQuad = InputQuads[2] ? 2 : 3;
11130     }
11131     if (InputQuads.count() > 2) {
11132       BestLoQuad = -1;
11133       BestHiQuad = -1;
11134     }
11135   }
11136
11137   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
11138   // the shuffle mask.  If a quad is scored as -1, that means that it contains
11139   // words from all 4 input quadwords.
11140   SDValue NewV;
11141   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
11142     int MaskV[] = {
11143       BestLoQuad < 0 ? 0 : BestLoQuad,
11144       BestHiQuad < 0 ? 1 : BestHiQuad
11145     };
11146     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
11147                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
11148                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
11149     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
11150
11151     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
11152     // source words for the shuffle, to aid later transformations.
11153     bool AllWordsInNewV = true;
11154     bool InOrder[2] = { true, true };
11155     for (unsigned i = 0; i != 8; ++i) {
11156       int idx = MaskVals[i];
11157       if (idx != (int)i)
11158         InOrder[i/4] = false;
11159       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
11160         continue;
11161       AllWordsInNewV = false;
11162       break;
11163     }
11164
11165     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
11166     if (AllWordsInNewV) {
11167       for (int i = 0; i != 8; ++i) {
11168         int idx = MaskVals[i];
11169         if (idx < 0)
11170           continue;
11171         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
11172         if ((idx != i) && idx < 4)
11173           pshufhw = false;
11174         if ((idx != i) && idx > 3)
11175           pshuflw = false;
11176       }
11177       V1 = NewV;
11178       V2Used = false;
11179       BestLoQuad = 0;
11180       BestHiQuad = 1;
11181     }
11182
11183     // If we've eliminated the use of V2, and the new mask is a pshuflw or
11184     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
11185     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
11186       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
11187       unsigned TargetMask = 0;
11188       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
11189                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
11190       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11191       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
11192                              getShufflePSHUFLWImmediate(SVOp);
11193       V1 = NewV.getOperand(0);
11194       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
11195     }
11196   }
11197
11198   // Promote splats to a larger type which usually leads to more efficient code.
11199   // FIXME: Is this true if pshufb is available?
11200   if (SVOp->isSplat())
11201     return PromoteSplat(SVOp, DAG);
11202
11203   // If we have SSSE3, and all words of the result are from 1 input vector,
11204   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
11205   // is present, fall back to case 4.
11206   if (Subtarget->hasSSSE3()) {
11207     SmallVector<SDValue,16> pshufbMask;
11208
11209     // If we have elements from both input vectors, set the high bit of the
11210     // shuffle mask element to zero out elements that come from V2 in the V1
11211     // mask, and elements that come from V1 in the V2 mask, so that the two
11212     // results can be OR'd together.
11213     bool TwoInputs = V1Used && V2Used;
11214     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
11215     if (!TwoInputs)
11216       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11217
11218     // Calculate the shuffle mask for the second input, shuffle it, and
11219     // OR it with the first shuffled input.
11220     CommuteVectorShuffleMask(MaskVals, 8);
11221     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
11222     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11223     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11224   }
11225
11226   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
11227   // and update MaskVals with new element order.
11228   std::bitset<8> InOrder;
11229   if (BestLoQuad >= 0) {
11230     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
11231     for (int i = 0; i != 4; ++i) {
11232       int idx = MaskVals[i];
11233       if (idx < 0) {
11234         InOrder.set(i);
11235       } else if ((idx / 4) == BestLoQuad) {
11236         MaskV[i] = idx & 3;
11237         InOrder.set(i);
11238       }
11239     }
11240     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11241                                 &MaskV[0]);
11242
11243     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11244       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11245       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
11246                                   NewV.getOperand(0),
11247                                   getShufflePSHUFLWImmediate(SVOp), DAG);
11248     }
11249   }
11250
11251   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
11252   // and update MaskVals with the new element order.
11253   if (BestHiQuad >= 0) {
11254     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
11255     for (unsigned i = 4; i != 8; ++i) {
11256       int idx = MaskVals[i];
11257       if (idx < 0) {
11258         InOrder.set(i);
11259       } else if ((idx / 4) == BestHiQuad) {
11260         MaskV[i] = (idx & 3) + 4;
11261         InOrder.set(i);
11262       }
11263     }
11264     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11265                                 &MaskV[0]);
11266
11267     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11268       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11269       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
11270                                   NewV.getOperand(0),
11271                                   getShufflePSHUFHWImmediate(SVOp), DAG);
11272     }
11273   }
11274
11275   // In case BestHi & BestLo were both -1, which means each quadword has a word
11276   // from each of the four input quadwords, calculate the InOrder bitvector now
11277   // before falling through to the insert/extract cleanup.
11278   if (BestLoQuad == -1 && BestHiQuad == -1) {
11279     NewV = V1;
11280     for (int i = 0; i != 8; ++i)
11281       if (MaskVals[i] < 0 || MaskVals[i] == i)
11282         InOrder.set(i);
11283   }
11284
11285   // The other elements are put in the right place using pextrw and pinsrw.
11286   for (unsigned i = 0; i != 8; ++i) {
11287     if (InOrder[i])
11288       continue;
11289     int EltIdx = MaskVals[i];
11290     if (EltIdx < 0)
11291       continue;
11292     SDValue ExtOp = (EltIdx < 8) ?
11293       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
11294                   DAG.getIntPtrConstant(EltIdx)) :
11295       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
11296                   DAG.getIntPtrConstant(EltIdx - 8));
11297     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
11298                        DAG.getIntPtrConstant(i));
11299   }
11300   return NewV;
11301 }
11302
11303 /// \brief v16i16 shuffles
11304 ///
11305 /// FIXME: We only support generation of a single pshufb currently.  We can
11306 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
11307 /// well (e.g 2 x pshufb + 1 x por).
11308 static SDValue
11309 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
11310   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11311   SDValue V1 = SVOp->getOperand(0);
11312   SDValue V2 = SVOp->getOperand(1);
11313   SDLoc dl(SVOp);
11314
11315   if (V2.getOpcode() != ISD::UNDEF)
11316     return SDValue();
11317
11318   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11319   return getPSHUFB(MaskVals, V1, dl, DAG);
11320 }
11321
11322 // v16i8 shuffles - Prefer shuffles in the following order:
11323 // 1. [ssse3] 1 x pshufb
11324 // 2. [ssse3] 2 x pshufb + 1 x por
11325 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
11326 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
11327                                         const X86Subtarget* Subtarget,
11328                                         SelectionDAG &DAG) {
11329   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11330   SDValue V1 = SVOp->getOperand(0);
11331   SDValue V2 = SVOp->getOperand(1);
11332   SDLoc dl(SVOp);
11333   ArrayRef<int> MaskVals = SVOp->getMask();
11334
11335   // Promote splats to a larger type which usually leads to more efficient code.
11336   // FIXME: Is this true if pshufb is available?
11337   if (SVOp->isSplat())
11338     return PromoteSplat(SVOp, DAG);
11339
11340   // If we have SSSE3, case 1 is generated when all result bytes come from
11341   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
11342   // present, fall back to case 3.
11343
11344   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
11345   if (Subtarget->hasSSSE3()) {
11346     SmallVector<SDValue,16> pshufbMask;
11347
11348     // If all result elements are from one input vector, then only translate
11349     // undef mask values to 0x80 (zero out result) in the pshufb mask.
11350     //
11351     // Otherwise, we have elements from both input vectors, and must zero out
11352     // elements that come from V2 in the first mask, and V1 in the second mask
11353     // so that we can OR them together.
11354     for (unsigned i = 0; i != 16; ++i) {
11355       int EltIdx = MaskVals[i];
11356       if (EltIdx < 0 || EltIdx >= 16)
11357         EltIdx = 0x80;
11358       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11359     }
11360     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
11361                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11362                                  MVT::v16i8, pshufbMask));
11363
11364     // As PSHUFB will zero elements with negative indices, it's safe to ignore
11365     // the 2nd operand if it's undefined or zero.
11366     if (V2.getOpcode() == ISD::UNDEF ||
11367         ISD::isBuildVectorAllZeros(V2.getNode()))
11368       return V1;
11369
11370     // Calculate the shuffle mask for the second input, shuffle it, and
11371     // OR it with the first shuffled input.
11372     pshufbMask.clear();
11373     for (unsigned i = 0; i != 16; ++i) {
11374       int EltIdx = MaskVals[i];
11375       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
11376       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11377     }
11378     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
11379                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11380                                  MVT::v16i8, pshufbMask));
11381     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11382   }
11383
11384   // No SSSE3 - Calculate in place words and then fix all out of place words
11385   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
11386   // the 16 different words that comprise the two doublequadword input vectors.
11387   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11388   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
11389   SDValue NewV = V1;
11390   for (int i = 0; i != 8; ++i) {
11391     int Elt0 = MaskVals[i*2];
11392     int Elt1 = MaskVals[i*2+1];
11393
11394     // This word of the result is all undef, skip it.
11395     if (Elt0 < 0 && Elt1 < 0)
11396       continue;
11397
11398     // This word of the result is already in the correct place, skip it.
11399     if ((Elt0 == i*2) && (Elt1 == i*2+1))
11400       continue;
11401
11402     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
11403     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
11404     SDValue InsElt;
11405
11406     // If Elt0 and Elt1 are defined, are consecutive, and can be load
11407     // using a single extract together, load it and store it.
11408     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
11409       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11410                            DAG.getIntPtrConstant(Elt1 / 2));
11411       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11412                         DAG.getIntPtrConstant(i));
11413       continue;
11414     }
11415
11416     // If Elt1 is defined, extract it from the appropriate source.  If the
11417     // source byte is not also odd, shift the extracted word left 8 bits
11418     // otherwise clear the bottom 8 bits if we need to do an or.
11419     if (Elt1 >= 0) {
11420       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11421                            DAG.getIntPtrConstant(Elt1 / 2));
11422       if ((Elt1 & 1) == 0)
11423         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
11424                              DAG.getConstant(8,
11425                                   TLI.getShiftAmountTy(InsElt.getValueType())));
11426       else if (Elt0 >= 0)
11427         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
11428                              DAG.getConstant(0xFF00, MVT::i16));
11429     }
11430     // If Elt0 is defined, extract it from the appropriate source.  If the
11431     // source byte is not also even, shift the extracted word right 8 bits. If
11432     // Elt1 was also defined, OR the extracted values together before
11433     // inserting them in the result.
11434     if (Elt0 >= 0) {
11435       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
11436                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
11437       if ((Elt0 & 1) != 0)
11438         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
11439                               DAG.getConstant(8,
11440                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
11441       else if (Elt1 >= 0)
11442         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
11443                              DAG.getConstant(0x00FF, MVT::i16));
11444       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
11445                          : InsElt0;
11446     }
11447     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11448                        DAG.getIntPtrConstant(i));
11449   }
11450   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
11451 }
11452
11453 // v32i8 shuffles - Translate to VPSHUFB if possible.
11454 static
11455 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
11456                                  const X86Subtarget *Subtarget,
11457                                  SelectionDAG &DAG) {
11458   MVT VT = SVOp->getSimpleValueType(0);
11459   SDValue V1 = SVOp->getOperand(0);
11460   SDValue V2 = SVOp->getOperand(1);
11461   SDLoc dl(SVOp);
11462   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11463
11464   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11465   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
11466   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
11467
11468   // VPSHUFB may be generated if
11469   // (1) one of input vector is undefined or zeroinitializer.
11470   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
11471   // And (2) the mask indexes don't cross the 128-bit lane.
11472   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
11473       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
11474     return SDValue();
11475
11476   if (V1IsAllZero && !V2IsAllZero) {
11477     CommuteVectorShuffleMask(MaskVals, 32);
11478     V1 = V2;
11479   }
11480   return getPSHUFB(MaskVals, V1, dl, DAG);
11481 }
11482
11483 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
11484 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
11485 /// done when every pair / quad of shuffle mask elements point to elements in
11486 /// the right sequence. e.g.
11487 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
11488 static
11489 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
11490                                  SelectionDAG &DAG) {
11491   MVT VT = SVOp->getSimpleValueType(0);
11492   SDLoc dl(SVOp);
11493   unsigned NumElems = VT.getVectorNumElements();
11494   MVT NewVT;
11495   unsigned Scale;
11496   switch (VT.SimpleTy) {
11497   default: llvm_unreachable("Unexpected!");
11498   case MVT::v2i64:
11499   case MVT::v2f64:
11500            return SDValue(SVOp, 0);
11501   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
11502   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
11503   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
11504   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
11505   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
11506   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
11507   }
11508
11509   SmallVector<int, 8> MaskVec;
11510   for (unsigned i = 0; i != NumElems; i += Scale) {
11511     int StartIdx = -1;
11512     for (unsigned j = 0; j != Scale; ++j) {
11513       int EltIdx = SVOp->getMaskElt(i+j);
11514       if (EltIdx < 0)
11515         continue;
11516       if (StartIdx < 0)
11517         StartIdx = (EltIdx / Scale);
11518       if (EltIdx != (int)(StartIdx*Scale + j))
11519         return SDValue();
11520     }
11521     MaskVec.push_back(StartIdx);
11522   }
11523
11524   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
11525   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
11526   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
11527 }
11528
11529 /// getVZextMovL - Return a zero-extending vector move low node.
11530 ///
11531 static SDValue getVZextMovL(MVT VT, MVT OpVT,
11532                             SDValue SrcOp, SelectionDAG &DAG,
11533                             const X86Subtarget *Subtarget, SDLoc dl) {
11534   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
11535     LoadSDNode *LD = nullptr;
11536     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
11537       LD = dyn_cast<LoadSDNode>(SrcOp);
11538     if (!LD) {
11539       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
11540       // instead.
11541       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
11542       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
11543           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11544           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
11545           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
11546         // PR2108
11547         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
11548         return DAG.getNode(ISD::BITCAST, dl, VT,
11549                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11550                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11551                                                    OpVT,
11552                                                    SrcOp.getOperand(0)
11553                                                           .getOperand(0))));
11554       }
11555     }
11556   }
11557
11558   return DAG.getNode(ISD::BITCAST, dl, VT,
11559                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11560                                  DAG.getNode(ISD::BITCAST, dl,
11561                                              OpVT, SrcOp)));
11562 }
11563
11564 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
11565 /// which could not be matched by any known target speficic shuffle
11566 static SDValue
11567 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11568
11569   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
11570   if (NewOp.getNode())
11571     return NewOp;
11572
11573   MVT VT = SVOp->getSimpleValueType(0);
11574
11575   unsigned NumElems = VT.getVectorNumElements();
11576   unsigned NumLaneElems = NumElems / 2;
11577
11578   SDLoc dl(SVOp);
11579   MVT EltVT = VT.getVectorElementType();
11580   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
11581   SDValue Output[2];
11582
11583   SmallVector<int, 16> Mask;
11584   for (unsigned l = 0; l < 2; ++l) {
11585     // Build a shuffle mask for the output, discovering on the fly which
11586     // input vectors to use as shuffle operands (recorded in InputUsed).
11587     // If building a suitable shuffle vector proves too hard, then bail
11588     // out with UseBuildVector set.
11589     bool UseBuildVector = false;
11590     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
11591     unsigned LaneStart = l * NumLaneElems;
11592     for (unsigned i = 0; i != NumLaneElems; ++i) {
11593       // The mask element.  This indexes into the input.
11594       int Idx = SVOp->getMaskElt(i+LaneStart);
11595       if (Idx < 0) {
11596         // the mask element does not index into any input vector.
11597         Mask.push_back(-1);
11598         continue;
11599       }
11600
11601       // The input vector this mask element indexes into.
11602       int Input = Idx / NumLaneElems;
11603
11604       // Turn the index into an offset from the start of the input vector.
11605       Idx -= Input * NumLaneElems;
11606
11607       // Find or create a shuffle vector operand to hold this input.
11608       unsigned OpNo;
11609       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
11610         if (InputUsed[OpNo] == Input)
11611           // This input vector is already an operand.
11612           break;
11613         if (InputUsed[OpNo] < 0) {
11614           // Create a new operand for this input vector.
11615           InputUsed[OpNo] = Input;
11616           break;
11617         }
11618       }
11619
11620       if (OpNo >= array_lengthof(InputUsed)) {
11621         // More than two input vectors used!  Give up on trying to create a
11622         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
11623         UseBuildVector = true;
11624         break;
11625       }
11626
11627       // Add the mask index for the new shuffle vector.
11628       Mask.push_back(Idx + OpNo * NumLaneElems);
11629     }
11630
11631     if (UseBuildVector) {
11632       SmallVector<SDValue, 16> SVOps;
11633       for (unsigned i = 0; i != NumLaneElems; ++i) {
11634         // The mask element.  This indexes into the input.
11635         int Idx = SVOp->getMaskElt(i+LaneStart);
11636         if (Idx < 0) {
11637           SVOps.push_back(DAG.getUNDEF(EltVT));
11638           continue;
11639         }
11640
11641         // The input vector this mask element indexes into.
11642         int Input = Idx / NumElems;
11643
11644         // Turn the index into an offset from the start of the input vector.
11645         Idx -= Input * NumElems;
11646
11647         // Extract the vector element by hand.
11648         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
11649                                     SVOp->getOperand(Input),
11650                                     DAG.getIntPtrConstant(Idx)));
11651       }
11652
11653       // Construct the output using a BUILD_VECTOR.
11654       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
11655     } else if (InputUsed[0] < 0) {
11656       // No input vectors were used! The result is undefined.
11657       Output[l] = DAG.getUNDEF(NVT);
11658     } else {
11659       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
11660                                         (InputUsed[0] % 2) * NumLaneElems,
11661                                         DAG, dl);
11662       // If only one input was used, use an undefined vector for the other.
11663       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
11664         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
11665                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
11666       // At least one input vector was used. Create a new shuffle vector.
11667       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
11668     }
11669
11670     Mask.clear();
11671   }
11672
11673   // Concatenate the result back
11674   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
11675 }
11676
11677 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
11678 /// 4 elements, and match them with several different shuffle types.
11679 static SDValue
11680 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11681   SDValue V1 = SVOp->getOperand(0);
11682   SDValue V2 = SVOp->getOperand(1);
11683   SDLoc dl(SVOp);
11684   MVT VT = SVOp->getSimpleValueType(0);
11685
11686   assert(VT.is128BitVector() && "Unsupported vector size");
11687
11688   std::pair<int, int> Locs[4];
11689   int Mask1[] = { -1, -1, -1, -1 };
11690   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
11691
11692   unsigned NumHi = 0;
11693   unsigned NumLo = 0;
11694   for (unsigned i = 0; i != 4; ++i) {
11695     int Idx = PermMask[i];
11696     if (Idx < 0) {
11697       Locs[i] = std::make_pair(-1, -1);
11698     } else {
11699       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
11700       if (Idx < 4) {
11701         Locs[i] = std::make_pair(0, NumLo);
11702         Mask1[NumLo] = Idx;
11703         NumLo++;
11704       } else {
11705         Locs[i] = std::make_pair(1, NumHi);
11706         if (2+NumHi < 4)
11707           Mask1[2+NumHi] = Idx;
11708         NumHi++;
11709       }
11710     }
11711   }
11712
11713   if (NumLo <= 2 && NumHi <= 2) {
11714     // If no more than two elements come from either vector. This can be
11715     // implemented with two shuffles. First shuffle gather the elements.
11716     // The second shuffle, which takes the first shuffle as both of its
11717     // vector operands, put the elements into the right order.
11718     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11719
11720     int Mask2[] = { -1, -1, -1, -1 };
11721
11722     for (unsigned i = 0; i != 4; ++i)
11723       if (Locs[i].first != -1) {
11724         unsigned Idx = (i < 2) ? 0 : 4;
11725         Idx += Locs[i].first * 2 + Locs[i].second;
11726         Mask2[i] = Idx;
11727       }
11728
11729     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
11730   }
11731
11732   if (NumLo == 3 || NumHi == 3) {
11733     // Otherwise, we must have three elements from one vector, call it X, and
11734     // one element from the other, call it Y.  First, use a shufps to build an
11735     // intermediate vector with the one element from Y and the element from X
11736     // that will be in the same half in the final destination (the indexes don't
11737     // matter). Then, use a shufps to build the final vector, taking the half
11738     // containing the element from Y from the intermediate, and the other half
11739     // from X.
11740     if (NumHi == 3) {
11741       // Normalize it so the 3 elements come from V1.
11742       CommuteVectorShuffleMask(PermMask, 4);
11743       std::swap(V1, V2);
11744     }
11745
11746     // Find the element from V2.
11747     unsigned HiIndex;
11748     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
11749       int Val = PermMask[HiIndex];
11750       if (Val < 0)
11751         continue;
11752       if (Val >= 4)
11753         break;
11754     }
11755
11756     Mask1[0] = PermMask[HiIndex];
11757     Mask1[1] = -1;
11758     Mask1[2] = PermMask[HiIndex^1];
11759     Mask1[3] = -1;
11760     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11761
11762     if (HiIndex >= 2) {
11763       Mask1[0] = PermMask[0];
11764       Mask1[1] = PermMask[1];
11765       Mask1[2] = HiIndex & 1 ? 6 : 4;
11766       Mask1[3] = HiIndex & 1 ? 4 : 6;
11767       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11768     }
11769
11770     Mask1[0] = HiIndex & 1 ? 2 : 0;
11771     Mask1[1] = HiIndex & 1 ? 0 : 2;
11772     Mask1[2] = PermMask[2];
11773     Mask1[3] = PermMask[3];
11774     if (Mask1[2] >= 0)
11775       Mask1[2] += 4;
11776     if (Mask1[3] >= 0)
11777       Mask1[3] += 4;
11778     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
11779   }
11780
11781   // Break it into (shuffle shuffle_hi, shuffle_lo).
11782   int LoMask[] = { -1, -1, -1, -1 };
11783   int HiMask[] = { -1, -1, -1, -1 };
11784
11785   int *MaskPtr = LoMask;
11786   unsigned MaskIdx = 0;
11787   unsigned LoIdx = 0;
11788   unsigned HiIdx = 2;
11789   for (unsigned i = 0; i != 4; ++i) {
11790     if (i == 2) {
11791       MaskPtr = HiMask;
11792       MaskIdx = 1;
11793       LoIdx = 0;
11794       HiIdx = 2;
11795     }
11796     int Idx = PermMask[i];
11797     if (Idx < 0) {
11798       Locs[i] = std::make_pair(-1, -1);
11799     } else if (Idx < 4) {
11800       Locs[i] = std::make_pair(MaskIdx, LoIdx);
11801       MaskPtr[LoIdx] = Idx;
11802       LoIdx++;
11803     } else {
11804       Locs[i] = std::make_pair(MaskIdx, HiIdx);
11805       MaskPtr[HiIdx] = Idx;
11806       HiIdx++;
11807     }
11808   }
11809
11810   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
11811   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
11812   int MaskOps[] = { -1, -1, -1, -1 };
11813   for (unsigned i = 0; i != 4; ++i)
11814     if (Locs[i].first != -1)
11815       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
11816   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
11817 }
11818
11819 static bool MayFoldVectorLoad(SDValue V) {
11820   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
11821     V = V.getOperand(0);
11822
11823   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
11824     V = V.getOperand(0);
11825   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
11826       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
11827     // BUILD_VECTOR (load), undef
11828     V = V.getOperand(0);
11829
11830   return MayFoldLoad(V);
11831 }
11832
11833 static
11834 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
11835   MVT VT = Op.getSimpleValueType();
11836
11837   // Canonizalize to v2f64.
11838   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
11839   return DAG.getNode(ISD::BITCAST, dl, VT,
11840                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
11841                                           V1, DAG));
11842 }
11843
11844 static
11845 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
11846                         bool HasSSE2) {
11847   SDValue V1 = Op.getOperand(0);
11848   SDValue V2 = Op.getOperand(1);
11849   MVT VT = Op.getSimpleValueType();
11850
11851   assert(VT != MVT::v2i64 && "unsupported shuffle type");
11852
11853   if (HasSSE2 && VT == MVT::v2f64)
11854     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
11855
11856   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
11857   return DAG.getNode(ISD::BITCAST, dl, VT,
11858                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
11859                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
11860                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
11861 }
11862
11863 static
11864 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
11865   SDValue V1 = Op.getOperand(0);
11866   SDValue V2 = Op.getOperand(1);
11867   MVT VT = Op.getSimpleValueType();
11868
11869   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
11870          "unsupported shuffle type");
11871
11872   if (V2.getOpcode() == ISD::UNDEF)
11873     V2 = V1;
11874
11875   // v4i32 or v4f32
11876   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
11877 }
11878
11879 static
11880 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
11881   SDValue V1 = Op.getOperand(0);
11882   SDValue V2 = Op.getOperand(1);
11883   MVT VT = Op.getSimpleValueType();
11884   unsigned NumElems = VT.getVectorNumElements();
11885
11886   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
11887   // operand of these instructions is only memory, so check if there's a
11888   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
11889   // same masks.
11890   bool CanFoldLoad = false;
11891
11892   // Trivial case, when V2 comes from a load.
11893   if (MayFoldVectorLoad(V2))
11894     CanFoldLoad = true;
11895
11896   // When V1 is a load, it can be folded later into a store in isel, example:
11897   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
11898   //    turns into:
11899   //  (MOVLPSmr addr:$src1, VR128:$src2)
11900   // So, recognize this potential and also use MOVLPS or MOVLPD
11901   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
11902     CanFoldLoad = true;
11903
11904   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11905   if (CanFoldLoad) {
11906     if (HasSSE2 && NumElems == 2)
11907       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
11908
11909     if (NumElems == 4)
11910       // If we don't care about the second element, proceed to use movss.
11911       if (SVOp->getMaskElt(1) != -1)
11912         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
11913   }
11914
11915   // movl and movlp will both match v2i64, but v2i64 is never matched by
11916   // movl earlier because we make it strict to avoid messing with the movlp load
11917   // folding logic (see the code above getMOVLP call). Match it here then,
11918   // this is horrible, but will stay like this until we move all shuffle
11919   // matching to x86 specific nodes. Note that for the 1st condition all
11920   // types are matched with movsd.
11921   if (HasSSE2) {
11922     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
11923     // as to remove this logic from here, as much as possible
11924     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
11925       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
11926     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
11927   }
11928
11929   assert(VT != MVT::v4i32 && "unsupported shuffle type");
11930
11931   // Invert the operand order and use SHUFPS to match it.
11932   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
11933                               getShuffleSHUFImmediate(SVOp), DAG);
11934 }
11935
11936 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
11937                                          SelectionDAG &DAG) {
11938   SDLoc dl(Load);
11939   MVT VT = Load->getSimpleValueType(0);
11940   MVT EVT = VT.getVectorElementType();
11941   SDValue Addr = Load->getOperand(1);
11942   SDValue NewAddr = DAG.getNode(
11943       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
11944       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
11945
11946   SDValue NewLoad =
11947       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
11948                   DAG.getMachineFunction().getMachineMemOperand(
11949                       Load->getMemOperand(), 0, EVT.getStoreSize()));
11950   return NewLoad;
11951 }
11952
11953 // It is only safe to call this function if isINSERTPSMask is true for
11954 // this shufflevector mask.
11955 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
11956                            SelectionDAG &DAG) {
11957   // Generate an insertps instruction when inserting an f32 from memory onto a
11958   // v4f32 or when copying a member from one v4f32 to another.
11959   // We also use it for transferring i32 from one register to another,
11960   // since it simply copies the same bits.
11961   // If we're transferring an i32 from memory to a specific element in a
11962   // register, we output a generic DAG that will match the PINSRD
11963   // instruction.
11964   MVT VT = SVOp->getSimpleValueType(0);
11965   MVT EVT = VT.getVectorElementType();
11966   SDValue V1 = SVOp->getOperand(0);
11967   SDValue V2 = SVOp->getOperand(1);
11968   auto Mask = SVOp->getMask();
11969   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
11970          "unsupported vector type for insertps/pinsrd");
11971
11972   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
11973   auto FromV2Predicate = [](const int &i) { return i >= 4; };
11974   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
11975
11976   SDValue From;
11977   SDValue To;
11978   unsigned DestIndex;
11979   if (FromV1 == 1) {
11980     From = V1;
11981     To = V2;
11982     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
11983                 Mask.begin();
11984
11985     // If we have 1 element from each vector, we have to check if we're
11986     // changing V1's element's place. If so, we're done. Otherwise, we
11987     // should assume we're changing V2's element's place and behave
11988     // accordingly.
11989     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
11990     assert(DestIndex <= INT32_MAX && "truncated destination index");
11991     if (FromV1 == FromV2 &&
11992         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
11993       From = V2;
11994       To = V1;
11995       DestIndex =
11996           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
11997     }
11998   } else {
11999     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
12000            "More than one element from V1 and from V2, or no elements from one "
12001            "of the vectors. This case should not have returned true from "
12002            "isINSERTPSMask");
12003     From = V2;
12004     To = V1;
12005     DestIndex =
12006         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
12007   }
12008
12009   // Get an index into the source vector in the range [0,4) (the mask is
12010   // in the range [0,8) because it can address V1 and V2)
12011   unsigned SrcIndex = Mask[DestIndex] % 4;
12012   if (MayFoldLoad(From)) {
12013     // Trivial case, when From comes from a load and is only used by the
12014     // shuffle. Make it use insertps from the vector that we need from that
12015     // load.
12016     SDValue NewLoad =
12017         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
12018     if (!NewLoad.getNode())
12019       return SDValue();
12020
12021     if (EVT == MVT::f32) {
12022       // Create this as a scalar to vector to match the instruction pattern.
12023       SDValue LoadScalarToVector =
12024           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
12025       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
12026       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
12027                          InsertpsMask);
12028     } else { // EVT == MVT::i32
12029       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
12030       // instruction, to match the PINSRD instruction, which loads an i32 to a
12031       // certain vector element.
12032       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
12033                          DAG.getConstant(DestIndex, MVT::i32));
12034     }
12035   }
12036
12037   // Vector-element-to-vector
12038   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
12039   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
12040 }
12041
12042 // Reduce a vector shuffle to zext.
12043 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
12044                                     SelectionDAG &DAG) {
12045   // PMOVZX is only available from SSE41.
12046   if (!Subtarget->hasSSE41())
12047     return SDValue();
12048
12049   MVT VT = Op.getSimpleValueType();
12050
12051   // Only AVX2 support 256-bit vector integer extending.
12052   if (!Subtarget->hasInt256() && VT.is256BitVector())
12053     return SDValue();
12054
12055   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12056   SDLoc DL(Op);
12057   SDValue V1 = Op.getOperand(0);
12058   SDValue V2 = Op.getOperand(1);
12059   unsigned NumElems = VT.getVectorNumElements();
12060
12061   // Extending is an unary operation and the element type of the source vector
12062   // won't be equal to or larger than i64.
12063   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
12064       VT.getVectorElementType() == MVT::i64)
12065     return SDValue();
12066
12067   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
12068   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
12069   while ((1U << Shift) < NumElems) {
12070     if (SVOp->getMaskElt(1U << Shift) == 1)
12071       break;
12072     Shift += 1;
12073     // The maximal ratio is 8, i.e. from i8 to i64.
12074     if (Shift > 3)
12075       return SDValue();
12076   }
12077
12078   // Check the shuffle mask.
12079   unsigned Mask = (1U << Shift) - 1;
12080   for (unsigned i = 0; i != NumElems; ++i) {
12081     int EltIdx = SVOp->getMaskElt(i);
12082     if ((i & Mask) != 0 && EltIdx != -1)
12083       return SDValue();
12084     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
12085       return SDValue();
12086   }
12087
12088   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
12089   MVT NeVT = MVT::getIntegerVT(NBits);
12090   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
12091
12092   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
12093     return SDValue();
12094
12095   return DAG.getNode(ISD::BITCAST, DL, VT,
12096                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
12097 }
12098
12099 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
12100                                       SelectionDAG &DAG) {
12101   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12102   MVT VT = Op.getSimpleValueType();
12103   SDLoc dl(Op);
12104   SDValue V1 = Op.getOperand(0);
12105   SDValue V2 = Op.getOperand(1);
12106
12107   if (isZeroShuffle(SVOp))
12108     return getZeroVector(VT, Subtarget, DAG, dl);
12109
12110   // Handle splat operations
12111   if (SVOp->isSplat()) {
12112     // Use vbroadcast whenever the splat comes from a foldable load
12113     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
12114     if (Broadcast.getNode())
12115       return Broadcast;
12116   }
12117
12118   // Check integer expanding shuffles.
12119   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
12120   if (NewOp.getNode())
12121     return NewOp;
12122
12123   // If the shuffle can be profitably rewritten as a narrower shuffle, then
12124   // do it!
12125   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
12126       VT == MVT::v32i8) {
12127     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12128     if (NewOp.getNode())
12129       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
12130   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
12131     // FIXME: Figure out a cleaner way to do this.
12132     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
12133       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12134       if (NewOp.getNode()) {
12135         MVT NewVT = NewOp.getSimpleValueType();
12136         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
12137                                NewVT, true, false))
12138           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
12139                               dl);
12140       }
12141     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
12142       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12143       if (NewOp.getNode()) {
12144         MVT NewVT = NewOp.getSimpleValueType();
12145         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
12146           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
12147                               dl);
12148       }
12149     }
12150   }
12151   return SDValue();
12152 }
12153
12154 SDValue
12155 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
12156   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12157   SDValue V1 = Op.getOperand(0);
12158   SDValue V2 = Op.getOperand(1);
12159   MVT VT = Op.getSimpleValueType();
12160   SDLoc dl(Op);
12161   unsigned NumElems = VT.getVectorNumElements();
12162   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
12163   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
12164   bool V1IsSplat = false;
12165   bool V2IsSplat = false;
12166   bool HasSSE2 = Subtarget->hasSSE2();
12167   bool HasFp256    = Subtarget->hasFp256();
12168   bool HasInt256   = Subtarget->hasInt256();
12169   MachineFunction &MF = DAG.getMachineFunction();
12170   bool OptForSize = MF.getFunction()->getAttributes().
12171     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
12172
12173   // Check if we should use the experimental vector shuffle lowering. If so,
12174   // delegate completely to that code path.
12175   if (ExperimentalVectorShuffleLowering)
12176     return lowerVectorShuffle(Op, Subtarget, DAG);
12177
12178   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
12179
12180   if (V1IsUndef && V2IsUndef)
12181     return DAG.getUNDEF(VT);
12182
12183   // When we create a shuffle node we put the UNDEF node to second operand,
12184   // but in some cases the first operand may be transformed to UNDEF.
12185   // In this case we should just commute the node.
12186   if (V1IsUndef)
12187     return DAG.getCommutedVectorShuffle(*SVOp);
12188
12189   // Vector shuffle lowering takes 3 steps:
12190   //
12191   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
12192   //    narrowing and commutation of operands should be handled.
12193   // 2) Matching of shuffles with known shuffle masks to x86 target specific
12194   //    shuffle nodes.
12195   // 3) Rewriting of unmatched masks into new generic shuffle operations,
12196   //    so the shuffle can be broken into other shuffles and the legalizer can
12197   //    try the lowering again.
12198   //
12199   // The general idea is that no vector_shuffle operation should be left to
12200   // be matched during isel, all of them must be converted to a target specific
12201   // node here.
12202
12203   // Normalize the input vectors. Here splats, zeroed vectors, profitable
12204   // narrowing and commutation of operands should be handled. The actual code
12205   // doesn't include all of those, work in progress...
12206   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
12207   if (NewOp.getNode())
12208     return NewOp;
12209
12210   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
12211
12212   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
12213   // unpckh_undef). Only use pshufd if speed is more important than size.
12214   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12215     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12216   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12217     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12218
12219   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
12220       V2IsUndef && MayFoldVectorLoad(V1))
12221     return getMOVDDup(Op, dl, V1, DAG);
12222
12223   if (isMOVHLPS_v_undef_Mask(M, VT))
12224     return getMOVHighToLow(Op, dl, DAG);
12225
12226   // Use to match splats
12227   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
12228       (VT == MVT::v2f64 || VT == MVT::v2i64))
12229     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12230
12231   if (isPSHUFDMask(M, VT)) {
12232     // The actual implementation will match the mask in the if above and then
12233     // during isel it can match several different instructions, not only pshufd
12234     // as its name says, sad but true, emulate the behavior for now...
12235     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
12236       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
12237
12238     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
12239
12240     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
12241       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
12242
12243     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
12244       return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1, TargetMask,
12245                                   DAG);
12246
12247     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
12248                                 TargetMask, DAG);
12249   }
12250
12251   if (isPALIGNRMask(M, VT, Subtarget))
12252     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
12253                                 getShufflePALIGNRImmediate(SVOp),
12254                                 DAG);
12255
12256   if (isVALIGNMask(M, VT, Subtarget))
12257     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
12258                                 getShuffleVALIGNImmediate(SVOp),
12259                                 DAG);
12260
12261   // Check if this can be converted into a logical shift.
12262   bool isLeft = false;
12263   unsigned ShAmt = 0;
12264   SDValue ShVal;
12265   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
12266   if (isShift && ShVal.hasOneUse()) {
12267     // If the shifted value has multiple uses, it may be cheaper to use
12268     // v_set0 + movlhps or movhlps, etc.
12269     MVT EltVT = VT.getVectorElementType();
12270     ShAmt *= EltVT.getSizeInBits();
12271     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12272   }
12273
12274   if (isMOVLMask(M, VT)) {
12275     if (ISD::isBuildVectorAllZeros(V1.getNode()))
12276       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
12277     if (!isMOVLPMask(M, VT)) {
12278       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
12279         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
12280
12281       if (VT == MVT::v4i32 || VT == MVT::v4f32)
12282         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
12283     }
12284   }
12285
12286   // FIXME: fold these into legal mask.
12287   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
12288     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
12289
12290   if (isMOVHLPSMask(M, VT))
12291     return getMOVHighToLow(Op, dl, DAG);
12292
12293   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
12294     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
12295
12296   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
12297     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
12298
12299   if (isMOVLPMask(M, VT))
12300     return getMOVLP(Op, dl, DAG, HasSSE2);
12301
12302   if (ShouldXformToMOVHLPS(M, VT) ||
12303       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
12304     return DAG.getCommutedVectorShuffle(*SVOp);
12305
12306   if (isShift) {
12307     // No better options. Use a vshldq / vsrldq.
12308     MVT EltVT = VT.getVectorElementType();
12309     ShAmt *= EltVT.getSizeInBits();
12310     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12311   }
12312
12313   bool Commuted = false;
12314   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
12315   // 1,1,1,1 -> v8i16 though.
12316   BitVector UndefElements;
12317   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
12318     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12319       V1IsSplat = true;
12320   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
12321     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12322       V2IsSplat = true;
12323
12324   // Canonicalize the splat or undef, if present, to be on the RHS.
12325   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
12326     CommuteVectorShuffleMask(M, NumElems);
12327     std::swap(V1, V2);
12328     std::swap(V1IsSplat, V2IsSplat);
12329     Commuted = true;
12330   }
12331
12332   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
12333     // Shuffling low element of v1 into undef, just return v1.
12334     if (V2IsUndef)
12335       return V1;
12336     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
12337     // the instruction selector will not match, so get a canonical MOVL with
12338     // swapped operands to undo the commute.
12339     return getMOVL(DAG, dl, VT, V2, V1);
12340   }
12341
12342   if (isUNPCKLMask(M, VT, HasInt256))
12343     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12344
12345   if (isUNPCKHMask(M, VT, HasInt256))
12346     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12347
12348   if (V2IsSplat) {
12349     // Normalize mask so all entries that point to V2 points to its first
12350     // element then try to match unpck{h|l} again. If match, return a
12351     // new vector_shuffle with the corrected mask.p
12352     SmallVector<int, 8> NewMask(M.begin(), M.end());
12353     NormalizeMask(NewMask, NumElems);
12354     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
12355       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12356     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
12357       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12358   }
12359
12360   if (Commuted) {
12361     // Commute is back and try unpck* again.
12362     // FIXME: this seems wrong.
12363     CommuteVectorShuffleMask(M, NumElems);
12364     std::swap(V1, V2);
12365     std::swap(V1IsSplat, V2IsSplat);
12366
12367     if (isUNPCKLMask(M, VT, HasInt256))
12368       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12369
12370     if (isUNPCKHMask(M, VT, HasInt256))
12371       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12372   }
12373
12374   // Normalize the node to match x86 shuffle ops if needed
12375   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
12376     return DAG.getCommutedVectorShuffle(*SVOp);
12377
12378   // The checks below are all present in isShuffleMaskLegal, but they are
12379   // inlined here right now to enable us to directly emit target specific
12380   // nodes, and remove one by one until they don't return Op anymore.
12381
12382   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
12383       SVOp->getSplatIndex() == 0 && V2IsUndef) {
12384     if (VT == MVT::v2f64 || VT == MVT::v2i64)
12385       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12386   }
12387
12388   if (isPSHUFHWMask(M, VT, HasInt256))
12389     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
12390                                 getShufflePSHUFHWImmediate(SVOp),
12391                                 DAG);
12392
12393   if (isPSHUFLWMask(M, VT, HasInt256))
12394     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
12395                                 getShufflePSHUFLWImmediate(SVOp),
12396                                 DAG);
12397
12398   unsigned MaskValue;
12399   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
12400                   &MaskValue))
12401     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
12402
12403   if (isSHUFPMask(M, VT))
12404     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
12405                                 getShuffleSHUFImmediate(SVOp), DAG);
12406
12407   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12408     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12409   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12410     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12411
12412   //===--------------------------------------------------------------------===//
12413   // Generate target specific nodes for 128 or 256-bit shuffles only
12414   // supported in the AVX instruction set.
12415   //
12416
12417   // Handle VMOVDDUPY permutations
12418   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
12419     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
12420
12421   // Handle VPERMILPS/D* permutations
12422   if (isVPERMILPMask(M, VT)) {
12423     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
12424       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
12425                                   getShuffleSHUFImmediate(SVOp), DAG);
12426     return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1,
12427                                 getShuffleSHUFImmediate(SVOp), DAG);
12428   }
12429
12430   unsigned Idx;
12431   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
12432     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
12433                               Idx*(NumElems/2), DAG, dl);
12434
12435   // Handle VPERM2F128/VPERM2I128 permutations
12436   if (isVPERM2X128Mask(M, VT, HasFp256))
12437     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
12438                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
12439
12440   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
12441     return getINSERTPS(SVOp, dl, DAG);
12442
12443   unsigned Imm8;
12444   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
12445     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
12446
12447   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
12448       VT.is512BitVector()) {
12449     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
12450     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
12451     SmallVector<SDValue, 16> permclMask;
12452     for (unsigned i = 0; i != NumElems; ++i) {
12453       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
12454     }
12455
12456     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
12457     if (V2IsUndef)
12458       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
12459       return DAG.getNode(X86ISD::VPERMV, dl, VT,
12460                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
12461     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
12462                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
12463   }
12464
12465   //===--------------------------------------------------------------------===//
12466   // Since no target specific shuffle was selected for this generic one,
12467   // lower it into other known shuffles. FIXME: this isn't true yet, but
12468   // this is the plan.
12469   //
12470
12471   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
12472   if (VT == MVT::v8i16) {
12473     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
12474     if (NewOp.getNode())
12475       return NewOp;
12476   }
12477
12478   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
12479     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
12480     if (NewOp.getNode())
12481       return NewOp;
12482   }
12483
12484   if (VT == MVT::v16i8) {
12485     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
12486     if (NewOp.getNode())
12487       return NewOp;
12488   }
12489
12490   if (VT == MVT::v32i8) {
12491     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
12492     if (NewOp.getNode())
12493       return NewOp;
12494   }
12495
12496   // Handle all 128-bit wide vectors with 4 elements, and match them with
12497   // several different shuffle types.
12498   if (NumElems == 4 && VT.is128BitVector())
12499     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
12500
12501   // Handle general 256-bit shuffles
12502   if (VT.is256BitVector())
12503     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
12504
12505   return SDValue();
12506 }
12507
12508 // This function assumes its argument is a BUILD_VECTOR of constants or
12509 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
12510 // true.
12511 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
12512                                     unsigned &MaskValue) {
12513   MaskValue = 0;
12514   unsigned NumElems = BuildVector->getNumOperands();
12515   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
12516   unsigned NumLanes = (NumElems - 1) / 8 + 1;
12517   unsigned NumElemsInLane = NumElems / NumLanes;
12518
12519   // Blend for v16i16 should be symetric for the both lanes.
12520   for (unsigned i = 0; i < NumElemsInLane; ++i) {
12521     SDValue EltCond = BuildVector->getOperand(i);
12522     SDValue SndLaneEltCond =
12523         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
12524
12525     int Lane1Cond = -1, Lane2Cond = -1;
12526     if (isa<ConstantSDNode>(EltCond))
12527       Lane1Cond = !isZero(EltCond);
12528     if (isa<ConstantSDNode>(SndLaneEltCond))
12529       Lane2Cond = !isZero(SndLaneEltCond);
12530
12531     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
12532       // Lane1Cond != 0, means we want the first argument.
12533       // Lane1Cond == 0, means we want the second argument.
12534       // The encoding of this argument is 0 for the first argument, 1
12535       // for the second. Therefore, invert the condition.
12536       MaskValue |= !Lane1Cond << i;
12537     else if (Lane1Cond < 0)
12538       MaskValue |= !Lane2Cond << i;
12539     else
12540       return false;
12541   }
12542   return true;
12543 }
12544
12545 /// \brief Try to lower a VSELECT instruction to an immediate-controlled blend
12546 /// instruction.
12547 static SDValue lowerVSELECTtoBLENDI(SDValue Op, const X86Subtarget *Subtarget,
12548                                     SelectionDAG &DAG) {
12549   SDValue Cond = Op.getOperand(0);
12550   SDValue LHS = Op.getOperand(1);
12551   SDValue RHS = Op.getOperand(2);
12552   SDLoc dl(Op);
12553   MVT VT = Op.getSimpleValueType();
12554   MVT EltVT = VT.getVectorElementType();
12555   unsigned NumElems = VT.getVectorNumElements();
12556
12557   // There is no blend with immediate in AVX-512.
12558   if (VT.is512BitVector())
12559     return SDValue();
12560
12561   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
12562     return SDValue();
12563   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
12564     return SDValue();
12565
12566   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
12567     return SDValue();
12568
12569   // Check the mask for BLEND and build the value.
12570   unsigned MaskValue = 0;
12571   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
12572     return SDValue();
12573
12574   // Convert i32 vectors to floating point if it is not AVX2.
12575   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
12576   MVT BlendVT = VT;
12577   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
12578     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
12579                                NumElems);
12580     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
12581     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
12582   }
12583
12584   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
12585                             DAG.getConstant(MaskValue, MVT::i32));
12586   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
12587 }
12588
12589 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
12590   // A vselect where all conditions and data are constants can be optimized into
12591   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
12592   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
12593       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
12594       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
12595     return SDValue();
12596
12597   SDValue BlendOp = lowerVSELECTtoBLENDI(Op, Subtarget, DAG);
12598   if (BlendOp.getNode())
12599     return BlendOp;
12600
12601   // Some types for vselect were previously set to Expand, not Legal or
12602   // Custom. Return an empty SDValue so we fall-through to Expand, after
12603   // the Custom lowering phase.
12604   MVT VT = Op.getSimpleValueType();
12605   switch (VT.SimpleTy) {
12606   default:
12607     break;
12608   case MVT::v8i16:
12609   case MVT::v16i16:
12610     if (Subtarget->hasBWI() && Subtarget->hasVLX())
12611       break;
12612     return SDValue();
12613   }
12614
12615   // We couldn't create a "Blend with immediate" node.
12616   // This node should still be legal, but we'll have to emit a blendv*
12617   // instruction.
12618   return Op;
12619 }
12620
12621 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
12622   MVT VT = Op.getSimpleValueType();
12623   SDLoc dl(Op);
12624
12625   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
12626     return SDValue();
12627
12628   if (VT.getSizeInBits() == 8) {
12629     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
12630                                   Op.getOperand(0), Op.getOperand(1));
12631     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12632                                   DAG.getValueType(VT));
12633     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12634   }
12635
12636   if (VT.getSizeInBits() == 16) {
12637     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12638     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
12639     if (Idx == 0)
12640       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12641                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12642                                      DAG.getNode(ISD::BITCAST, dl,
12643                                                  MVT::v4i32,
12644                                                  Op.getOperand(0)),
12645                                      Op.getOperand(1)));
12646     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
12647                                   Op.getOperand(0), Op.getOperand(1));
12648     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12649                                   DAG.getValueType(VT));
12650     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12651   }
12652
12653   if (VT == MVT::f32) {
12654     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
12655     // the result back to FR32 register. It's only worth matching if the
12656     // result has a single use which is a store or a bitcast to i32.  And in
12657     // the case of a store, it's not worth it if the index is a constant 0,
12658     // because a MOVSSmr can be used instead, which is smaller and faster.
12659     if (!Op.hasOneUse())
12660       return SDValue();
12661     SDNode *User = *Op.getNode()->use_begin();
12662     if ((User->getOpcode() != ISD::STORE ||
12663          (isa<ConstantSDNode>(Op.getOperand(1)) &&
12664           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
12665         (User->getOpcode() != ISD::BITCAST ||
12666          User->getValueType(0) != MVT::i32))
12667       return SDValue();
12668     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12669                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
12670                                               Op.getOperand(0)),
12671                                               Op.getOperand(1));
12672     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
12673   }
12674
12675   if (VT == MVT::i32 || VT == MVT::i64) {
12676     // ExtractPS/pextrq works with constant index.
12677     if (isa<ConstantSDNode>(Op.getOperand(1)))
12678       return Op;
12679   }
12680   return SDValue();
12681 }
12682
12683 /// Extract one bit from mask vector, like v16i1 or v8i1.
12684 /// AVX-512 feature.
12685 SDValue
12686 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
12687   SDValue Vec = Op.getOperand(0);
12688   SDLoc dl(Vec);
12689   MVT VecVT = Vec.getSimpleValueType();
12690   SDValue Idx = Op.getOperand(1);
12691   MVT EltVT = Op.getSimpleValueType();
12692
12693   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
12694
12695   // variable index can't be handled in mask registers,
12696   // extend vector to VR512
12697   if (!isa<ConstantSDNode>(Idx)) {
12698     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12699     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
12700     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
12701                               ExtVT.getVectorElementType(), Ext, Idx);
12702     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
12703   }
12704
12705   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12706   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12707   unsigned MaxSift = rc->getSize()*8 - 1;
12708   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
12709                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12710   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
12711                     DAG.getConstant(MaxSift, MVT::i8));
12712   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
12713                        DAG.getIntPtrConstant(0));
12714 }
12715
12716 SDValue
12717 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
12718                                            SelectionDAG &DAG) const {
12719   SDLoc dl(Op);
12720   SDValue Vec = Op.getOperand(0);
12721   MVT VecVT = Vec.getSimpleValueType();
12722   SDValue Idx = Op.getOperand(1);
12723
12724   if (Op.getSimpleValueType() == MVT::i1)
12725     return ExtractBitFromMaskVector(Op, DAG);
12726
12727   if (!isa<ConstantSDNode>(Idx)) {
12728     if (VecVT.is512BitVector() ||
12729         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
12730          VecVT.getVectorElementType().getSizeInBits() == 32)) {
12731
12732       MVT MaskEltVT =
12733         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
12734       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
12735                                     MaskEltVT.getSizeInBits());
12736
12737       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
12738       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
12739                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
12740                                 Idx, DAG.getConstant(0, getPointerTy()));
12741       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
12742       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
12743                         Perm, DAG.getConstant(0, getPointerTy()));
12744     }
12745     return SDValue();
12746   }
12747
12748   // If this is a 256-bit vector result, first extract the 128-bit vector and
12749   // then extract the element from the 128-bit vector.
12750   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
12751
12752     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12753     // Get the 128-bit vector.
12754     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
12755     MVT EltVT = VecVT.getVectorElementType();
12756
12757     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
12758
12759     //if (IdxVal >= NumElems/2)
12760     //  IdxVal -= NumElems/2;
12761     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
12762     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
12763                        DAG.getConstant(IdxVal, MVT::i32));
12764   }
12765
12766   assert(VecVT.is128BitVector() && "Unexpected vector length");
12767
12768   if (Subtarget->hasSSE41()) {
12769     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
12770     if (Res.getNode())
12771       return Res;
12772   }
12773
12774   MVT VT = Op.getSimpleValueType();
12775   // TODO: handle v16i8.
12776   if (VT.getSizeInBits() == 16) {
12777     SDValue Vec = Op.getOperand(0);
12778     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12779     if (Idx == 0)
12780       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12781                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12782                                      DAG.getNode(ISD::BITCAST, dl,
12783                                                  MVT::v4i32, Vec),
12784                                      Op.getOperand(1)));
12785     // Transform it so it match pextrw which produces a 32-bit result.
12786     MVT EltVT = MVT::i32;
12787     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
12788                                   Op.getOperand(0), Op.getOperand(1));
12789     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
12790                                   DAG.getValueType(VT));
12791     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12792   }
12793
12794   if (VT.getSizeInBits() == 32) {
12795     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12796     if (Idx == 0)
12797       return Op;
12798
12799     // SHUFPS the element to the lowest double word, then movss.
12800     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
12801     MVT VVT = Op.getOperand(0).getSimpleValueType();
12802     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12803                                        DAG.getUNDEF(VVT), Mask);
12804     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12805                        DAG.getIntPtrConstant(0));
12806   }
12807
12808   if (VT.getSizeInBits() == 64) {
12809     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
12810     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
12811     //        to match extract_elt for f64.
12812     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12813     if (Idx == 0)
12814       return Op;
12815
12816     // UNPCKHPD the element to the lowest double word, then movsd.
12817     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
12818     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
12819     int Mask[2] = { 1, -1 };
12820     MVT VVT = Op.getOperand(0).getSimpleValueType();
12821     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12822                                        DAG.getUNDEF(VVT), Mask);
12823     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12824                        DAG.getIntPtrConstant(0));
12825   }
12826
12827   return SDValue();
12828 }
12829
12830 /// Insert one bit to mask vector, like v16i1 or v8i1.
12831 /// AVX-512 feature.
12832 SDValue
12833 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
12834   SDLoc dl(Op);
12835   SDValue Vec = Op.getOperand(0);
12836   SDValue Elt = Op.getOperand(1);
12837   SDValue Idx = Op.getOperand(2);
12838   MVT VecVT = Vec.getSimpleValueType();
12839
12840   if (!isa<ConstantSDNode>(Idx)) {
12841     // Non constant index. Extend source and destination,
12842     // insert element and then truncate the result.
12843     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12844     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
12845     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
12846       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
12847       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
12848     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
12849   }
12850
12851   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12852   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
12853   if (Vec.getOpcode() == ISD::UNDEF)
12854     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12855                        DAG.getConstant(IdxVal, MVT::i8));
12856   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12857   unsigned MaxSift = rc->getSize()*8 - 1;
12858   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12859                     DAG.getConstant(MaxSift, MVT::i8));
12860   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
12861                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12862   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
12863 }
12864
12865 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12866                                                   SelectionDAG &DAG) const {
12867   MVT VT = Op.getSimpleValueType();
12868   MVT EltVT = VT.getVectorElementType();
12869
12870   if (EltVT == MVT::i1)
12871     return InsertBitToMaskVector(Op, DAG);
12872
12873   SDLoc dl(Op);
12874   SDValue N0 = Op.getOperand(0);
12875   SDValue N1 = Op.getOperand(1);
12876   SDValue N2 = Op.getOperand(2);
12877   if (!isa<ConstantSDNode>(N2))
12878     return SDValue();
12879   auto *N2C = cast<ConstantSDNode>(N2);
12880   unsigned IdxVal = N2C->getZExtValue();
12881
12882   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
12883   // into that, and then insert the subvector back into the result.
12884   if (VT.is256BitVector() || VT.is512BitVector()) {
12885     // Get the desired 128-bit vector half.
12886     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
12887
12888     // Insert the element into the desired half.
12889     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
12890     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
12891
12892     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
12893                     DAG.getConstant(IdxIn128, MVT::i32));
12894
12895     // Insert the changed part back to the 256-bit vector
12896     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
12897   }
12898   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
12899
12900   if (Subtarget->hasSSE41()) {
12901     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
12902       unsigned Opc;
12903       if (VT == MVT::v8i16) {
12904         Opc = X86ISD::PINSRW;
12905       } else {
12906         assert(VT == MVT::v16i8);
12907         Opc = X86ISD::PINSRB;
12908       }
12909
12910       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
12911       // argument.
12912       if (N1.getValueType() != MVT::i32)
12913         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12914       if (N2.getValueType() != MVT::i32)
12915         N2 = DAG.getIntPtrConstant(IdxVal);
12916       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
12917     }
12918
12919     if (EltVT == MVT::f32) {
12920       // Bits [7:6] of the constant are the source select.  This will always be
12921       //  zero here.  The DAG Combiner may combine an extract_elt index into
12922       //  these
12923       //  bits.  For example (insert (extract, 3), 2) could be matched by
12924       //  putting
12925       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
12926       // Bits [5:4] of the constant are the destination select.  This is the
12927       //  value of the incoming immediate.
12928       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
12929       //   combine either bitwise AND or insert of float 0.0 to set these bits.
12930       N2 = DAG.getIntPtrConstant(IdxVal << 4);
12931       // Create this as a scalar to vector..
12932       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
12933       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
12934     }
12935
12936     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
12937       // PINSR* works with constant index.
12938       return Op;
12939     }
12940   }
12941
12942   if (EltVT == MVT::i8)
12943     return SDValue();
12944
12945   if (EltVT.getSizeInBits() == 16) {
12946     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12947     // as its second argument.
12948     if (N1.getValueType() != MVT::i32)
12949       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12950     if (N2.getValueType() != MVT::i32)
12951       N2 = DAG.getIntPtrConstant(IdxVal);
12952     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12953   }
12954   return SDValue();
12955 }
12956
12957 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12958   SDLoc dl(Op);
12959   MVT OpVT = Op.getSimpleValueType();
12960
12961   // If this is a 256-bit vector result, first insert into a 128-bit
12962   // vector and then insert into the 256-bit vector.
12963   if (!OpVT.is128BitVector()) {
12964     // Insert into a 128-bit vector.
12965     unsigned SizeFactor = OpVT.getSizeInBits()/128;
12966     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12967                                  OpVT.getVectorNumElements() / SizeFactor);
12968
12969     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12970
12971     // Insert the 128-bit vector.
12972     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12973   }
12974
12975   if (OpVT == MVT::v1i64 &&
12976       Op.getOperand(0).getValueType() == MVT::i64)
12977     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12978
12979   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12980   assert(OpVT.is128BitVector() && "Expected an SSE type!");
12981   return DAG.getNode(ISD::BITCAST, dl, OpVT,
12982                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
12983 }
12984
12985 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
12986 // a simple subregister reference or explicit instructions to grab
12987 // upper bits of a vector.
12988 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12989                                       SelectionDAG &DAG) {
12990   SDLoc dl(Op);
12991   SDValue In =  Op.getOperand(0);
12992   SDValue Idx = Op.getOperand(1);
12993   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12994   MVT ResVT   = Op.getSimpleValueType();
12995   MVT InVT    = In.getSimpleValueType();
12996
12997   if (Subtarget->hasFp256()) {
12998     if (ResVT.is128BitVector() &&
12999         (InVT.is256BitVector() || InVT.is512BitVector()) &&
13000         isa<ConstantSDNode>(Idx)) {
13001       return Extract128BitVector(In, IdxVal, DAG, dl);
13002     }
13003     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
13004         isa<ConstantSDNode>(Idx)) {
13005       return Extract256BitVector(In, IdxVal, DAG, dl);
13006     }
13007   }
13008   return SDValue();
13009 }
13010
13011 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
13012 // simple superregister reference or explicit instructions to insert
13013 // the upper bits of a vector.
13014 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
13015                                      SelectionDAG &DAG) {
13016   if (Subtarget->hasFp256()) {
13017     SDLoc dl(Op.getNode());
13018     SDValue Vec = Op.getNode()->getOperand(0);
13019     SDValue SubVec = Op.getNode()->getOperand(1);
13020     SDValue Idx = Op.getNode()->getOperand(2);
13021
13022     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
13023          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
13024         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
13025         isa<ConstantSDNode>(Idx)) {
13026       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13027       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
13028     }
13029
13030     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
13031         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
13032         isa<ConstantSDNode>(Idx)) {
13033       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13034       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
13035     }
13036   }
13037   return SDValue();
13038 }
13039
13040 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
13041 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
13042 // one of the above mentioned nodes. It has to be wrapped because otherwise
13043 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
13044 // be used to form addressing mode. These wrapped nodes will be selected
13045 // into MOV32ri.
13046 SDValue
13047 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
13048   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
13049
13050   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13051   // global base reg.
13052   unsigned char OpFlag = 0;
13053   unsigned WrapperKind = X86ISD::Wrapper;
13054   CodeModel::Model M = DAG.getTarget().getCodeModel();
13055
13056   if (Subtarget->isPICStyleRIPRel() &&
13057       (M == CodeModel::Small || M == CodeModel::Kernel))
13058     WrapperKind = X86ISD::WrapperRIP;
13059   else if (Subtarget->isPICStyleGOT())
13060     OpFlag = X86II::MO_GOTOFF;
13061   else if (Subtarget->isPICStyleStubPIC())
13062     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13063
13064   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
13065                                              CP->getAlignment(),
13066                                              CP->getOffset(), OpFlag);
13067   SDLoc DL(CP);
13068   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13069   // With PIC, the address is actually $g + Offset.
13070   if (OpFlag) {
13071     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13072                          DAG.getNode(X86ISD::GlobalBaseReg,
13073                                      SDLoc(), getPointerTy()),
13074                          Result);
13075   }
13076
13077   return Result;
13078 }
13079
13080 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
13081   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
13082
13083   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13084   // global base reg.
13085   unsigned char OpFlag = 0;
13086   unsigned WrapperKind = X86ISD::Wrapper;
13087   CodeModel::Model M = DAG.getTarget().getCodeModel();
13088
13089   if (Subtarget->isPICStyleRIPRel() &&
13090       (M == CodeModel::Small || M == CodeModel::Kernel))
13091     WrapperKind = X86ISD::WrapperRIP;
13092   else if (Subtarget->isPICStyleGOT())
13093     OpFlag = X86II::MO_GOTOFF;
13094   else if (Subtarget->isPICStyleStubPIC())
13095     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13096
13097   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
13098                                           OpFlag);
13099   SDLoc DL(JT);
13100   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13101
13102   // With PIC, the address is actually $g + Offset.
13103   if (OpFlag)
13104     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13105                          DAG.getNode(X86ISD::GlobalBaseReg,
13106                                      SDLoc(), getPointerTy()),
13107                          Result);
13108
13109   return Result;
13110 }
13111
13112 SDValue
13113 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
13114   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13115
13116   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13117   // global base reg.
13118   unsigned char OpFlag = 0;
13119   unsigned WrapperKind = X86ISD::Wrapper;
13120   CodeModel::Model M = DAG.getTarget().getCodeModel();
13121
13122   if (Subtarget->isPICStyleRIPRel() &&
13123       (M == CodeModel::Small || M == CodeModel::Kernel)) {
13124     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
13125       OpFlag = X86II::MO_GOTPCREL;
13126     WrapperKind = X86ISD::WrapperRIP;
13127   } else if (Subtarget->isPICStyleGOT()) {
13128     OpFlag = X86II::MO_GOT;
13129   } else if (Subtarget->isPICStyleStubPIC()) {
13130     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
13131   } else if (Subtarget->isPICStyleStubNoDynamic()) {
13132     OpFlag = X86II::MO_DARWIN_NONLAZY;
13133   }
13134
13135   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
13136
13137   SDLoc DL(Op);
13138   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13139
13140   // With PIC, the address is actually $g + Offset.
13141   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
13142       !Subtarget->is64Bit()) {
13143     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13144                          DAG.getNode(X86ISD::GlobalBaseReg,
13145                                      SDLoc(), getPointerTy()),
13146                          Result);
13147   }
13148
13149   // For symbols that require a load from a stub to get the address, emit the
13150   // load.
13151   if (isGlobalStubReference(OpFlag))
13152     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
13153                          MachinePointerInfo::getGOT(), false, false, false, 0);
13154
13155   return Result;
13156 }
13157
13158 SDValue
13159 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
13160   // Create the TargetBlockAddressAddress node.
13161   unsigned char OpFlags =
13162     Subtarget->ClassifyBlockAddressReference();
13163   CodeModel::Model M = DAG.getTarget().getCodeModel();
13164   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
13165   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
13166   SDLoc dl(Op);
13167   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
13168                                              OpFlags);
13169
13170   if (Subtarget->isPICStyleRIPRel() &&
13171       (M == CodeModel::Small || M == CodeModel::Kernel))
13172     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13173   else
13174     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13175
13176   // With PIC, the address is actually $g + Offset.
13177   if (isGlobalRelativeToPICBase(OpFlags)) {
13178     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13179                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13180                          Result);
13181   }
13182
13183   return Result;
13184 }
13185
13186 SDValue
13187 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
13188                                       int64_t Offset, SelectionDAG &DAG) const {
13189   // Create the TargetGlobalAddress node, folding in the constant
13190   // offset if it is legal.
13191   unsigned char OpFlags =
13192       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
13193   CodeModel::Model M = DAG.getTarget().getCodeModel();
13194   SDValue Result;
13195   if (OpFlags == X86II::MO_NO_FLAG &&
13196       X86::isOffsetSuitableForCodeModel(Offset, M)) {
13197     // A direct static reference to a global.
13198     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
13199     Offset = 0;
13200   } else {
13201     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
13202   }
13203
13204   if (Subtarget->isPICStyleRIPRel() &&
13205       (M == CodeModel::Small || M == CodeModel::Kernel))
13206     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13207   else
13208     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13209
13210   // With PIC, the address is actually $g + Offset.
13211   if (isGlobalRelativeToPICBase(OpFlags)) {
13212     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13213                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13214                          Result);
13215   }
13216
13217   // For globals that require a load from a stub to get the address, emit the
13218   // load.
13219   if (isGlobalStubReference(OpFlags))
13220     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
13221                          MachinePointerInfo::getGOT(), false, false, false, 0);
13222
13223   // If there was a non-zero offset that we didn't fold, create an explicit
13224   // addition for it.
13225   if (Offset != 0)
13226     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
13227                          DAG.getConstant(Offset, getPointerTy()));
13228
13229   return Result;
13230 }
13231
13232 SDValue
13233 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
13234   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
13235   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
13236   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
13237 }
13238
13239 static SDValue
13240 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
13241            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
13242            unsigned char OperandFlags, bool LocalDynamic = false) {
13243   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13244   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13245   SDLoc dl(GA);
13246   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13247                                            GA->getValueType(0),
13248                                            GA->getOffset(),
13249                                            OperandFlags);
13250
13251   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
13252                                            : X86ISD::TLSADDR;
13253
13254   if (InFlag) {
13255     SDValue Ops[] = { Chain,  TGA, *InFlag };
13256     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13257   } else {
13258     SDValue Ops[]  = { Chain, TGA };
13259     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13260   }
13261
13262   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
13263   MFI->setAdjustsStack(true);
13264   MFI->setHasCalls(true);
13265
13266   SDValue Flag = Chain.getValue(1);
13267   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
13268 }
13269
13270 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
13271 static SDValue
13272 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13273                                 const EVT PtrVT) {
13274   SDValue InFlag;
13275   SDLoc dl(GA);  // ? function entry point might be better
13276   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13277                                    DAG.getNode(X86ISD::GlobalBaseReg,
13278                                                SDLoc(), PtrVT), InFlag);
13279   InFlag = Chain.getValue(1);
13280
13281   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
13282 }
13283
13284 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
13285 static SDValue
13286 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13287                                 const EVT PtrVT) {
13288   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
13289                     X86::RAX, X86II::MO_TLSGD);
13290 }
13291
13292 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
13293                                            SelectionDAG &DAG,
13294                                            const EVT PtrVT,
13295                                            bool is64Bit) {
13296   SDLoc dl(GA);
13297
13298   // Get the start address of the TLS block for this module.
13299   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
13300       .getInfo<X86MachineFunctionInfo>();
13301   MFI->incNumLocalDynamicTLSAccesses();
13302
13303   SDValue Base;
13304   if (is64Bit) {
13305     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
13306                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
13307   } else {
13308     SDValue InFlag;
13309     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13310         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
13311     InFlag = Chain.getValue(1);
13312     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
13313                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
13314   }
13315
13316   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
13317   // of Base.
13318
13319   // Build x@dtpoff.
13320   unsigned char OperandFlags = X86II::MO_DTPOFF;
13321   unsigned WrapperKind = X86ISD::Wrapper;
13322   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13323                                            GA->getValueType(0),
13324                                            GA->getOffset(), OperandFlags);
13325   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13326
13327   // Add x@dtpoff with the base.
13328   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
13329 }
13330
13331 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
13332 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13333                                    const EVT PtrVT, TLSModel::Model model,
13334                                    bool is64Bit, bool isPIC) {
13335   SDLoc dl(GA);
13336
13337   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
13338   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
13339                                                          is64Bit ? 257 : 256));
13340
13341   SDValue ThreadPointer =
13342       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
13343                   MachinePointerInfo(Ptr), false, false, false, 0);
13344
13345   unsigned char OperandFlags = 0;
13346   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
13347   // initialexec.
13348   unsigned WrapperKind = X86ISD::Wrapper;
13349   if (model == TLSModel::LocalExec) {
13350     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
13351   } else if (model == TLSModel::InitialExec) {
13352     if (is64Bit) {
13353       OperandFlags = X86II::MO_GOTTPOFF;
13354       WrapperKind = X86ISD::WrapperRIP;
13355     } else {
13356       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
13357     }
13358   } else {
13359     llvm_unreachable("Unexpected model");
13360   }
13361
13362   // emit "addl x@ntpoff,%eax" (local exec)
13363   // or "addl x@indntpoff,%eax" (initial exec)
13364   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
13365   SDValue TGA =
13366       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
13367                                  GA->getOffset(), OperandFlags);
13368   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13369
13370   if (model == TLSModel::InitialExec) {
13371     if (isPIC && !is64Bit) {
13372       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
13373                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
13374                            Offset);
13375     }
13376
13377     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
13378                          MachinePointerInfo::getGOT(), false, false, false, 0);
13379   }
13380
13381   // The address of the thread local variable is the add of the thread
13382   // pointer with the offset of the variable.
13383   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
13384 }
13385
13386 SDValue
13387 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
13388
13389   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
13390   const GlobalValue *GV = GA->getGlobal();
13391
13392   if (Subtarget->isTargetELF()) {
13393     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
13394
13395     switch (model) {
13396       case TLSModel::GeneralDynamic:
13397         if (Subtarget->is64Bit())
13398           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
13399         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
13400       case TLSModel::LocalDynamic:
13401         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
13402                                            Subtarget->is64Bit());
13403       case TLSModel::InitialExec:
13404       case TLSModel::LocalExec:
13405         return LowerToTLSExecModel(
13406             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
13407             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
13408     }
13409     llvm_unreachable("Unknown TLS model.");
13410   }
13411
13412   if (Subtarget->isTargetDarwin()) {
13413     // Darwin only has one model of TLS.  Lower to that.
13414     unsigned char OpFlag = 0;
13415     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
13416                            X86ISD::WrapperRIP : X86ISD::Wrapper;
13417
13418     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13419     // global base reg.
13420     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
13421                  !Subtarget->is64Bit();
13422     if (PIC32)
13423       OpFlag = X86II::MO_TLVP_PIC_BASE;
13424     else
13425       OpFlag = X86II::MO_TLVP;
13426     SDLoc DL(Op);
13427     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
13428                                                 GA->getValueType(0),
13429                                                 GA->getOffset(), OpFlag);
13430     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13431
13432     // With PIC32, the address is actually $g + Offset.
13433     if (PIC32)
13434       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13435                            DAG.getNode(X86ISD::GlobalBaseReg,
13436                                        SDLoc(), getPointerTy()),
13437                            Offset);
13438
13439     // Lowering the machine isd will make sure everything is in the right
13440     // location.
13441     SDValue Chain = DAG.getEntryNode();
13442     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13443     SDValue Args[] = { Chain, Offset };
13444     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
13445
13446     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
13447     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13448     MFI->setAdjustsStack(true);
13449
13450     // And our return value (tls address) is in the standard call return value
13451     // location.
13452     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13453     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
13454                               Chain.getValue(1));
13455   }
13456
13457   if (Subtarget->isTargetKnownWindowsMSVC() ||
13458       Subtarget->isTargetWindowsGNU()) {
13459     // Just use the implicit TLS architecture
13460     // Need to generate someting similar to:
13461     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
13462     //                                  ; from TEB
13463     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
13464     //   mov     rcx, qword [rdx+rcx*8]
13465     //   mov     eax, .tls$:tlsvar
13466     //   [rax+rcx] contains the address
13467     // Windows 64bit: gs:0x58
13468     // Windows 32bit: fs:__tls_array
13469
13470     SDLoc dl(GA);
13471     SDValue Chain = DAG.getEntryNode();
13472
13473     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
13474     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
13475     // use its literal value of 0x2C.
13476     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
13477                                         ? Type::getInt8PtrTy(*DAG.getContext(),
13478                                                              256)
13479                                         : Type::getInt32PtrTy(*DAG.getContext(),
13480                                                               257));
13481
13482     SDValue TlsArray =
13483         Subtarget->is64Bit()
13484             ? DAG.getIntPtrConstant(0x58)
13485             : (Subtarget->isTargetWindowsGNU()
13486                    ? DAG.getIntPtrConstant(0x2C)
13487                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
13488
13489     SDValue ThreadPointer =
13490         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
13491                     MachinePointerInfo(Ptr), false, false, false, 0);
13492
13493     // Load the _tls_index variable
13494     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
13495     if (Subtarget->is64Bit())
13496       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
13497                            IDX, MachinePointerInfo(), MVT::i32,
13498                            false, false, false, 0);
13499     else
13500       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
13501                         false, false, false, 0);
13502
13503     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
13504                                     getPointerTy());
13505     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
13506
13507     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
13508     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
13509                       false, false, false, 0);
13510
13511     // Get the offset of start of .tls section
13512     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13513                                              GA->getValueType(0),
13514                                              GA->getOffset(), X86II::MO_SECREL);
13515     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
13516
13517     // The address of the thread local variable is the add of the thread
13518     // pointer with the offset of the variable.
13519     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
13520   }
13521
13522   llvm_unreachable("TLS not implemented for this target.");
13523 }
13524
13525 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
13526 /// and take a 2 x i32 value to shift plus a shift amount.
13527 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
13528   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
13529   MVT VT = Op.getSimpleValueType();
13530   unsigned VTBits = VT.getSizeInBits();
13531   SDLoc dl(Op);
13532   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
13533   SDValue ShOpLo = Op.getOperand(0);
13534   SDValue ShOpHi = Op.getOperand(1);
13535   SDValue ShAmt  = Op.getOperand(2);
13536   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
13537   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
13538   // during isel.
13539   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13540                                   DAG.getConstant(VTBits - 1, MVT::i8));
13541   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
13542                                      DAG.getConstant(VTBits - 1, MVT::i8))
13543                        : DAG.getConstant(0, VT);
13544
13545   SDValue Tmp2, Tmp3;
13546   if (Op.getOpcode() == ISD::SHL_PARTS) {
13547     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
13548     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
13549   } else {
13550     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
13551     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
13552   }
13553
13554   // If the shift amount is larger or equal than the width of a part we can't
13555   // rely on the results of shld/shrd. Insert a test and select the appropriate
13556   // values for large shift amounts.
13557   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13558                                 DAG.getConstant(VTBits, MVT::i8));
13559   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13560                              AndNode, DAG.getConstant(0, MVT::i8));
13561
13562   SDValue Hi, Lo;
13563   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13564   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
13565   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
13566
13567   if (Op.getOpcode() == ISD::SHL_PARTS) {
13568     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13569     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13570   } else {
13571     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13572     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13573   }
13574
13575   SDValue Ops[2] = { Lo, Hi };
13576   return DAG.getMergeValues(Ops, dl);
13577 }
13578
13579 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
13580                                            SelectionDAG &DAG) const {
13581   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13582   SDLoc dl(Op);
13583
13584   if (SrcVT.isVector()) {
13585     if (SrcVT.getVectorElementType() == MVT::i1) {
13586       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
13587       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13588                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
13589                                      Op.getOperand(0)));
13590     }
13591     return SDValue();
13592   }
13593
13594   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
13595          "Unknown SINT_TO_FP to lower!");
13596
13597   // These are really Legal; return the operand so the caller accepts it as
13598   // Legal.
13599   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
13600     return Op;
13601   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
13602       Subtarget->is64Bit()) {
13603     return Op;
13604   }
13605
13606   unsigned Size = SrcVT.getSizeInBits()/8;
13607   MachineFunction &MF = DAG.getMachineFunction();
13608   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
13609   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13610   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13611                                StackSlot,
13612                                MachinePointerInfo::getFixedStack(SSFI),
13613                                false, false, 0);
13614   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
13615 }
13616
13617 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
13618                                      SDValue StackSlot,
13619                                      SelectionDAG &DAG) const {
13620   // Build the FILD
13621   SDLoc DL(Op);
13622   SDVTList Tys;
13623   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
13624   if (useSSE)
13625     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
13626   else
13627     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
13628
13629   unsigned ByteSize = SrcVT.getSizeInBits()/8;
13630
13631   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
13632   MachineMemOperand *MMO;
13633   if (FI) {
13634     int SSFI = FI->getIndex();
13635     MMO =
13636       DAG.getMachineFunction()
13637       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13638                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
13639   } else {
13640     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
13641     StackSlot = StackSlot.getOperand(1);
13642   }
13643   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
13644   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
13645                                            X86ISD::FILD, DL,
13646                                            Tys, Ops, SrcVT, MMO);
13647
13648   if (useSSE) {
13649     Chain = Result.getValue(1);
13650     SDValue InFlag = Result.getValue(2);
13651
13652     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
13653     // shouldn't be necessary except that RFP cannot be live across
13654     // multiple blocks. When stackifier is fixed, they can be uncoupled.
13655     MachineFunction &MF = DAG.getMachineFunction();
13656     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
13657     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
13658     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13659     Tys = DAG.getVTList(MVT::Other);
13660     SDValue Ops[] = {
13661       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
13662     };
13663     MachineMemOperand *MMO =
13664       DAG.getMachineFunction()
13665       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13666                             MachineMemOperand::MOStore, SSFISize, SSFISize);
13667
13668     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
13669                                     Ops, Op.getValueType(), MMO);
13670     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
13671                          MachinePointerInfo::getFixedStack(SSFI),
13672                          false, false, false, 0);
13673   }
13674
13675   return Result;
13676 }
13677
13678 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
13679 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
13680                                                SelectionDAG &DAG) const {
13681   // This algorithm is not obvious. Here it is what we're trying to output:
13682   /*
13683      movq       %rax,  %xmm0
13684      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
13685      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
13686      #ifdef __SSE3__
13687        haddpd   %xmm0, %xmm0
13688      #else
13689        pshufd   $0x4e, %xmm0, %xmm1
13690        addpd    %xmm1, %xmm0
13691      #endif
13692   */
13693
13694   SDLoc dl(Op);
13695   LLVMContext *Context = DAG.getContext();
13696
13697   // Build some magic constants.
13698   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
13699   Constant *C0 = ConstantDataVector::get(*Context, CV0);
13700   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
13701
13702   SmallVector<Constant*,2> CV1;
13703   CV1.push_back(
13704     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13705                                       APInt(64, 0x4330000000000000ULL))));
13706   CV1.push_back(
13707     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13708                                       APInt(64, 0x4530000000000000ULL))));
13709   Constant *C1 = ConstantVector::get(CV1);
13710   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
13711
13712   // Load the 64-bit value into an XMM register.
13713   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
13714                             Op.getOperand(0));
13715   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
13716                               MachinePointerInfo::getConstantPool(),
13717                               false, false, false, 16);
13718   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
13719                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
13720                               CLod0);
13721
13722   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
13723                               MachinePointerInfo::getConstantPool(),
13724                               false, false, false, 16);
13725   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
13726   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
13727   SDValue Result;
13728
13729   if (Subtarget->hasSSE3()) {
13730     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
13731     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
13732   } else {
13733     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
13734     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
13735                                            S2F, 0x4E, DAG);
13736     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
13737                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
13738                          Sub);
13739   }
13740
13741   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
13742                      DAG.getIntPtrConstant(0));
13743 }
13744
13745 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
13746 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
13747                                                SelectionDAG &DAG) const {
13748   SDLoc dl(Op);
13749   // FP constant to bias correct the final result.
13750   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13751                                    MVT::f64);
13752
13753   // Load the 32-bit value into an XMM register.
13754   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
13755                              Op.getOperand(0));
13756
13757   // Zero out the upper parts of the register.
13758   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
13759
13760   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13761                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
13762                      DAG.getIntPtrConstant(0));
13763
13764   // Or the load with the bias.
13765   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
13766                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13767                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13768                                                    MVT::v2f64, Load)),
13769                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13770                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13771                                                    MVT::v2f64, Bias)));
13772   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13773                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
13774                    DAG.getIntPtrConstant(0));
13775
13776   // Subtract the bias.
13777   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
13778
13779   // Handle final rounding.
13780   EVT DestVT = Op.getValueType();
13781
13782   if (DestVT.bitsLT(MVT::f64))
13783     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
13784                        DAG.getIntPtrConstant(0));
13785   if (DestVT.bitsGT(MVT::f64))
13786     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
13787
13788   // Handle final rounding.
13789   return Sub;
13790 }
13791
13792 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
13793                                      const X86Subtarget &Subtarget) {
13794   // The algorithm is the following:
13795   // #ifdef __SSE4_1__
13796   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13797   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13798   //                                 (uint4) 0x53000000, 0xaa);
13799   // #else
13800   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13801   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13802   // #endif
13803   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13804   //     return (float4) lo + fhi;
13805
13806   SDLoc DL(Op);
13807   SDValue V = Op->getOperand(0);
13808   EVT VecIntVT = V.getValueType();
13809   bool Is128 = VecIntVT == MVT::v4i32;
13810   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
13811   // If we convert to something else than the supported type, e.g., to v4f64,
13812   // abort early.
13813   if (VecFloatVT != Op->getValueType(0))
13814     return SDValue();
13815
13816   unsigned NumElts = VecIntVT.getVectorNumElements();
13817   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
13818          "Unsupported custom type");
13819   assert(NumElts <= 8 && "The size of the constant array must be fixed");
13820
13821   // In the #idef/#else code, we have in common:
13822   // - The vector of constants:
13823   // -- 0x4b000000
13824   // -- 0x53000000
13825   // - A shift:
13826   // -- v >> 16
13827
13828   // Create the splat vector for 0x4b000000.
13829   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
13830   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
13831                            CstLow, CstLow, CstLow, CstLow};
13832   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13833                                   makeArrayRef(&CstLowArray[0], NumElts));
13834   // Create the splat vector for 0x53000000.
13835   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
13836   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
13837                             CstHigh, CstHigh, CstHigh, CstHigh};
13838   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13839                                    makeArrayRef(&CstHighArray[0], NumElts));
13840
13841   // Create the right shift.
13842   SDValue CstShift = DAG.getConstant(16, MVT::i32);
13843   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
13844                              CstShift, CstShift, CstShift, CstShift};
13845   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13846                                     makeArrayRef(&CstShiftArray[0], NumElts));
13847   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
13848
13849   SDValue Low, High;
13850   if (Subtarget.hasSSE41()) {
13851     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
13852     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13853     SDValue VecCstLowBitcast =
13854         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
13855     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
13856     // Low will be bitcasted right away, so do not bother bitcasting back to its
13857     // original type.
13858     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
13859                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
13860     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13861     //                                 (uint4) 0x53000000, 0xaa);
13862     SDValue VecCstHighBitcast =
13863         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
13864     SDValue VecShiftBitcast =
13865         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
13866     // High will be bitcasted right away, so do not bother bitcasting back to
13867     // its original type.
13868     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
13869                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
13870   } else {
13871     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
13872     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13873                                      CstMask, CstMask, CstMask);
13874     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13875     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13876     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13877
13878     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13879     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13880   }
13881
13882   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13883   SDValue CstFAdd = DAG.getConstantFP(
13884       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
13885   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13886                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13887   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13888                                    makeArrayRef(&CstFAddArray[0], NumElts));
13889
13890   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13891   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
13892   SDValue FHigh =
13893       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13894   //     return (float4) lo + fhi;
13895   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
13896   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13897 }
13898
13899 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13900                                                SelectionDAG &DAG) const {
13901   SDValue N0 = Op.getOperand(0);
13902   MVT SVT = N0.getSimpleValueType();
13903   SDLoc dl(Op);
13904
13905   switch (SVT.SimpleTy) {
13906   default:
13907     llvm_unreachable("Custom UINT_TO_FP is not supported!");
13908   case MVT::v4i8:
13909   case MVT::v4i16:
13910   case MVT::v8i8:
13911   case MVT::v8i16: {
13912     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13913     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13914                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13915   }
13916   case MVT::v4i32:
13917   case MVT::v8i32:
13918     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13919   }
13920   llvm_unreachable(nullptr);
13921 }
13922
13923 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13924                                            SelectionDAG &DAG) const {
13925   SDValue N0 = Op.getOperand(0);
13926   SDLoc dl(Op);
13927
13928   if (Op.getValueType().isVector())
13929     return lowerUINT_TO_FP_vec(Op, DAG);
13930
13931   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13932   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13933   // the optimization here.
13934   if (DAG.SignBitIsZero(N0))
13935     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13936
13937   MVT SrcVT = N0.getSimpleValueType();
13938   MVT DstVT = Op.getSimpleValueType();
13939   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13940     return LowerUINT_TO_FP_i64(Op, DAG);
13941   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13942     return LowerUINT_TO_FP_i32(Op, DAG);
13943   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13944     return SDValue();
13945
13946   // Make a 64-bit buffer, and use it to build an FILD.
13947   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13948   if (SrcVT == MVT::i32) {
13949     SDValue WordOff = DAG.getConstant(4, getPointerTy());
13950     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
13951                                      getPointerTy(), StackSlot, WordOff);
13952     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13953                                   StackSlot, MachinePointerInfo(),
13954                                   false, false, 0);
13955     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
13956                                   OffsetSlot, MachinePointerInfo(),
13957                                   false, false, 0);
13958     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13959     return Fild;
13960   }
13961
13962   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13963   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13964                                StackSlot, MachinePointerInfo(),
13965                                false, false, 0);
13966   // For i64 source, we need to add the appropriate power of 2 if the input
13967   // was negative.  This is the same as the optimization in
13968   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13969   // we must be careful to do the computation in x87 extended precision, not
13970   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13971   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13972   MachineMemOperand *MMO =
13973     DAG.getMachineFunction()
13974     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13975                           MachineMemOperand::MOLoad, 8, 8);
13976
13977   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13978   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13979   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13980                                          MVT::i64, MMO);
13981
13982   APInt FF(32, 0x5F800000ULL);
13983
13984   // Check whether the sign bit is set.
13985   SDValue SignSet = DAG.getSetCC(dl,
13986                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
13987                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
13988                                  ISD::SETLT);
13989
13990   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13991   SDValue FudgePtr = DAG.getConstantPool(
13992                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
13993                                          getPointerTy());
13994
13995   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13996   SDValue Zero = DAG.getIntPtrConstant(0);
13997   SDValue Four = DAG.getIntPtrConstant(4);
13998   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13999                                Zero, Four);
14000   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
14001
14002   // Load the value out, extending it from f32 to f80.
14003   // FIXME: Avoid the extend by constructing the right constant pool?
14004   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
14005                                  FudgePtr, MachinePointerInfo::getConstantPool(),
14006                                  MVT::f32, false, false, false, 4);
14007   // Extend everything to 80 bits to force it to be done on x87.
14008   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
14009   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
14010 }
14011
14012 std::pair<SDValue,SDValue>
14013 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
14014                                     bool IsSigned, bool IsReplace) const {
14015   SDLoc DL(Op);
14016
14017   EVT DstTy = Op.getValueType();
14018
14019   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
14020     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
14021     DstTy = MVT::i64;
14022   }
14023
14024   assert(DstTy.getSimpleVT() <= MVT::i64 &&
14025          DstTy.getSimpleVT() >= MVT::i16 &&
14026          "Unknown FP_TO_INT to lower!");
14027
14028   // These are really Legal.
14029   if (DstTy == MVT::i32 &&
14030       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14031     return std::make_pair(SDValue(), SDValue());
14032   if (Subtarget->is64Bit() &&
14033       DstTy == MVT::i64 &&
14034       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14035     return std::make_pair(SDValue(), SDValue());
14036
14037   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
14038   // stack slot, or into the FTOL runtime function.
14039   MachineFunction &MF = DAG.getMachineFunction();
14040   unsigned MemSize = DstTy.getSizeInBits()/8;
14041   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14042   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14043
14044   unsigned Opc;
14045   if (!IsSigned && isIntegerTypeFTOL(DstTy))
14046     Opc = X86ISD::WIN_FTOL;
14047   else
14048     switch (DstTy.getSimpleVT().SimpleTy) {
14049     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
14050     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
14051     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
14052     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
14053     }
14054
14055   SDValue Chain = DAG.getEntryNode();
14056   SDValue Value = Op.getOperand(0);
14057   EVT TheVT = Op.getOperand(0).getValueType();
14058   // FIXME This causes a redundant load/store if the SSE-class value is already
14059   // in memory, such as if it is on the callstack.
14060   if (isScalarFPTypeInSSEReg(TheVT)) {
14061     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
14062     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
14063                          MachinePointerInfo::getFixedStack(SSFI),
14064                          false, false, 0);
14065     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
14066     SDValue Ops[] = {
14067       Chain, StackSlot, DAG.getValueType(TheVT)
14068     };
14069
14070     MachineMemOperand *MMO =
14071       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14072                               MachineMemOperand::MOLoad, MemSize, MemSize);
14073     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
14074     Chain = Value.getValue(1);
14075     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14076     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14077   }
14078
14079   MachineMemOperand *MMO =
14080     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14081                             MachineMemOperand::MOStore, MemSize, MemSize);
14082
14083   if (Opc != X86ISD::WIN_FTOL) {
14084     // Build the FP_TO_INT*_IN_MEM
14085     SDValue Ops[] = { Chain, Value, StackSlot };
14086     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
14087                                            Ops, DstTy, MMO);
14088     return std::make_pair(FIST, StackSlot);
14089   } else {
14090     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
14091       DAG.getVTList(MVT::Other, MVT::Glue),
14092       Chain, Value);
14093     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
14094       MVT::i32, ftol.getValue(1));
14095     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
14096       MVT::i32, eax.getValue(2));
14097     SDValue Ops[] = { eax, edx };
14098     SDValue pair = IsReplace
14099       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
14100       : DAG.getMergeValues(Ops, DL);
14101     return std::make_pair(pair, SDValue());
14102   }
14103 }
14104
14105 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
14106                               const X86Subtarget *Subtarget) {
14107   MVT VT = Op->getSimpleValueType(0);
14108   SDValue In = Op->getOperand(0);
14109   MVT InVT = In.getSimpleValueType();
14110   SDLoc dl(Op);
14111
14112   // Optimize vectors in AVX mode:
14113   //
14114   //   v8i16 -> v8i32
14115   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
14116   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
14117   //   Concat upper and lower parts.
14118   //
14119   //   v4i32 -> v4i64
14120   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
14121   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
14122   //   Concat upper and lower parts.
14123   //
14124
14125   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
14126       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
14127       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
14128     return SDValue();
14129
14130   if (Subtarget->hasInt256())
14131     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
14132
14133   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
14134   SDValue Undef = DAG.getUNDEF(InVT);
14135   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
14136   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14137   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14138
14139   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
14140                              VT.getVectorNumElements()/2);
14141
14142   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
14143   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
14144
14145   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14146 }
14147
14148 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
14149                                         SelectionDAG &DAG) {
14150   MVT VT = Op->getSimpleValueType(0);
14151   SDValue In = Op->getOperand(0);
14152   MVT InVT = In.getSimpleValueType();
14153   SDLoc DL(Op);
14154   unsigned int NumElts = VT.getVectorNumElements();
14155   if (NumElts != 8 && NumElts != 16)
14156     return SDValue();
14157
14158   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
14159     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
14160
14161   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
14162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14163   // Now we have only mask extension
14164   assert(InVT.getVectorElementType() == MVT::i1);
14165   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
14166   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14167   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
14168   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14169   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14170                            MachinePointerInfo::getConstantPool(),
14171                            false, false, false, Alignment);
14172
14173   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
14174   if (VT.is512BitVector())
14175     return Brcst;
14176   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
14177 }
14178
14179 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14180                                SelectionDAG &DAG) {
14181   if (Subtarget->hasFp256()) {
14182     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14183     if (Res.getNode())
14184       return Res;
14185   }
14186
14187   return SDValue();
14188 }
14189
14190 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14191                                 SelectionDAG &DAG) {
14192   SDLoc DL(Op);
14193   MVT VT = Op.getSimpleValueType();
14194   SDValue In = Op.getOperand(0);
14195   MVT SVT = In.getSimpleValueType();
14196
14197   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
14198     return LowerZERO_EXTEND_AVX512(Op, DAG);
14199
14200   if (Subtarget->hasFp256()) {
14201     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14202     if (Res.getNode())
14203       return Res;
14204   }
14205
14206   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
14207          VT.getVectorNumElements() != SVT.getVectorNumElements());
14208   return SDValue();
14209 }
14210
14211 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
14212   SDLoc DL(Op);
14213   MVT VT = Op.getSimpleValueType();
14214   SDValue In = Op.getOperand(0);
14215   MVT InVT = In.getSimpleValueType();
14216
14217   if (VT == MVT::i1) {
14218     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
14219            "Invalid scalar TRUNCATE operation");
14220     if (InVT.getSizeInBits() >= 32)
14221       return SDValue();
14222     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
14223     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
14224   }
14225   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
14226          "Invalid TRUNCATE operation");
14227
14228   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
14229     if (VT.getVectorElementType().getSizeInBits() >=8)
14230       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
14231
14232     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14233     unsigned NumElts = InVT.getVectorNumElements();
14234     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
14235     if (InVT.getSizeInBits() < 512) {
14236       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
14237       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
14238       InVT = ExtVT;
14239     }
14240
14241     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
14242     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14243     SDValue CP = DAG.getConstantPool(C, getPointerTy());
14244     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14245     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14246                            MachinePointerInfo::getConstantPool(),
14247                            false, false, false, Alignment);
14248     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
14249     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
14250     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
14251   }
14252
14253   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
14254     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
14255     if (Subtarget->hasInt256()) {
14256       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14257       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
14258       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
14259                                 ShufMask);
14260       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
14261                          DAG.getIntPtrConstant(0));
14262     }
14263
14264     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14265                                DAG.getIntPtrConstant(0));
14266     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14267                                DAG.getIntPtrConstant(2));
14268     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14269     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14270     static const int ShufMask[] = {0, 2, 4, 6};
14271     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
14272   }
14273
14274   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
14275     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
14276     if (Subtarget->hasInt256()) {
14277       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
14278
14279       SmallVector<SDValue,32> pshufbMask;
14280       for (unsigned i = 0; i < 2; ++i) {
14281         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14282         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14283         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14284         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14285         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14286         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14287         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14288         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14289         for (unsigned j = 0; j < 8; ++j)
14290           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14291       }
14292       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
14293       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
14294       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
14295
14296       static const int ShufMask[] = {0,  2,  -1,  -1};
14297       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
14298                                 &ShufMask[0]);
14299       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14300                        DAG.getIntPtrConstant(0));
14301       return DAG.getNode(ISD::BITCAST, DL, VT, In);
14302     }
14303
14304     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14305                                DAG.getIntPtrConstant(0));
14306
14307     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14308                                DAG.getIntPtrConstant(4));
14309
14310     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
14311     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
14312
14313     // The PSHUFB mask:
14314     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14315                                    -1, -1, -1, -1, -1, -1, -1, -1};
14316
14317     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14318     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
14319     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
14320
14321     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14322     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14323
14324     // The MOVLHPS Mask:
14325     static const int ShufMask2[] = {0, 1, 4, 5};
14326     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
14327     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
14328   }
14329
14330   // Handle truncation of V256 to V128 using shuffles.
14331   if (!VT.is128BitVector() || !InVT.is256BitVector())
14332     return SDValue();
14333
14334   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
14335
14336   unsigned NumElems = VT.getVectorNumElements();
14337   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
14338
14339   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
14340   // Prepare truncation shuffle mask
14341   for (unsigned i = 0; i != NumElems; ++i)
14342     MaskVec[i] = i * 2;
14343   SDValue V = DAG.getVectorShuffle(NVT, DL,
14344                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
14345                                    DAG.getUNDEF(NVT), &MaskVec[0]);
14346   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
14347                      DAG.getIntPtrConstant(0));
14348 }
14349
14350 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
14351                                            SelectionDAG &DAG) const {
14352   assert(!Op.getSimpleValueType().isVector());
14353
14354   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14355     /*IsSigned=*/ true, /*IsReplace=*/ false);
14356   SDValue FIST = Vals.first, StackSlot = Vals.second;
14357   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
14358   if (!FIST.getNode()) return Op;
14359
14360   if (StackSlot.getNode())
14361     // Load the result.
14362     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14363                        FIST, StackSlot, MachinePointerInfo(),
14364                        false, false, false, 0);
14365
14366   // The node is the result.
14367   return FIST;
14368 }
14369
14370 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
14371                                            SelectionDAG &DAG) const {
14372   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14373     /*IsSigned=*/ false, /*IsReplace=*/ false);
14374   SDValue FIST = Vals.first, StackSlot = Vals.second;
14375   assert(FIST.getNode() && "Unexpected failure");
14376
14377   if (StackSlot.getNode())
14378     // Load the result.
14379     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14380                        FIST, StackSlot, MachinePointerInfo(),
14381                        false, false, false, 0);
14382
14383   // The node is the result.
14384   return FIST;
14385 }
14386
14387 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
14388   SDLoc DL(Op);
14389   MVT VT = Op.getSimpleValueType();
14390   SDValue In = Op.getOperand(0);
14391   MVT SVT = In.getSimpleValueType();
14392
14393   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
14394
14395   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
14396                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
14397                                  In, DAG.getUNDEF(SVT)));
14398 }
14399
14400 /// The only differences between FABS and FNEG are the mask and the logic op.
14401 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
14402 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
14403   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
14404          "Wrong opcode for lowering FABS or FNEG.");
14405
14406   bool IsFABS = (Op.getOpcode() == ISD::FABS);
14407
14408   // If this is a FABS and it has an FNEG user, bail out to fold the combination
14409   // into an FNABS. We'll lower the FABS after that if it is still in use.
14410   if (IsFABS)
14411     for (SDNode *User : Op->uses())
14412       if (User->getOpcode() == ISD::FNEG)
14413         return Op;
14414
14415   SDValue Op0 = Op.getOperand(0);
14416   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
14417
14418   SDLoc dl(Op);
14419   MVT VT = Op.getSimpleValueType();
14420   // Assume scalar op for initialization; update for vector if needed.
14421   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
14422   // generate a 16-byte vector constant and logic op even for the scalar case.
14423   // Using a 16-byte mask allows folding the load of the mask with
14424   // the logic op, so it can save (~4 bytes) on code size.
14425   MVT EltVT = VT;
14426   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
14427   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
14428   // decide if we should generate a 16-byte constant mask when we only need 4 or
14429   // 8 bytes for the scalar case.
14430   if (VT.isVector()) {
14431     EltVT = VT.getVectorElementType();
14432     NumElts = VT.getVectorNumElements();
14433   }
14434
14435   unsigned EltBits = EltVT.getSizeInBits();
14436   LLVMContext *Context = DAG.getContext();
14437   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
14438   APInt MaskElt =
14439     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
14440   Constant *C = ConstantInt::get(*Context, MaskElt);
14441   C = ConstantVector::getSplat(NumElts, C);
14442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14443   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
14444   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14445   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14446                              MachinePointerInfo::getConstantPool(),
14447                              false, false, false, Alignment);
14448
14449   if (VT.isVector()) {
14450     // For a vector, cast operands to a vector type, perform the logic op,
14451     // and cast the result back to the original value type.
14452     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
14453     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
14454     SDValue Operand = IsFNABS ?
14455       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
14456       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
14457     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
14458     return DAG.getNode(ISD::BITCAST, dl, VT,
14459                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
14460   }
14461
14462   // If not vector, then scalar.
14463   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
14464   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
14465   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
14466 }
14467
14468 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
14469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14470   LLVMContext *Context = DAG.getContext();
14471   SDValue Op0 = Op.getOperand(0);
14472   SDValue Op1 = Op.getOperand(1);
14473   SDLoc dl(Op);
14474   MVT VT = Op.getSimpleValueType();
14475   MVT SrcVT = Op1.getSimpleValueType();
14476
14477   // If second operand is smaller, extend it first.
14478   if (SrcVT.bitsLT(VT)) {
14479     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
14480     SrcVT = VT;
14481   }
14482   // And if it is bigger, shrink it first.
14483   if (SrcVT.bitsGT(VT)) {
14484     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
14485     SrcVT = VT;
14486   }
14487
14488   // At this point the operands and the result should have the same
14489   // type, and that won't be f80 since that is not custom lowered.
14490
14491   const fltSemantics &Sem =
14492       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
14493   const unsigned SizeInBits = VT.getSizeInBits();
14494
14495   SmallVector<Constant *, 4> CV(
14496       VT == MVT::f64 ? 2 : 4,
14497       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
14498
14499   // First, clear all bits but the sign bit from the second operand (sign).
14500   CV[0] = ConstantFP::get(*Context,
14501                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
14502   Constant *C = ConstantVector::get(CV);
14503   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14504   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
14505                               MachinePointerInfo::getConstantPool(),
14506                               false, false, false, 16);
14507   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
14508
14509   // Next, clear the sign bit from the first operand (magnitude).
14510   CV[0] = ConstantFP::get(
14511       *Context, APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
14512   C = ConstantVector::get(CV);
14513   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14514   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14515                               MachinePointerInfo::getConstantPool(),
14516                               false, false, false, 16);
14517   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
14518
14519   // OR the magnitude value with the sign bit.
14520   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
14521 }
14522
14523 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
14524   SDValue N0 = Op.getOperand(0);
14525   SDLoc dl(Op);
14526   MVT VT = Op.getSimpleValueType();
14527
14528   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
14529   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
14530                                   DAG.getConstant(1, VT));
14531   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
14532 }
14533
14534 // Check whether an OR'd tree is PTEST-able.
14535 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
14536                                       SelectionDAG &DAG) {
14537   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
14538
14539   if (!Subtarget->hasSSE41())
14540     return SDValue();
14541
14542   if (!Op->hasOneUse())
14543     return SDValue();
14544
14545   SDNode *N = Op.getNode();
14546   SDLoc DL(N);
14547
14548   SmallVector<SDValue, 8> Opnds;
14549   DenseMap<SDValue, unsigned> VecInMap;
14550   SmallVector<SDValue, 8> VecIns;
14551   EVT VT = MVT::Other;
14552
14553   // Recognize a special case where a vector is casted into wide integer to
14554   // test all 0s.
14555   Opnds.push_back(N->getOperand(0));
14556   Opnds.push_back(N->getOperand(1));
14557
14558   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14559     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
14560     // BFS traverse all OR'd operands.
14561     if (I->getOpcode() == ISD::OR) {
14562       Opnds.push_back(I->getOperand(0));
14563       Opnds.push_back(I->getOperand(1));
14564       // Re-evaluate the number of nodes to be traversed.
14565       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14566       continue;
14567     }
14568
14569     // Quit if a non-EXTRACT_VECTOR_ELT
14570     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14571       return SDValue();
14572
14573     // Quit if without a constant index.
14574     SDValue Idx = I->getOperand(1);
14575     if (!isa<ConstantSDNode>(Idx))
14576       return SDValue();
14577
14578     SDValue ExtractedFromVec = I->getOperand(0);
14579     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
14580     if (M == VecInMap.end()) {
14581       VT = ExtractedFromVec.getValueType();
14582       // Quit if not 128/256-bit vector.
14583       if (!VT.is128BitVector() && !VT.is256BitVector())
14584         return SDValue();
14585       // Quit if not the same type.
14586       if (VecInMap.begin() != VecInMap.end() &&
14587           VT != VecInMap.begin()->first.getValueType())
14588         return SDValue();
14589       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
14590       VecIns.push_back(ExtractedFromVec);
14591     }
14592     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14593   }
14594
14595   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14596          "Not extracted from 128-/256-bit vector.");
14597
14598   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
14599
14600   for (DenseMap<SDValue, unsigned>::const_iterator
14601         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
14602     // Quit if not all elements are used.
14603     if (I->second != FullMask)
14604       return SDValue();
14605   }
14606
14607   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
14608
14609   // Cast all vectors into TestVT for PTEST.
14610   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
14611     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
14612
14613   // If more than one full vectors are evaluated, OR them first before PTEST.
14614   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
14615     // Each iteration will OR 2 nodes and append the result until there is only
14616     // 1 node left, i.e. the final OR'd value of all vectors.
14617     SDValue LHS = VecIns[Slot];
14618     SDValue RHS = VecIns[Slot + 1];
14619     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
14620   }
14621
14622   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
14623                      VecIns.back(), VecIns.back());
14624 }
14625
14626 /// \brief return true if \c Op has a use that doesn't just read flags.
14627 static bool hasNonFlagsUse(SDValue Op) {
14628   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
14629        ++UI) {
14630     SDNode *User = *UI;
14631     unsigned UOpNo = UI.getOperandNo();
14632     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
14633       // Look pass truncate.
14634       UOpNo = User->use_begin().getOperandNo();
14635       User = *User->use_begin();
14636     }
14637
14638     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
14639         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
14640       return true;
14641   }
14642   return false;
14643 }
14644
14645 /// Emit nodes that will be selected as "test Op0,Op0", or something
14646 /// equivalent.
14647 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
14648                                     SelectionDAG &DAG) const {
14649   if (Op.getValueType() == MVT::i1)
14650     // KORTEST instruction should be selected
14651     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14652                        DAG.getConstant(0, Op.getValueType()));
14653
14654   // CF and OF aren't always set the way we want. Determine which
14655   // of these we need.
14656   bool NeedCF = false;
14657   bool NeedOF = false;
14658   switch (X86CC) {
14659   default: break;
14660   case X86::COND_A: case X86::COND_AE:
14661   case X86::COND_B: case X86::COND_BE:
14662     NeedCF = true;
14663     break;
14664   case X86::COND_G: case X86::COND_GE:
14665   case X86::COND_L: case X86::COND_LE:
14666   case X86::COND_O: case X86::COND_NO: {
14667     // Check if we really need to set the
14668     // Overflow flag. If NoSignedWrap is present
14669     // that is not actually needed.
14670     switch (Op->getOpcode()) {
14671     case ISD::ADD:
14672     case ISD::SUB:
14673     case ISD::MUL:
14674     case ISD::SHL: {
14675       const BinaryWithFlagsSDNode *BinNode =
14676           cast<BinaryWithFlagsSDNode>(Op.getNode());
14677       if (BinNode->hasNoSignedWrap())
14678         break;
14679     }
14680     default:
14681       NeedOF = true;
14682       break;
14683     }
14684     break;
14685   }
14686   }
14687   // See if we can use the EFLAGS value from the operand instead of
14688   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14689   // we prove that the arithmetic won't overflow, we can't use OF or CF.
14690   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14691     // Emit a CMP with 0, which is the TEST pattern.
14692     //if (Op.getValueType() == MVT::i1)
14693     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14694     //                     DAG.getConstant(0, MVT::i1));
14695     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14696                        DAG.getConstant(0, Op.getValueType()));
14697   }
14698   unsigned Opcode = 0;
14699   unsigned NumOperands = 0;
14700
14701   // Truncate operations may prevent the merge of the SETCC instruction
14702   // and the arithmetic instruction before it. Attempt to truncate the operands
14703   // of the arithmetic instruction and use a reduced bit-width instruction.
14704   bool NeedTruncation = false;
14705   SDValue ArithOp = Op;
14706   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14707     SDValue Arith = Op->getOperand(0);
14708     // Both the trunc and the arithmetic op need to have one user each.
14709     if (Arith->hasOneUse())
14710       switch (Arith.getOpcode()) {
14711         default: break;
14712         case ISD::ADD:
14713         case ISD::SUB:
14714         case ISD::AND:
14715         case ISD::OR:
14716         case ISD::XOR: {
14717           NeedTruncation = true;
14718           ArithOp = Arith;
14719         }
14720       }
14721   }
14722
14723   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14724   // which may be the result of a CAST.  We use the variable 'Op', which is the
14725   // non-casted variable when we check for possible users.
14726   switch (ArithOp.getOpcode()) {
14727   case ISD::ADD:
14728     // Due to an isel shortcoming, be conservative if this add is likely to be
14729     // selected as part of a load-modify-store instruction. When the root node
14730     // in a match is a store, isel doesn't know how to remap non-chain non-flag
14731     // uses of other nodes in the match, such as the ADD in this case. This
14732     // leads to the ADD being left around and reselected, with the result being
14733     // two adds in the output.  Alas, even if none our users are stores, that
14734     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
14735     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
14736     // climbing the DAG back to the root, and it doesn't seem to be worth the
14737     // effort.
14738     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14739          UE = Op.getNode()->use_end(); UI != UE; ++UI)
14740       if (UI->getOpcode() != ISD::CopyToReg &&
14741           UI->getOpcode() != ISD::SETCC &&
14742           UI->getOpcode() != ISD::STORE)
14743         goto default_case;
14744
14745     if (ConstantSDNode *C =
14746         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14747       // An add of one will be selected as an INC.
14748       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
14749         Opcode = X86ISD::INC;
14750         NumOperands = 1;
14751         break;
14752       }
14753
14754       // An add of negative one (subtract of one) will be selected as a DEC.
14755       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
14756         Opcode = X86ISD::DEC;
14757         NumOperands = 1;
14758         break;
14759       }
14760     }
14761
14762     // Otherwise use a regular EFLAGS-setting add.
14763     Opcode = X86ISD::ADD;
14764     NumOperands = 2;
14765     break;
14766   case ISD::SHL:
14767   case ISD::SRL:
14768     // If we have a constant logical shift that's only used in a comparison
14769     // against zero turn it into an equivalent AND. This allows turning it into
14770     // a TEST instruction later.
14771     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14772         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14773       EVT VT = Op.getValueType();
14774       unsigned BitWidth = VT.getSizeInBits();
14775       unsigned ShAmt = Op->getConstantOperandVal(1);
14776       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14777         break;
14778       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14779                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14780                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14781       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14782         break;
14783       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14784                                 DAG.getConstant(Mask, VT));
14785       DAG.ReplaceAllUsesWith(Op, New);
14786       Op = New;
14787     }
14788     break;
14789
14790   case ISD::AND:
14791     // If the primary and result isn't used, don't bother using X86ISD::AND,
14792     // because a TEST instruction will be better.
14793     if (!hasNonFlagsUse(Op))
14794       break;
14795     // FALL THROUGH
14796   case ISD::SUB:
14797   case ISD::OR:
14798   case ISD::XOR:
14799     // Due to the ISEL shortcoming noted above, be conservative if this op is
14800     // likely to be selected as part of a load-modify-store instruction.
14801     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14802            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14803       if (UI->getOpcode() == ISD::STORE)
14804         goto default_case;
14805
14806     // Otherwise use a regular EFLAGS-setting instruction.
14807     switch (ArithOp.getOpcode()) {
14808     default: llvm_unreachable("unexpected operator!");
14809     case ISD::SUB: Opcode = X86ISD::SUB; break;
14810     case ISD::XOR: Opcode = X86ISD::XOR; break;
14811     case ISD::AND: Opcode = X86ISD::AND; break;
14812     case ISD::OR: {
14813       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14814         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14815         if (EFLAGS.getNode())
14816           return EFLAGS;
14817       }
14818       Opcode = X86ISD::OR;
14819       break;
14820     }
14821     }
14822
14823     NumOperands = 2;
14824     break;
14825   case X86ISD::ADD:
14826   case X86ISD::SUB:
14827   case X86ISD::INC:
14828   case X86ISD::DEC:
14829   case X86ISD::OR:
14830   case X86ISD::XOR:
14831   case X86ISD::AND:
14832     return SDValue(Op.getNode(), 1);
14833   default:
14834   default_case:
14835     break;
14836   }
14837
14838   // If we found that truncation is beneficial, perform the truncation and
14839   // update 'Op'.
14840   if (NeedTruncation) {
14841     EVT VT = Op.getValueType();
14842     SDValue WideVal = Op->getOperand(0);
14843     EVT WideVT = WideVal.getValueType();
14844     unsigned ConvertedOp = 0;
14845     // Use a target machine opcode to prevent further DAGCombine
14846     // optimizations that may separate the arithmetic operations
14847     // from the setcc node.
14848     switch (WideVal.getOpcode()) {
14849       default: break;
14850       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14851       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14852       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14853       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14854       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14855     }
14856
14857     if (ConvertedOp) {
14858       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14859       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14860         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14861         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14862         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14863       }
14864     }
14865   }
14866
14867   if (Opcode == 0)
14868     // Emit a CMP with 0, which is the TEST pattern.
14869     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14870                        DAG.getConstant(0, Op.getValueType()));
14871
14872   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14873   SmallVector<SDValue, 4> Ops;
14874   for (unsigned i = 0; i != NumOperands; ++i)
14875     Ops.push_back(Op.getOperand(i));
14876
14877   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14878   DAG.ReplaceAllUsesWith(Op, New);
14879   return SDValue(New.getNode(), 1);
14880 }
14881
14882 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14883 /// equivalent.
14884 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14885                                    SDLoc dl, SelectionDAG &DAG) const {
14886   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
14887     if (C->getAPIntValue() == 0)
14888       return EmitTest(Op0, X86CC, dl, DAG);
14889
14890      if (Op0.getValueType() == MVT::i1)
14891        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
14892   }
14893
14894   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14895        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14896     // Do the comparison at i32 if it's smaller, besides the Atom case.
14897     // This avoids subregister aliasing issues. Keep the smaller reference
14898     // if we're optimizing for size, however, as that'll allow better folding
14899     // of memory operations.
14900     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14901         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
14902              AttributeSet::FunctionIndex, Attribute::MinSize) &&
14903         !Subtarget->isAtom()) {
14904       unsigned ExtendOp =
14905           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14906       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14907       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14908     }
14909     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14910     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14911     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14912                               Op0, Op1);
14913     return SDValue(Sub.getNode(), 1);
14914   }
14915   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14916 }
14917
14918 /// Convert a comparison if required by the subtarget.
14919 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14920                                                  SelectionDAG &DAG) const {
14921   // If the subtarget does not support the FUCOMI instruction, floating-point
14922   // comparisons have to be converted.
14923   if (Subtarget->hasCMov() ||
14924       Cmp.getOpcode() != X86ISD::CMP ||
14925       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14926       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14927     return Cmp;
14928
14929   // The instruction selector will select an FUCOM instruction instead of
14930   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14931   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14932   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14933   SDLoc dl(Cmp);
14934   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14935   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14936   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14937                             DAG.getConstant(8, MVT::i8));
14938   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14939   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14940 }
14941
14942 /// The minimum architected relative accuracy is 2^-12. We need one
14943 /// Newton-Raphson step to have a good float result (24 bits of precision).
14944 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14945                                             DAGCombinerInfo &DCI,
14946                                             unsigned &RefinementSteps,
14947                                             bool &UseOneConstNR) const {
14948   // FIXME: We should use instruction latency models to calculate the cost of
14949   // each potential sequence, but this is very hard to do reliably because
14950   // at least Intel's Core* chips have variable timing based on the number of
14951   // significant digits in the divisor and/or sqrt operand.
14952   if (!Subtarget->useSqrtEst())
14953     return SDValue();
14954
14955   EVT VT = Op.getValueType();
14956
14957   // SSE1 has rsqrtss and rsqrtps.
14958   // TODO: Add support for AVX512 (v16f32).
14959   // It is likely not profitable to do this for f64 because a double-precision
14960   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14961   // instructions: convert to single, rsqrtss, convert back to double, refine
14962   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14963   // along with FMA, this could be a throughput win.
14964   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14965       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14966     RefinementSteps = 1;
14967     UseOneConstNR = false;
14968     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14969   }
14970   return SDValue();
14971 }
14972
14973 /// The minimum architected relative accuracy is 2^-12. We need one
14974 /// Newton-Raphson step to have a good float result (24 bits of precision).
14975 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14976                                             DAGCombinerInfo &DCI,
14977                                             unsigned &RefinementSteps) const {
14978   // FIXME: We should use instruction latency models to calculate the cost of
14979   // each potential sequence, but this is very hard to do reliably because
14980   // at least Intel's Core* chips have variable timing based on the number of
14981   // significant digits in the divisor.
14982   if (!Subtarget->useReciprocalEst())
14983     return SDValue();
14984
14985   EVT VT = Op.getValueType();
14986
14987   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14988   // TODO: Add support for AVX512 (v16f32).
14989   // It is likely not profitable to do this for f64 because a double-precision
14990   // reciprocal estimate with refinement on x86 prior to FMA requires
14991   // 15 instructions: convert to single, rcpss, convert back to double, refine
14992   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14993   // along with FMA, this could be a throughput win.
14994   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14995       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14996     RefinementSteps = ReciprocalEstimateRefinementSteps;
14997     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14998   }
14999   return SDValue();
15000 }
15001
15002 static bool isAllOnes(SDValue V) {
15003   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
15004   return C && C->isAllOnesValue();
15005 }
15006
15007 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
15008 /// if it's possible.
15009 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
15010                                      SDLoc dl, SelectionDAG &DAG) const {
15011   SDValue Op0 = And.getOperand(0);
15012   SDValue Op1 = And.getOperand(1);
15013   if (Op0.getOpcode() == ISD::TRUNCATE)
15014     Op0 = Op0.getOperand(0);
15015   if (Op1.getOpcode() == ISD::TRUNCATE)
15016     Op1 = Op1.getOperand(0);
15017
15018   SDValue LHS, RHS;
15019   if (Op1.getOpcode() == ISD::SHL)
15020     std::swap(Op0, Op1);
15021   if (Op0.getOpcode() == ISD::SHL) {
15022     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
15023       if (And00C->getZExtValue() == 1) {
15024         // If we looked past a truncate, check that it's only truncating away
15025         // known zeros.
15026         unsigned BitWidth = Op0.getValueSizeInBits();
15027         unsigned AndBitWidth = And.getValueSizeInBits();
15028         if (BitWidth > AndBitWidth) {
15029           APInt Zeros, Ones;
15030           DAG.computeKnownBits(Op0, Zeros, Ones);
15031           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
15032             return SDValue();
15033         }
15034         LHS = Op1;
15035         RHS = Op0.getOperand(1);
15036       }
15037   } else if (Op1.getOpcode() == ISD::Constant) {
15038     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
15039     uint64_t AndRHSVal = AndRHS->getZExtValue();
15040     SDValue AndLHS = Op0;
15041
15042     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
15043       LHS = AndLHS.getOperand(0);
15044       RHS = AndLHS.getOperand(1);
15045     }
15046
15047     // Use BT if the immediate can't be encoded in a TEST instruction.
15048     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
15049       LHS = AndLHS;
15050       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
15051     }
15052   }
15053
15054   if (LHS.getNode()) {
15055     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
15056     // instruction.  Since the shift amount is in-range-or-undefined, we know
15057     // that doing a bittest on the i32 value is ok.  We extend to i32 because
15058     // the encoding for the i16 version is larger than the i32 version.
15059     // Also promote i16 to i32 for performance / code size reason.
15060     if (LHS.getValueType() == MVT::i8 ||
15061         LHS.getValueType() == MVT::i16)
15062       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
15063
15064     // If the operand types disagree, extend the shift amount to match.  Since
15065     // BT ignores high bits (like shifts) we can use anyextend.
15066     if (LHS.getValueType() != RHS.getValueType())
15067       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
15068
15069     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
15070     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
15071     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15072                        DAG.getConstant(Cond, MVT::i8), BT);
15073   }
15074
15075   return SDValue();
15076 }
15077
15078 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
15079 /// mask CMPs.
15080 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
15081                               SDValue &Op1) {
15082   unsigned SSECC;
15083   bool Swap = false;
15084
15085   // SSE Condition code mapping:
15086   //  0 - EQ
15087   //  1 - LT
15088   //  2 - LE
15089   //  3 - UNORD
15090   //  4 - NEQ
15091   //  5 - NLT
15092   //  6 - NLE
15093   //  7 - ORD
15094   switch (SetCCOpcode) {
15095   default: llvm_unreachable("Unexpected SETCC condition");
15096   case ISD::SETOEQ:
15097   case ISD::SETEQ:  SSECC = 0; break;
15098   case ISD::SETOGT:
15099   case ISD::SETGT:  Swap = true; // Fallthrough
15100   case ISD::SETLT:
15101   case ISD::SETOLT: SSECC = 1; break;
15102   case ISD::SETOGE:
15103   case ISD::SETGE:  Swap = true; // Fallthrough
15104   case ISD::SETLE:
15105   case ISD::SETOLE: SSECC = 2; break;
15106   case ISD::SETUO:  SSECC = 3; break;
15107   case ISD::SETUNE:
15108   case ISD::SETNE:  SSECC = 4; break;
15109   case ISD::SETULE: Swap = true; // Fallthrough
15110   case ISD::SETUGE: SSECC = 5; break;
15111   case ISD::SETULT: Swap = true; // Fallthrough
15112   case ISD::SETUGT: SSECC = 6; break;
15113   case ISD::SETO:   SSECC = 7; break;
15114   case ISD::SETUEQ:
15115   case ISD::SETONE: SSECC = 8; break;
15116   }
15117   if (Swap)
15118     std::swap(Op0, Op1);
15119
15120   return SSECC;
15121 }
15122
15123 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
15124 // ones, and then concatenate the result back.
15125 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
15126   MVT VT = Op.getSimpleValueType();
15127
15128   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
15129          "Unsupported value type for operation");
15130
15131   unsigned NumElems = VT.getVectorNumElements();
15132   SDLoc dl(Op);
15133   SDValue CC = Op.getOperand(2);
15134
15135   // Extract the LHS vectors
15136   SDValue LHS = Op.getOperand(0);
15137   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15138   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15139
15140   // Extract the RHS vectors
15141   SDValue RHS = Op.getOperand(1);
15142   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15143   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15144
15145   // Issue the operation on the smaller types and concatenate the result back
15146   MVT EltVT = VT.getVectorElementType();
15147   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15148   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15149                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
15150                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
15151 }
15152
15153 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
15154                                      const X86Subtarget *Subtarget) {
15155   SDValue Op0 = Op.getOperand(0);
15156   SDValue Op1 = Op.getOperand(1);
15157   SDValue CC = Op.getOperand(2);
15158   MVT VT = Op.getSimpleValueType();
15159   SDLoc dl(Op);
15160
15161   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
15162          Op.getValueType().getScalarType() == MVT::i1 &&
15163          "Cannot set masked compare for this operation");
15164
15165   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15166   unsigned  Opc = 0;
15167   bool Unsigned = false;
15168   bool Swap = false;
15169   unsigned SSECC;
15170   switch (SetCCOpcode) {
15171   default: llvm_unreachable("Unexpected SETCC condition");
15172   case ISD::SETNE:  SSECC = 4; break;
15173   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
15174   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
15175   case ISD::SETLT:  Swap = true; //fall-through
15176   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
15177   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
15178   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
15179   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
15180   case ISD::SETULE: Unsigned = true; //fall-through
15181   case ISD::SETLE:  SSECC = 2; break;
15182   }
15183
15184   if (Swap)
15185     std::swap(Op0, Op1);
15186   if (Opc)
15187     return DAG.getNode(Opc, dl, VT, Op0, Op1);
15188   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
15189   return DAG.getNode(Opc, dl, VT, Op0, Op1,
15190                      DAG.getConstant(SSECC, MVT::i8));
15191 }
15192
15193 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
15194 /// operand \p Op1.  If non-trivial (for example because it's not constant)
15195 /// return an empty value.
15196 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
15197 {
15198   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
15199   if (!BV)
15200     return SDValue();
15201
15202   MVT VT = Op1.getSimpleValueType();
15203   MVT EVT = VT.getVectorElementType();
15204   unsigned n = VT.getVectorNumElements();
15205   SmallVector<SDValue, 8> ULTOp1;
15206
15207   for (unsigned i = 0; i < n; ++i) {
15208     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
15209     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
15210       return SDValue();
15211
15212     // Avoid underflow.
15213     APInt Val = Elt->getAPIntValue();
15214     if (Val == 0)
15215       return SDValue();
15216
15217     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
15218   }
15219
15220   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
15221 }
15222
15223 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
15224                            SelectionDAG &DAG) {
15225   SDValue Op0 = Op.getOperand(0);
15226   SDValue Op1 = Op.getOperand(1);
15227   SDValue CC = Op.getOperand(2);
15228   MVT VT = Op.getSimpleValueType();
15229   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15230   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
15231   SDLoc dl(Op);
15232
15233   if (isFP) {
15234 #ifndef NDEBUG
15235     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
15236     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
15237 #endif
15238
15239     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
15240     unsigned Opc = X86ISD::CMPP;
15241     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
15242       assert(VT.getVectorNumElements() <= 16);
15243       Opc = X86ISD::CMPM;
15244     }
15245     // In the two special cases we can't handle, emit two comparisons.
15246     if (SSECC == 8) {
15247       unsigned CC0, CC1;
15248       unsigned CombineOpc;
15249       if (SetCCOpcode == ISD::SETUEQ) {
15250         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
15251       } else {
15252         assert(SetCCOpcode == ISD::SETONE);
15253         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
15254       }
15255
15256       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15257                                  DAG.getConstant(CC0, MVT::i8));
15258       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15259                                  DAG.getConstant(CC1, MVT::i8));
15260       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
15261     }
15262     // Handle all other FP comparisons here.
15263     return DAG.getNode(Opc, dl, VT, Op0, Op1,
15264                        DAG.getConstant(SSECC, MVT::i8));
15265   }
15266
15267   // Break 256-bit integer vector compare into smaller ones.
15268   if (VT.is256BitVector() && !Subtarget->hasInt256())
15269     return Lower256IntVSETCC(Op, DAG);
15270
15271   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
15272   EVT OpVT = Op1.getValueType();
15273   if (Subtarget->hasAVX512()) {
15274     if (Op1.getValueType().is512BitVector() ||
15275         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
15276         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
15277       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
15278
15279     // In AVX-512 architecture setcc returns mask with i1 elements,
15280     // But there is no compare instruction for i8 and i16 elements in KNL.
15281     // We are not talking about 512-bit operands in this case, these
15282     // types are illegal.
15283     if (MaskResult &&
15284         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
15285          OpVT.getVectorElementType().getSizeInBits() >= 8))
15286       return DAG.getNode(ISD::TRUNCATE, dl, VT,
15287                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
15288   }
15289
15290   // We are handling one of the integer comparisons here.  Since SSE only has
15291   // GT and EQ comparisons for integer, swapping operands and multiple
15292   // operations may be required for some comparisons.
15293   unsigned Opc;
15294   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
15295   bool Subus = false;
15296
15297   switch (SetCCOpcode) {
15298   default: llvm_unreachable("Unexpected SETCC condition");
15299   case ISD::SETNE:  Invert = true;
15300   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
15301   case ISD::SETLT:  Swap = true;
15302   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
15303   case ISD::SETGE:  Swap = true;
15304   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
15305                     Invert = true; break;
15306   case ISD::SETULT: Swap = true;
15307   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
15308                     FlipSigns = true; break;
15309   case ISD::SETUGE: Swap = true;
15310   case ISD::SETULE: Opc = X86ISD::PCMPGT;
15311                     FlipSigns = true; Invert = true; break;
15312   }
15313
15314   // Special case: Use min/max operations for SETULE/SETUGE
15315   MVT VET = VT.getVectorElementType();
15316   bool hasMinMax =
15317        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
15318     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
15319
15320   if (hasMinMax) {
15321     switch (SetCCOpcode) {
15322     default: break;
15323     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
15324     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
15325     }
15326
15327     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
15328   }
15329
15330   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
15331   if (!MinMax && hasSubus) {
15332     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
15333     // Op0 u<= Op1:
15334     //   t = psubus Op0, Op1
15335     //   pcmpeq t, <0..0>
15336     switch (SetCCOpcode) {
15337     default: break;
15338     case ISD::SETULT: {
15339       // If the comparison is against a constant we can turn this into a
15340       // setule.  With psubus, setule does not require a swap.  This is
15341       // beneficial because the constant in the register is no longer
15342       // destructed as the destination so it can be hoisted out of a loop.
15343       // Only do this pre-AVX since vpcmp* is no longer destructive.
15344       if (Subtarget->hasAVX())
15345         break;
15346       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
15347       if (ULEOp1.getNode()) {
15348         Op1 = ULEOp1;
15349         Subus = true; Invert = false; Swap = false;
15350       }
15351       break;
15352     }
15353     // Psubus is better than flip-sign because it requires no inversion.
15354     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
15355     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
15356     }
15357
15358     if (Subus) {
15359       Opc = X86ISD::SUBUS;
15360       FlipSigns = false;
15361     }
15362   }
15363
15364   if (Swap)
15365     std::swap(Op0, Op1);
15366
15367   // Check that the operation in question is available (most are plain SSE2,
15368   // but PCMPGTQ and PCMPEQQ have different requirements).
15369   if (VT == MVT::v2i64) {
15370     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
15371       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
15372
15373       // First cast everything to the right type.
15374       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15375       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15376
15377       // Since SSE has no unsigned integer comparisons, we need to flip the sign
15378       // bits of the inputs before performing those operations. The lower
15379       // compare is always unsigned.
15380       SDValue SB;
15381       if (FlipSigns) {
15382         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
15383       } else {
15384         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
15385         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
15386         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
15387                          Sign, Zero, Sign, Zero);
15388       }
15389       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
15390       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
15391
15392       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
15393       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
15394       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
15395
15396       // Create masks for only the low parts/high parts of the 64 bit integers.
15397       static const int MaskHi[] = { 1, 1, 3, 3 };
15398       static const int MaskLo[] = { 0, 0, 2, 2 };
15399       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
15400       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
15401       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
15402
15403       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
15404       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
15405
15406       if (Invert)
15407         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15408
15409       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15410     }
15411
15412     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
15413       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
15414       // pcmpeqd + pshufd + pand.
15415       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
15416
15417       // First cast everything to the right type.
15418       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15419       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15420
15421       // Do the compare.
15422       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
15423
15424       // Make sure the lower and upper halves are both all-ones.
15425       static const int Mask[] = { 1, 0, 3, 2 };
15426       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
15427       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
15428
15429       if (Invert)
15430         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15431
15432       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15433     }
15434   }
15435
15436   // Since SSE has no unsigned integer comparisons, we need to flip the sign
15437   // bits of the inputs before performing those operations.
15438   if (FlipSigns) {
15439     EVT EltVT = VT.getVectorElementType();
15440     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
15441     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
15442     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
15443   }
15444
15445   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
15446
15447   // If the logical-not of the result is required, perform that now.
15448   if (Invert)
15449     Result = DAG.getNOT(dl, Result, VT);
15450
15451   if (MinMax)
15452     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
15453
15454   if (Subus)
15455     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
15456                          getZeroVector(VT, Subtarget, DAG, dl));
15457
15458   return Result;
15459 }
15460
15461 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
15462
15463   MVT VT = Op.getSimpleValueType();
15464
15465   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
15466
15467   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
15468          && "SetCC type must be 8-bit or 1-bit integer");
15469   SDValue Op0 = Op.getOperand(0);
15470   SDValue Op1 = Op.getOperand(1);
15471   SDLoc dl(Op);
15472   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
15473
15474   // Optimize to BT if possible.
15475   // Lower (X & (1 << N)) == 0 to BT(X, N).
15476   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
15477   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
15478   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
15479       Op1.getOpcode() == ISD::Constant &&
15480       cast<ConstantSDNode>(Op1)->isNullValue() &&
15481       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15482     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
15483     if (NewSetCC.getNode()) {
15484       if (VT == MVT::i1)
15485         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
15486       return NewSetCC;
15487     }
15488   }
15489
15490   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
15491   // these.
15492   if (Op1.getOpcode() == ISD::Constant &&
15493       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
15494        cast<ConstantSDNode>(Op1)->isNullValue()) &&
15495       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15496
15497     // If the input is a setcc, then reuse the input setcc or use a new one with
15498     // the inverted condition.
15499     if (Op0.getOpcode() == X86ISD::SETCC) {
15500       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
15501       bool Invert = (CC == ISD::SETNE) ^
15502         cast<ConstantSDNode>(Op1)->isNullValue();
15503       if (!Invert)
15504         return Op0;
15505
15506       CCode = X86::GetOppositeBranchCondition(CCode);
15507       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15508                                   DAG.getConstant(CCode, MVT::i8),
15509                                   Op0.getOperand(1));
15510       if (VT == MVT::i1)
15511         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15512       return SetCC;
15513     }
15514   }
15515   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
15516       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
15517       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15518
15519     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
15520     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
15521   }
15522
15523   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
15524   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
15525   if (X86CC == X86::COND_INVALID)
15526     return SDValue();
15527
15528   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
15529   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
15530   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15531                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
15532   if (VT == MVT::i1)
15533     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15534   return SetCC;
15535 }
15536
15537 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
15538 static bool isX86LogicalCmp(SDValue Op) {
15539   unsigned Opc = Op.getNode()->getOpcode();
15540   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
15541       Opc == X86ISD::SAHF)
15542     return true;
15543   if (Op.getResNo() == 1 &&
15544       (Opc == X86ISD::ADD ||
15545        Opc == X86ISD::SUB ||
15546        Opc == X86ISD::ADC ||
15547        Opc == X86ISD::SBB ||
15548        Opc == X86ISD::SMUL ||
15549        Opc == X86ISD::UMUL ||
15550        Opc == X86ISD::INC ||
15551        Opc == X86ISD::DEC ||
15552        Opc == X86ISD::OR ||
15553        Opc == X86ISD::XOR ||
15554        Opc == X86ISD::AND))
15555     return true;
15556
15557   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15558     return true;
15559
15560   return false;
15561 }
15562
15563 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15564   if (V.getOpcode() != ISD::TRUNCATE)
15565     return false;
15566
15567   SDValue VOp0 = V.getOperand(0);
15568   unsigned InBits = VOp0.getValueSizeInBits();
15569   unsigned Bits = V.getValueSizeInBits();
15570   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15571 }
15572
15573 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15574   bool addTest = true;
15575   SDValue Cond  = Op.getOperand(0);
15576   SDValue Op1 = Op.getOperand(1);
15577   SDValue Op2 = Op.getOperand(2);
15578   SDLoc DL(Op);
15579   EVT VT = Op1.getValueType();
15580   SDValue CC;
15581
15582   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15583   // are available. Otherwise fp cmovs get lowered into a less efficient branch
15584   // sequence later on.
15585   if (Cond.getOpcode() == ISD::SETCC &&
15586       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15587        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15588       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
15589     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15590     int SSECC = translateX86FSETCC(
15591         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15592
15593     if (SSECC != 8) {
15594       if (Subtarget->hasAVX512()) {
15595         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15596                                   DAG.getConstant(SSECC, MVT::i8));
15597         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15598       }
15599       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15600                                 DAG.getConstant(SSECC, MVT::i8));
15601       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15602       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15603       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15604     }
15605   }
15606
15607   if (Cond.getOpcode() == ISD::SETCC) {
15608     SDValue NewCond = LowerSETCC(Cond, DAG);
15609     if (NewCond.getNode())
15610       Cond = NewCond;
15611   }
15612
15613   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15614   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15615   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15616   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15617   if (Cond.getOpcode() == X86ISD::SETCC &&
15618       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15619       isZero(Cond.getOperand(1).getOperand(1))) {
15620     SDValue Cmp = Cond.getOperand(1);
15621
15622     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15623
15624     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
15625         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15626       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
15627
15628       SDValue CmpOp0 = Cmp.getOperand(0);
15629       // Apply further optimizations for special cases
15630       // (select (x != 0), -1, 0) -> neg & sbb
15631       // (select (x == 0), 0, -1) -> neg & sbb
15632       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
15633         if (YC->isNullValue() &&
15634             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
15635           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15636           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15637                                     DAG.getConstant(0, CmpOp0.getValueType()),
15638                                     CmpOp0);
15639           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15640                                     DAG.getConstant(X86::COND_B, MVT::i8),
15641                                     SDValue(Neg.getNode(), 1));
15642           return Res;
15643         }
15644
15645       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15646                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
15647       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15648
15649       SDValue Res =   // Res = 0 or -1.
15650         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15651                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
15652
15653       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
15654         Res = DAG.getNOT(DL, Res, Res.getValueType());
15655
15656       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
15657       if (!N2C || !N2C->isNullValue())
15658         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15659       return Res;
15660     }
15661   }
15662
15663   // Look past (and (setcc_carry (cmp ...)), 1).
15664   if (Cond.getOpcode() == ISD::AND &&
15665       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15666     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15667     if (C && C->getAPIntValue() == 1)
15668       Cond = Cond.getOperand(0);
15669   }
15670
15671   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15672   // setting operand in place of the X86ISD::SETCC.
15673   unsigned CondOpcode = Cond.getOpcode();
15674   if (CondOpcode == X86ISD::SETCC ||
15675       CondOpcode == X86ISD::SETCC_CARRY) {
15676     CC = Cond.getOperand(0);
15677
15678     SDValue Cmp = Cond.getOperand(1);
15679     unsigned Opc = Cmp.getOpcode();
15680     MVT VT = Op.getSimpleValueType();
15681
15682     bool IllegalFPCMov = false;
15683     if (VT.isFloatingPoint() && !VT.isVector() &&
15684         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15685       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15686
15687     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15688         Opc == X86ISD::BT) { // FIXME
15689       Cond = Cmp;
15690       addTest = false;
15691     }
15692   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15693              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15694              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15695               Cond.getOperand(0).getValueType() != MVT::i8)) {
15696     SDValue LHS = Cond.getOperand(0);
15697     SDValue RHS = Cond.getOperand(1);
15698     unsigned X86Opcode;
15699     unsigned X86Cond;
15700     SDVTList VTs;
15701     switch (CondOpcode) {
15702     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15703     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15704     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15705     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15706     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15707     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15708     default: llvm_unreachable("unexpected overflowing operator");
15709     }
15710     if (CondOpcode == ISD::UMULO)
15711       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15712                           MVT::i32);
15713     else
15714       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15715
15716     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15717
15718     if (CondOpcode == ISD::UMULO)
15719       Cond = X86Op.getValue(2);
15720     else
15721       Cond = X86Op.getValue(1);
15722
15723     CC = DAG.getConstant(X86Cond, MVT::i8);
15724     addTest = false;
15725   }
15726
15727   if (addTest) {
15728     // Look pass the truncate if the high bits are known zero.
15729     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15730         Cond = Cond.getOperand(0);
15731
15732     // We know the result of AND is compared against zero. Try to match
15733     // it to BT.
15734     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15735       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
15736       if (NewSetCC.getNode()) {
15737         CC = NewSetCC.getOperand(0);
15738         Cond = NewSetCC.getOperand(1);
15739         addTest = false;
15740       }
15741     }
15742   }
15743
15744   if (addTest) {
15745     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15746     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15747   }
15748
15749   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15750   // a <  b ?  0 : -1 -> RES = setcc_carry
15751   // a >= b ? -1 :  0 -> RES = setcc_carry
15752   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15753   if (Cond.getOpcode() == X86ISD::SUB) {
15754     Cond = ConvertCmpIfNecessary(Cond, DAG);
15755     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15756
15757     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15758         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
15759       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15760                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
15761       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
15762         return DAG.getNOT(DL, Res, Res.getValueType());
15763       return Res;
15764     }
15765   }
15766
15767   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15768   // widen the cmov and push the truncate through. This avoids introducing a new
15769   // branch during isel and doesn't add any extensions.
15770   if (Op.getValueType() == MVT::i8 &&
15771       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15772     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15773     if (T1.getValueType() == T2.getValueType() &&
15774         // Blacklist CopyFromReg to avoid partial register stalls.
15775         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15776       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15777       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15778       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15779     }
15780   }
15781
15782   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15783   // condition is true.
15784   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15785   SDValue Ops[] = { Op2, Op1, CC, Cond };
15786   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15787 }
15788
15789 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
15790                                        SelectionDAG &DAG) {
15791   MVT VT = Op->getSimpleValueType(0);
15792   SDValue In = Op->getOperand(0);
15793   MVT InVT = In.getSimpleValueType();
15794   MVT VTElt = VT.getVectorElementType();
15795   MVT InVTElt = InVT.getVectorElementType();
15796   SDLoc dl(Op);
15797
15798   // SKX processor
15799   if ((InVTElt == MVT::i1) &&
15800       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15801         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15802
15803        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15804         VTElt.getSizeInBits() <= 16)) ||
15805
15806        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15807         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15808
15809        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15810         VTElt.getSizeInBits() >= 32))))
15811     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15812
15813   unsigned int NumElts = VT.getVectorNumElements();
15814
15815   if (NumElts != 8 && NumElts != 16)
15816     return SDValue();
15817
15818   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15819     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15820       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15821     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15822   }
15823
15824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15825   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15826
15827   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
15828   Constant *C = ConstantInt::get(*DAG.getContext(),
15829     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
15830
15831   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
15832   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
15833   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
15834                           MachinePointerInfo::getConstantPool(),
15835                           false, false, false, Alignment);
15836   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
15837   if (VT.is512BitVector())
15838     return Brcst;
15839   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
15840 }
15841
15842 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15843                                 SelectionDAG &DAG) {
15844   MVT VT = Op->getSimpleValueType(0);
15845   SDValue In = Op->getOperand(0);
15846   MVT InVT = In.getSimpleValueType();
15847   SDLoc dl(Op);
15848
15849   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15850     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15851
15852   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15853       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15854       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15855     return SDValue();
15856
15857   if (Subtarget->hasInt256())
15858     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15859
15860   // Optimize vectors in AVX mode
15861   // Sign extend  v8i16 to v8i32 and
15862   //              v4i32 to v4i64
15863   //
15864   // Divide input vector into two parts
15865   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15866   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15867   // concat the vectors to original VT
15868
15869   unsigned NumElems = InVT.getVectorNumElements();
15870   SDValue Undef = DAG.getUNDEF(InVT);
15871
15872   SmallVector<int,8> ShufMask1(NumElems, -1);
15873   for (unsigned i = 0; i != NumElems/2; ++i)
15874     ShufMask1[i] = i;
15875
15876   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15877
15878   SmallVector<int,8> ShufMask2(NumElems, -1);
15879   for (unsigned i = 0; i != NumElems/2; ++i)
15880     ShufMask2[i] = i + NumElems/2;
15881
15882   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15883
15884   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15885                                 VT.getVectorNumElements()/2);
15886
15887   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15888   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15889
15890   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15891 }
15892
15893 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15894 // may emit an illegal shuffle but the expansion is still better than scalar
15895 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15896 // we'll emit a shuffle and a arithmetic shift.
15897 // TODO: It is possible to support ZExt by zeroing the undef values during
15898 // the shuffle phase or after the shuffle.
15899 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15900                                  SelectionDAG &DAG) {
15901   MVT RegVT = Op.getSimpleValueType();
15902   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15903   assert(RegVT.isInteger() &&
15904          "We only custom lower integer vector sext loads.");
15905
15906   // Nothing useful we can do without SSE2 shuffles.
15907   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15908
15909   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15910   SDLoc dl(Ld);
15911   EVT MemVT = Ld->getMemoryVT();
15912   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15913   unsigned RegSz = RegVT.getSizeInBits();
15914
15915   ISD::LoadExtType Ext = Ld->getExtensionType();
15916
15917   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15918          && "Only anyext and sext are currently implemented.");
15919   assert(MemVT != RegVT && "Cannot extend to the same type");
15920   assert(MemVT.isVector() && "Must load a vector from memory");
15921
15922   unsigned NumElems = RegVT.getVectorNumElements();
15923   unsigned MemSz = MemVT.getSizeInBits();
15924   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15925
15926   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15927     // The only way in which we have a legal 256-bit vector result but not the
15928     // integer 256-bit operations needed to directly lower a sextload is if we
15929     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15930     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15931     // correctly legalized. We do this late to allow the canonical form of
15932     // sextload to persist throughout the rest of the DAG combiner -- it wants
15933     // to fold together any extensions it can, and so will fuse a sign_extend
15934     // of an sextload into a sextload targeting a wider value.
15935     SDValue Load;
15936     if (MemSz == 128) {
15937       // Just switch this to a normal load.
15938       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15939                                        "it must be a legal 128-bit vector "
15940                                        "type!");
15941       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15942                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15943                   Ld->isInvariant(), Ld->getAlignment());
15944     } else {
15945       assert(MemSz < 128 &&
15946              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15947       // Do an sext load to a 128-bit vector type. We want to use the same
15948       // number of elements, but elements half as wide. This will end up being
15949       // recursively lowered by this routine, but will succeed as we definitely
15950       // have all the necessary features if we're using AVX1.
15951       EVT HalfEltVT =
15952           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15953       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15954       Load =
15955           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15956                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15957                          Ld->isNonTemporal(), Ld->isInvariant(),
15958                          Ld->getAlignment());
15959     }
15960
15961     // Replace chain users with the new chain.
15962     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15963     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15964
15965     // Finally, do a normal sign-extend to the desired register.
15966     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15967   }
15968
15969   // All sizes must be a power of two.
15970   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15971          "Non-power-of-two elements are not custom lowered!");
15972
15973   // Attempt to load the original value using scalar loads.
15974   // Find the largest scalar type that divides the total loaded size.
15975   MVT SclrLoadTy = MVT::i8;
15976   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15977        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15978     MVT Tp = (MVT::SimpleValueType)tp;
15979     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15980       SclrLoadTy = Tp;
15981     }
15982   }
15983
15984   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15985   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15986       (64 <= MemSz))
15987     SclrLoadTy = MVT::f64;
15988
15989   // Calculate the number of scalar loads that we need to perform
15990   // in order to load our vector from memory.
15991   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15992
15993   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15994          "Can only lower sext loads with a single scalar load!");
15995
15996   unsigned loadRegZize = RegSz;
15997   if (Ext == ISD::SEXTLOAD && RegSz == 256)
15998     loadRegZize /= 2;
15999
16000   // Represent our vector as a sequence of elements which are the
16001   // largest scalar that we can load.
16002   EVT LoadUnitVecVT = EVT::getVectorVT(
16003       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
16004
16005   // Represent the data using the same element type that is stored in
16006   // memory. In practice, we ''widen'' MemVT.
16007   EVT WideVecVT =
16008       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16009                        loadRegZize / MemVT.getScalarType().getSizeInBits());
16010
16011   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16012          "Invalid vector type");
16013
16014   // We can't shuffle using an illegal type.
16015   assert(TLI.isTypeLegal(WideVecVT) &&
16016          "We only lower types that form legal widened vector types");
16017
16018   SmallVector<SDValue, 8> Chains;
16019   SDValue Ptr = Ld->getBasePtr();
16020   SDValue Increment =
16021       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
16022   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16023
16024   for (unsigned i = 0; i < NumLoads; ++i) {
16025     // Perform a single load.
16026     SDValue ScalarLoad =
16027         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
16028                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
16029                     Ld->getAlignment());
16030     Chains.push_back(ScalarLoad.getValue(1));
16031     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16032     // another round of DAGCombining.
16033     if (i == 0)
16034       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16035     else
16036       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16037                         ScalarLoad, DAG.getIntPtrConstant(i));
16038
16039     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16040   }
16041
16042   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
16043
16044   // Bitcast the loaded value to a vector of the original element type, in
16045   // the size of the target vector type.
16046   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16047   unsigned SizeRatio = RegSz / MemSz;
16048
16049   if (Ext == ISD::SEXTLOAD) {
16050     // If we have SSE4.1, we can directly emit a VSEXT node.
16051     if (Subtarget->hasSSE41()) {
16052       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16053       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16054       return Sext;
16055     }
16056
16057     // Otherwise we'll shuffle the small elements in the high bits of the
16058     // larger type and perform an arithmetic shift. If the shift is not legal
16059     // it's better to scalarize.
16060     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
16061            "We can't implement a sext load without an arithmetic right shift!");
16062
16063     // Redistribute the loaded elements into the different locations.
16064     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16065     for (unsigned i = 0; i != NumElems; ++i)
16066       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
16067
16068     SDValue Shuff = DAG.getVectorShuffle(
16069         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16070
16071     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16072
16073     // Build the arithmetic shift.
16074     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16075                    MemVT.getVectorElementType().getSizeInBits();
16076     Shuff =
16077         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
16078
16079     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16080     return Shuff;
16081   }
16082
16083   // Redistribute the loaded elements into the different locations.
16084   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16085   for (unsigned i = 0; i != NumElems; ++i)
16086     ShuffleVec[i * SizeRatio] = i;
16087
16088   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16089                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16090
16091   // Bitcast to the requested type.
16092   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16093   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16094   return Shuff;
16095 }
16096
16097 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
16098 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
16099 // from the AND / OR.
16100 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
16101   Opc = Op.getOpcode();
16102   if (Opc != ISD::OR && Opc != ISD::AND)
16103     return false;
16104   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16105           Op.getOperand(0).hasOneUse() &&
16106           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
16107           Op.getOperand(1).hasOneUse());
16108 }
16109
16110 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
16111 // 1 and that the SETCC node has a single use.
16112 static bool isXor1OfSetCC(SDValue Op) {
16113   if (Op.getOpcode() != ISD::XOR)
16114     return false;
16115   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
16116   if (N1C && N1C->getAPIntValue() == 1) {
16117     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16118       Op.getOperand(0).hasOneUse();
16119   }
16120   return false;
16121 }
16122
16123 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
16124   bool addTest = true;
16125   SDValue Chain = Op.getOperand(0);
16126   SDValue Cond  = Op.getOperand(1);
16127   SDValue Dest  = Op.getOperand(2);
16128   SDLoc dl(Op);
16129   SDValue CC;
16130   bool Inverted = false;
16131
16132   if (Cond.getOpcode() == ISD::SETCC) {
16133     // Check for setcc([su]{add,sub,mul}o == 0).
16134     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
16135         isa<ConstantSDNode>(Cond.getOperand(1)) &&
16136         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
16137         Cond.getOperand(0).getResNo() == 1 &&
16138         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
16139          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
16140          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
16141          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
16142          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
16143          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
16144       Inverted = true;
16145       Cond = Cond.getOperand(0);
16146     } else {
16147       SDValue NewCond = LowerSETCC(Cond, DAG);
16148       if (NewCond.getNode())
16149         Cond = NewCond;
16150     }
16151   }
16152 #if 0
16153   // FIXME: LowerXALUO doesn't handle these!!
16154   else if (Cond.getOpcode() == X86ISD::ADD  ||
16155            Cond.getOpcode() == X86ISD::SUB  ||
16156            Cond.getOpcode() == X86ISD::SMUL ||
16157            Cond.getOpcode() == X86ISD::UMUL)
16158     Cond = LowerXALUO(Cond, DAG);
16159 #endif
16160
16161   // Look pass (and (setcc_carry (cmp ...)), 1).
16162   if (Cond.getOpcode() == ISD::AND &&
16163       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
16164     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
16165     if (C && C->getAPIntValue() == 1)
16166       Cond = Cond.getOperand(0);
16167   }
16168
16169   // If condition flag is set by a X86ISD::CMP, then use it as the condition
16170   // setting operand in place of the X86ISD::SETCC.
16171   unsigned CondOpcode = Cond.getOpcode();
16172   if (CondOpcode == X86ISD::SETCC ||
16173       CondOpcode == X86ISD::SETCC_CARRY) {
16174     CC = Cond.getOperand(0);
16175
16176     SDValue Cmp = Cond.getOperand(1);
16177     unsigned Opc = Cmp.getOpcode();
16178     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
16179     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
16180       Cond = Cmp;
16181       addTest = false;
16182     } else {
16183       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
16184       default: break;
16185       case X86::COND_O:
16186       case X86::COND_B:
16187         // These can only come from an arithmetic instruction with overflow,
16188         // e.g. SADDO, UADDO.
16189         Cond = Cond.getNode()->getOperand(1);
16190         addTest = false;
16191         break;
16192       }
16193     }
16194   }
16195   CondOpcode = Cond.getOpcode();
16196   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
16197       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
16198       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
16199        Cond.getOperand(0).getValueType() != MVT::i8)) {
16200     SDValue LHS = Cond.getOperand(0);
16201     SDValue RHS = Cond.getOperand(1);
16202     unsigned X86Opcode;
16203     unsigned X86Cond;
16204     SDVTList VTs;
16205     // Keep this in sync with LowerXALUO, otherwise we might create redundant
16206     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
16207     // X86ISD::INC).
16208     switch (CondOpcode) {
16209     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
16210     case ISD::SADDO:
16211       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16212         if (C->isOne()) {
16213           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
16214           break;
16215         }
16216       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
16217     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
16218     case ISD::SSUBO:
16219       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16220         if (C->isOne()) {
16221           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
16222           break;
16223         }
16224       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
16225     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
16226     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
16227     default: llvm_unreachable("unexpected overflowing operator");
16228     }
16229     if (Inverted)
16230       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
16231     if (CondOpcode == ISD::UMULO)
16232       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
16233                           MVT::i32);
16234     else
16235       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
16236
16237     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
16238
16239     if (CondOpcode == ISD::UMULO)
16240       Cond = X86Op.getValue(2);
16241     else
16242       Cond = X86Op.getValue(1);
16243
16244     CC = DAG.getConstant(X86Cond, MVT::i8);
16245     addTest = false;
16246   } else {
16247     unsigned CondOpc;
16248     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
16249       SDValue Cmp = Cond.getOperand(0).getOperand(1);
16250       if (CondOpc == ISD::OR) {
16251         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
16252         // two branches instead of an explicit OR instruction with a
16253         // separate test.
16254         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16255             isX86LogicalCmp(Cmp)) {
16256           CC = Cond.getOperand(0).getOperand(0);
16257           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16258                               Chain, Dest, CC, Cmp);
16259           CC = Cond.getOperand(1).getOperand(0);
16260           Cond = Cmp;
16261           addTest = false;
16262         }
16263       } else { // ISD::AND
16264         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
16265         // two branches instead of an explicit AND instruction with a
16266         // separate test. However, we only do this if this block doesn't
16267         // have a fall-through edge, because this requires an explicit
16268         // jmp when the condition is false.
16269         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16270             isX86LogicalCmp(Cmp) &&
16271             Op.getNode()->hasOneUse()) {
16272           X86::CondCode CCode =
16273             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16274           CCode = X86::GetOppositeBranchCondition(CCode);
16275           CC = DAG.getConstant(CCode, MVT::i8);
16276           SDNode *User = *Op.getNode()->use_begin();
16277           // Look for an unconditional branch following this conditional branch.
16278           // We need this because we need to reverse the successors in order
16279           // to implement FCMP_OEQ.
16280           if (User->getOpcode() == ISD::BR) {
16281             SDValue FalseBB = User->getOperand(1);
16282             SDNode *NewBR =
16283               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16284             assert(NewBR == User);
16285             (void)NewBR;
16286             Dest = FalseBB;
16287
16288             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16289                                 Chain, Dest, CC, Cmp);
16290             X86::CondCode CCode =
16291               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
16292             CCode = X86::GetOppositeBranchCondition(CCode);
16293             CC = DAG.getConstant(CCode, MVT::i8);
16294             Cond = Cmp;
16295             addTest = false;
16296           }
16297         }
16298       }
16299     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
16300       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
16301       // It should be transformed during dag combiner except when the condition
16302       // is set by a arithmetics with overflow node.
16303       X86::CondCode CCode =
16304         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16305       CCode = X86::GetOppositeBranchCondition(CCode);
16306       CC = DAG.getConstant(CCode, MVT::i8);
16307       Cond = Cond.getOperand(0).getOperand(1);
16308       addTest = false;
16309     } else if (Cond.getOpcode() == ISD::SETCC &&
16310                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
16311       // For FCMP_OEQ, we can emit
16312       // two branches instead of an explicit AND instruction with a
16313       // separate test. However, we only do this if this block doesn't
16314       // have a fall-through edge, because this requires an explicit
16315       // jmp when the condition is false.
16316       if (Op.getNode()->hasOneUse()) {
16317         SDNode *User = *Op.getNode()->use_begin();
16318         // Look for an unconditional branch following this conditional branch.
16319         // We need this because we need to reverse the successors in order
16320         // to implement FCMP_OEQ.
16321         if (User->getOpcode() == ISD::BR) {
16322           SDValue FalseBB = User->getOperand(1);
16323           SDNode *NewBR =
16324             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16325           assert(NewBR == User);
16326           (void)NewBR;
16327           Dest = FalseBB;
16328
16329           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16330                                     Cond.getOperand(0), Cond.getOperand(1));
16331           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16332           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16333           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16334                               Chain, Dest, CC, Cmp);
16335           CC = DAG.getConstant(X86::COND_P, MVT::i8);
16336           Cond = Cmp;
16337           addTest = false;
16338         }
16339       }
16340     } else if (Cond.getOpcode() == ISD::SETCC &&
16341                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
16342       // For FCMP_UNE, we can emit
16343       // two branches instead of an explicit AND instruction with a
16344       // separate test. However, we only do this if this block doesn't
16345       // have a fall-through edge, because this requires an explicit
16346       // jmp when the condition is false.
16347       if (Op.getNode()->hasOneUse()) {
16348         SDNode *User = *Op.getNode()->use_begin();
16349         // Look for an unconditional branch following this conditional branch.
16350         // We need this because we need to reverse the successors in order
16351         // to implement FCMP_UNE.
16352         if (User->getOpcode() == ISD::BR) {
16353           SDValue FalseBB = User->getOperand(1);
16354           SDNode *NewBR =
16355             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16356           assert(NewBR == User);
16357           (void)NewBR;
16358
16359           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16360                                     Cond.getOperand(0), Cond.getOperand(1));
16361           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16362           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16363           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16364                               Chain, Dest, CC, Cmp);
16365           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
16366           Cond = Cmp;
16367           addTest = false;
16368           Dest = FalseBB;
16369         }
16370       }
16371     }
16372   }
16373
16374   if (addTest) {
16375     // Look pass the truncate if the high bits are known zero.
16376     if (isTruncWithZeroHighBitsInput(Cond, DAG))
16377         Cond = Cond.getOperand(0);
16378
16379     // We know the result of AND is compared against zero. Try to match
16380     // it to BT.
16381     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
16382       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
16383       if (NewSetCC.getNode()) {
16384         CC = NewSetCC.getOperand(0);
16385         Cond = NewSetCC.getOperand(1);
16386         addTest = false;
16387       }
16388     }
16389   }
16390
16391   if (addTest) {
16392     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
16393     CC = DAG.getConstant(X86Cond, MVT::i8);
16394     Cond = EmitTest(Cond, X86Cond, dl, DAG);
16395   }
16396   Cond = ConvertCmpIfNecessary(Cond, DAG);
16397   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16398                      Chain, Dest, CC, Cond);
16399 }
16400
16401 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
16402 // Calls to _alloca are needed to probe the stack when allocating more than 4k
16403 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
16404 // that the guard pages used by the OS virtual memory manager are allocated in
16405 // correct sequence.
16406 SDValue
16407 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
16408                                            SelectionDAG &DAG) const {
16409   MachineFunction &MF = DAG.getMachineFunction();
16410   bool SplitStack = MF.shouldSplitStack();
16411   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
16412                SplitStack;
16413   SDLoc dl(Op);
16414
16415   if (!Lower) {
16416     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16417     SDNode* Node = Op.getNode();
16418
16419     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
16420     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
16421         " not tell us which reg is the stack pointer!");
16422     EVT VT = Node->getValueType(0);
16423     SDValue Tmp1 = SDValue(Node, 0);
16424     SDValue Tmp2 = SDValue(Node, 1);
16425     SDValue Tmp3 = Node->getOperand(2);
16426     SDValue Chain = Tmp1.getOperand(0);
16427
16428     // Chain the dynamic stack allocation so that it doesn't modify the stack
16429     // pointer when other instructions are using the stack.
16430     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
16431         SDLoc(Node));
16432
16433     SDValue Size = Tmp2.getOperand(1);
16434     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
16435     Chain = SP.getValue(1);
16436     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
16437     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
16438     unsigned StackAlign = TFI.getStackAlignment();
16439     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
16440     if (Align > StackAlign)
16441       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
16442           DAG.getConstant(-(uint64_t)Align, VT));
16443     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
16444
16445     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
16446         DAG.getIntPtrConstant(0, true), SDValue(),
16447         SDLoc(Node));
16448
16449     SDValue Ops[2] = { Tmp1, Tmp2 };
16450     return DAG.getMergeValues(Ops, dl);
16451   }
16452
16453   // Get the inputs.
16454   SDValue Chain = Op.getOperand(0);
16455   SDValue Size  = Op.getOperand(1);
16456   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16457   EVT VT = Op.getNode()->getValueType(0);
16458
16459   bool Is64Bit = Subtarget->is64Bit();
16460   EVT SPTy = getPointerTy();
16461
16462   if (SplitStack) {
16463     MachineRegisterInfo &MRI = MF.getRegInfo();
16464
16465     if (Is64Bit) {
16466       // The 64 bit implementation of segmented stacks needs to clobber both r10
16467       // r11. This makes it impossible to use it along with nested parameters.
16468       const Function *F = MF.getFunction();
16469
16470       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16471            I != E; ++I)
16472         if (I->hasNestAttr())
16473           report_fatal_error("Cannot use segmented stacks with functions that "
16474                              "have nested arguments.");
16475     }
16476
16477     const TargetRegisterClass *AddrRegClass =
16478       getRegClassFor(getPointerTy());
16479     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16480     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16481     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16482                                 DAG.getRegister(Vreg, SPTy));
16483     SDValue Ops1[2] = { Value, Chain };
16484     return DAG.getMergeValues(Ops1, dl);
16485   } else {
16486     SDValue Flag;
16487     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16488
16489     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16490     Flag = Chain.getValue(1);
16491     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16492
16493     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16494
16495     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16496         DAG.getSubtarget().getRegisterInfo());
16497     unsigned SPReg = RegInfo->getStackRegister();
16498     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16499     Chain = SP.getValue(1);
16500
16501     if (Align) {
16502       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16503                        DAG.getConstant(-(uint64_t)Align, VT));
16504       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16505     }
16506
16507     SDValue Ops1[2] = { SP, Chain };
16508     return DAG.getMergeValues(Ops1, dl);
16509   }
16510 }
16511
16512 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16513   MachineFunction &MF = DAG.getMachineFunction();
16514   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16515
16516   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16517   SDLoc DL(Op);
16518
16519   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
16520     // vastart just stores the address of the VarArgsFrameIndex slot into the
16521     // memory location argument.
16522     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16523                                    getPointerTy());
16524     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16525                         MachinePointerInfo(SV), false, false, 0);
16526   }
16527
16528   // __va_list_tag:
16529   //   gp_offset         (0 - 6 * 8)
16530   //   fp_offset         (48 - 48 + 8 * 16)
16531   //   overflow_arg_area (point to parameters coming in memory).
16532   //   reg_save_area
16533   SmallVector<SDValue, 8> MemOps;
16534   SDValue FIN = Op.getOperand(1);
16535   // Store gp_offset
16536   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16537                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16538                                                MVT::i32),
16539                                FIN, MachinePointerInfo(SV), false, false, 0);
16540   MemOps.push_back(Store);
16541
16542   // Store fp_offset
16543   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16544                     FIN, DAG.getIntPtrConstant(4));
16545   Store = DAG.getStore(Op.getOperand(0), DL,
16546                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
16547                                        MVT::i32),
16548                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16549   MemOps.push_back(Store);
16550
16551   // Store ptr to overflow_arg_area
16552   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16553                     FIN, DAG.getIntPtrConstant(4));
16554   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16555                                     getPointerTy());
16556   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16557                        MachinePointerInfo(SV, 8),
16558                        false, false, 0);
16559   MemOps.push_back(Store);
16560
16561   // Store ptr to reg_save_area.
16562   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16563                     FIN, DAG.getIntPtrConstant(8));
16564   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
16565                                     getPointerTy());
16566   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
16567                        MachinePointerInfo(SV, 16), false, false, 0);
16568   MemOps.push_back(Store);
16569   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16570 }
16571
16572 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16573   assert(Subtarget->is64Bit() &&
16574          "LowerVAARG only handles 64-bit va_arg!");
16575   assert((Subtarget->isTargetLinux() ||
16576           Subtarget->isTargetDarwin()) &&
16577           "Unhandled target in LowerVAARG");
16578   assert(Op.getNode()->getNumOperands() == 4);
16579   SDValue Chain = Op.getOperand(0);
16580   SDValue SrcPtr = Op.getOperand(1);
16581   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16582   unsigned Align = Op.getConstantOperandVal(3);
16583   SDLoc dl(Op);
16584
16585   EVT ArgVT = Op.getNode()->getValueType(0);
16586   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16587   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
16588   uint8_t ArgMode;
16589
16590   // Decide which area this value should be read from.
16591   // TODO: Implement the AMD64 ABI in its entirety. This simple
16592   // selection mechanism works only for the basic types.
16593   if (ArgVT == MVT::f80) {
16594     llvm_unreachable("va_arg for f80 not yet implemented");
16595   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16596     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16597   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16598     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16599   } else {
16600     llvm_unreachable("Unhandled argument type in LowerVAARG");
16601   }
16602
16603   if (ArgMode == 2) {
16604     // Sanity Check: Make sure using fp_offset makes sense.
16605     assert(!DAG.getTarget().Options.UseSoftFloat &&
16606            !(DAG.getMachineFunction()
16607                 .getFunction()->getAttributes()
16608                 .hasAttribute(AttributeSet::FunctionIndex,
16609                               Attribute::NoImplicitFloat)) &&
16610            Subtarget->hasSSE1());
16611   }
16612
16613   // Insert VAARG_64 node into the DAG
16614   // VAARG_64 returns two values: Variable Argument Address, Chain
16615   SmallVector<SDValue, 11> InstOps;
16616   InstOps.push_back(Chain);
16617   InstOps.push_back(SrcPtr);
16618   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
16619   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
16620   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
16621   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
16622   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16623                                           VTs, InstOps, MVT::i64,
16624                                           MachinePointerInfo(SV),
16625                                           /*Align=*/0,
16626                                           /*Volatile=*/false,
16627                                           /*ReadMem=*/true,
16628                                           /*WriteMem=*/true);
16629   Chain = VAARG.getValue(1);
16630
16631   // Load the next argument and return it
16632   return DAG.getLoad(ArgVT, dl,
16633                      Chain,
16634                      VAARG,
16635                      MachinePointerInfo(),
16636                      false, false, false, 0);
16637 }
16638
16639 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16640                            SelectionDAG &DAG) {
16641   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
16642   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16643   SDValue Chain = Op.getOperand(0);
16644   SDValue DstPtr = Op.getOperand(1);
16645   SDValue SrcPtr = Op.getOperand(2);
16646   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16647   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16648   SDLoc DL(Op);
16649
16650   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16651                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
16652                        false,
16653                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16654 }
16655
16656 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16657 // amount is a constant. Takes immediate version of shift as input.
16658 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16659                                           SDValue SrcOp, uint64_t ShiftAmt,
16660                                           SelectionDAG &DAG) {
16661   MVT ElementType = VT.getVectorElementType();
16662
16663   // Fold this packed shift into its first operand if ShiftAmt is 0.
16664   if (ShiftAmt == 0)
16665     return SrcOp;
16666
16667   // Check for ShiftAmt >= element width
16668   if (ShiftAmt >= ElementType.getSizeInBits()) {
16669     if (Opc == X86ISD::VSRAI)
16670       ShiftAmt = ElementType.getSizeInBits() - 1;
16671     else
16672       return DAG.getConstant(0, VT);
16673   }
16674
16675   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16676          && "Unknown target vector shift-by-constant node");
16677
16678   // Fold this packed vector shift into a build vector if SrcOp is a
16679   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16680   if (VT == SrcOp.getSimpleValueType() &&
16681       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16682     SmallVector<SDValue, 8> Elts;
16683     unsigned NumElts = SrcOp->getNumOperands();
16684     ConstantSDNode *ND;
16685
16686     switch(Opc) {
16687     default: llvm_unreachable(nullptr);
16688     case X86ISD::VSHLI:
16689       for (unsigned i=0; i!=NumElts; ++i) {
16690         SDValue CurrentOp = SrcOp->getOperand(i);
16691         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16692           Elts.push_back(CurrentOp);
16693           continue;
16694         }
16695         ND = cast<ConstantSDNode>(CurrentOp);
16696         const APInt &C = ND->getAPIntValue();
16697         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
16698       }
16699       break;
16700     case X86ISD::VSRLI:
16701       for (unsigned i=0; i!=NumElts; ++i) {
16702         SDValue CurrentOp = SrcOp->getOperand(i);
16703         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16704           Elts.push_back(CurrentOp);
16705           continue;
16706         }
16707         ND = cast<ConstantSDNode>(CurrentOp);
16708         const APInt &C = ND->getAPIntValue();
16709         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
16710       }
16711       break;
16712     case X86ISD::VSRAI:
16713       for (unsigned i=0; i!=NumElts; ++i) {
16714         SDValue CurrentOp = SrcOp->getOperand(i);
16715         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16716           Elts.push_back(CurrentOp);
16717           continue;
16718         }
16719         ND = cast<ConstantSDNode>(CurrentOp);
16720         const APInt &C = ND->getAPIntValue();
16721         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
16722       }
16723       break;
16724     }
16725
16726     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16727   }
16728
16729   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
16730 }
16731
16732 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16733 // may or may not be a constant. Takes immediate version of shift as input.
16734 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16735                                    SDValue SrcOp, SDValue ShAmt,
16736                                    SelectionDAG &DAG) {
16737   MVT SVT = ShAmt.getSimpleValueType();
16738   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16739
16740   // Catch shift-by-constant.
16741   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16742     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16743                                       CShAmt->getZExtValue(), DAG);
16744
16745   // Change opcode to non-immediate version
16746   switch (Opc) {
16747     default: llvm_unreachable("Unknown target vector shift node");
16748     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16749     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16750     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16751   }
16752
16753   const X86Subtarget &Subtarget =
16754       DAG.getTarget().getSubtarget<X86Subtarget>();
16755   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16756       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16757     // Let the shuffle legalizer expand this shift amount node.
16758     SDValue Op0 = ShAmt.getOperand(0);
16759     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16760     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16761   } else {
16762     // Need to build a vector containing shift amount.
16763     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16764     SmallVector<SDValue, 4> ShOps;
16765     ShOps.push_back(ShAmt);
16766     if (SVT == MVT::i32) {
16767       ShOps.push_back(DAG.getConstant(0, SVT));
16768       ShOps.push_back(DAG.getUNDEF(SVT));
16769     }
16770     ShOps.push_back(DAG.getUNDEF(SVT));
16771
16772     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16773     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16774   }
16775
16776   // The return type has to be a 128-bit type with the same element
16777   // type as the input type.
16778   MVT EltVT = VT.getVectorElementType();
16779   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16780
16781   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
16782   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16783 }
16784
16785 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16786 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16787 /// necessary casting for \p Mask when lowering masking intrinsics.
16788 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16789                                     SDValue PreservedSrc,
16790                                     const X86Subtarget *Subtarget,
16791                                     SelectionDAG &DAG) {
16792     EVT VT = Op.getValueType();
16793     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16794                                   MVT::i1, VT.getVectorNumElements());
16795     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16796                                      Mask.getValueType().getSizeInBits());
16797     SDLoc dl(Op);
16798
16799     assert(MaskVT.isSimple() && "invalid mask type");
16800
16801     if (isAllOnes(Mask))
16802       return Op;
16803
16804     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16805     // are extracted by EXTRACT_SUBVECTOR.
16806     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16807                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
16808                               DAG.getIntPtrConstant(0));
16809
16810     switch (Op.getOpcode()) {
16811       default: break;
16812       case X86ISD::PCMPEQM:
16813       case X86ISD::PCMPGTM:
16814       case X86ISD::CMPM:
16815       case X86ISD::CMPMU:
16816         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16817     }
16818     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16819       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16820     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
16821 }
16822
16823 /// \brief Creates an SDNode for a predicated scalar operation.
16824 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16825 /// The mask is comming as MVT::i8 and it should be truncated
16826 /// to MVT::i1 while lowering masking intrinsics.
16827 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16828 /// "X86select" instead of "vselect". We just can't create the "vselect" node for 
16829 /// a scalar instruction.
16830 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16831                                     SDValue PreservedSrc,
16832                                     const X86Subtarget *Subtarget,
16833                                     SelectionDAG &DAG) {
16834     if (isAllOnes(Mask))
16835       return Op;
16836
16837     EVT VT = Op.getValueType();
16838     SDLoc dl(Op);
16839     // The mask should be of type MVT::i1
16840     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16841
16842     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16843       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16844     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16845 }
16846
16847 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
16848     switch (IntNo) {
16849     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16850     case Intrinsic::x86_fma_vfmadd_ps:
16851     case Intrinsic::x86_fma_vfmadd_pd:
16852     case Intrinsic::x86_fma_vfmadd_ps_256:
16853     case Intrinsic::x86_fma_vfmadd_pd_256:
16854     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
16855     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
16856       return X86ISD::FMADD;
16857     case Intrinsic::x86_fma_vfmsub_ps:
16858     case Intrinsic::x86_fma_vfmsub_pd:
16859     case Intrinsic::x86_fma_vfmsub_ps_256:
16860     case Intrinsic::x86_fma_vfmsub_pd_256:
16861     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
16862     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
16863       return X86ISD::FMSUB;
16864     case Intrinsic::x86_fma_vfnmadd_ps:
16865     case Intrinsic::x86_fma_vfnmadd_pd:
16866     case Intrinsic::x86_fma_vfnmadd_ps_256:
16867     case Intrinsic::x86_fma_vfnmadd_pd_256:
16868     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
16869     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
16870       return X86ISD::FNMADD;
16871     case Intrinsic::x86_fma_vfnmsub_ps:
16872     case Intrinsic::x86_fma_vfnmsub_pd:
16873     case Intrinsic::x86_fma_vfnmsub_ps_256:
16874     case Intrinsic::x86_fma_vfnmsub_pd_256:
16875     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
16876     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
16877       return X86ISD::FNMSUB;
16878     case Intrinsic::x86_fma_vfmaddsub_ps:
16879     case Intrinsic::x86_fma_vfmaddsub_pd:
16880     case Intrinsic::x86_fma_vfmaddsub_ps_256:
16881     case Intrinsic::x86_fma_vfmaddsub_pd_256:
16882     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
16883     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
16884       return X86ISD::FMADDSUB;
16885     case Intrinsic::x86_fma_vfmsubadd_ps:
16886     case Intrinsic::x86_fma_vfmsubadd_pd:
16887     case Intrinsic::x86_fma_vfmsubadd_ps_256:
16888     case Intrinsic::x86_fma_vfmsubadd_pd_256:
16889     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
16890     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
16891       return X86ISD::FMSUBADD;
16892     }
16893 }
16894
16895 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16896                                        SelectionDAG &DAG) {
16897   SDLoc dl(Op);
16898   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16899   EVT VT = Op.getValueType();
16900   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16901   if (IntrData) {
16902     switch(IntrData->Type) {
16903     case INTR_TYPE_1OP:
16904       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16905     case INTR_TYPE_2OP:
16906       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16907         Op.getOperand(2));
16908     case INTR_TYPE_3OP:
16909       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16910         Op.getOperand(2), Op.getOperand(3));
16911     case INTR_TYPE_1OP_MASK_RM: {
16912       SDValue Src = Op.getOperand(1);
16913       SDValue Src0 = Op.getOperand(2);
16914       SDValue Mask = Op.getOperand(3);
16915       SDValue RoundingMode = Op.getOperand(4);
16916       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16917                                               RoundingMode),
16918                                   Mask, Src0, Subtarget, DAG);
16919     }
16920     case INTR_TYPE_SCALAR_MASK_RM: {
16921       SDValue Src1 = Op.getOperand(1);
16922       SDValue Src2 = Op.getOperand(2);
16923       SDValue Src0 = Op.getOperand(3);
16924       SDValue Mask = Op.getOperand(4);
16925       SDValue RoundingMode = Op.getOperand(5);
16926       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16927                                               RoundingMode),
16928                                   Mask, Src0, Subtarget, DAG);
16929     }
16930     case INTR_TYPE_2OP_MASK: {
16931       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Op.getOperand(1),
16932                                               Op.getOperand(2)),
16933                                   Op.getOperand(4), Op.getOperand(3), Subtarget, DAG);
16934     }
16935     case CMP_MASK:
16936     case CMP_MASK_CC: {
16937       // Comparison intrinsics with masks.
16938       // Example of transformation:
16939       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16940       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16941       // (i8 (bitcast
16942       //   (v8i1 (insert_subvector undef,
16943       //           (v2i1 (and (PCMPEQM %a, %b),
16944       //                      (extract_subvector
16945       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16946       EVT VT = Op.getOperand(1).getValueType();
16947       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16948                                     VT.getVectorNumElements());
16949       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16950       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16951                                        Mask.getValueType().getSizeInBits());
16952       SDValue Cmp;
16953       if (IntrData->Type == CMP_MASK_CC) {
16954         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16955                     Op.getOperand(2), Op.getOperand(3));
16956       } else {
16957         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16958         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16959                     Op.getOperand(2));
16960       }
16961       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16962                                              DAG.getTargetConstant(0, MaskVT),
16963                                              Subtarget, DAG);
16964       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16965                                 DAG.getUNDEF(BitcastVT), CmpMask,
16966                                 DAG.getIntPtrConstant(0));
16967       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
16968     }
16969     case COMI: { // Comparison intrinsics
16970       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16971       SDValue LHS = Op.getOperand(1);
16972       SDValue RHS = Op.getOperand(2);
16973       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
16974       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16975       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16976       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16977                                   DAG.getConstant(X86CC, MVT::i8), Cond);
16978       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16979     }
16980     case VSHIFT:
16981       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16982                                  Op.getOperand(1), Op.getOperand(2), DAG);
16983     case VSHIFT_MASK:
16984       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16985                                                       Op.getSimpleValueType(),
16986                                                       Op.getOperand(1),
16987                                                       Op.getOperand(2), DAG),
16988                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16989                                   DAG);
16990     case COMPRESS_EXPAND_IN_REG: {
16991       SDValue Mask = Op.getOperand(3);
16992       SDValue DataToCompress = Op.getOperand(1);
16993       SDValue PassThru = Op.getOperand(2);
16994       if (isAllOnes(Mask)) // return data as is
16995         return Op.getOperand(1);
16996       EVT VT = Op.getValueType();
16997       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16998                                     VT.getVectorNumElements());
16999       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17000                                        Mask.getValueType().getSizeInBits());
17001       SDLoc dl(Op);
17002       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17003                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17004                                   DAG.getIntPtrConstant(0));
17005
17006       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
17007                          PassThru);
17008     }
17009     case BLEND: {
17010       SDValue Mask = Op.getOperand(3);
17011       EVT VT = Op.getValueType();
17012       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17013                                     VT.getVectorNumElements());
17014       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17015                                        Mask.getValueType().getSizeInBits());
17016       SDLoc dl(Op);
17017       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17018                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17019                                   DAG.getIntPtrConstant(0));
17020       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
17021                          Op.getOperand(2));
17022     }
17023     default:
17024       break;
17025     }
17026   }
17027
17028   switch (IntNo) {
17029   default: return SDValue();    // Don't custom lower most intrinsics.
17030
17031   case Intrinsic::x86_avx512_mask_valign_q_512:
17032   case Intrinsic::x86_avx512_mask_valign_d_512:
17033     // Vector source operands are swapped.
17034     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
17035                                             Op.getValueType(), Op.getOperand(2),
17036                                             Op.getOperand(1),
17037                                             Op.getOperand(3)),
17038                                 Op.getOperand(5), Op.getOperand(4),
17039                                 Subtarget, DAG);
17040
17041   // ptest and testp intrinsics. The intrinsic these come from are designed to
17042   // return an integer value, not just an instruction so lower it to the ptest
17043   // or testp pattern and a setcc for the result.
17044   case Intrinsic::x86_sse41_ptestz:
17045   case Intrinsic::x86_sse41_ptestc:
17046   case Intrinsic::x86_sse41_ptestnzc:
17047   case Intrinsic::x86_avx_ptestz_256:
17048   case Intrinsic::x86_avx_ptestc_256:
17049   case Intrinsic::x86_avx_ptestnzc_256:
17050   case Intrinsic::x86_avx_vtestz_ps:
17051   case Intrinsic::x86_avx_vtestc_ps:
17052   case Intrinsic::x86_avx_vtestnzc_ps:
17053   case Intrinsic::x86_avx_vtestz_pd:
17054   case Intrinsic::x86_avx_vtestc_pd:
17055   case Intrinsic::x86_avx_vtestnzc_pd:
17056   case Intrinsic::x86_avx_vtestz_ps_256:
17057   case Intrinsic::x86_avx_vtestc_ps_256:
17058   case Intrinsic::x86_avx_vtestnzc_ps_256:
17059   case Intrinsic::x86_avx_vtestz_pd_256:
17060   case Intrinsic::x86_avx_vtestc_pd_256:
17061   case Intrinsic::x86_avx_vtestnzc_pd_256: {
17062     bool IsTestPacked = false;
17063     unsigned X86CC;
17064     switch (IntNo) {
17065     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17066     case Intrinsic::x86_avx_vtestz_ps:
17067     case Intrinsic::x86_avx_vtestz_pd:
17068     case Intrinsic::x86_avx_vtestz_ps_256:
17069     case Intrinsic::x86_avx_vtestz_pd_256:
17070       IsTestPacked = true; // Fallthrough
17071     case Intrinsic::x86_sse41_ptestz:
17072     case Intrinsic::x86_avx_ptestz_256:
17073       // ZF = 1
17074       X86CC = X86::COND_E;
17075       break;
17076     case Intrinsic::x86_avx_vtestc_ps:
17077     case Intrinsic::x86_avx_vtestc_pd:
17078     case Intrinsic::x86_avx_vtestc_ps_256:
17079     case Intrinsic::x86_avx_vtestc_pd_256:
17080       IsTestPacked = true; // Fallthrough
17081     case Intrinsic::x86_sse41_ptestc:
17082     case Intrinsic::x86_avx_ptestc_256:
17083       // CF = 1
17084       X86CC = X86::COND_B;
17085       break;
17086     case Intrinsic::x86_avx_vtestnzc_ps:
17087     case Intrinsic::x86_avx_vtestnzc_pd:
17088     case Intrinsic::x86_avx_vtestnzc_ps_256:
17089     case Intrinsic::x86_avx_vtestnzc_pd_256:
17090       IsTestPacked = true; // Fallthrough
17091     case Intrinsic::x86_sse41_ptestnzc:
17092     case Intrinsic::x86_avx_ptestnzc_256:
17093       // ZF and CF = 0
17094       X86CC = X86::COND_A;
17095       break;
17096     }
17097
17098     SDValue LHS = Op.getOperand(1);
17099     SDValue RHS = Op.getOperand(2);
17100     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17101     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17102     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17103     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17104     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17105   }
17106   case Intrinsic::x86_avx512_kortestz_w:
17107   case Intrinsic::x86_avx512_kortestc_w: {
17108     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17109     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
17110     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
17111     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17112     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17113     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17114     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17115   }
17116
17117   case Intrinsic::x86_sse42_pcmpistria128:
17118   case Intrinsic::x86_sse42_pcmpestria128:
17119   case Intrinsic::x86_sse42_pcmpistric128:
17120   case Intrinsic::x86_sse42_pcmpestric128:
17121   case Intrinsic::x86_sse42_pcmpistrio128:
17122   case Intrinsic::x86_sse42_pcmpestrio128:
17123   case Intrinsic::x86_sse42_pcmpistris128:
17124   case Intrinsic::x86_sse42_pcmpestris128:
17125   case Intrinsic::x86_sse42_pcmpistriz128:
17126   case Intrinsic::x86_sse42_pcmpestriz128: {
17127     unsigned Opcode;
17128     unsigned X86CC;
17129     switch (IntNo) {
17130     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17131     case Intrinsic::x86_sse42_pcmpistria128:
17132       Opcode = X86ISD::PCMPISTRI;
17133       X86CC = X86::COND_A;
17134       break;
17135     case Intrinsic::x86_sse42_pcmpestria128:
17136       Opcode = X86ISD::PCMPESTRI;
17137       X86CC = X86::COND_A;
17138       break;
17139     case Intrinsic::x86_sse42_pcmpistric128:
17140       Opcode = X86ISD::PCMPISTRI;
17141       X86CC = X86::COND_B;
17142       break;
17143     case Intrinsic::x86_sse42_pcmpestric128:
17144       Opcode = X86ISD::PCMPESTRI;
17145       X86CC = X86::COND_B;
17146       break;
17147     case Intrinsic::x86_sse42_pcmpistrio128:
17148       Opcode = X86ISD::PCMPISTRI;
17149       X86CC = X86::COND_O;
17150       break;
17151     case Intrinsic::x86_sse42_pcmpestrio128:
17152       Opcode = X86ISD::PCMPESTRI;
17153       X86CC = X86::COND_O;
17154       break;
17155     case Intrinsic::x86_sse42_pcmpistris128:
17156       Opcode = X86ISD::PCMPISTRI;
17157       X86CC = X86::COND_S;
17158       break;
17159     case Intrinsic::x86_sse42_pcmpestris128:
17160       Opcode = X86ISD::PCMPESTRI;
17161       X86CC = X86::COND_S;
17162       break;
17163     case Intrinsic::x86_sse42_pcmpistriz128:
17164       Opcode = X86ISD::PCMPISTRI;
17165       X86CC = X86::COND_E;
17166       break;
17167     case Intrinsic::x86_sse42_pcmpestriz128:
17168       Opcode = X86ISD::PCMPESTRI;
17169       X86CC = X86::COND_E;
17170       break;
17171     }
17172     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17173     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17174     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17175     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17176                                 DAG.getConstant(X86CC, MVT::i8),
17177                                 SDValue(PCMP.getNode(), 1));
17178     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17179   }
17180
17181   case Intrinsic::x86_sse42_pcmpistri128:
17182   case Intrinsic::x86_sse42_pcmpestri128: {
17183     unsigned Opcode;
17184     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17185       Opcode = X86ISD::PCMPISTRI;
17186     else
17187       Opcode = X86ISD::PCMPESTRI;
17188
17189     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17190     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17191     return DAG.getNode(Opcode, dl, VTs, NewOps);
17192   }
17193
17194   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
17195   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
17196   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
17197   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
17198   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
17199   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
17200   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
17201   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
17202   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
17203   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
17204   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
17205   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
17206     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
17207     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
17208       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
17209                                               dl, Op.getValueType(),
17210                                               Op.getOperand(1),
17211                                               Op.getOperand(2),
17212                                               Op.getOperand(3)),
17213                                   Op.getOperand(4), Op.getOperand(1),
17214                                   Subtarget, DAG);
17215     else
17216       return SDValue();
17217   }
17218
17219   case Intrinsic::x86_fma_vfmadd_ps:
17220   case Intrinsic::x86_fma_vfmadd_pd:
17221   case Intrinsic::x86_fma_vfmsub_ps:
17222   case Intrinsic::x86_fma_vfmsub_pd:
17223   case Intrinsic::x86_fma_vfnmadd_ps:
17224   case Intrinsic::x86_fma_vfnmadd_pd:
17225   case Intrinsic::x86_fma_vfnmsub_ps:
17226   case Intrinsic::x86_fma_vfnmsub_pd:
17227   case Intrinsic::x86_fma_vfmaddsub_ps:
17228   case Intrinsic::x86_fma_vfmaddsub_pd:
17229   case Intrinsic::x86_fma_vfmsubadd_ps:
17230   case Intrinsic::x86_fma_vfmsubadd_pd:
17231   case Intrinsic::x86_fma_vfmadd_ps_256:
17232   case Intrinsic::x86_fma_vfmadd_pd_256:
17233   case Intrinsic::x86_fma_vfmsub_ps_256:
17234   case Intrinsic::x86_fma_vfmsub_pd_256:
17235   case Intrinsic::x86_fma_vfnmadd_ps_256:
17236   case Intrinsic::x86_fma_vfnmadd_pd_256:
17237   case Intrinsic::x86_fma_vfnmsub_ps_256:
17238   case Intrinsic::x86_fma_vfnmsub_pd_256:
17239   case Intrinsic::x86_fma_vfmaddsub_ps_256:
17240   case Intrinsic::x86_fma_vfmaddsub_pd_256:
17241   case Intrinsic::x86_fma_vfmsubadd_ps_256:
17242   case Intrinsic::x86_fma_vfmsubadd_pd_256:
17243     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
17244                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
17245   }
17246 }
17247
17248 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17249                               SDValue Src, SDValue Mask, SDValue Base,
17250                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17251                               const X86Subtarget * Subtarget) {
17252   SDLoc dl(Op);
17253   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17254   assert(C && "Invalid scale type");
17255   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17256   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17257                              Index.getSimpleValueType().getVectorNumElements());
17258   SDValue MaskInReg;
17259   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17260   if (MaskC)
17261     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17262   else
17263     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17264   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17265   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17266   SDValue Segment = DAG.getRegister(0, MVT::i32);
17267   if (Src.getOpcode() == ISD::UNDEF)
17268     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
17269   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17270   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17271   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17272   return DAG.getMergeValues(RetOps, dl);
17273 }
17274
17275 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17276                                SDValue Src, SDValue Mask, SDValue Base,
17277                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17278   SDLoc dl(Op);
17279   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17280   assert(C && "Invalid scale type");
17281   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17282   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17283   SDValue Segment = DAG.getRegister(0, MVT::i32);
17284   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17285                              Index.getSimpleValueType().getVectorNumElements());
17286   SDValue MaskInReg;
17287   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17288   if (MaskC)
17289     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17290   else
17291     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17292   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17293   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17294   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17295   return SDValue(Res, 1);
17296 }
17297
17298 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17299                                SDValue Mask, SDValue Base, SDValue Index,
17300                                SDValue ScaleOp, SDValue Chain) {
17301   SDLoc dl(Op);
17302   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17303   assert(C && "Invalid scale type");
17304   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17305   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17306   SDValue Segment = DAG.getRegister(0, MVT::i32);
17307   EVT MaskVT =
17308     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17309   SDValue MaskInReg;
17310   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17311   if (MaskC)
17312     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17313   else
17314     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17315   //SDVTList VTs = DAG.getVTList(MVT::Other);
17316   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17317   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17318   return SDValue(Res, 0);
17319 }
17320
17321 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17322 // read performance monitor counters (x86_rdpmc).
17323 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17324                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17325                               SmallVectorImpl<SDValue> &Results) {
17326   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17327   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17328   SDValue LO, HI;
17329
17330   // The ECX register is used to select the index of the performance counter
17331   // to read.
17332   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17333                                    N->getOperand(2));
17334   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17335
17336   // Reads the content of a 64-bit performance counter and returns it in the
17337   // registers EDX:EAX.
17338   if (Subtarget->is64Bit()) {
17339     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17340     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17341                             LO.getValue(2));
17342   } else {
17343     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17344     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17345                             LO.getValue(2));
17346   }
17347   Chain = HI.getValue(1);
17348
17349   if (Subtarget->is64Bit()) {
17350     // The EAX register is loaded with the low-order 32 bits. The EDX register
17351     // is loaded with the supported high-order bits of the counter.
17352     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17353                               DAG.getConstant(32, MVT::i8));
17354     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17355     Results.push_back(Chain);
17356     return;
17357   }
17358
17359   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17360   SDValue Ops[] = { LO, HI };
17361   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17362   Results.push_back(Pair);
17363   Results.push_back(Chain);
17364 }
17365
17366 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17367 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17368 // also used to custom lower READCYCLECOUNTER nodes.
17369 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17370                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17371                               SmallVectorImpl<SDValue> &Results) {
17372   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17373   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17374   SDValue LO, HI;
17375
17376   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17377   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17378   // and the EAX register is loaded with the low-order 32 bits.
17379   if (Subtarget->is64Bit()) {
17380     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17381     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17382                             LO.getValue(2));
17383   } else {
17384     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17385     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17386                             LO.getValue(2));
17387   }
17388   SDValue Chain = HI.getValue(1);
17389
17390   if (Opcode == X86ISD::RDTSCP_DAG) {
17391     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17392
17393     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17394     // the ECX register. Add 'ecx' explicitly to the chain.
17395     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17396                                      HI.getValue(2));
17397     // Explicitly store the content of ECX at the location passed in input
17398     // to the 'rdtscp' intrinsic.
17399     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17400                          MachinePointerInfo(), false, false, 0);
17401   }
17402
17403   if (Subtarget->is64Bit()) {
17404     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17405     // the EAX register is loaded with the low-order 32 bits.
17406     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17407                               DAG.getConstant(32, MVT::i8));
17408     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17409     Results.push_back(Chain);
17410     return;
17411   }
17412
17413   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17414   SDValue Ops[] = { LO, HI };
17415   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17416   Results.push_back(Pair);
17417   Results.push_back(Chain);
17418 }
17419
17420 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17421                                      SelectionDAG &DAG) {
17422   SmallVector<SDValue, 2> Results;
17423   SDLoc DL(Op);
17424   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17425                           Results);
17426   return DAG.getMergeValues(Results, DL);
17427 }
17428
17429
17430 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17431                                       SelectionDAG &DAG) {
17432   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17433
17434   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17435   if (!IntrData)
17436     return SDValue();
17437
17438   SDLoc dl(Op);
17439   switch(IntrData->Type) {
17440   default:
17441     llvm_unreachable("Unknown Intrinsic Type");
17442     break;
17443   case RDSEED:
17444   case RDRAND: {
17445     // Emit the node with the right value type.
17446     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17447     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17448
17449     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17450     // Otherwise return the value from Rand, which is always 0, casted to i32.
17451     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17452                       DAG.getConstant(1, Op->getValueType(1)),
17453                       DAG.getConstant(X86::COND_B, MVT::i32),
17454                       SDValue(Result.getNode(), 1) };
17455     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17456                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17457                                   Ops);
17458
17459     // Return { result, isValid, chain }.
17460     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17461                        SDValue(Result.getNode(), 2));
17462   }
17463   case GATHER: {
17464   //gather(v1, mask, index, base, scale);
17465     SDValue Chain = Op.getOperand(0);
17466     SDValue Src   = Op.getOperand(2);
17467     SDValue Base  = Op.getOperand(3);
17468     SDValue Index = Op.getOperand(4);
17469     SDValue Mask  = Op.getOperand(5);
17470     SDValue Scale = Op.getOperand(6);
17471     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
17472                           Subtarget);
17473   }
17474   case SCATTER: {
17475   //scatter(base, mask, index, v1, scale);
17476     SDValue Chain = Op.getOperand(0);
17477     SDValue Base  = Op.getOperand(2);
17478     SDValue Mask  = Op.getOperand(3);
17479     SDValue Index = Op.getOperand(4);
17480     SDValue Src   = Op.getOperand(5);
17481     SDValue Scale = Op.getOperand(6);
17482     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
17483   }
17484   case PREFETCH: {
17485     SDValue Hint = Op.getOperand(6);
17486     unsigned HintVal;
17487     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
17488         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
17489       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
17490     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17491     SDValue Chain = Op.getOperand(0);
17492     SDValue Mask  = Op.getOperand(2);
17493     SDValue Index = Op.getOperand(3);
17494     SDValue Base  = Op.getOperand(4);
17495     SDValue Scale = Op.getOperand(5);
17496     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17497   }
17498   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17499   case RDTSC: {
17500     SmallVector<SDValue, 2> Results;
17501     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
17502     return DAG.getMergeValues(Results, dl);
17503   }
17504   // Read Performance Monitoring Counters.
17505   case RDPMC: {
17506     SmallVector<SDValue, 2> Results;
17507     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17508     return DAG.getMergeValues(Results, dl);
17509   }
17510   // XTEST intrinsics.
17511   case XTEST: {
17512     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17513     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17514     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17515                                 DAG.getConstant(X86::COND_NE, MVT::i8),
17516                                 InTrans);
17517     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17518     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17519                        Ret, SDValue(InTrans.getNode(), 1));
17520   }
17521   // ADC/ADCX/SBB
17522   case ADX: {
17523     SmallVector<SDValue, 2> Results;
17524     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17525     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17526     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17527                                 DAG.getConstant(-1, MVT::i8));
17528     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17529                               Op.getOperand(4), GenCF.getValue(1));
17530     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17531                                  Op.getOperand(5), MachinePointerInfo(),
17532                                  false, false, 0);
17533     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17534                                 DAG.getConstant(X86::COND_B, MVT::i8),
17535                                 Res.getValue(1));
17536     Results.push_back(SetCC);
17537     Results.push_back(Store);
17538     return DAG.getMergeValues(Results, dl);
17539   }
17540   case COMPRESS_TO_MEM: {
17541     SDLoc dl(Op);
17542     SDValue Mask = Op.getOperand(4);
17543     SDValue DataToCompress = Op.getOperand(3);
17544     SDValue Addr = Op.getOperand(2);
17545     SDValue Chain = Op.getOperand(0);
17546
17547     if (isAllOnes(Mask)) // return just a store
17548       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17549                           MachinePointerInfo(), false, false, 0);
17550
17551     EVT VT = DataToCompress.getValueType();
17552     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17553                                   VT.getVectorNumElements());
17554     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17555                                      Mask.getValueType().getSizeInBits());
17556     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17557                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17558                                 DAG.getIntPtrConstant(0));
17559
17560     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
17561                                       DataToCompress, DAG.getUNDEF(VT));
17562     return DAG.getStore(Chain, dl, Compressed, Addr,
17563                         MachinePointerInfo(), false, false, 0);
17564   }
17565   case EXPAND_FROM_MEM: {
17566     SDLoc dl(Op);
17567     SDValue Mask = Op.getOperand(4);
17568     SDValue PathThru = Op.getOperand(3);
17569     SDValue Addr = Op.getOperand(2);
17570     SDValue Chain = Op.getOperand(0);
17571     EVT VT = Op.getValueType();
17572
17573     if (isAllOnes(Mask)) // return just a load
17574       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17575                          false, 0);
17576     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17577                                   VT.getVectorNumElements());
17578     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17579                                      Mask.getValueType().getSizeInBits());
17580     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17581                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17582                                 DAG.getIntPtrConstant(0));
17583
17584     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17585                                    false, false, false, 0);
17586
17587     SmallVector<SDValue, 2> Results;
17588     Results.push_back(DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand,
17589                                   PathThru));
17590     Results.push_back(Chain);
17591     return DAG.getMergeValues(Results, dl);
17592   }
17593   }
17594 }
17595
17596 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17597                                            SelectionDAG &DAG) const {
17598   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17599   MFI->setReturnAddressIsTaken(true);
17600
17601   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17602     return SDValue();
17603
17604   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17605   SDLoc dl(Op);
17606   EVT PtrVT = getPointerTy();
17607
17608   if (Depth > 0) {
17609     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17610     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17611         DAG.getSubtarget().getRegisterInfo());
17612     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
17613     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17614                        DAG.getNode(ISD::ADD, dl, PtrVT,
17615                                    FrameAddr, Offset),
17616                        MachinePointerInfo(), false, false, false, 0);
17617   }
17618
17619   // Just load the return address.
17620   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17621   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17622                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17623 }
17624
17625 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17626   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17627   MFI->setFrameAddressIsTaken(true);
17628
17629   EVT VT = Op.getValueType();
17630   SDLoc dl(Op);  // FIXME probably not meaningful
17631   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17632   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17633       DAG.getSubtarget().getRegisterInfo());
17634   unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(
17635       DAG.getMachineFunction());
17636   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17637           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17638          "Invalid Frame Register!");
17639   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17640   while (Depth--)
17641     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17642                             MachinePointerInfo(),
17643                             false, false, false, 0);
17644   return FrameAddr;
17645 }
17646
17647 // FIXME? Maybe this could be a TableGen attribute on some registers and
17648 // this table could be generated automatically from RegInfo.
17649 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
17650                                               EVT VT) const {
17651   unsigned Reg = StringSwitch<unsigned>(RegName)
17652                        .Case("esp", X86::ESP)
17653                        .Case("rsp", X86::RSP)
17654                        .Default(0);
17655   if (Reg)
17656     return Reg;
17657   report_fatal_error("Invalid register name global variable");
17658 }
17659
17660 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17661                                                      SelectionDAG &DAG) const {
17662   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17663       DAG.getSubtarget().getRegisterInfo());
17664   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
17665 }
17666
17667 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17668   SDValue Chain     = Op.getOperand(0);
17669   SDValue Offset    = Op.getOperand(1);
17670   SDValue Handler   = Op.getOperand(2);
17671   SDLoc dl      (Op);
17672
17673   EVT PtrVT = getPointerTy();
17674   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17675       DAG.getSubtarget().getRegisterInfo());
17676   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17677   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17678           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17679          "Invalid Frame Register!");
17680   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17681   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17682
17683   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17684                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
17685   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17686   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17687                        false, false, 0);
17688   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17689
17690   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17691                      DAG.getRegister(StoreAddrReg, PtrVT));
17692 }
17693
17694 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17695                                                SelectionDAG &DAG) const {
17696   SDLoc DL(Op);
17697   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17698                      DAG.getVTList(MVT::i32, MVT::Other),
17699                      Op.getOperand(0), Op.getOperand(1));
17700 }
17701
17702 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17703                                                 SelectionDAG &DAG) const {
17704   SDLoc DL(Op);
17705   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17706                      Op.getOperand(0), Op.getOperand(1));
17707 }
17708
17709 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17710   return Op.getOperand(0);
17711 }
17712
17713 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17714                                                 SelectionDAG &DAG) const {
17715   SDValue Root = Op.getOperand(0);
17716   SDValue Trmp = Op.getOperand(1); // trampoline
17717   SDValue FPtr = Op.getOperand(2); // nested function
17718   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17719   SDLoc dl (Op);
17720
17721   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17722   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
17723
17724   if (Subtarget->is64Bit()) {
17725     SDValue OutChains[6];
17726
17727     // Large code-model.
17728     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17729     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17730
17731     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17732     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17733
17734     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17735
17736     // Load the pointer to the nested function into R11.
17737     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17738     SDValue Addr = Trmp;
17739     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17740                                 Addr, MachinePointerInfo(TrmpAddr),
17741                                 false, false, 0);
17742
17743     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17744                        DAG.getConstant(2, MVT::i64));
17745     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17746                                 MachinePointerInfo(TrmpAddr, 2),
17747                                 false, false, 2);
17748
17749     // Load the 'nest' parameter value into R10.
17750     // R10 is specified in X86CallingConv.td
17751     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17752     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17753                        DAG.getConstant(10, MVT::i64));
17754     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17755                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17756                                 false, false, 0);
17757
17758     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17759                        DAG.getConstant(12, MVT::i64));
17760     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17761                                 MachinePointerInfo(TrmpAddr, 12),
17762                                 false, false, 2);
17763
17764     // Jump to the nested function.
17765     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17766     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17767                        DAG.getConstant(20, MVT::i64));
17768     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17769                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17770                                 false, false, 0);
17771
17772     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17773     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17774                        DAG.getConstant(22, MVT::i64));
17775     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
17776                                 MachinePointerInfo(TrmpAddr, 22),
17777                                 false, false, 0);
17778
17779     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17780   } else {
17781     const Function *Func =
17782       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17783     CallingConv::ID CC = Func->getCallingConv();
17784     unsigned NestReg;
17785
17786     switch (CC) {
17787     default:
17788       llvm_unreachable("Unsupported calling convention");
17789     case CallingConv::C:
17790     case CallingConv::X86_StdCall: {
17791       // Pass 'nest' parameter in ECX.
17792       // Must be kept in sync with X86CallingConv.td
17793       NestReg = X86::ECX;
17794
17795       // Check that ECX wasn't needed by an 'inreg' parameter.
17796       FunctionType *FTy = Func->getFunctionType();
17797       const AttributeSet &Attrs = Func->getAttributes();
17798
17799       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17800         unsigned InRegCount = 0;
17801         unsigned Idx = 1;
17802
17803         for (FunctionType::param_iterator I = FTy->param_begin(),
17804              E = FTy->param_end(); I != E; ++I, ++Idx)
17805           if (Attrs.hasAttribute(Idx, Attribute::InReg))
17806             // FIXME: should only count parameters that are lowered to integers.
17807             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
17808
17809         if (InRegCount > 2) {
17810           report_fatal_error("Nest register in use - reduce number of inreg"
17811                              " parameters!");
17812         }
17813       }
17814       break;
17815     }
17816     case CallingConv::X86_FastCall:
17817     case CallingConv::X86_ThisCall:
17818     case CallingConv::Fast:
17819       // Pass 'nest' parameter in EAX.
17820       // Must be kept in sync with X86CallingConv.td
17821       NestReg = X86::EAX;
17822       break;
17823     }
17824
17825     SDValue OutChains[4];
17826     SDValue Addr, Disp;
17827
17828     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17829                        DAG.getConstant(10, MVT::i32));
17830     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17831
17832     // This is storing the opcode for MOV32ri.
17833     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17834     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17835     OutChains[0] = DAG.getStore(Root, dl,
17836                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
17837                                 Trmp, MachinePointerInfo(TrmpAddr),
17838                                 false, false, 0);
17839
17840     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17841                        DAG.getConstant(1, MVT::i32));
17842     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17843                                 MachinePointerInfo(TrmpAddr, 1),
17844                                 false, false, 1);
17845
17846     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17847     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17848                        DAG.getConstant(5, MVT::i32));
17849     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
17850                                 MachinePointerInfo(TrmpAddr, 5),
17851                                 false, false, 1);
17852
17853     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17854                        DAG.getConstant(6, MVT::i32));
17855     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17856                                 MachinePointerInfo(TrmpAddr, 6),
17857                                 false, false, 1);
17858
17859     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17860   }
17861 }
17862
17863 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17864                                             SelectionDAG &DAG) const {
17865   /*
17866    The rounding mode is in bits 11:10 of FPSR, and has the following
17867    settings:
17868      00 Round to nearest
17869      01 Round to -inf
17870      10 Round to +inf
17871      11 Round to 0
17872
17873   FLT_ROUNDS, on the other hand, expects the following:
17874     -1 Undefined
17875      0 Round to 0
17876      1 Round to nearest
17877      2 Round to +inf
17878      3 Round to -inf
17879
17880   To perform the conversion, we do:
17881     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17882   */
17883
17884   MachineFunction &MF = DAG.getMachineFunction();
17885   const TargetMachine &TM = MF.getTarget();
17886   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
17887   unsigned StackAlignment = TFI.getStackAlignment();
17888   MVT VT = Op.getSimpleValueType();
17889   SDLoc DL(Op);
17890
17891   // Save FP Control Word to stack slot
17892   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17893   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
17894
17895   MachineMemOperand *MMO =
17896    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
17897                            MachineMemOperand::MOStore, 2, 2);
17898
17899   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17900   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17901                                           DAG.getVTList(MVT::Other),
17902                                           Ops, MVT::i16, MMO);
17903
17904   // Load FP Control Word from stack slot
17905   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17906                             MachinePointerInfo(), false, false, false, 0);
17907
17908   // Transform as necessary
17909   SDValue CWD1 =
17910     DAG.getNode(ISD::SRL, DL, MVT::i16,
17911                 DAG.getNode(ISD::AND, DL, MVT::i16,
17912                             CWD, DAG.getConstant(0x800, MVT::i16)),
17913                 DAG.getConstant(11, MVT::i8));
17914   SDValue CWD2 =
17915     DAG.getNode(ISD::SRL, DL, MVT::i16,
17916                 DAG.getNode(ISD::AND, DL, MVT::i16,
17917                             CWD, DAG.getConstant(0x400, MVT::i16)),
17918                 DAG.getConstant(9, MVT::i8));
17919
17920   SDValue RetVal =
17921     DAG.getNode(ISD::AND, DL, MVT::i16,
17922                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17923                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17924                             DAG.getConstant(1, MVT::i16)),
17925                 DAG.getConstant(3, MVT::i16));
17926
17927   return DAG.getNode((VT.getSizeInBits() < 16 ?
17928                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17929 }
17930
17931 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17932   MVT VT = Op.getSimpleValueType();
17933   EVT OpVT = VT;
17934   unsigned NumBits = VT.getSizeInBits();
17935   SDLoc dl(Op);
17936
17937   Op = Op.getOperand(0);
17938   if (VT == MVT::i8) {
17939     // Zero extend to i32 since there is not an i8 bsr.
17940     OpVT = MVT::i32;
17941     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17942   }
17943
17944   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17945   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17946   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17947
17948   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17949   SDValue Ops[] = {
17950     Op,
17951     DAG.getConstant(NumBits+NumBits-1, OpVT),
17952     DAG.getConstant(X86::COND_E, MVT::i8),
17953     Op.getValue(1)
17954   };
17955   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17956
17957   // Finally xor with NumBits-1.
17958   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17959
17960   if (VT == MVT::i8)
17961     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17962   return Op;
17963 }
17964
17965 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17966   MVT VT = Op.getSimpleValueType();
17967   EVT OpVT = VT;
17968   unsigned NumBits = VT.getSizeInBits();
17969   SDLoc dl(Op);
17970
17971   Op = Op.getOperand(0);
17972   if (VT == MVT::i8) {
17973     // Zero extend to i32 since there is not an i8 bsr.
17974     OpVT = MVT::i32;
17975     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17976   }
17977
17978   // Issue a bsr (scan bits in reverse).
17979   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17980   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17981
17982   // And xor with NumBits-1.
17983   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17984
17985   if (VT == MVT::i8)
17986     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17987   return Op;
17988 }
17989
17990 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17991   MVT VT = Op.getSimpleValueType();
17992   unsigned NumBits = VT.getSizeInBits();
17993   SDLoc dl(Op);
17994   Op = Op.getOperand(0);
17995
17996   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17997   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17998   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17999
18000   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18001   SDValue Ops[] = {
18002     Op,
18003     DAG.getConstant(NumBits, VT),
18004     DAG.getConstant(X86::COND_E, MVT::i8),
18005     Op.getValue(1)
18006   };
18007   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18008 }
18009
18010 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18011 // ones, and then concatenate the result back.
18012 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18013   MVT VT = Op.getSimpleValueType();
18014
18015   assert(VT.is256BitVector() && VT.isInteger() &&
18016          "Unsupported value type for operation");
18017
18018   unsigned NumElems = VT.getVectorNumElements();
18019   SDLoc dl(Op);
18020
18021   // Extract the LHS vectors
18022   SDValue LHS = Op.getOperand(0);
18023   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18024   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18025
18026   // Extract the RHS vectors
18027   SDValue RHS = Op.getOperand(1);
18028   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18029   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18030
18031   MVT EltVT = VT.getVectorElementType();
18032   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18033
18034   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18035                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18036                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18037 }
18038
18039 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18040   assert(Op.getSimpleValueType().is256BitVector() &&
18041          Op.getSimpleValueType().isInteger() &&
18042          "Only handle AVX 256-bit vector integer operation");
18043   return Lower256IntArith(Op, DAG);
18044 }
18045
18046 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18047   assert(Op.getSimpleValueType().is256BitVector() &&
18048          Op.getSimpleValueType().isInteger() &&
18049          "Only handle AVX 256-bit vector integer operation");
18050   return Lower256IntArith(Op, DAG);
18051 }
18052
18053 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18054                         SelectionDAG &DAG) {
18055   SDLoc dl(Op);
18056   MVT VT = Op.getSimpleValueType();
18057
18058   // Decompose 256-bit ops into smaller 128-bit ops.
18059   if (VT.is256BitVector() && !Subtarget->hasInt256())
18060     return Lower256IntArith(Op, DAG);
18061
18062   SDValue A = Op.getOperand(0);
18063   SDValue B = Op.getOperand(1);
18064
18065   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18066   if (VT == MVT::v4i32) {
18067     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18068            "Should not custom lower when pmuldq is available!");
18069
18070     // Extract the odd parts.
18071     static const int UnpackMask[] = { 1, -1, 3, -1 };
18072     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18073     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18074
18075     // Multiply the even parts.
18076     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18077     // Now multiply odd parts.
18078     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18079
18080     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
18081     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
18082
18083     // Merge the two vectors back together with a shuffle. This expands into 2
18084     // shuffles.
18085     static const int ShufMask[] = { 0, 4, 2, 6 };
18086     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18087   }
18088
18089   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18090          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18091
18092   //  Ahi = psrlqi(a, 32);
18093   //  Bhi = psrlqi(b, 32);
18094   //
18095   //  AloBlo = pmuludq(a, b);
18096   //  AloBhi = pmuludq(a, Bhi);
18097   //  AhiBlo = pmuludq(Ahi, b);
18098
18099   //  AloBhi = psllqi(AloBhi, 32);
18100   //  AhiBlo = psllqi(AhiBlo, 32);
18101   //  return AloBlo + AloBhi + AhiBlo;
18102
18103   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18104   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18105
18106   // Bit cast to 32-bit vectors for MULUDQ
18107   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18108                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18109   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
18110   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
18111   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
18112   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
18113
18114   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18115   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18116   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18117
18118   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18119   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18120
18121   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18122   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18123 }
18124
18125 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18126   assert(Subtarget->isTargetWin64() && "Unexpected target");
18127   EVT VT = Op.getValueType();
18128   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18129          "Unexpected return type for lowering");
18130
18131   RTLIB::Libcall LC;
18132   bool isSigned;
18133   switch (Op->getOpcode()) {
18134   default: llvm_unreachable("Unexpected request for libcall!");
18135   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18136   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18137   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18138   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18139   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18140   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18141   }
18142
18143   SDLoc dl(Op);
18144   SDValue InChain = DAG.getEntryNode();
18145
18146   TargetLowering::ArgListTy Args;
18147   TargetLowering::ArgListEntry Entry;
18148   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18149     EVT ArgVT = Op->getOperand(i).getValueType();
18150     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18151            "Unexpected argument type for lowering");
18152     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18153     Entry.Node = StackPtr;
18154     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18155                            false, false, 16);
18156     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18157     Entry.Ty = PointerType::get(ArgTy,0);
18158     Entry.isSExt = false;
18159     Entry.isZExt = false;
18160     Args.push_back(Entry);
18161   }
18162
18163   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18164                                          getPointerTy());
18165
18166   TargetLowering::CallLoweringInfo CLI(DAG);
18167   CLI.setDebugLoc(dl).setChain(InChain)
18168     .setCallee(getLibcallCallingConv(LC),
18169                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18170                Callee, std::move(Args), 0)
18171     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18172
18173   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18174   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
18175 }
18176
18177 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18178                              SelectionDAG &DAG) {
18179   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18180   EVT VT = Op0.getValueType();
18181   SDLoc dl(Op);
18182
18183   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18184          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18185
18186   // PMULxD operations multiply each even value (starting at 0) of LHS with
18187   // the related value of RHS and produce a widen result.
18188   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18189   // => <2 x i64> <ae|cg>
18190   //
18191   // In other word, to have all the results, we need to perform two PMULxD:
18192   // 1. one with the even values.
18193   // 2. one with the odd values.
18194   // To achieve #2, with need to place the odd values at an even position.
18195   //
18196   // Place the odd value at an even position (basically, shift all values 1
18197   // step to the left):
18198   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18199   // <a|b|c|d> => <b|undef|d|undef>
18200   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18201   // <e|f|g|h> => <f|undef|h|undef>
18202   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18203
18204   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18205   // ints.
18206   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18207   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18208   unsigned Opcode =
18209       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18210   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18211   // => <2 x i64> <ae|cg>
18212   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
18213                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18214   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18215   // => <2 x i64> <bf|dh>
18216   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
18217                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18218
18219   // Shuffle it back into the right order.
18220   SDValue Highs, Lows;
18221   if (VT == MVT::v8i32) {
18222     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18223     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18224     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18225     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18226   } else {
18227     const int HighMask[] = {1, 5, 3, 7};
18228     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18229     const int LowMask[] = {0, 4, 2, 6};
18230     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18231   }
18232
18233   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18234   // unsigned multiply.
18235   if (IsSigned && !Subtarget->hasSSE41()) {
18236     SDValue ShAmt =
18237         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
18238     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18239                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18240     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18241                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18242
18243     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18244     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18245   }
18246
18247   // The first result of MUL_LOHI is actually the low value, followed by the
18248   // high value.
18249   SDValue Ops[] = {Lows, Highs};
18250   return DAG.getMergeValues(Ops, dl);
18251 }
18252
18253 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18254                                          const X86Subtarget *Subtarget) {
18255   MVT VT = Op.getSimpleValueType();
18256   SDLoc dl(Op);
18257   SDValue R = Op.getOperand(0);
18258   SDValue Amt = Op.getOperand(1);
18259
18260   // Optimize shl/srl/sra with constant shift amount.
18261   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18262     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18263       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18264
18265       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
18266           (Subtarget->hasInt256() &&
18267            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18268           (Subtarget->hasAVX512() &&
18269            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18270         if (Op.getOpcode() == ISD::SHL)
18271           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18272                                             DAG);
18273         if (Op.getOpcode() == ISD::SRL)
18274           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18275                                             DAG);
18276         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
18277           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18278                                             DAG);
18279       }
18280
18281       if (VT == MVT::v16i8) {
18282         if (Op.getOpcode() == ISD::SHL) {
18283           // Make a large shift.
18284           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18285                                                    MVT::v8i16, R, ShiftAmt,
18286                                                    DAG);
18287           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18288           // Zero out the rightmost bits.
18289           SmallVector<SDValue, 16> V(16,
18290                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18291                                                      MVT::i8));
18292           return DAG.getNode(ISD::AND, dl, VT, SHL,
18293                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18294         }
18295         if (Op.getOpcode() == ISD::SRL) {
18296           // Make a large shift.
18297           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18298                                                    MVT::v8i16, R, ShiftAmt,
18299                                                    DAG);
18300           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18301           // Zero out the leftmost bits.
18302           SmallVector<SDValue, 16> V(16,
18303                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18304                                                      MVT::i8));
18305           return DAG.getNode(ISD::AND, dl, VT, SRL,
18306                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18307         }
18308         if (Op.getOpcode() == ISD::SRA) {
18309           if (ShiftAmt == 7) {
18310             // R s>> 7  ===  R s< 0
18311             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18312             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18313           }
18314
18315           // R s>> a === ((R u>> a) ^ m) - m
18316           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18317           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
18318                                                          MVT::i8));
18319           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18320           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18321           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18322           return Res;
18323         }
18324         llvm_unreachable("Unknown shift opcode.");
18325       }
18326
18327       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
18328         if (Op.getOpcode() == ISD::SHL) {
18329           // Make a large shift.
18330           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18331                                                    MVT::v16i16, R, ShiftAmt,
18332                                                    DAG);
18333           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18334           // Zero out the rightmost bits.
18335           SmallVector<SDValue, 32> V(32,
18336                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18337                                                      MVT::i8));
18338           return DAG.getNode(ISD::AND, dl, VT, SHL,
18339                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18340         }
18341         if (Op.getOpcode() == ISD::SRL) {
18342           // Make a large shift.
18343           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18344                                                    MVT::v16i16, R, ShiftAmt,
18345                                                    DAG);
18346           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18347           // Zero out the leftmost bits.
18348           SmallVector<SDValue, 32> V(32,
18349                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18350                                                      MVT::i8));
18351           return DAG.getNode(ISD::AND, dl, VT, SRL,
18352                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18353         }
18354         if (Op.getOpcode() == ISD::SRA) {
18355           if (ShiftAmt == 7) {
18356             // R s>> 7  ===  R s< 0
18357             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18358             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18359           }
18360
18361           // R s>> a === ((R u>> a) ^ m) - m
18362           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18363           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
18364                                                          MVT::i8));
18365           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18366           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18367           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18368           return Res;
18369         }
18370         llvm_unreachable("Unknown shift opcode.");
18371       }
18372     }
18373   }
18374
18375   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18376   if (!Subtarget->is64Bit() &&
18377       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18378       Amt.getOpcode() == ISD::BITCAST &&
18379       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18380     Amt = Amt.getOperand(0);
18381     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18382                      VT.getVectorNumElements();
18383     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18384     uint64_t ShiftAmt = 0;
18385     for (unsigned i = 0; i != Ratio; ++i) {
18386       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
18387       if (!C)
18388         return SDValue();
18389       // 6 == Log2(64)
18390       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18391     }
18392     // Check remaining shift amounts.
18393     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18394       uint64_t ShAmt = 0;
18395       for (unsigned j = 0; j != Ratio; ++j) {
18396         ConstantSDNode *C =
18397           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18398         if (!C)
18399           return SDValue();
18400         // 6 == Log2(64)
18401         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18402       }
18403       if (ShAmt != ShiftAmt)
18404         return SDValue();
18405     }
18406     switch (Op.getOpcode()) {
18407     default:
18408       llvm_unreachable("Unknown shift opcode!");
18409     case ISD::SHL:
18410       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18411                                         DAG);
18412     case ISD::SRL:
18413       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18414                                         DAG);
18415     case ISD::SRA:
18416       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18417                                         DAG);
18418     }
18419   }
18420
18421   return SDValue();
18422 }
18423
18424 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18425                                         const X86Subtarget* Subtarget) {
18426   MVT VT = Op.getSimpleValueType();
18427   SDLoc dl(Op);
18428   SDValue R = Op.getOperand(0);
18429   SDValue Amt = Op.getOperand(1);
18430
18431   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
18432       VT == MVT::v4i32 || VT == MVT::v8i16 ||
18433       (Subtarget->hasInt256() &&
18434        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
18435         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18436        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18437     SDValue BaseShAmt;
18438     EVT EltVT = VT.getVectorElementType();
18439
18440     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18441       // Check if this build_vector node is doing a splat.
18442       // If so, then set BaseShAmt equal to the splat value.
18443       BaseShAmt = BV->getSplatValue();
18444       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18445         BaseShAmt = SDValue();
18446     } else {
18447       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18448         Amt = Amt.getOperand(0);
18449
18450       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18451       if (SVN && SVN->isSplat()) {
18452         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18453         SDValue InVec = Amt.getOperand(0);
18454         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18455           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18456                  "Unexpected shuffle index found!");
18457           BaseShAmt = InVec.getOperand(SplatIdx);
18458         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18459            if (ConstantSDNode *C =
18460                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18461              if (C->getZExtValue() == SplatIdx)
18462                BaseShAmt = InVec.getOperand(1);
18463            }
18464         }
18465
18466         if (!BaseShAmt)
18467           // Avoid introducing an extract element from a shuffle.
18468           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18469                                     DAG.getIntPtrConstant(SplatIdx));
18470       }
18471     }
18472
18473     if (BaseShAmt.getNode()) {
18474       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18475       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18476         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18477       else if (EltVT.bitsLT(MVT::i32))
18478         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18479
18480       switch (Op.getOpcode()) {
18481       default:
18482         llvm_unreachable("Unknown shift opcode!");
18483       case ISD::SHL:
18484         switch (VT.SimpleTy) {
18485         default: return SDValue();
18486         case MVT::v2i64:
18487         case MVT::v4i32:
18488         case MVT::v8i16:
18489         case MVT::v4i64:
18490         case MVT::v8i32:
18491         case MVT::v16i16:
18492         case MVT::v16i32:
18493         case MVT::v8i64:
18494           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
18495         }
18496       case ISD::SRA:
18497         switch (VT.SimpleTy) {
18498         default: return SDValue();
18499         case MVT::v4i32:
18500         case MVT::v8i16:
18501         case MVT::v8i32:
18502         case MVT::v16i16:
18503         case MVT::v16i32:
18504         case MVT::v8i64:
18505           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
18506         }
18507       case ISD::SRL:
18508         switch (VT.SimpleTy) {
18509         default: return SDValue();
18510         case MVT::v2i64:
18511         case MVT::v4i32:
18512         case MVT::v8i16:
18513         case MVT::v4i64:
18514         case MVT::v8i32:
18515         case MVT::v16i16:
18516         case MVT::v16i32:
18517         case MVT::v8i64:
18518           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
18519         }
18520       }
18521     }
18522   }
18523
18524   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18525   if (!Subtarget->is64Bit() &&
18526       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
18527       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
18528       Amt.getOpcode() == ISD::BITCAST &&
18529       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18530     Amt = Amt.getOperand(0);
18531     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18532                      VT.getVectorNumElements();
18533     std::vector<SDValue> Vals(Ratio);
18534     for (unsigned i = 0; i != Ratio; ++i)
18535       Vals[i] = Amt.getOperand(i);
18536     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18537       for (unsigned j = 0; j != Ratio; ++j)
18538         if (Vals[j] != Amt.getOperand(i + j))
18539           return SDValue();
18540     }
18541     switch (Op.getOpcode()) {
18542     default:
18543       llvm_unreachable("Unknown shift opcode!");
18544     case ISD::SHL:
18545       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
18546     case ISD::SRL:
18547       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
18548     case ISD::SRA:
18549       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
18550     }
18551   }
18552
18553   return SDValue();
18554 }
18555
18556 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18557                           SelectionDAG &DAG) {
18558   MVT VT = Op.getSimpleValueType();
18559   SDLoc dl(Op);
18560   SDValue R = Op.getOperand(0);
18561   SDValue Amt = Op.getOperand(1);
18562   SDValue V;
18563
18564   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18565   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18566
18567   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
18568   if (V.getNode())
18569     return V;
18570
18571   V = LowerScalarVariableShift(Op, DAG, Subtarget);
18572   if (V.getNode())
18573       return V;
18574
18575   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
18576     return Op;
18577   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
18578   if (Subtarget->hasInt256()) {
18579     if (Op.getOpcode() == ISD::SRL &&
18580         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18581          VT == MVT::v4i64 || VT == MVT::v8i32))
18582       return Op;
18583     if (Op.getOpcode() == ISD::SHL &&
18584         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18585          VT == MVT::v4i64 || VT == MVT::v8i32))
18586       return Op;
18587     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
18588       return Op;
18589   }
18590
18591   // If possible, lower this packed shift into a vector multiply instead of
18592   // expanding it into a sequence of scalar shifts.
18593   // Do this only if the vector shift count is a constant build_vector.
18594   if (Op.getOpcode() == ISD::SHL &&
18595       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18596        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18597       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18598     SmallVector<SDValue, 8> Elts;
18599     EVT SVT = VT.getScalarType();
18600     unsigned SVTBits = SVT.getSizeInBits();
18601     const APInt &One = APInt(SVTBits, 1);
18602     unsigned NumElems = VT.getVectorNumElements();
18603
18604     for (unsigned i=0; i !=NumElems; ++i) {
18605       SDValue Op = Amt->getOperand(i);
18606       if (Op->getOpcode() == ISD::UNDEF) {
18607         Elts.push_back(Op);
18608         continue;
18609       }
18610
18611       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18612       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18613       uint64_t ShAmt = C.getZExtValue();
18614       if (ShAmt >= SVTBits) {
18615         Elts.push_back(DAG.getUNDEF(SVT));
18616         continue;
18617       }
18618       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
18619     }
18620     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18621     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18622   }
18623
18624   // Lower SHL with variable shift amount.
18625   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18626     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
18627
18628     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
18629     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
18630     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18631     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18632   }
18633
18634   // If possible, lower this shift as a sequence of two shifts by
18635   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18636   // Example:
18637   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18638   //
18639   // Could be rewritten as:
18640   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18641   //
18642   // The advantage is that the two shifts from the example would be
18643   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18644   // the vector shift into four scalar shifts plus four pairs of vector
18645   // insert/extract.
18646   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18647       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18648     unsigned TargetOpcode = X86ISD::MOVSS;
18649     bool CanBeSimplified;
18650     // The splat value for the first packed shift (the 'X' from the example).
18651     SDValue Amt1 = Amt->getOperand(0);
18652     // The splat value for the second packed shift (the 'Y' from the example).
18653     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18654                                         Amt->getOperand(2);
18655
18656     // See if it is possible to replace this node with a sequence of
18657     // two shifts followed by a MOVSS/MOVSD
18658     if (VT == MVT::v4i32) {
18659       // Check if it is legal to use a MOVSS.
18660       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18661                         Amt2 == Amt->getOperand(3);
18662       if (!CanBeSimplified) {
18663         // Otherwise, check if we can still simplify this node using a MOVSD.
18664         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18665                           Amt->getOperand(2) == Amt->getOperand(3);
18666         TargetOpcode = X86ISD::MOVSD;
18667         Amt2 = Amt->getOperand(2);
18668       }
18669     } else {
18670       // Do similar checks for the case where the machine value type
18671       // is MVT::v8i16.
18672       CanBeSimplified = Amt1 == Amt->getOperand(1);
18673       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18674         CanBeSimplified = Amt2 == Amt->getOperand(i);
18675
18676       if (!CanBeSimplified) {
18677         TargetOpcode = X86ISD::MOVSD;
18678         CanBeSimplified = true;
18679         Amt2 = Amt->getOperand(4);
18680         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18681           CanBeSimplified = Amt1 == Amt->getOperand(i);
18682         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18683           CanBeSimplified = Amt2 == Amt->getOperand(j);
18684       }
18685     }
18686
18687     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18688         isa<ConstantSDNode>(Amt2)) {
18689       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18690       EVT CastVT = MVT::v4i32;
18691       SDValue Splat1 =
18692         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
18693       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18694       SDValue Splat2 =
18695         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
18696       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18697       if (TargetOpcode == X86ISD::MOVSD)
18698         CastVT = MVT::v2i64;
18699       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
18700       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
18701       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18702                                             BitCast1, DAG);
18703       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
18704     }
18705   }
18706
18707   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
18708     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
18709
18710     // a = a << 5;
18711     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
18712     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
18713
18714     // Turn 'a' into a mask suitable for VSELECT
18715     SDValue VSelM = DAG.getConstant(0x80, VT);
18716     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18717     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18718
18719     SDValue CM1 = DAG.getConstant(0x0f, VT);
18720     SDValue CM2 = DAG.getConstant(0x3f, VT);
18721
18722     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
18723     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
18724     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
18725     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18726     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18727
18728     // a += a
18729     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18730     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18731     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18732
18733     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
18734     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
18735     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
18736     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18737     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18738
18739     // a += a
18740     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18741     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18742     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18743
18744     // return VSELECT(r, r+r, a);
18745     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
18746                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
18747     return R;
18748   }
18749
18750   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18751   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18752   // solution better.
18753   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18754     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
18755     unsigned ExtOpc =
18756         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18757     R = DAG.getNode(ExtOpc, dl, NewVT, R);
18758     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
18759     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18760                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
18761     }
18762
18763   // Decompose 256-bit shifts into smaller 128-bit shifts.
18764   if (VT.is256BitVector()) {
18765     unsigned NumElems = VT.getVectorNumElements();
18766     MVT EltVT = VT.getVectorElementType();
18767     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18768
18769     // Extract the two vectors
18770     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18771     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18772
18773     // Recreate the shift amount vectors
18774     SDValue Amt1, Amt2;
18775     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18776       // Constant shift amount
18777       SmallVector<SDValue, 4> Amt1Csts;
18778       SmallVector<SDValue, 4> Amt2Csts;
18779       for (unsigned i = 0; i != NumElems/2; ++i)
18780         Amt1Csts.push_back(Amt->getOperand(i));
18781       for (unsigned i = NumElems/2; i != NumElems; ++i)
18782         Amt2Csts.push_back(Amt->getOperand(i));
18783
18784       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18785       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18786     } else {
18787       // Variable shift amount
18788       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18789       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18790     }
18791
18792     // Issue new vector shifts for the smaller types
18793     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18794     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18795
18796     // Concatenate the result back
18797     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18798   }
18799
18800   return SDValue();
18801 }
18802
18803 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18804   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18805   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18806   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18807   // has only one use.
18808   SDNode *N = Op.getNode();
18809   SDValue LHS = N->getOperand(0);
18810   SDValue RHS = N->getOperand(1);
18811   unsigned BaseOp = 0;
18812   unsigned Cond = 0;
18813   SDLoc DL(Op);
18814   switch (Op.getOpcode()) {
18815   default: llvm_unreachable("Unknown ovf instruction!");
18816   case ISD::SADDO:
18817     // A subtract of one will be selected as a INC. Note that INC doesn't
18818     // set CF, so we can't do this for UADDO.
18819     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18820       if (C->isOne()) {
18821         BaseOp = X86ISD::INC;
18822         Cond = X86::COND_O;
18823         break;
18824       }
18825     BaseOp = X86ISD::ADD;
18826     Cond = X86::COND_O;
18827     break;
18828   case ISD::UADDO:
18829     BaseOp = X86ISD::ADD;
18830     Cond = X86::COND_B;
18831     break;
18832   case ISD::SSUBO:
18833     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18834     // set CF, so we can't do this for USUBO.
18835     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18836       if (C->isOne()) {
18837         BaseOp = X86ISD::DEC;
18838         Cond = X86::COND_O;
18839         break;
18840       }
18841     BaseOp = X86ISD::SUB;
18842     Cond = X86::COND_O;
18843     break;
18844   case ISD::USUBO:
18845     BaseOp = X86ISD::SUB;
18846     Cond = X86::COND_B;
18847     break;
18848   case ISD::SMULO:
18849     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18850     Cond = X86::COND_O;
18851     break;
18852   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18853     if (N->getValueType(0) == MVT::i8) {
18854       BaseOp = X86ISD::UMUL8;
18855       Cond = X86::COND_O;
18856       break;
18857     }
18858     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18859                                  MVT::i32);
18860     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18861
18862     SDValue SetCC =
18863       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18864                   DAG.getConstant(X86::COND_O, MVT::i32),
18865                   SDValue(Sum.getNode(), 2));
18866
18867     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18868   }
18869   }
18870
18871   // Also sets EFLAGS.
18872   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18873   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18874
18875   SDValue SetCC =
18876     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18877                 DAG.getConstant(Cond, MVT::i32),
18878                 SDValue(Sum.getNode(), 1));
18879
18880   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18881 }
18882
18883 // Sign extension of the low part of vector elements. This may be used either
18884 // when sign extend instructions are not available or if the vector element
18885 // sizes already match the sign-extended size. If the vector elements are in
18886 // their pre-extended size and sign extend instructions are available, that will
18887 // be handled by LowerSIGN_EXTEND.
18888 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
18889                                                   SelectionDAG &DAG) const {
18890   SDLoc dl(Op);
18891   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
18892   MVT VT = Op.getSimpleValueType();
18893
18894   if (!Subtarget->hasSSE2() || !VT.isVector())
18895     return SDValue();
18896
18897   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
18898                       ExtraVT.getScalarType().getSizeInBits();
18899
18900   switch (VT.SimpleTy) {
18901     default: return SDValue();
18902     case MVT::v8i32:
18903     case MVT::v16i16:
18904       if (!Subtarget->hasFp256())
18905         return SDValue();
18906       if (!Subtarget->hasInt256()) {
18907         // needs to be split
18908         unsigned NumElems = VT.getVectorNumElements();
18909
18910         // Extract the LHS vectors
18911         SDValue LHS = Op.getOperand(0);
18912         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18913         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18914
18915         MVT EltVT = VT.getVectorElementType();
18916         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18917
18918         EVT ExtraEltVT = ExtraVT.getVectorElementType();
18919         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
18920         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
18921                                    ExtraNumElems/2);
18922         SDValue Extra = DAG.getValueType(ExtraVT);
18923
18924         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
18925         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
18926
18927         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
18928       }
18929       // fall through
18930     case MVT::v4i32:
18931     case MVT::v8i16: {
18932       SDValue Op0 = Op.getOperand(0);
18933
18934       // This is a sign extension of some low part of vector elements without
18935       // changing the size of the vector elements themselves:
18936       // Shift-Left + Shift-Right-Algebraic.
18937       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
18938                                                BitsDiff, DAG);
18939       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
18940                                         DAG);
18941     }
18942   }
18943 }
18944
18945 /// Returns true if the operand type is exactly twice the native width, and
18946 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18947 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18948 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18949 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
18950   const X86Subtarget &Subtarget =
18951       getTargetMachine().getSubtarget<X86Subtarget>();
18952   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18953
18954   if (OpWidth == 64)
18955     return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18956   else if (OpWidth == 128)
18957     return Subtarget.hasCmpxchg16b();
18958   else
18959     return false;
18960 }
18961
18962 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18963   return needsCmpXchgNb(SI->getValueOperand()->getType());
18964 }
18965
18966 // Note: this turns large loads into lock cmpxchg8b/16b.
18967 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18968 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18969   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18970   return needsCmpXchgNb(PTy->getElementType());
18971 }
18972
18973 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18974   const X86Subtarget &Subtarget =
18975       getTargetMachine().getSubtarget<X86Subtarget>();
18976   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
18977   const Type *MemType = AI->getType();
18978
18979   // If the operand is too big, we must see if cmpxchg8/16b is available
18980   // and default to library calls otherwise.
18981   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18982     return needsCmpXchgNb(MemType);
18983
18984   AtomicRMWInst::BinOp Op = AI->getOperation();
18985   switch (Op) {
18986   default:
18987     llvm_unreachable("Unknown atomic operation");
18988   case AtomicRMWInst::Xchg:
18989   case AtomicRMWInst::Add:
18990   case AtomicRMWInst::Sub:
18991     // It's better to use xadd, xsub or xchg for these in all cases.
18992     return false;
18993   case AtomicRMWInst::Or:
18994   case AtomicRMWInst::And:
18995   case AtomicRMWInst::Xor:
18996     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18997     // prefix to a normal instruction for these operations.
18998     return !AI->use_empty();
18999   case AtomicRMWInst::Nand:
19000   case AtomicRMWInst::Max:
19001   case AtomicRMWInst::Min:
19002   case AtomicRMWInst::UMax:
19003   case AtomicRMWInst::UMin:
19004     // These always require a non-trivial set of data operations on x86. We must
19005     // use a cmpxchg loop.
19006     return true;
19007   }
19008 }
19009
19010 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19011   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19012   // no-sse2). There isn't any reason to disable it if the target processor
19013   // supports it.
19014   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19015 }
19016
19017 LoadInst *
19018 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19019   const X86Subtarget &Subtarget =
19020       getTargetMachine().getSubtarget<X86Subtarget>();
19021   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
19022   const Type *MemType = AI->getType();
19023   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19024   // there is no benefit in turning such RMWs into loads, and it is actually
19025   // harmful as it introduces a mfence.
19026   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19027     return nullptr;
19028
19029   auto Builder = IRBuilder<>(AI);
19030   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19031   auto SynchScope = AI->getSynchScope();
19032   // We must restrict the ordering to avoid generating loads with Release or
19033   // ReleaseAcquire orderings.
19034   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19035   auto Ptr = AI->getPointerOperand();
19036
19037   // Before the load we need a fence. Here is an example lifted from
19038   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19039   // is required:
19040   // Thread 0:
19041   //   x.store(1, relaxed);
19042   //   r1 = y.fetch_add(0, release);
19043   // Thread 1:
19044   //   y.fetch_add(42, acquire);
19045   //   r2 = x.load(relaxed);
19046   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19047   // lowered to just a load without a fence. A mfence flushes the store buffer,
19048   // making the optimization clearly correct.
19049   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19050   // otherwise, we might be able to be more agressive on relaxed idempotent
19051   // rmw. In practice, they do not look useful, so we don't try to be
19052   // especially clever.
19053   if (SynchScope == SingleThread) {
19054     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19055     // the IR level, so we must wrap it in an intrinsic.
19056     return nullptr;
19057   } else if (hasMFENCE(Subtarget)) {
19058     Function *MFence = llvm::Intrinsic::getDeclaration(M,
19059             Intrinsic::x86_sse2_mfence);
19060     Builder.CreateCall(MFence);
19061   } else {
19062     // FIXME: it might make sense to use a locked operation here but on a
19063     // different cache-line to prevent cache-line bouncing. In practice it
19064     // is probably a small win, and x86 processors without mfence are rare
19065     // enough that we do not bother.
19066     return nullptr;
19067   }
19068
19069   // Finally we can emit the atomic load.
19070   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19071           AI->getType()->getPrimitiveSizeInBits());
19072   Loaded->setAtomic(Order, SynchScope);
19073   AI->replaceAllUsesWith(Loaded);
19074   AI->eraseFromParent();
19075   return Loaded;
19076 }
19077
19078 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19079                                  SelectionDAG &DAG) {
19080   SDLoc dl(Op);
19081   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19082     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19083   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19084     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19085
19086   // The only fence that needs an instruction is a sequentially-consistent
19087   // cross-thread fence.
19088   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19089     if (hasMFENCE(*Subtarget))
19090       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19091
19092     SDValue Chain = Op.getOperand(0);
19093     SDValue Zero = DAG.getConstant(0, MVT::i32);
19094     SDValue Ops[] = {
19095       DAG.getRegister(X86::ESP, MVT::i32), // Base
19096       DAG.getTargetConstant(1, MVT::i8),   // Scale
19097       DAG.getRegister(0, MVT::i32),        // Index
19098       DAG.getTargetConstant(0, MVT::i32),  // Disp
19099       DAG.getRegister(0, MVT::i32),        // Segment.
19100       Zero,
19101       Chain
19102     };
19103     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19104     return SDValue(Res, 0);
19105   }
19106
19107   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19108   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19109 }
19110
19111 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19112                              SelectionDAG &DAG) {
19113   MVT T = Op.getSimpleValueType();
19114   SDLoc DL(Op);
19115   unsigned Reg = 0;
19116   unsigned size = 0;
19117   switch(T.SimpleTy) {
19118   default: llvm_unreachable("Invalid value type!");
19119   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19120   case MVT::i16: Reg = X86::AX;  size = 2; break;
19121   case MVT::i32: Reg = X86::EAX; size = 4; break;
19122   case MVT::i64:
19123     assert(Subtarget->is64Bit() && "Node not type legal!");
19124     Reg = X86::RAX; size = 8;
19125     break;
19126   }
19127   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19128                                   Op.getOperand(2), SDValue());
19129   SDValue Ops[] = { cpIn.getValue(0),
19130                     Op.getOperand(1),
19131                     Op.getOperand(3),
19132                     DAG.getTargetConstant(size, MVT::i8),
19133                     cpIn.getValue(1) };
19134   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19135   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19136   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19137                                            Ops, T, MMO);
19138
19139   SDValue cpOut =
19140     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19141   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19142                                       MVT::i32, cpOut.getValue(2));
19143   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19144                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19145
19146   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19147   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19148   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19149   return SDValue();
19150 }
19151
19152 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19153                             SelectionDAG &DAG) {
19154   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19155   MVT DstVT = Op.getSimpleValueType();
19156
19157   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19158     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19159     if (DstVT != MVT::f64)
19160       // This conversion needs to be expanded.
19161       return SDValue();
19162
19163     SDValue InVec = Op->getOperand(0);
19164     SDLoc dl(Op);
19165     unsigned NumElts = SrcVT.getVectorNumElements();
19166     EVT SVT = SrcVT.getVectorElementType();
19167
19168     // Widen the vector in input in the case of MVT::v2i32.
19169     // Example: from MVT::v2i32 to MVT::v4i32.
19170     SmallVector<SDValue, 16> Elts;
19171     for (unsigned i = 0, e = NumElts; i != e; ++i)
19172       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19173                                  DAG.getIntPtrConstant(i)));
19174
19175     // Explicitly mark the extra elements as Undef.
19176     SDValue Undef = DAG.getUNDEF(SVT);
19177     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
19178       Elts.push_back(Undef);
19179
19180     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19181     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19182     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
19183     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19184                        DAG.getIntPtrConstant(0));
19185   }
19186
19187   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19188          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19189   assert((DstVT == MVT::i64 ||
19190           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19191          "Unexpected custom BITCAST");
19192   // i64 <=> MMX conversions are Legal.
19193   if (SrcVT==MVT::i64 && DstVT.isVector())
19194     return Op;
19195   if (DstVT==MVT::i64 && SrcVT.isVector())
19196     return Op;
19197   // MMX <=> MMX conversions are Legal.
19198   if (SrcVT.isVector() && DstVT.isVector())
19199     return Op;
19200   // All other conversions need to be expanded.
19201   return SDValue();
19202 }
19203
19204 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19205                           SelectionDAG &DAG) {
19206   SDNode *Node = Op.getNode();
19207   SDLoc dl(Node);
19208
19209   Op = Op.getOperand(0);
19210   EVT VT = Op.getValueType();
19211   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19212          "CTPOP lowering only implemented for 128/256-bit wide vector types");
19213
19214   unsigned NumElts = VT.getVectorNumElements();
19215   EVT EltVT = VT.getVectorElementType();
19216   unsigned Len = EltVT.getSizeInBits();
19217
19218   // This is the vectorized version of the "best" algorithm from
19219   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19220   // with a minor tweak to use a series of adds + shifts instead of vector
19221   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
19222   //
19223   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
19224   //  v8i32 => Always profitable
19225   //
19226   // FIXME: There a couple of possible improvements:
19227   //
19228   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
19229   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
19230   //
19231   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
19232          "CTPOP not implemented for this vector element type.");
19233
19234   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
19235   // extra legalization.
19236   bool NeedsBitcast = EltVT == MVT::i32;
19237   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
19238
19239   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
19240   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
19241   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
19242
19243   // v = v - ((v >> 1) & 0x55555555...)
19244   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
19245   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
19246   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
19247   if (NeedsBitcast)
19248     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
19249
19250   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
19251   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
19252   if (NeedsBitcast)
19253     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
19254
19255   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
19256   if (VT != And.getValueType())
19257     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19258   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
19259
19260   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19261   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
19262   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
19263   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
19264   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
19265
19266   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
19267   if (NeedsBitcast) {
19268     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
19269     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
19270     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
19271   }
19272
19273   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
19274   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
19275   if (VT != AndRHS.getValueType()) {
19276     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
19277     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
19278   }
19279   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
19280
19281   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19282   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
19283   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
19284   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
19285   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
19286
19287   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
19288   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
19289   if (NeedsBitcast) {
19290     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
19291     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
19292   }
19293   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
19294   if (VT != And.getValueType())
19295     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19296
19297   // The algorithm mentioned above uses:
19298   //    v = (v * 0x01010101...) >> (Len - 8)
19299   //
19300   // Change it to use vector adds + vector shifts which yield faster results on
19301   // Haswell than using vector integer multiplication.
19302   //
19303   // For i32 elements:
19304   //    v = v + (v >> 8)
19305   //    v = v + (v >> 16)
19306   //
19307   // For i64 elements:
19308   //    v = v + (v >> 8)
19309   //    v = v + (v >> 16)
19310   //    v = v + (v >> 32)
19311   //
19312   Add = And;
19313   SmallVector<SDValue, 8> Csts;
19314   for (unsigned i = 8; i <= Len/2; i *= 2) {
19315     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
19316     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
19317     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
19318     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
19319     Csts.clear();
19320   }
19321
19322   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
19323   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
19324   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
19325   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
19326   if (NeedsBitcast) {
19327     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
19328     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
19329   }
19330   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
19331   if (VT != And.getValueType())
19332     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
19333
19334   return And;
19335 }
19336
19337 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19338   SDNode *Node = Op.getNode();
19339   SDLoc dl(Node);
19340   EVT T = Node->getValueType(0);
19341   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19342                               DAG.getConstant(0, T), Node->getOperand(2));
19343   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19344                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19345                        Node->getOperand(0),
19346                        Node->getOperand(1), negOp,
19347                        cast<AtomicSDNode>(Node)->getMemOperand(),
19348                        cast<AtomicSDNode>(Node)->getOrdering(),
19349                        cast<AtomicSDNode>(Node)->getSynchScope());
19350 }
19351
19352 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19353   SDNode *Node = Op.getNode();
19354   SDLoc dl(Node);
19355   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19356
19357   // Convert seq_cst store -> xchg
19358   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19359   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19360   //        (The only way to get a 16-byte store is cmpxchg16b)
19361   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19362   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19363       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19364     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19365                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19366                                  Node->getOperand(0),
19367                                  Node->getOperand(1), Node->getOperand(2),
19368                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19369                                  cast<AtomicSDNode>(Node)->getOrdering(),
19370                                  cast<AtomicSDNode>(Node)->getSynchScope());
19371     return Swap.getValue(1);
19372   }
19373   // Other atomic stores have a simple pattern.
19374   return Op;
19375 }
19376
19377 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19378   EVT VT = Op.getNode()->getSimpleValueType(0);
19379
19380   // Let legalize expand this if it isn't a legal type yet.
19381   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19382     return SDValue();
19383
19384   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19385
19386   unsigned Opc;
19387   bool ExtraOp = false;
19388   switch (Op.getOpcode()) {
19389   default: llvm_unreachable("Invalid code");
19390   case ISD::ADDC: Opc = X86ISD::ADD; break;
19391   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19392   case ISD::SUBC: Opc = X86ISD::SUB; break;
19393   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19394   }
19395
19396   if (!ExtraOp)
19397     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19398                        Op.getOperand(1));
19399   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19400                      Op.getOperand(1), Op.getOperand(2));
19401 }
19402
19403 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19404                             SelectionDAG &DAG) {
19405   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19406
19407   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19408   // which returns the values as { float, float } (in XMM0) or
19409   // { double, double } (which is returned in XMM0, XMM1).
19410   SDLoc dl(Op);
19411   SDValue Arg = Op.getOperand(0);
19412   EVT ArgVT = Arg.getValueType();
19413   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19414
19415   TargetLowering::ArgListTy Args;
19416   TargetLowering::ArgListEntry Entry;
19417
19418   Entry.Node = Arg;
19419   Entry.Ty = ArgTy;
19420   Entry.isSExt = false;
19421   Entry.isZExt = false;
19422   Args.push_back(Entry);
19423
19424   bool isF64 = ArgVT == MVT::f64;
19425   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19426   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19427   // the results are returned via SRet in memory.
19428   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19429   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19430   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
19431
19432   Type *RetTy = isF64
19433     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19434     : (Type*)VectorType::get(ArgTy, 4);
19435
19436   TargetLowering::CallLoweringInfo CLI(DAG);
19437   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19438     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19439
19440   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19441
19442   if (isF64)
19443     // Returned in xmm0 and xmm1.
19444     return CallResult.first;
19445
19446   // Returned in bits 0:31 and 32:64 xmm0.
19447   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19448                                CallResult.first, DAG.getIntPtrConstant(0));
19449   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19450                                CallResult.first, DAG.getIntPtrConstant(1));
19451   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19452   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19453 }
19454
19455 /// LowerOperation - Provide custom lowering hooks for some operations.
19456 ///
19457 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19458   switch (Op.getOpcode()) {
19459   default: llvm_unreachable("Should not custom lower this!");
19460   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
19461   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19462   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19463     return LowerCMP_SWAP(Op, Subtarget, DAG);
19464   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19465   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19466   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19467   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19468   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
19469   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
19470   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19471   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19472   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19473   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19474   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19475   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19476   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19477   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19478   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19479   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19480   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19481   case ISD::SHL_PARTS:
19482   case ISD::SRA_PARTS:
19483   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19484   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19485   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19486   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19487   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19488   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19489   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19490   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19491   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19492   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19493   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19494   case ISD::FABS:
19495   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19496   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19497   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19498   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19499   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19500   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19501   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19502   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19503   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19504   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19505   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19506   case ISD::INTRINSIC_VOID:
19507   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19508   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19509   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19510   case ISD::FRAME_TO_ARGS_OFFSET:
19511                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19512   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19513   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19514   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19515   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19516   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19517   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19518   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19519   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19520   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19521   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
19522   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19523   case ISD::UMUL_LOHI:
19524   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19525   case ISD::SRA:
19526   case ISD::SRL:
19527   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19528   case ISD::SADDO:
19529   case ISD::UADDO:
19530   case ISD::SSUBO:
19531   case ISD::USUBO:
19532   case ISD::SMULO:
19533   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19534   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19535   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19536   case ISD::ADDC:
19537   case ISD::ADDE:
19538   case ISD::SUBC:
19539   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19540   case ISD::ADD:                return LowerADD(Op, DAG);
19541   case ISD::SUB:                return LowerSUB(Op, DAG);
19542   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19543   }
19544 }
19545
19546 /// ReplaceNodeResults - Replace a node with an illegal result type
19547 /// with a new node built out of custom code.
19548 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19549                                            SmallVectorImpl<SDValue>&Results,
19550                                            SelectionDAG &DAG) const {
19551   SDLoc dl(N);
19552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19553   switch (N->getOpcode()) {
19554   default:
19555     llvm_unreachable("Do not know how to custom type legalize this operation!");
19556   case ISD::SIGN_EXTEND_INREG:
19557   case ISD::ADDC:
19558   case ISD::ADDE:
19559   case ISD::SUBC:
19560   case ISD::SUBE:
19561     // We don't want to expand or promote these.
19562     return;
19563   case ISD::SDIV:
19564   case ISD::UDIV:
19565   case ISD::SREM:
19566   case ISD::UREM:
19567   case ISD::SDIVREM:
19568   case ISD::UDIVREM: {
19569     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19570     Results.push_back(V);
19571     return;
19572   }
19573   case ISD::FP_TO_SINT:
19574   case ISD::FP_TO_UINT: {
19575     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19576
19577     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
19578       return;
19579
19580     std::pair<SDValue,SDValue> Vals =
19581         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19582     SDValue FIST = Vals.first, StackSlot = Vals.second;
19583     if (FIST.getNode()) {
19584       EVT VT = N->getValueType(0);
19585       // Return a load from the stack slot.
19586       if (StackSlot.getNode())
19587         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19588                                       MachinePointerInfo(),
19589                                       false, false, false, 0));
19590       else
19591         Results.push_back(FIST);
19592     }
19593     return;
19594   }
19595   case ISD::UINT_TO_FP: {
19596     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19597     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19598         N->getValueType(0) != MVT::v2f32)
19599       return;
19600     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19601                                  N->getOperand(0));
19602     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
19603                                      MVT::f64);
19604     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19605     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19606                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
19607     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
19608     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19609     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19610     return;
19611   }
19612   case ISD::FP_ROUND: {
19613     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19614         return;
19615     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19616     Results.push_back(V);
19617     return;
19618   }
19619   case ISD::INTRINSIC_W_CHAIN: {
19620     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19621     switch (IntNo) {
19622     default : llvm_unreachable("Do not know how to custom type "
19623                                "legalize this intrinsic operation!");
19624     case Intrinsic::x86_rdtsc:
19625       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19626                                      Results);
19627     case Intrinsic::x86_rdtscp:
19628       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19629                                      Results);
19630     case Intrinsic::x86_rdpmc:
19631       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19632     }
19633   }
19634   case ISD::READCYCLECOUNTER: {
19635     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19636                                    Results);
19637   }
19638   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19639     EVT T = N->getValueType(0);
19640     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19641     bool Regs64bit = T == MVT::i128;
19642     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19643     SDValue cpInL, cpInH;
19644     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19645                         DAG.getConstant(0, HalfT));
19646     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19647                         DAG.getConstant(1, HalfT));
19648     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19649                              Regs64bit ? X86::RAX : X86::EAX,
19650                              cpInL, SDValue());
19651     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19652                              Regs64bit ? X86::RDX : X86::EDX,
19653                              cpInH, cpInL.getValue(1));
19654     SDValue swapInL, swapInH;
19655     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19656                           DAG.getConstant(0, HalfT));
19657     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19658                           DAG.getConstant(1, HalfT));
19659     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19660                                Regs64bit ? X86::RBX : X86::EBX,
19661                                swapInL, cpInH.getValue(1));
19662     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19663                                Regs64bit ? X86::RCX : X86::ECX,
19664                                swapInH, swapInL.getValue(1));
19665     SDValue Ops[] = { swapInH.getValue(0),
19666                       N->getOperand(1),
19667                       swapInH.getValue(1) };
19668     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19669     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19670     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19671                                   X86ISD::LCMPXCHG8_DAG;
19672     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19673     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19674                                         Regs64bit ? X86::RAX : X86::EAX,
19675                                         HalfT, Result.getValue(1));
19676     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19677                                         Regs64bit ? X86::RDX : X86::EDX,
19678                                         HalfT, cpOutL.getValue(2));
19679     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19680
19681     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19682                                         MVT::i32, cpOutH.getValue(2));
19683     SDValue Success =
19684         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19685                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19686     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19687
19688     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19689     Results.push_back(Success);
19690     Results.push_back(EFLAGS.getValue(1));
19691     return;
19692   }
19693   case ISD::ATOMIC_SWAP:
19694   case ISD::ATOMIC_LOAD_ADD:
19695   case ISD::ATOMIC_LOAD_SUB:
19696   case ISD::ATOMIC_LOAD_AND:
19697   case ISD::ATOMIC_LOAD_OR:
19698   case ISD::ATOMIC_LOAD_XOR:
19699   case ISD::ATOMIC_LOAD_NAND:
19700   case ISD::ATOMIC_LOAD_MIN:
19701   case ISD::ATOMIC_LOAD_MAX:
19702   case ISD::ATOMIC_LOAD_UMIN:
19703   case ISD::ATOMIC_LOAD_UMAX:
19704   case ISD::ATOMIC_LOAD: {
19705     // Delegate to generic TypeLegalization. Situations we can really handle
19706     // should have already been dealt with by AtomicExpandPass.cpp.
19707     break;
19708   }
19709   case ISD::BITCAST: {
19710     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19711     EVT DstVT = N->getValueType(0);
19712     EVT SrcVT = N->getOperand(0)->getValueType(0);
19713
19714     if (SrcVT != MVT::f64 ||
19715         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19716       return;
19717
19718     unsigned NumElts = DstVT.getVectorNumElements();
19719     EVT SVT = DstVT.getVectorElementType();
19720     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19721     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19722                                    MVT::v2f64, N->getOperand(0));
19723     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
19724
19725     if (ExperimentalVectorWideningLegalization) {
19726       // If we are legalizing vectors by widening, we already have the desired
19727       // legal vector type, just return it.
19728       Results.push_back(ToVecInt);
19729       return;
19730     }
19731
19732     SmallVector<SDValue, 8> Elts;
19733     for (unsigned i = 0, e = NumElts; i != e; ++i)
19734       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19735                                    ToVecInt, DAG.getIntPtrConstant(i)));
19736
19737     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19738   }
19739   }
19740 }
19741
19742 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19743   switch (Opcode) {
19744   default: return nullptr;
19745   case X86ISD::BSF:                return "X86ISD::BSF";
19746   case X86ISD::BSR:                return "X86ISD::BSR";
19747   case X86ISD::SHLD:               return "X86ISD::SHLD";
19748   case X86ISD::SHRD:               return "X86ISD::SHRD";
19749   case X86ISD::FAND:               return "X86ISD::FAND";
19750   case X86ISD::FANDN:              return "X86ISD::FANDN";
19751   case X86ISD::FOR:                return "X86ISD::FOR";
19752   case X86ISD::FXOR:               return "X86ISD::FXOR";
19753   case X86ISD::FSRL:               return "X86ISD::FSRL";
19754   case X86ISD::FILD:               return "X86ISD::FILD";
19755   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19756   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19757   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19758   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19759   case X86ISD::FLD:                return "X86ISD::FLD";
19760   case X86ISD::FST:                return "X86ISD::FST";
19761   case X86ISD::CALL:               return "X86ISD::CALL";
19762   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19763   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19764   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19765   case X86ISD::BT:                 return "X86ISD::BT";
19766   case X86ISD::CMP:                return "X86ISD::CMP";
19767   case X86ISD::COMI:               return "X86ISD::COMI";
19768   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19769   case X86ISD::CMPM:               return "X86ISD::CMPM";
19770   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19771   case X86ISD::SETCC:              return "X86ISD::SETCC";
19772   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19773   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19774   case X86ISD::CMOV:               return "X86ISD::CMOV";
19775   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19776   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19777   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19778   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19779   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19780   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19781   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19782   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19783   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19784   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19785   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19786   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19787   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19788   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19789   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19790   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19791   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19792   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19793   case X86ISD::HADD:               return "X86ISD::HADD";
19794   case X86ISD::HSUB:               return "X86ISD::HSUB";
19795   case X86ISD::FHADD:              return "X86ISD::FHADD";
19796   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19797   case X86ISD::UMAX:               return "X86ISD::UMAX";
19798   case X86ISD::UMIN:               return "X86ISD::UMIN";
19799   case X86ISD::SMAX:               return "X86ISD::SMAX";
19800   case X86ISD::SMIN:               return "X86ISD::SMIN";
19801   case X86ISD::FMAX:               return "X86ISD::FMAX";
19802   case X86ISD::FMIN:               return "X86ISD::FMIN";
19803   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19804   case X86ISD::FMINC:              return "X86ISD::FMINC";
19805   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19806   case X86ISD::FRCP:               return "X86ISD::FRCP";
19807   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19808   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19809   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19810   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19811   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19812   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19813   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19814   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19815   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19816   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19817   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19818   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19819   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19820   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19821   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19822   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19823   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19824   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
19825   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19826   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19827   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19828   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19829   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19830   case X86ISD::VSHL:               return "X86ISD::VSHL";
19831   case X86ISD::VSRL:               return "X86ISD::VSRL";
19832   case X86ISD::VSRA:               return "X86ISD::VSRA";
19833   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19834   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19835   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19836   case X86ISD::CMPP:               return "X86ISD::CMPP";
19837   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19838   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19839   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19840   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19841   case X86ISD::ADD:                return "X86ISD::ADD";
19842   case X86ISD::SUB:                return "X86ISD::SUB";
19843   case X86ISD::ADC:                return "X86ISD::ADC";
19844   case X86ISD::SBB:                return "X86ISD::SBB";
19845   case X86ISD::SMUL:               return "X86ISD::SMUL";
19846   case X86ISD::UMUL:               return "X86ISD::UMUL";
19847   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19848   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19849   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19850   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19851   case X86ISD::INC:                return "X86ISD::INC";
19852   case X86ISD::DEC:                return "X86ISD::DEC";
19853   case X86ISD::OR:                 return "X86ISD::OR";
19854   case X86ISD::XOR:                return "X86ISD::XOR";
19855   case X86ISD::AND:                return "X86ISD::AND";
19856   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19857   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19858   case X86ISD::PTEST:              return "X86ISD::PTEST";
19859   case X86ISD::TESTP:              return "X86ISD::TESTP";
19860   case X86ISD::TESTM:              return "X86ISD::TESTM";
19861   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19862   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19863   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19864   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19865   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19866   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19867   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19868   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19869   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19870   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19871   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19872   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19873   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19874   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19875   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19876   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19877   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19878   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19879   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19880   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19881   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19882   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19883   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19884   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
19885   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19886   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19887   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19888   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19889   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19890   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19891   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19892   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19893   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19894   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19895   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19896   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19897   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19898   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19899   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19900   case X86ISD::SAHF:               return "X86ISD::SAHF";
19901   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19902   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19903   case X86ISD::FMADD:              return "X86ISD::FMADD";
19904   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19905   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19906   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19907   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19908   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19909   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19910   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19911   case X86ISD::XTEST:              return "X86ISD::XTEST";
19912   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19913   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19914   }
19915 }
19916
19917 // isLegalAddressingMode - Return true if the addressing mode represented
19918 // by AM is legal for this target, for a load/store of the specified type.
19919 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
19920                                               Type *Ty) const {
19921   // X86 supports extremely general addressing modes.
19922   CodeModel::Model M = getTargetMachine().getCodeModel();
19923   Reloc::Model R = getTargetMachine().getRelocationModel();
19924
19925   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19926   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19927     return false;
19928
19929   if (AM.BaseGV) {
19930     unsigned GVFlags =
19931       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19932
19933     // If a reference to this global requires an extra load, we can't fold it.
19934     if (isGlobalStubReference(GVFlags))
19935       return false;
19936
19937     // If BaseGV requires a register for the PIC base, we cannot also have a
19938     // BaseReg specified.
19939     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19940       return false;
19941
19942     // If lower 4G is not available, then we must use rip-relative addressing.
19943     if ((M != CodeModel::Small || R != Reloc::Static) &&
19944         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19945       return false;
19946   }
19947
19948   switch (AM.Scale) {
19949   case 0:
19950   case 1:
19951   case 2:
19952   case 4:
19953   case 8:
19954     // These scales always work.
19955     break;
19956   case 3:
19957   case 5:
19958   case 9:
19959     // These scales are formed with basereg+scalereg.  Only accept if there is
19960     // no basereg yet.
19961     if (AM.HasBaseReg)
19962       return false;
19963     break;
19964   default:  // Other stuff never works.
19965     return false;
19966   }
19967
19968   return true;
19969 }
19970
19971 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19972   unsigned Bits = Ty->getScalarSizeInBits();
19973
19974   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19975   // particularly cheaper than those without.
19976   if (Bits == 8)
19977     return false;
19978
19979   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19980   // variable shifts just as cheap as scalar ones.
19981   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19982     return false;
19983
19984   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19985   // fully general vector.
19986   return true;
19987 }
19988
19989 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19990   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19991     return false;
19992   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19993   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19994   return NumBits1 > NumBits2;
19995 }
19996
19997 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19998   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19999     return false;
20000
20001   if (!isTypeLegal(EVT::getEVT(Ty1)))
20002     return false;
20003
20004   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20005
20006   // Assuming the caller doesn't have a zeroext or signext return parameter,
20007   // truncation all the way down to i1 is valid.
20008   return true;
20009 }
20010
20011 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20012   return isInt<32>(Imm);
20013 }
20014
20015 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20016   // Can also use sub to handle negated immediates.
20017   return isInt<32>(Imm);
20018 }
20019
20020 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20021   if (!VT1.isInteger() || !VT2.isInteger())
20022     return false;
20023   unsigned NumBits1 = VT1.getSizeInBits();
20024   unsigned NumBits2 = VT2.getSizeInBits();
20025   return NumBits1 > NumBits2;
20026 }
20027
20028 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20029   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20030   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20031 }
20032
20033 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20034   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20035   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20036 }
20037
20038 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20039   EVT VT1 = Val.getValueType();
20040   if (isZExtFree(VT1, VT2))
20041     return true;
20042
20043   if (Val.getOpcode() != ISD::LOAD)
20044     return false;
20045
20046   if (!VT1.isSimple() || !VT1.isInteger() ||
20047       !VT2.isSimple() || !VT2.isInteger())
20048     return false;
20049
20050   switch (VT1.getSimpleVT().SimpleTy) {
20051   default: break;
20052   case MVT::i8:
20053   case MVT::i16:
20054   case MVT::i32:
20055     // X86 has 8, 16, and 32-bit zero-extending loads.
20056     return true;
20057   }
20058
20059   return false;
20060 }
20061
20062 bool
20063 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20064   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
20065     return false;
20066
20067   VT = VT.getScalarType();
20068
20069   if (!VT.isSimple())
20070     return false;
20071
20072   switch (VT.getSimpleVT().SimpleTy) {
20073   case MVT::f32:
20074   case MVT::f64:
20075     return true;
20076   default:
20077     break;
20078   }
20079
20080   return false;
20081 }
20082
20083 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20084   // i16 instructions are longer (0x66 prefix) and potentially slower.
20085   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20086 }
20087
20088 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20089 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20090 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20091 /// are assumed to be legal.
20092 bool
20093 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20094                                       EVT VT) const {
20095   if (!VT.isSimple())
20096     return false;
20097
20098   MVT SVT = VT.getSimpleVT();
20099
20100   // Very little shuffling can be done for 64-bit vectors right now.
20101   if (VT.getSizeInBits() == 64)
20102     return false;
20103
20104   // If this is a single-input shuffle with no 128 bit lane crossings we can
20105   // lower it into pshufb.
20106   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
20107       (SVT.is256BitVector() && Subtarget->hasInt256())) {
20108     bool isLegal = true;
20109     for (unsigned I = 0, E = M.size(); I != E; ++I) {
20110       if (M[I] >= (int)SVT.getVectorNumElements() ||
20111           ShuffleCrosses128bitLane(SVT, I, M[I])) {
20112         isLegal = false;
20113         break;
20114       }
20115     }
20116     if (isLegal)
20117       return true;
20118   }
20119
20120   // FIXME: blends, shifts.
20121   return (SVT.getVectorNumElements() == 2 ||
20122           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
20123           isMOVLMask(M, SVT) ||
20124           isCommutedMOVLMask(M, SVT) ||
20125           isMOVHLPSMask(M, SVT) ||
20126           isSHUFPMask(M, SVT) ||
20127           isSHUFPMask(M, SVT, /* Commuted */ true) ||
20128           isPSHUFDMask(M, SVT) ||
20129           isPSHUFDMask(M, SVT, /* SecondOperand */ true) ||
20130           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
20131           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
20132           isPALIGNRMask(M, SVT, Subtarget) ||
20133           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
20134           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
20135           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
20136           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
20137           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()) ||
20138           (Subtarget->hasSSE41() && isINSERTPSMask(M, SVT)));
20139 }
20140
20141 bool
20142 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20143                                           EVT VT) const {
20144   if (!VT.isSimple())
20145     return false;
20146
20147   MVT SVT = VT.getSimpleVT();
20148   unsigned NumElts = SVT.getVectorNumElements();
20149   // FIXME: This collection of masks seems suspect.
20150   if (NumElts == 2)
20151     return true;
20152   if (NumElts == 4 && SVT.is128BitVector()) {
20153     return (isMOVLMask(Mask, SVT)  ||
20154             isCommutedMOVLMask(Mask, SVT, true) ||
20155             isSHUFPMask(Mask, SVT) ||
20156             isSHUFPMask(Mask, SVT, /* Commuted */ true) ||
20157             isBlendMask(Mask, SVT, Subtarget->hasSSE41(),
20158                         Subtarget->hasInt256()));
20159   }
20160   return false;
20161 }
20162
20163 //===----------------------------------------------------------------------===//
20164 //                           X86 Scheduler Hooks
20165 //===----------------------------------------------------------------------===//
20166
20167 /// Utility function to emit xbegin specifying the start of an RTM region.
20168 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20169                                      const TargetInstrInfo *TII) {
20170   DebugLoc DL = MI->getDebugLoc();
20171
20172   const BasicBlock *BB = MBB->getBasicBlock();
20173   MachineFunction::iterator I = MBB;
20174   ++I;
20175
20176   // For the v = xbegin(), we generate
20177   //
20178   // thisMBB:
20179   //  xbegin sinkMBB
20180   //
20181   // mainMBB:
20182   //  eax = -1
20183   //
20184   // sinkMBB:
20185   //  v = eax
20186
20187   MachineBasicBlock *thisMBB = MBB;
20188   MachineFunction *MF = MBB->getParent();
20189   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20190   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20191   MF->insert(I, mainMBB);
20192   MF->insert(I, sinkMBB);
20193
20194   // Transfer the remainder of BB and its successor edges to sinkMBB.
20195   sinkMBB->splice(sinkMBB->begin(), MBB,
20196                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20197   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20198
20199   // thisMBB:
20200   //  xbegin sinkMBB
20201   //  # fallthrough to mainMBB
20202   //  # abortion to sinkMBB
20203   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20204   thisMBB->addSuccessor(mainMBB);
20205   thisMBB->addSuccessor(sinkMBB);
20206
20207   // mainMBB:
20208   //  EAX = -1
20209   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20210   mainMBB->addSuccessor(sinkMBB);
20211
20212   // sinkMBB:
20213   // EAX is live into the sinkMBB
20214   sinkMBB->addLiveIn(X86::EAX);
20215   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20216           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20217     .addReg(X86::EAX);
20218
20219   MI->eraseFromParent();
20220   return sinkMBB;
20221 }
20222
20223 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20224 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20225 // in the .td file.
20226 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20227                                        const TargetInstrInfo *TII) {
20228   unsigned Opc;
20229   switch (MI->getOpcode()) {
20230   default: llvm_unreachable("illegal opcode!");
20231   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20232   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20233   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20234   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20235   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20236   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20237   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20238   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20239   }
20240
20241   DebugLoc dl = MI->getDebugLoc();
20242   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20243
20244   unsigned NumArgs = MI->getNumOperands();
20245   for (unsigned i = 1; i < NumArgs; ++i) {
20246     MachineOperand &Op = MI->getOperand(i);
20247     if (!(Op.isReg() && Op.isImplicit()))
20248       MIB.addOperand(Op);
20249   }
20250   if (MI->hasOneMemOperand())
20251     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20252
20253   BuildMI(*BB, MI, dl,
20254     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20255     .addReg(X86::XMM0);
20256
20257   MI->eraseFromParent();
20258   return BB;
20259 }
20260
20261 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20262 // defs in an instruction pattern
20263 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20264                                        const TargetInstrInfo *TII) {
20265   unsigned Opc;
20266   switch (MI->getOpcode()) {
20267   default: llvm_unreachable("illegal opcode!");
20268   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20269   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20270   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20271   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20272   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20273   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20274   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20275   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20276   }
20277
20278   DebugLoc dl = MI->getDebugLoc();
20279   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20280
20281   unsigned NumArgs = MI->getNumOperands(); // remove the results
20282   for (unsigned i = 1; i < NumArgs; ++i) {
20283     MachineOperand &Op = MI->getOperand(i);
20284     if (!(Op.isReg() && Op.isImplicit()))
20285       MIB.addOperand(Op);
20286   }
20287   if (MI->hasOneMemOperand())
20288     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20289
20290   BuildMI(*BB, MI, dl,
20291     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20292     .addReg(X86::ECX);
20293
20294   MI->eraseFromParent();
20295   return BB;
20296 }
20297
20298 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20299                                        const TargetInstrInfo *TII,
20300                                        const X86Subtarget* Subtarget) {
20301   DebugLoc dl = MI->getDebugLoc();
20302
20303   // Address into RAX/EAX, other two args into ECX, EDX.
20304   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20305   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20306   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20307   for (int i = 0; i < X86::AddrNumOperands; ++i)
20308     MIB.addOperand(MI->getOperand(i));
20309
20310   unsigned ValOps = X86::AddrNumOperands;
20311   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20312     .addReg(MI->getOperand(ValOps).getReg());
20313   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20314     .addReg(MI->getOperand(ValOps+1).getReg());
20315
20316   // The instruction doesn't actually take any operands though.
20317   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20318
20319   MI->eraseFromParent(); // The pseudo is gone now.
20320   return BB;
20321 }
20322
20323 MachineBasicBlock *
20324 X86TargetLowering::EmitVAARG64WithCustomInserter(
20325                    MachineInstr *MI,
20326                    MachineBasicBlock *MBB) const {
20327   // Emit va_arg instruction on X86-64.
20328
20329   // Operands to this pseudo-instruction:
20330   // 0  ) Output        : destination address (reg)
20331   // 1-5) Input         : va_list address (addr, i64mem)
20332   // 6  ) ArgSize       : Size (in bytes) of vararg type
20333   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20334   // 8  ) Align         : Alignment of type
20335   // 9  ) EFLAGS (implicit-def)
20336
20337   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20338   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
20339
20340   unsigned DestReg = MI->getOperand(0).getReg();
20341   MachineOperand &Base = MI->getOperand(1);
20342   MachineOperand &Scale = MI->getOperand(2);
20343   MachineOperand &Index = MI->getOperand(3);
20344   MachineOperand &Disp = MI->getOperand(4);
20345   MachineOperand &Segment = MI->getOperand(5);
20346   unsigned ArgSize = MI->getOperand(6).getImm();
20347   unsigned ArgMode = MI->getOperand(7).getImm();
20348   unsigned Align = MI->getOperand(8).getImm();
20349
20350   // Memory Reference
20351   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20352   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20353   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20354
20355   // Machine Information
20356   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20357   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20358   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20359   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20360   DebugLoc DL = MI->getDebugLoc();
20361
20362   // struct va_list {
20363   //   i32   gp_offset
20364   //   i32   fp_offset
20365   //   i64   overflow_area (address)
20366   //   i64   reg_save_area (address)
20367   // }
20368   // sizeof(va_list) = 24
20369   // alignment(va_list) = 8
20370
20371   unsigned TotalNumIntRegs = 6;
20372   unsigned TotalNumXMMRegs = 8;
20373   bool UseGPOffset = (ArgMode == 1);
20374   bool UseFPOffset = (ArgMode == 2);
20375   unsigned MaxOffset = TotalNumIntRegs * 8 +
20376                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20377
20378   /* Align ArgSize to a multiple of 8 */
20379   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20380   bool NeedsAlign = (Align > 8);
20381
20382   MachineBasicBlock *thisMBB = MBB;
20383   MachineBasicBlock *overflowMBB;
20384   MachineBasicBlock *offsetMBB;
20385   MachineBasicBlock *endMBB;
20386
20387   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20388   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20389   unsigned OffsetReg = 0;
20390
20391   if (!UseGPOffset && !UseFPOffset) {
20392     // If we only pull from the overflow region, we don't create a branch.
20393     // We don't need to alter control flow.
20394     OffsetDestReg = 0; // unused
20395     OverflowDestReg = DestReg;
20396
20397     offsetMBB = nullptr;
20398     overflowMBB = thisMBB;
20399     endMBB = thisMBB;
20400   } else {
20401     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20402     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20403     // If not, pull from overflow_area. (branch to overflowMBB)
20404     //
20405     //       thisMBB
20406     //         |     .
20407     //         |        .
20408     //     offsetMBB   overflowMBB
20409     //         |        .
20410     //         |     .
20411     //        endMBB
20412
20413     // Registers for the PHI in endMBB
20414     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20415     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20416
20417     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20418     MachineFunction *MF = MBB->getParent();
20419     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20420     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20421     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20422
20423     MachineFunction::iterator MBBIter = MBB;
20424     ++MBBIter;
20425
20426     // Insert the new basic blocks
20427     MF->insert(MBBIter, offsetMBB);
20428     MF->insert(MBBIter, overflowMBB);
20429     MF->insert(MBBIter, endMBB);
20430
20431     // Transfer the remainder of MBB and its successor edges to endMBB.
20432     endMBB->splice(endMBB->begin(), thisMBB,
20433                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20434     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20435
20436     // Make offsetMBB and overflowMBB successors of thisMBB
20437     thisMBB->addSuccessor(offsetMBB);
20438     thisMBB->addSuccessor(overflowMBB);
20439
20440     // endMBB is a successor of both offsetMBB and overflowMBB
20441     offsetMBB->addSuccessor(endMBB);
20442     overflowMBB->addSuccessor(endMBB);
20443
20444     // Load the offset value into a register
20445     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20446     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20447       .addOperand(Base)
20448       .addOperand(Scale)
20449       .addOperand(Index)
20450       .addDisp(Disp, UseFPOffset ? 4 : 0)
20451       .addOperand(Segment)
20452       .setMemRefs(MMOBegin, MMOEnd);
20453
20454     // Check if there is enough room left to pull this argument.
20455     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20456       .addReg(OffsetReg)
20457       .addImm(MaxOffset + 8 - ArgSizeA8);
20458
20459     // Branch to "overflowMBB" if offset >= max
20460     // Fall through to "offsetMBB" otherwise
20461     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20462       .addMBB(overflowMBB);
20463   }
20464
20465   // In offsetMBB, emit code to use the reg_save_area.
20466   if (offsetMBB) {
20467     assert(OffsetReg != 0);
20468
20469     // Read the reg_save_area address.
20470     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20471     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20472       .addOperand(Base)
20473       .addOperand(Scale)
20474       .addOperand(Index)
20475       .addDisp(Disp, 16)
20476       .addOperand(Segment)
20477       .setMemRefs(MMOBegin, MMOEnd);
20478
20479     // Zero-extend the offset
20480     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20481       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20482         .addImm(0)
20483         .addReg(OffsetReg)
20484         .addImm(X86::sub_32bit);
20485
20486     // Add the offset to the reg_save_area to get the final address.
20487     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20488       .addReg(OffsetReg64)
20489       .addReg(RegSaveReg);
20490
20491     // Compute the offset for the next argument
20492     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20493     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20494       .addReg(OffsetReg)
20495       .addImm(UseFPOffset ? 16 : 8);
20496
20497     // Store it back into the va_list.
20498     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20499       .addOperand(Base)
20500       .addOperand(Scale)
20501       .addOperand(Index)
20502       .addDisp(Disp, UseFPOffset ? 4 : 0)
20503       .addOperand(Segment)
20504       .addReg(NextOffsetReg)
20505       .setMemRefs(MMOBegin, MMOEnd);
20506
20507     // Jump to endMBB
20508     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
20509       .addMBB(endMBB);
20510   }
20511
20512   //
20513   // Emit code to use overflow area
20514   //
20515
20516   // Load the overflow_area address into a register.
20517   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20518   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20519     .addOperand(Base)
20520     .addOperand(Scale)
20521     .addOperand(Index)
20522     .addDisp(Disp, 8)
20523     .addOperand(Segment)
20524     .setMemRefs(MMOBegin, MMOEnd);
20525
20526   // If we need to align it, do so. Otherwise, just copy the address
20527   // to OverflowDestReg.
20528   if (NeedsAlign) {
20529     // Align the overflow address
20530     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20531     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20532
20533     // aligned_addr = (addr + (align-1)) & ~(align-1)
20534     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20535       .addReg(OverflowAddrReg)
20536       .addImm(Align-1);
20537
20538     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20539       .addReg(TmpReg)
20540       .addImm(~(uint64_t)(Align-1));
20541   } else {
20542     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20543       .addReg(OverflowAddrReg);
20544   }
20545
20546   // Compute the next overflow address after this argument.
20547   // (the overflow address should be kept 8-byte aligned)
20548   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20549   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20550     .addReg(OverflowDestReg)
20551     .addImm(ArgSizeA8);
20552
20553   // Store the new overflow address.
20554   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20555     .addOperand(Base)
20556     .addOperand(Scale)
20557     .addOperand(Index)
20558     .addDisp(Disp, 8)
20559     .addOperand(Segment)
20560     .addReg(NextAddrReg)
20561     .setMemRefs(MMOBegin, MMOEnd);
20562
20563   // If we branched, emit the PHI to the front of endMBB.
20564   if (offsetMBB) {
20565     BuildMI(*endMBB, endMBB->begin(), DL,
20566             TII->get(X86::PHI), DestReg)
20567       .addReg(OffsetDestReg).addMBB(offsetMBB)
20568       .addReg(OverflowDestReg).addMBB(overflowMBB);
20569   }
20570
20571   // Erase the pseudo instruction
20572   MI->eraseFromParent();
20573
20574   return endMBB;
20575 }
20576
20577 MachineBasicBlock *
20578 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20579                                                  MachineInstr *MI,
20580                                                  MachineBasicBlock *MBB) const {
20581   // Emit code to save XMM registers to the stack. The ABI says that the
20582   // number of registers to save is given in %al, so it's theoretically
20583   // possible to do an indirect jump trick to avoid saving all of them,
20584   // however this code takes a simpler approach and just executes all
20585   // of the stores if %al is non-zero. It's less code, and it's probably
20586   // easier on the hardware branch predictor, and stores aren't all that
20587   // expensive anyway.
20588
20589   // Create the new basic blocks. One block contains all the XMM stores,
20590   // and one block is the final destination regardless of whether any
20591   // stores were performed.
20592   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20593   MachineFunction *F = MBB->getParent();
20594   MachineFunction::iterator MBBIter = MBB;
20595   ++MBBIter;
20596   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20597   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20598   F->insert(MBBIter, XMMSaveMBB);
20599   F->insert(MBBIter, EndMBB);
20600
20601   // Transfer the remainder of MBB and its successor edges to EndMBB.
20602   EndMBB->splice(EndMBB->begin(), MBB,
20603                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20604   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20605
20606   // The original block will now fall through to the XMM save block.
20607   MBB->addSuccessor(XMMSaveMBB);
20608   // The XMMSaveMBB will fall through to the end block.
20609   XMMSaveMBB->addSuccessor(EndMBB);
20610
20611   // Now add the instructions.
20612   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20613   DebugLoc DL = MI->getDebugLoc();
20614
20615   unsigned CountReg = MI->getOperand(0).getReg();
20616   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20617   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20618
20619   if (!Subtarget->isTargetWin64()) {
20620     // If %al is 0, branch around the XMM save block.
20621     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20622     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
20623     MBB->addSuccessor(EndMBB);
20624   }
20625
20626   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20627   // that was just emitted, but clearly shouldn't be "saved".
20628   assert((MI->getNumOperands() <= 3 ||
20629           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20630           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20631          && "Expected last argument to be EFLAGS");
20632   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20633   // In the XMM save block, save all the XMM argument registers.
20634   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20635     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20636     MachineMemOperand *MMO =
20637       F->getMachineMemOperand(
20638           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
20639         MachineMemOperand::MOStore,
20640         /*Size=*/16, /*Align=*/16);
20641     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20642       .addFrameIndex(RegSaveFrameIndex)
20643       .addImm(/*Scale=*/1)
20644       .addReg(/*IndexReg=*/0)
20645       .addImm(/*Disp=*/Offset)
20646       .addReg(/*Segment=*/0)
20647       .addReg(MI->getOperand(i).getReg())
20648       .addMemOperand(MMO);
20649   }
20650
20651   MI->eraseFromParent();   // The pseudo instruction is gone now.
20652
20653   return EndMBB;
20654 }
20655
20656 // The EFLAGS operand of SelectItr might be missing a kill marker
20657 // because there were multiple uses of EFLAGS, and ISel didn't know
20658 // which to mark. Figure out whether SelectItr should have had a
20659 // kill marker, and set it if it should. Returns the correct kill
20660 // marker value.
20661 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20662                                      MachineBasicBlock* BB,
20663                                      const TargetRegisterInfo* TRI) {
20664   // Scan forward through BB for a use/def of EFLAGS.
20665   MachineBasicBlock::iterator miI(std::next(SelectItr));
20666   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20667     const MachineInstr& mi = *miI;
20668     if (mi.readsRegister(X86::EFLAGS))
20669       return false;
20670     if (mi.definesRegister(X86::EFLAGS))
20671       break; // Should have kill-flag - update below.
20672   }
20673
20674   // If we hit the end of the block, check whether EFLAGS is live into a
20675   // successor.
20676   if (miI == BB->end()) {
20677     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20678                                           sEnd = BB->succ_end();
20679          sItr != sEnd; ++sItr) {
20680       MachineBasicBlock* succ = *sItr;
20681       if (succ->isLiveIn(X86::EFLAGS))
20682         return false;
20683     }
20684   }
20685
20686   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20687   // out. SelectMI should have a kill flag on EFLAGS.
20688   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20689   return true;
20690 }
20691
20692 MachineBasicBlock *
20693 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20694                                      MachineBasicBlock *BB) const {
20695   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20696   DebugLoc DL = MI->getDebugLoc();
20697
20698   // To "insert" a SELECT_CC instruction, we actually have to insert the
20699   // diamond control-flow pattern.  The incoming instruction knows the
20700   // destination vreg to set, the condition code register to branch on, the
20701   // true/false values to select between, and a branch opcode to use.
20702   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20703   MachineFunction::iterator It = BB;
20704   ++It;
20705
20706   //  thisMBB:
20707   //  ...
20708   //   TrueVal = ...
20709   //   cmpTY ccX, r1, r2
20710   //   bCC copy1MBB
20711   //   fallthrough --> copy0MBB
20712   MachineBasicBlock *thisMBB = BB;
20713   MachineFunction *F = BB->getParent();
20714   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20715   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20716   F->insert(It, copy0MBB);
20717   F->insert(It, sinkMBB);
20718
20719   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20720   // live into the sink and copy blocks.
20721   const TargetRegisterInfo *TRI =
20722       BB->getParent()->getSubtarget().getRegisterInfo();
20723   if (!MI->killsRegister(X86::EFLAGS) &&
20724       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
20725     copy0MBB->addLiveIn(X86::EFLAGS);
20726     sinkMBB->addLiveIn(X86::EFLAGS);
20727   }
20728
20729   // Transfer the remainder of BB and its successor edges to sinkMBB.
20730   sinkMBB->splice(sinkMBB->begin(), BB,
20731                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
20732   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20733
20734   // Add the true and fallthrough blocks as its successors.
20735   BB->addSuccessor(copy0MBB);
20736   BB->addSuccessor(sinkMBB);
20737
20738   // Create the conditional branch instruction.
20739   unsigned Opc =
20740     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20741   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20742
20743   //  copy0MBB:
20744   //   %FalseValue = ...
20745   //   # fallthrough to sinkMBB
20746   copy0MBB->addSuccessor(sinkMBB);
20747
20748   //  sinkMBB:
20749   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20750   //  ...
20751   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20752           TII->get(X86::PHI), MI->getOperand(0).getReg())
20753     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20754     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20755
20756   MI->eraseFromParent();   // The pseudo instruction is gone now.
20757   return sinkMBB;
20758 }
20759
20760 MachineBasicBlock *
20761 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20762                                         MachineBasicBlock *BB) const {
20763   MachineFunction *MF = BB->getParent();
20764   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20765   DebugLoc DL = MI->getDebugLoc();
20766   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20767
20768   assert(MF->shouldSplitStack());
20769
20770   const bool Is64Bit = Subtarget->is64Bit();
20771   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20772
20773   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20774   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20775
20776   // BB:
20777   //  ... [Till the alloca]
20778   // If stacklet is not large enough, jump to mallocMBB
20779   //
20780   // bumpMBB:
20781   //  Allocate by subtracting from RSP
20782   //  Jump to continueMBB
20783   //
20784   // mallocMBB:
20785   //  Allocate by call to runtime
20786   //
20787   // continueMBB:
20788   //  ...
20789   //  [rest of original BB]
20790   //
20791
20792   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20793   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20794   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20795
20796   MachineRegisterInfo &MRI = MF->getRegInfo();
20797   const TargetRegisterClass *AddrRegClass =
20798     getRegClassFor(getPointerTy());
20799
20800   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20801     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20802     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20803     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20804     sizeVReg = MI->getOperand(1).getReg(),
20805     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20806
20807   MachineFunction::iterator MBBIter = BB;
20808   ++MBBIter;
20809
20810   MF->insert(MBBIter, bumpMBB);
20811   MF->insert(MBBIter, mallocMBB);
20812   MF->insert(MBBIter, continueMBB);
20813
20814   continueMBB->splice(continueMBB->begin(), BB,
20815                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20816   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20817
20818   // Add code to the main basic block to check if the stack limit has been hit,
20819   // and if so, jump to mallocMBB otherwise to bumpMBB.
20820   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20821   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20822     .addReg(tmpSPVReg).addReg(sizeVReg);
20823   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20824     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20825     .addReg(SPLimitVReg);
20826   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
20827
20828   // bumpMBB simply decreases the stack pointer, since we know the current
20829   // stacklet has enough space.
20830   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20831     .addReg(SPLimitVReg);
20832   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20833     .addReg(SPLimitVReg);
20834   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20835
20836   // Calls into a routine in libgcc to allocate more space from the heap.
20837   const uint32_t *RegMask = MF->getTarget()
20838                                 .getSubtargetImpl()
20839                                 ->getRegisterInfo()
20840                                 ->getCallPreservedMask(CallingConv::C);
20841   if (IsLP64) {
20842     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20843       .addReg(sizeVReg);
20844     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20845       .addExternalSymbol("__morestack_allocate_stack_space")
20846       .addRegMask(RegMask)
20847       .addReg(X86::RDI, RegState::Implicit)
20848       .addReg(X86::RAX, RegState::ImplicitDefine);
20849   } else if (Is64Bit) {
20850     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20851       .addReg(sizeVReg);
20852     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20853       .addExternalSymbol("__morestack_allocate_stack_space")
20854       .addRegMask(RegMask)
20855       .addReg(X86::EDI, RegState::Implicit)
20856       .addReg(X86::EAX, RegState::ImplicitDefine);
20857   } else {
20858     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20859       .addImm(12);
20860     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20861     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20862       .addExternalSymbol("__morestack_allocate_stack_space")
20863       .addRegMask(RegMask)
20864       .addReg(X86::EAX, RegState::ImplicitDefine);
20865   }
20866
20867   if (!Is64Bit)
20868     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20869       .addImm(16);
20870
20871   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20872     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20873   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20874
20875   // Set up the CFG correctly.
20876   BB->addSuccessor(bumpMBB);
20877   BB->addSuccessor(mallocMBB);
20878   mallocMBB->addSuccessor(continueMBB);
20879   bumpMBB->addSuccessor(continueMBB);
20880
20881   // Take care of the PHI nodes.
20882   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20883           MI->getOperand(0).getReg())
20884     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20885     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20886
20887   // Delete the original pseudo instruction.
20888   MI->eraseFromParent();
20889
20890   // And we're done.
20891   return continueMBB;
20892 }
20893
20894 MachineBasicBlock *
20895 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20896                                         MachineBasicBlock *BB) const {
20897   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20898   DebugLoc DL = MI->getDebugLoc();
20899
20900   assert(!Subtarget->isTargetMachO());
20901
20902   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
20903   // non-trivial part is impdef of ESP.
20904
20905   if (Subtarget->isTargetWin64()) {
20906     if (Subtarget->isTargetCygMing()) {
20907       // ___chkstk(Mingw64):
20908       // Clobbers R10, R11, RAX and EFLAGS.
20909       // Updates RSP.
20910       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20911         .addExternalSymbol("___chkstk")
20912         .addReg(X86::RAX, RegState::Implicit)
20913         .addReg(X86::RSP, RegState::Implicit)
20914         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
20915         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
20916         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20917     } else {
20918       // __chkstk(MSVCRT): does not update stack pointer.
20919       // Clobbers R10, R11 and EFLAGS.
20920       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20921         .addExternalSymbol("__chkstk")
20922         .addReg(X86::RAX, RegState::Implicit)
20923         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20924       // RAX has the offset to be subtracted from RSP.
20925       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
20926         .addReg(X86::RSP)
20927         .addReg(X86::RAX);
20928     }
20929   } else {
20930     const char *StackProbeSymbol = (Subtarget->isTargetKnownWindowsMSVC() ||
20931                                     Subtarget->isTargetWindowsItanium())
20932                                        ? "_chkstk"
20933                                        : "_alloca";
20934
20935     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
20936       .addExternalSymbol(StackProbeSymbol)
20937       .addReg(X86::EAX, RegState::Implicit)
20938       .addReg(X86::ESP, RegState::Implicit)
20939       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
20940       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
20941       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20942   }
20943
20944   MI->eraseFromParent();   // The pseudo instruction is gone now.
20945   return BB;
20946 }
20947
20948 MachineBasicBlock *
20949 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20950                                       MachineBasicBlock *BB) const {
20951   // This is pretty easy.  We're taking the value that we received from
20952   // our load from the relocation, sticking it in either RDI (x86-64)
20953   // or EAX and doing an indirect call.  The return value will then
20954   // be in the normal return register.
20955   MachineFunction *F = BB->getParent();
20956   const X86InstrInfo *TII =
20957       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
20958   DebugLoc DL = MI->getDebugLoc();
20959
20960   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20961   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20962
20963   // Get a register mask for the lowered call.
20964   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20965   // proper register mask.
20966   const uint32_t *RegMask = F->getTarget()
20967                                 .getSubtargetImpl()
20968                                 ->getRegisterInfo()
20969                                 ->getCallPreservedMask(CallingConv::C);
20970   if (Subtarget->is64Bit()) {
20971     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20972                                       TII->get(X86::MOV64rm), X86::RDI)
20973     .addReg(X86::RIP)
20974     .addImm(0).addReg(0)
20975     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20976                       MI->getOperand(3).getTargetFlags())
20977     .addReg(0);
20978     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20979     addDirectMem(MIB, X86::RDI);
20980     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20981   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20982     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20983                                       TII->get(X86::MOV32rm), X86::EAX)
20984     .addReg(0)
20985     .addImm(0).addReg(0)
20986     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20987                       MI->getOperand(3).getTargetFlags())
20988     .addReg(0);
20989     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20990     addDirectMem(MIB, X86::EAX);
20991     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20992   } else {
20993     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20994                                       TII->get(X86::MOV32rm), X86::EAX)
20995     .addReg(TII->getGlobalBaseReg(F))
20996     .addImm(0).addReg(0)
20997     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20998                       MI->getOperand(3).getTargetFlags())
20999     .addReg(0);
21000     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21001     addDirectMem(MIB, X86::EAX);
21002     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21003   }
21004
21005   MI->eraseFromParent(); // The pseudo instruction is gone now.
21006   return BB;
21007 }
21008
21009 MachineBasicBlock *
21010 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21011                                     MachineBasicBlock *MBB) const {
21012   DebugLoc DL = MI->getDebugLoc();
21013   MachineFunction *MF = MBB->getParent();
21014   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
21015   MachineRegisterInfo &MRI = MF->getRegInfo();
21016
21017   const BasicBlock *BB = MBB->getBasicBlock();
21018   MachineFunction::iterator I = MBB;
21019   ++I;
21020
21021   // Memory Reference
21022   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21023   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21024
21025   unsigned DstReg;
21026   unsigned MemOpndSlot = 0;
21027
21028   unsigned CurOp = 0;
21029
21030   DstReg = MI->getOperand(CurOp++).getReg();
21031   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21032   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21033   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21034   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21035
21036   MemOpndSlot = CurOp;
21037
21038   MVT PVT = getPointerTy();
21039   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21040          "Invalid Pointer Size!");
21041
21042   // For v = setjmp(buf), we generate
21043   //
21044   // thisMBB:
21045   //  buf[LabelOffset] = restoreMBB
21046   //  SjLjSetup restoreMBB
21047   //
21048   // mainMBB:
21049   //  v_main = 0
21050   //
21051   // sinkMBB:
21052   //  v = phi(main, restore)
21053   //
21054   // restoreMBB:
21055   //  if base pointer being used, load it from frame
21056   //  v_restore = 1
21057
21058   MachineBasicBlock *thisMBB = MBB;
21059   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21060   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21061   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21062   MF->insert(I, mainMBB);
21063   MF->insert(I, sinkMBB);
21064   MF->push_back(restoreMBB);
21065
21066   MachineInstrBuilder MIB;
21067
21068   // Transfer the remainder of BB and its successor edges to sinkMBB.
21069   sinkMBB->splice(sinkMBB->begin(), MBB,
21070                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21071   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21072
21073   // thisMBB:
21074   unsigned PtrStoreOpc = 0;
21075   unsigned LabelReg = 0;
21076   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21077   Reloc::Model RM = MF->getTarget().getRelocationModel();
21078   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21079                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21080
21081   // Prepare IP either in reg or imm.
21082   if (!UseImmLabel) {
21083     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21084     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21085     LabelReg = MRI.createVirtualRegister(PtrRC);
21086     if (Subtarget->is64Bit()) {
21087       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21088               .addReg(X86::RIP)
21089               .addImm(0)
21090               .addReg(0)
21091               .addMBB(restoreMBB)
21092               .addReg(0);
21093     } else {
21094       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21095       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21096               .addReg(XII->getGlobalBaseReg(MF))
21097               .addImm(0)
21098               .addReg(0)
21099               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21100               .addReg(0);
21101     }
21102   } else
21103     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21104   // Store IP
21105   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21106   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21107     if (i == X86::AddrDisp)
21108       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21109     else
21110       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21111   }
21112   if (!UseImmLabel)
21113     MIB.addReg(LabelReg);
21114   else
21115     MIB.addMBB(restoreMBB);
21116   MIB.setMemRefs(MMOBegin, MMOEnd);
21117   // Setup
21118   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21119           .addMBB(restoreMBB);
21120
21121   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
21122       MF->getSubtarget().getRegisterInfo());
21123   MIB.addRegMask(RegInfo->getNoPreservedMask());
21124   thisMBB->addSuccessor(mainMBB);
21125   thisMBB->addSuccessor(restoreMBB);
21126
21127   // mainMBB:
21128   //  EAX = 0
21129   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21130   mainMBB->addSuccessor(sinkMBB);
21131
21132   // sinkMBB:
21133   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21134           TII->get(X86::PHI), DstReg)
21135     .addReg(mainDstReg).addMBB(mainMBB)
21136     .addReg(restoreDstReg).addMBB(restoreMBB);
21137
21138   // restoreMBB:
21139   if (RegInfo->hasBasePointer(*MF)) {
21140     const X86Subtarget &STI = MF->getTarget().getSubtarget<X86Subtarget>();
21141     const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
21142     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21143     X86FI->setRestoreBasePointer(MF);
21144     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21145     unsigned BasePtr = RegInfo->getBaseRegister();
21146     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21147     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21148                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21149       .setMIFlag(MachineInstr::FrameSetup);
21150   }
21151   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21152   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
21153   restoreMBB->addSuccessor(sinkMBB);
21154
21155   MI->eraseFromParent();
21156   return sinkMBB;
21157 }
21158
21159 MachineBasicBlock *
21160 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21161                                      MachineBasicBlock *MBB) const {
21162   DebugLoc DL = MI->getDebugLoc();
21163   MachineFunction *MF = MBB->getParent();
21164   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
21165   MachineRegisterInfo &MRI = MF->getRegInfo();
21166
21167   // Memory Reference
21168   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21169   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21170
21171   MVT PVT = getPointerTy();
21172   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21173          "Invalid Pointer Size!");
21174
21175   const TargetRegisterClass *RC =
21176     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21177   unsigned Tmp = MRI.createVirtualRegister(RC);
21178   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21179   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
21180       MF->getSubtarget().getRegisterInfo());
21181   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21182   unsigned SP = RegInfo->getStackRegister();
21183
21184   MachineInstrBuilder MIB;
21185
21186   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21187   const int64_t SPOffset = 2 * PVT.getStoreSize();
21188
21189   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21190   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21191
21192   // Reload FP
21193   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21194   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21195     MIB.addOperand(MI->getOperand(i));
21196   MIB.setMemRefs(MMOBegin, MMOEnd);
21197   // Reload IP
21198   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21199   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21200     if (i == X86::AddrDisp)
21201       MIB.addDisp(MI->getOperand(i), LabelOffset);
21202     else
21203       MIB.addOperand(MI->getOperand(i));
21204   }
21205   MIB.setMemRefs(MMOBegin, MMOEnd);
21206   // Reload SP
21207   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21208   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21209     if (i == X86::AddrDisp)
21210       MIB.addDisp(MI->getOperand(i), SPOffset);
21211     else
21212       MIB.addOperand(MI->getOperand(i));
21213   }
21214   MIB.setMemRefs(MMOBegin, MMOEnd);
21215   // Jump
21216   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21217
21218   MI->eraseFromParent();
21219   return MBB;
21220 }
21221
21222 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21223 // accumulator loops. Writing back to the accumulator allows the coalescer
21224 // to remove extra copies in the loop.
21225 MachineBasicBlock *
21226 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21227                                  MachineBasicBlock *MBB) const {
21228   MachineOperand &AddendOp = MI->getOperand(3);
21229
21230   // Bail out early if the addend isn't a register - we can't switch these.
21231   if (!AddendOp.isReg())
21232     return MBB;
21233
21234   MachineFunction &MF = *MBB->getParent();
21235   MachineRegisterInfo &MRI = MF.getRegInfo();
21236
21237   // Check whether the addend is defined by a PHI:
21238   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21239   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21240   if (!AddendDef.isPHI())
21241     return MBB;
21242
21243   // Look for the following pattern:
21244   // loop:
21245   //   %addend = phi [%entry, 0], [%loop, %result]
21246   //   ...
21247   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21248
21249   // Replace with:
21250   //   loop:
21251   //   %addend = phi [%entry, 0], [%loop, %result]
21252   //   ...
21253   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21254
21255   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21256     assert(AddendDef.getOperand(i).isReg());
21257     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21258     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21259     if (&PHISrcInst == MI) {
21260       // Found a matching instruction.
21261       unsigned NewFMAOpc = 0;
21262       switch (MI->getOpcode()) {
21263         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21264         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21265         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21266         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21267         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21268         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21269         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21270         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21271         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21272         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21273         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21274         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21275         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21276         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21277         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21278         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21279         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21280         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21281         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21282         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21283
21284         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21285         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21286         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21287         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21288         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21289         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21290         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21291         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21292         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21293         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21294         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21295         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21296         default: llvm_unreachable("Unrecognized FMA variant.");
21297       }
21298
21299       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
21300       MachineInstrBuilder MIB =
21301         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21302         .addOperand(MI->getOperand(0))
21303         .addOperand(MI->getOperand(3))
21304         .addOperand(MI->getOperand(2))
21305         .addOperand(MI->getOperand(1));
21306       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21307       MI->eraseFromParent();
21308     }
21309   }
21310
21311   return MBB;
21312 }
21313
21314 MachineBasicBlock *
21315 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21316                                                MachineBasicBlock *BB) const {
21317   switch (MI->getOpcode()) {
21318   default: llvm_unreachable("Unexpected instr type to insert");
21319   case X86::TAILJMPd64:
21320   case X86::TAILJMPr64:
21321   case X86::TAILJMPm64:
21322     llvm_unreachable("TAILJMP64 would not be touched here.");
21323   case X86::TCRETURNdi64:
21324   case X86::TCRETURNri64:
21325   case X86::TCRETURNmi64:
21326     return BB;
21327   case X86::WIN_ALLOCA:
21328     return EmitLoweredWinAlloca(MI, BB);
21329   case X86::SEG_ALLOCA_32:
21330   case X86::SEG_ALLOCA_64:
21331     return EmitLoweredSegAlloca(MI, BB);
21332   case X86::TLSCall_32:
21333   case X86::TLSCall_64:
21334     return EmitLoweredTLSCall(MI, BB);
21335   case X86::CMOV_GR8:
21336   case X86::CMOV_FR32:
21337   case X86::CMOV_FR64:
21338   case X86::CMOV_V4F32:
21339   case X86::CMOV_V2F64:
21340   case X86::CMOV_V2I64:
21341   case X86::CMOV_V8F32:
21342   case X86::CMOV_V4F64:
21343   case X86::CMOV_V4I64:
21344   case X86::CMOV_V16F32:
21345   case X86::CMOV_V8F64:
21346   case X86::CMOV_V8I64:
21347   case X86::CMOV_GR16:
21348   case X86::CMOV_GR32:
21349   case X86::CMOV_RFP32:
21350   case X86::CMOV_RFP64:
21351   case X86::CMOV_RFP80:
21352     return EmitLoweredSelect(MI, BB);
21353
21354   case X86::FP32_TO_INT16_IN_MEM:
21355   case X86::FP32_TO_INT32_IN_MEM:
21356   case X86::FP32_TO_INT64_IN_MEM:
21357   case X86::FP64_TO_INT16_IN_MEM:
21358   case X86::FP64_TO_INT32_IN_MEM:
21359   case X86::FP64_TO_INT64_IN_MEM:
21360   case X86::FP80_TO_INT16_IN_MEM:
21361   case X86::FP80_TO_INT32_IN_MEM:
21362   case X86::FP80_TO_INT64_IN_MEM: {
21363     MachineFunction *F = BB->getParent();
21364     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
21365     DebugLoc DL = MI->getDebugLoc();
21366
21367     // Change the floating point control register to use "round towards zero"
21368     // mode when truncating to an integer value.
21369     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21370     addFrameReference(BuildMI(*BB, MI, DL,
21371                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21372
21373     // Load the old value of the high byte of the control word...
21374     unsigned OldCW =
21375       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21376     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21377                       CWFrameIdx);
21378
21379     // Set the high part to be round to zero...
21380     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21381       .addImm(0xC7F);
21382
21383     // Reload the modified control word now...
21384     addFrameReference(BuildMI(*BB, MI, DL,
21385                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21386
21387     // Restore the memory image of control word to original value
21388     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21389       .addReg(OldCW);
21390
21391     // Get the X86 opcode to use.
21392     unsigned Opc;
21393     switch (MI->getOpcode()) {
21394     default: llvm_unreachable("illegal opcode!");
21395     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21396     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21397     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21398     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21399     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21400     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21401     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21402     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21403     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21404     }
21405
21406     X86AddressMode AM;
21407     MachineOperand &Op = MI->getOperand(0);
21408     if (Op.isReg()) {
21409       AM.BaseType = X86AddressMode::RegBase;
21410       AM.Base.Reg = Op.getReg();
21411     } else {
21412       AM.BaseType = X86AddressMode::FrameIndexBase;
21413       AM.Base.FrameIndex = Op.getIndex();
21414     }
21415     Op = MI->getOperand(1);
21416     if (Op.isImm())
21417       AM.Scale = Op.getImm();
21418     Op = MI->getOperand(2);
21419     if (Op.isImm())
21420       AM.IndexReg = Op.getImm();
21421     Op = MI->getOperand(3);
21422     if (Op.isGlobal()) {
21423       AM.GV = Op.getGlobal();
21424     } else {
21425       AM.Disp = Op.getImm();
21426     }
21427     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21428                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21429
21430     // Reload the original control word now.
21431     addFrameReference(BuildMI(*BB, MI, DL,
21432                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21433
21434     MI->eraseFromParent();   // The pseudo instruction is gone now.
21435     return BB;
21436   }
21437     // String/text processing lowering.
21438   case X86::PCMPISTRM128REG:
21439   case X86::VPCMPISTRM128REG:
21440   case X86::PCMPISTRM128MEM:
21441   case X86::VPCMPISTRM128MEM:
21442   case X86::PCMPESTRM128REG:
21443   case X86::VPCMPESTRM128REG:
21444   case X86::PCMPESTRM128MEM:
21445   case X86::VPCMPESTRM128MEM:
21446     assert(Subtarget->hasSSE42() &&
21447            "Target must have SSE4.2 or AVX features enabled");
21448     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21449
21450   // String/text processing lowering.
21451   case X86::PCMPISTRIREG:
21452   case X86::VPCMPISTRIREG:
21453   case X86::PCMPISTRIMEM:
21454   case X86::VPCMPISTRIMEM:
21455   case X86::PCMPESTRIREG:
21456   case X86::VPCMPESTRIREG:
21457   case X86::PCMPESTRIMEM:
21458   case X86::VPCMPESTRIMEM:
21459     assert(Subtarget->hasSSE42() &&
21460            "Target must have SSE4.2 or AVX features enabled");
21461     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21462
21463   // Thread synchronization.
21464   case X86::MONITOR:
21465     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
21466                        Subtarget);
21467
21468   // xbegin
21469   case X86::XBEGIN:
21470     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21471
21472   case X86::VASTART_SAVE_XMM_REGS:
21473     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21474
21475   case X86::VAARG_64:
21476     return EmitVAARG64WithCustomInserter(MI, BB);
21477
21478   case X86::EH_SjLj_SetJmp32:
21479   case X86::EH_SjLj_SetJmp64:
21480     return emitEHSjLjSetJmp(MI, BB);
21481
21482   case X86::EH_SjLj_LongJmp32:
21483   case X86::EH_SjLj_LongJmp64:
21484     return emitEHSjLjLongJmp(MI, BB);
21485
21486   case TargetOpcode::STATEPOINT:
21487     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21488     // this point in the process.  We diverge later.
21489     return emitPatchPoint(MI, BB);
21490
21491   case TargetOpcode::STACKMAP:
21492   case TargetOpcode::PATCHPOINT:
21493     return emitPatchPoint(MI, BB);
21494
21495   case X86::VFMADDPDr213r:
21496   case X86::VFMADDPSr213r:
21497   case X86::VFMADDSDr213r:
21498   case X86::VFMADDSSr213r:
21499   case X86::VFMSUBPDr213r:
21500   case X86::VFMSUBPSr213r:
21501   case X86::VFMSUBSDr213r:
21502   case X86::VFMSUBSSr213r:
21503   case X86::VFNMADDPDr213r:
21504   case X86::VFNMADDPSr213r:
21505   case X86::VFNMADDSDr213r:
21506   case X86::VFNMADDSSr213r:
21507   case X86::VFNMSUBPDr213r:
21508   case X86::VFNMSUBPSr213r:
21509   case X86::VFNMSUBSDr213r:
21510   case X86::VFNMSUBSSr213r:
21511   case X86::VFMADDSUBPDr213r:
21512   case X86::VFMADDSUBPSr213r:
21513   case X86::VFMSUBADDPDr213r:
21514   case X86::VFMSUBADDPSr213r:
21515   case X86::VFMADDPDr213rY:
21516   case X86::VFMADDPSr213rY:
21517   case X86::VFMSUBPDr213rY:
21518   case X86::VFMSUBPSr213rY:
21519   case X86::VFNMADDPDr213rY:
21520   case X86::VFNMADDPSr213rY:
21521   case X86::VFNMSUBPDr213rY:
21522   case X86::VFNMSUBPSr213rY:
21523   case X86::VFMADDSUBPDr213rY:
21524   case X86::VFMADDSUBPSr213rY:
21525   case X86::VFMSUBADDPDr213rY:
21526   case X86::VFMSUBADDPSr213rY:
21527     return emitFMA3Instr(MI, BB);
21528   }
21529 }
21530
21531 //===----------------------------------------------------------------------===//
21532 //                           X86 Optimization Hooks
21533 //===----------------------------------------------------------------------===//
21534
21535 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21536                                                       APInt &KnownZero,
21537                                                       APInt &KnownOne,
21538                                                       const SelectionDAG &DAG,
21539                                                       unsigned Depth) const {
21540   unsigned BitWidth = KnownZero.getBitWidth();
21541   unsigned Opc = Op.getOpcode();
21542   assert((Opc >= ISD::BUILTIN_OP_END ||
21543           Opc == ISD::INTRINSIC_WO_CHAIN ||
21544           Opc == ISD::INTRINSIC_W_CHAIN ||
21545           Opc == ISD::INTRINSIC_VOID) &&
21546          "Should use MaskedValueIsZero if you don't know whether Op"
21547          " is a target node!");
21548
21549   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21550   switch (Opc) {
21551   default: break;
21552   case X86ISD::ADD:
21553   case X86ISD::SUB:
21554   case X86ISD::ADC:
21555   case X86ISD::SBB:
21556   case X86ISD::SMUL:
21557   case X86ISD::UMUL:
21558   case X86ISD::INC:
21559   case X86ISD::DEC:
21560   case X86ISD::OR:
21561   case X86ISD::XOR:
21562   case X86ISD::AND:
21563     // These nodes' second result is a boolean.
21564     if (Op.getResNo() == 0)
21565       break;
21566     // Fallthrough
21567   case X86ISD::SETCC:
21568     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21569     break;
21570   case ISD::INTRINSIC_WO_CHAIN: {
21571     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21572     unsigned NumLoBits = 0;
21573     switch (IntId) {
21574     default: break;
21575     case Intrinsic::x86_sse_movmsk_ps:
21576     case Intrinsic::x86_avx_movmsk_ps_256:
21577     case Intrinsic::x86_sse2_movmsk_pd:
21578     case Intrinsic::x86_avx_movmsk_pd_256:
21579     case Intrinsic::x86_mmx_pmovmskb:
21580     case Intrinsic::x86_sse2_pmovmskb_128:
21581     case Intrinsic::x86_avx2_pmovmskb: {
21582       // High bits of movmskp{s|d}, pmovmskb are known zero.
21583       switch (IntId) {
21584         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21585         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21586         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21587         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21588         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21589         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21590         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21591         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21592       }
21593       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21594       break;
21595     }
21596     }
21597     break;
21598   }
21599   }
21600 }
21601
21602 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21603   SDValue Op,
21604   const SelectionDAG &,
21605   unsigned Depth) const {
21606   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21607   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21608     return Op.getValueType().getScalarType().getSizeInBits();
21609
21610   // Fallback case.
21611   return 1;
21612 }
21613
21614 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21615 /// node is a GlobalAddress + offset.
21616 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21617                                        const GlobalValue* &GA,
21618                                        int64_t &Offset) const {
21619   if (N->getOpcode() == X86ISD::Wrapper) {
21620     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21621       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21622       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21623       return true;
21624     }
21625   }
21626   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21627 }
21628
21629 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21630 /// same as extracting the high 128-bit part of 256-bit vector and then
21631 /// inserting the result into the low part of a new 256-bit vector
21632 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21633   EVT VT = SVOp->getValueType(0);
21634   unsigned NumElems = VT.getVectorNumElements();
21635
21636   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21637   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21638     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21639         SVOp->getMaskElt(j) >= 0)
21640       return false;
21641
21642   return true;
21643 }
21644
21645 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21646 /// same as extracting the low 128-bit part of 256-bit vector and then
21647 /// inserting the result into the high part of a new 256-bit vector
21648 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21649   EVT VT = SVOp->getValueType(0);
21650   unsigned NumElems = VT.getVectorNumElements();
21651
21652   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21653   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21654     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21655         SVOp->getMaskElt(j) >= 0)
21656       return false;
21657
21658   return true;
21659 }
21660
21661 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21662 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21663                                         TargetLowering::DAGCombinerInfo &DCI,
21664                                         const X86Subtarget* Subtarget) {
21665   SDLoc dl(N);
21666   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21667   SDValue V1 = SVOp->getOperand(0);
21668   SDValue V2 = SVOp->getOperand(1);
21669   EVT VT = SVOp->getValueType(0);
21670   unsigned NumElems = VT.getVectorNumElements();
21671
21672   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21673       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21674     //
21675     //                   0,0,0,...
21676     //                      |
21677     //    V      UNDEF    BUILD_VECTOR    UNDEF
21678     //     \      /           \           /
21679     //  CONCAT_VECTOR         CONCAT_VECTOR
21680     //         \                  /
21681     //          \                /
21682     //          RESULT: V + zero extended
21683     //
21684     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21685         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21686         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21687       return SDValue();
21688
21689     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21690       return SDValue();
21691
21692     // To match the shuffle mask, the first half of the mask should
21693     // be exactly the first vector, and all the rest a splat with the
21694     // first element of the second one.
21695     for (unsigned i = 0; i != NumElems/2; ++i)
21696       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21697           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21698         return SDValue();
21699
21700     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21701     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21702       if (Ld->hasNUsesOfValue(1, 0)) {
21703         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21704         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21705         SDValue ResNode =
21706           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21707                                   Ld->getMemoryVT(),
21708                                   Ld->getPointerInfo(),
21709                                   Ld->getAlignment(),
21710                                   false/*isVolatile*/, true/*ReadMem*/,
21711                                   false/*WriteMem*/);
21712
21713         // Make sure the newly-created LOAD is in the same position as Ld in
21714         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21715         // and update uses of Ld's output chain to use the TokenFactor.
21716         if (Ld->hasAnyUseOfValue(1)) {
21717           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21718                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21719           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21720           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21721                                  SDValue(ResNode.getNode(), 1));
21722         }
21723
21724         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
21725       }
21726     }
21727
21728     // Emit a zeroed vector and insert the desired subvector on its
21729     // first half.
21730     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21731     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21732     return DCI.CombineTo(N, InsV);
21733   }
21734
21735   //===--------------------------------------------------------------------===//
21736   // Combine some shuffles into subvector extracts and inserts:
21737   //
21738
21739   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21740   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21741     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21742     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21743     return DCI.CombineTo(N, InsV);
21744   }
21745
21746   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21747   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21748     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21749     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21750     return DCI.CombineTo(N, InsV);
21751   }
21752
21753   return SDValue();
21754 }
21755
21756 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21757 /// possible.
21758 ///
21759 /// This is the leaf of the recursive combinine below. When we have found some
21760 /// chain of single-use x86 shuffle instructions and accumulated the combined
21761 /// shuffle mask represented by them, this will try to pattern match that mask
21762 /// into either a single instruction if there is a special purpose instruction
21763 /// for this operation, or into a PSHUFB instruction which is a fully general
21764 /// instruction but should only be used to replace chains over a certain depth.
21765 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21766                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21767                                    TargetLowering::DAGCombinerInfo &DCI,
21768                                    const X86Subtarget *Subtarget) {
21769   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21770
21771   // Find the operand that enters the chain. Note that multiple uses are OK
21772   // here, we're not going to remove the operand we find.
21773   SDValue Input = Op.getOperand(0);
21774   while (Input.getOpcode() == ISD::BITCAST)
21775     Input = Input.getOperand(0);
21776
21777   MVT VT = Input.getSimpleValueType();
21778   MVT RootVT = Root.getSimpleValueType();
21779   SDLoc DL(Root);
21780
21781   // Just remove no-op shuffle masks.
21782   if (Mask.size() == 1) {
21783     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
21784                   /*AddTo*/ true);
21785     return true;
21786   }
21787
21788   // Use the float domain if the operand type is a floating point type.
21789   bool FloatDomain = VT.isFloatingPoint();
21790
21791   // For floating point shuffles, we don't have free copies in the shuffle
21792   // instructions or the ability to load as part of the instruction, so
21793   // canonicalize their shuffles to UNPCK or MOV variants.
21794   //
21795   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21796   // vectors because it can have a load folded into it that UNPCK cannot. This
21797   // doesn't preclude something switching to the shorter encoding post-RA.
21798   if (FloatDomain) {
21799     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
21800       bool Lo = Mask.equals(0, 0);
21801       unsigned Shuffle;
21802       MVT ShuffleVT;
21803       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21804       // is no slower than UNPCKLPD but has the option to fold the input operand
21805       // into even an unaligned memory load.
21806       if (Lo && Subtarget->hasSSE3()) {
21807         Shuffle = X86ISD::MOVDDUP;
21808         ShuffleVT = MVT::v2f64;
21809       } else {
21810         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21811         // than the UNPCK variants.
21812         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21813         ShuffleVT = MVT::v4f32;
21814       }
21815       if (Depth == 1 && Root->getOpcode() == Shuffle)
21816         return false; // Nothing to do!
21817       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21818       DCI.AddToWorklist(Op.getNode());
21819       if (Shuffle == X86ISD::MOVDDUP)
21820         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21821       else
21822         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21823       DCI.AddToWorklist(Op.getNode());
21824       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21825                     /*AddTo*/ true);
21826       return true;
21827     }
21828     if (Subtarget->hasSSE3() &&
21829         (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
21830       bool Lo = Mask.equals(0, 0, 2, 2);
21831       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21832       MVT ShuffleVT = MVT::v4f32;
21833       if (Depth == 1 && Root->getOpcode() == Shuffle)
21834         return false; // Nothing to do!
21835       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21836       DCI.AddToWorklist(Op.getNode());
21837       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21838       DCI.AddToWorklist(Op.getNode());
21839       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21840                     /*AddTo*/ true);
21841       return true;
21842     }
21843     if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
21844       bool Lo = Mask.equals(0, 0, 1, 1);
21845       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21846       MVT ShuffleVT = MVT::v4f32;
21847       if (Depth == 1 && Root->getOpcode() == Shuffle)
21848         return false; // Nothing to do!
21849       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21850       DCI.AddToWorklist(Op.getNode());
21851       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21852       DCI.AddToWorklist(Op.getNode());
21853       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21854                     /*AddTo*/ true);
21855       return true;
21856     }
21857   }
21858
21859   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21860   // variants as none of these have single-instruction variants that are
21861   // superior to the UNPCK formulation.
21862   if (!FloatDomain &&
21863       (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
21864        Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
21865        Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
21866        Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
21867                    15))) {
21868     bool Lo = Mask[0] == 0;
21869     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21870     if (Depth == 1 && Root->getOpcode() == Shuffle)
21871       return false; // Nothing to do!
21872     MVT ShuffleVT;
21873     switch (Mask.size()) {
21874     case 8:
21875       ShuffleVT = MVT::v8i16;
21876       break;
21877     case 16:
21878       ShuffleVT = MVT::v16i8;
21879       break;
21880     default:
21881       llvm_unreachable("Impossible mask size!");
21882     };
21883     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21884     DCI.AddToWorklist(Op.getNode());
21885     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21886     DCI.AddToWorklist(Op.getNode());
21887     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21888                   /*AddTo*/ true);
21889     return true;
21890   }
21891
21892   // Don't try to re-form single instruction chains under any circumstances now
21893   // that we've done encoding canonicalization for them.
21894   if (Depth < 2)
21895     return false;
21896
21897   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21898   // can replace them with a single PSHUFB instruction profitably. Intel's
21899   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21900   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21901   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21902     SmallVector<SDValue, 16> PSHUFBMask;
21903     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
21904     int Ratio = 16 / Mask.size();
21905     for (unsigned i = 0; i < 16; ++i) {
21906       if (Mask[i / Ratio] == SM_SentinelUndef) {
21907         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21908         continue;
21909       }
21910       int M = Mask[i / Ratio] != SM_SentinelZero
21911                   ? Ratio * Mask[i / Ratio] + i % Ratio
21912                   : 255;
21913       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
21914     }
21915     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
21916     DCI.AddToWorklist(Op.getNode());
21917     SDValue PSHUFBMaskOp =
21918         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
21919     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21920     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
21921     DCI.AddToWorklist(Op.getNode());
21922     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21923                   /*AddTo*/ true);
21924     return true;
21925   }
21926
21927   // Failed to find any combines.
21928   return false;
21929 }
21930
21931 /// \brief Fully generic combining of x86 shuffle instructions.
21932 ///
21933 /// This should be the last combine run over the x86 shuffle instructions. Once
21934 /// they have been fully optimized, this will recursively consider all chains
21935 /// of single-use shuffle instructions, build a generic model of the cumulative
21936 /// shuffle operation, and check for simpler instructions which implement this
21937 /// operation. We use this primarily for two purposes:
21938 ///
21939 /// 1) Collapse generic shuffles to specialized single instructions when
21940 ///    equivalent. In most cases, this is just an encoding size win, but
21941 ///    sometimes we will collapse multiple generic shuffles into a single
21942 ///    special-purpose shuffle.
21943 /// 2) Look for sequences of shuffle instructions with 3 or more total
21944 ///    instructions, and replace them with the slightly more expensive SSSE3
21945 ///    PSHUFB instruction if available. We do this as the last combining step
21946 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21947 ///    a suitable short sequence of other instructions. The PHUFB will either
21948 ///    use a register or have to read from memory and so is slightly (but only
21949 ///    slightly) more expensive than the other shuffle instructions.
21950 ///
21951 /// Because this is inherently a quadratic operation (for each shuffle in
21952 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21953 /// This should never be an issue in practice as the shuffle lowering doesn't
21954 /// produce sequences of more than 8 instructions.
21955 ///
21956 /// FIXME: We will currently miss some cases where the redundant shuffling
21957 /// would simplify under the threshold for PSHUFB formation because of
21958 /// combine-ordering. To fix this, we should do the redundant instruction
21959 /// combining in this recursive walk.
21960 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21961                                           ArrayRef<int> RootMask,
21962                                           int Depth, bool HasPSHUFB,
21963                                           SelectionDAG &DAG,
21964                                           TargetLowering::DAGCombinerInfo &DCI,
21965                                           const X86Subtarget *Subtarget) {
21966   // Bound the depth of our recursive combine because this is ultimately
21967   // quadratic in nature.
21968   if (Depth > 8)
21969     return false;
21970
21971   // Directly rip through bitcasts to find the underlying operand.
21972   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21973     Op = Op.getOperand(0);
21974
21975   MVT VT = Op.getSimpleValueType();
21976   if (!VT.isVector())
21977     return false; // Bail if we hit a non-vector.
21978   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
21979   // version should be added.
21980   if (VT.getSizeInBits() != 128)
21981     return false;
21982
21983   assert(Root.getSimpleValueType().isVector() &&
21984          "Shuffles operate on vector types!");
21985   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21986          "Can only combine shuffles of the same vector register size.");
21987
21988   if (!isTargetShuffle(Op.getOpcode()))
21989     return false;
21990   SmallVector<int, 16> OpMask;
21991   bool IsUnary;
21992   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21993   // We only can combine unary shuffles which we can decode the mask for.
21994   if (!HaveMask || !IsUnary)
21995     return false;
21996
21997   assert(VT.getVectorNumElements() == OpMask.size() &&
21998          "Different mask size from vector size!");
21999   assert(((RootMask.size() > OpMask.size() &&
22000            RootMask.size() % OpMask.size() == 0) ||
22001           (OpMask.size() > RootMask.size() &&
22002            OpMask.size() % RootMask.size() == 0) ||
22003           OpMask.size() == RootMask.size()) &&
22004          "The smaller number of elements must divide the larger.");
22005   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22006   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22007   assert(((RootRatio == 1 && OpRatio == 1) ||
22008           (RootRatio == 1) != (OpRatio == 1)) &&
22009          "Must not have a ratio for both incoming and op masks!");
22010
22011   SmallVector<int, 16> Mask;
22012   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22013
22014   // Merge this shuffle operation's mask into our accumulated mask. Note that
22015   // this shuffle's mask will be the first applied to the input, followed by the
22016   // root mask to get us all the way to the root value arrangement. The reason
22017   // for this order is that we are recursing up the operation chain.
22018   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22019     int RootIdx = i / RootRatio;
22020     if (RootMask[RootIdx] < 0) {
22021       // This is a zero or undef lane, we're done.
22022       Mask.push_back(RootMask[RootIdx]);
22023       continue;
22024     }
22025
22026     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22027     int OpIdx = RootMaskedIdx / OpRatio;
22028     if (OpMask[OpIdx] < 0) {
22029       // The incoming lanes are zero or undef, it doesn't matter which ones we
22030       // are using.
22031       Mask.push_back(OpMask[OpIdx]);
22032       continue;
22033     }
22034
22035     // Ok, we have non-zero lanes, map them through.
22036     Mask.push_back(OpMask[OpIdx] * OpRatio +
22037                    RootMaskedIdx % OpRatio);
22038   }
22039
22040   // See if we can recurse into the operand to combine more things.
22041   switch (Op.getOpcode()) {
22042     case X86ISD::PSHUFB:
22043       HasPSHUFB = true;
22044     case X86ISD::PSHUFD:
22045     case X86ISD::PSHUFHW:
22046     case X86ISD::PSHUFLW:
22047       if (Op.getOperand(0).hasOneUse() &&
22048           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22049                                         HasPSHUFB, DAG, DCI, Subtarget))
22050         return true;
22051       break;
22052
22053     case X86ISD::UNPCKL:
22054     case X86ISD::UNPCKH:
22055       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
22056       // We can't check for single use, we have to check that this shuffle is the only user.
22057       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22058           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22059                                         HasPSHUFB, DAG, DCI, Subtarget))
22060           return true;
22061       break;
22062   }
22063
22064   // Minor canonicalization of the accumulated shuffle mask to make it easier
22065   // to match below. All this does is detect masks with squential pairs of
22066   // elements, and shrink them to the half-width mask. It does this in a loop
22067   // so it will reduce the size of the mask to the minimal width mask which
22068   // performs an equivalent shuffle.
22069   SmallVector<int, 16> WidenedMask;
22070   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22071     Mask = std::move(WidenedMask);
22072     WidenedMask.clear();
22073   }
22074
22075   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22076                                 Subtarget);
22077 }
22078
22079 /// \brief Get the PSHUF-style mask from PSHUF node.
22080 ///
22081 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22082 /// PSHUF-style masks that can be reused with such instructions.
22083 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22084   SmallVector<int, 4> Mask;
22085   bool IsUnary;
22086   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
22087   (void)HaveMask;
22088   assert(HaveMask);
22089
22090   switch (N.getOpcode()) {
22091   case X86ISD::PSHUFD:
22092     return Mask;
22093   case X86ISD::PSHUFLW:
22094     Mask.resize(4);
22095     return Mask;
22096   case X86ISD::PSHUFHW:
22097     Mask.erase(Mask.begin(), Mask.begin() + 4);
22098     for (int &M : Mask)
22099       M -= 4;
22100     return Mask;
22101   default:
22102     llvm_unreachable("No valid shuffle instruction found!");
22103   }
22104 }
22105
22106 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22107 ///
22108 /// We walk up the chain and look for a combinable shuffle, skipping over
22109 /// shuffles that we could hoist this shuffle's transformation past without
22110 /// altering anything.
22111 static SDValue
22112 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22113                              SelectionDAG &DAG,
22114                              TargetLowering::DAGCombinerInfo &DCI) {
22115   assert(N.getOpcode() == X86ISD::PSHUFD &&
22116          "Called with something other than an x86 128-bit half shuffle!");
22117   SDLoc DL(N);
22118
22119   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22120   // of the shuffles in the chain so that we can form a fresh chain to replace
22121   // this one.
22122   SmallVector<SDValue, 8> Chain;
22123   SDValue V = N.getOperand(0);
22124   for (; V.hasOneUse(); V = V.getOperand(0)) {
22125     switch (V.getOpcode()) {
22126     default:
22127       return SDValue(); // Nothing combined!
22128
22129     case ISD::BITCAST:
22130       // Skip bitcasts as we always know the type for the target specific
22131       // instructions.
22132       continue;
22133
22134     case X86ISD::PSHUFD:
22135       // Found another dword shuffle.
22136       break;
22137
22138     case X86ISD::PSHUFLW:
22139       // Check that the low words (being shuffled) are the identity in the
22140       // dword shuffle, and the high words are self-contained.
22141       if (Mask[0] != 0 || Mask[1] != 1 ||
22142           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22143         return SDValue();
22144
22145       Chain.push_back(V);
22146       continue;
22147
22148     case X86ISD::PSHUFHW:
22149       // Check that the high words (being shuffled) are the identity in the
22150       // dword shuffle, and the low words are self-contained.
22151       if (Mask[2] != 2 || Mask[3] != 3 ||
22152           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22153         return SDValue();
22154
22155       Chain.push_back(V);
22156       continue;
22157
22158     case X86ISD::UNPCKL:
22159     case X86ISD::UNPCKH:
22160       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22161       // shuffle into a preceding word shuffle.
22162       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
22163         return SDValue();
22164
22165       // Search for a half-shuffle which we can combine with.
22166       unsigned CombineOp =
22167           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22168       if (V.getOperand(0) != V.getOperand(1) ||
22169           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22170         return SDValue();
22171       Chain.push_back(V);
22172       V = V.getOperand(0);
22173       do {
22174         switch (V.getOpcode()) {
22175         default:
22176           return SDValue(); // Nothing to combine.
22177
22178         case X86ISD::PSHUFLW:
22179         case X86ISD::PSHUFHW:
22180           if (V.getOpcode() == CombineOp)
22181             break;
22182
22183           Chain.push_back(V);
22184
22185           // Fallthrough!
22186         case ISD::BITCAST:
22187           V = V.getOperand(0);
22188           continue;
22189         }
22190         break;
22191       } while (V.hasOneUse());
22192       break;
22193     }
22194     // Break out of the loop if we break out of the switch.
22195     break;
22196   }
22197
22198   if (!V.hasOneUse())
22199     // We fell out of the loop without finding a viable combining instruction.
22200     return SDValue();
22201
22202   // Merge this node's mask and our incoming mask.
22203   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22204   for (int &M : Mask)
22205     M = VMask[M];
22206   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22207                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22208
22209   // Rebuild the chain around this new shuffle.
22210   while (!Chain.empty()) {
22211     SDValue W = Chain.pop_back_val();
22212
22213     if (V.getValueType() != W.getOperand(0).getValueType())
22214       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
22215
22216     switch (W.getOpcode()) {
22217     default:
22218       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22219
22220     case X86ISD::UNPCKL:
22221     case X86ISD::UNPCKH:
22222       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22223       break;
22224
22225     case X86ISD::PSHUFD:
22226     case X86ISD::PSHUFLW:
22227     case X86ISD::PSHUFHW:
22228       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22229       break;
22230     }
22231   }
22232   if (V.getValueType() != N.getValueType())
22233     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
22234
22235   // Return the new chain to replace N.
22236   return V;
22237 }
22238
22239 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22240 ///
22241 /// We walk up the chain, skipping shuffles of the other half and looking
22242 /// through shuffles which switch halves trying to find a shuffle of the same
22243 /// pair of dwords.
22244 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22245                                         SelectionDAG &DAG,
22246                                         TargetLowering::DAGCombinerInfo &DCI) {
22247   assert(
22248       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22249       "Called with something other than an x86 128-bit half shuffle!");
22250   SDLoc DL(N);
22251   unsigned CombineOpcode = N.getOpcode();
22252
22253   // Walk up a single-use chain looking for a combinable shuffle.
22254   SDValue V = N.getOperand(0);
22255   for (; V.hasOneUse(); V = V.getOperand(0)) {
22256     switch (V.getOpcode()) {
22257     default:
22258       return false; // Nothing combined!
22259
22260     case ISD::BITCAST:
22261       // Skip bitcasts as we always know the type for the target specific
22262       // instructions.
22263       continue;
22264
22265     case X86ISD::PSHUFLW:
22266     case X86ISD::PSHUFHW:
22267       if (V.getOpcode() == CombineOpcode)
22268         break;
22269
22270       // Other-half shuffles are no-ops.
22271       continue;
22272     }
22273     // Break out of the loop if we break out of the switch.
22274     break;
22275   }
22276
22277   if (!V.hasOneUse())
22278     // We fell out of the loop without finding a viable combining instruction.
22279     return false;
22280
22281   // Combine away the bottom node as its shuffle will be accumulated into
22282   // a preceding shuffle.
22283   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22284
22285   // Record the old value.
22286   SDValue Old = V;
22287
22288   // Merge this node's mask and our incoming mask (adjusted to account for all
22289   // the pshufd instructions encountered).
22290   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22291   for (int &M : Mask)
22292     M = VMask[M];
22293   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22294                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22295
22296   // Check that the shuffles didn't cancel each other out. If not, we need to
22297   // combine to the new one.
22298   if (Old != V)
22299     // Replace the combinable shuffle with the combined one, updating all users
22300     // so that we re-evaluate the chain here.
22301     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22302
22303   return true;
22304 }
22305
22306 /// \brief Try to combine x86 target specific shuffles.
22307 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22308                                            TargetLowering::DAGCombinerInfo &DCI,
22309                                            const X86Subtarget *Subtarget) {
22310   SDLoc DL(N);
22311   MVT VT = N.getSimpleValueType();
22312   SmallVector<int, 4> Mask;
22313
22314   switch (N.getOpcode()) {
22315   case X86ISD::PSHUFD:
22316   case X86ISD::PSHUFLW:
22317   case X86ISD::PSHUFHW:
22318     Mask = getPSHUFShuffleMask(N);
22319     assert(Mask.size() == 4);
22320     break;
22321   default:
22322     return SDValue();
22323   }
22324
22325   // Nuke no-op shuffles that show up after combining.
22326   if (isNoopShuffleMask(Mask))
22327     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22328
22329   // Look for simplifications involving one or two shuffle instructions.
22330   SDValue V = N.getOperand(0);
22331   switch (N.getOpcode()) {
22332   default:
22333     break;
22334   case X86ISD::PSHUFLW:
22335   case X86ISD::PSHUFHW:
22336     assert(VT == MVT::v8i16);
22337     (void)VT;
22338
22339     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22340       return SDValue(); // We combined away this shuffle, so we're done.
22341
22342     // See if this reduces to a PSHUFD which is no more expensive and can
22343     // combine with more operations. Note that it has to at least flip the
22344     // dwords as otherwise it would have been removed as a no-op.
22345     if (Mask[0] == 2 && Mask[1] == 3 && Mask[2] == 0 && Mask[3] == 1) {
22346       int DMask[] = {0, 1, 2, 3};
22347       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22348       DMask[DOffset + 0] = DOffset + 1;
22349       DMask[DOffset + 1] = DOffset + 0;
22350       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
22351       DCI.AddToWorklist(V.getNode());
22352       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
22353                       getV4X86ShuffleImm8ForMask(DMask, DAG));
22354       DCI.AddToWorklist(V.getNode());
22355       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
22356     }
22357
22358     // Look for shuffle patterns which can be implemented as a single unpack.
22359     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22360     // only works when we have a PSHUFD followed by two half-shuffles.
22361     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22362         (V.getOpcode() == X86ISD::PSHUFLW ||
22363          V.getOpcode() == X86ISD::PSHUFHW) &&
22364         V.getOpcode() != N.getOpcode() &&
22365         V.hasOneUse()) {
22366       SDValue D = V.getOperand(0);
22367       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22368         D = D.getOperand(0);
22369       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22370         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22371         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22372         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22373         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22374         int WordMask[8];
22375         for (int i = 0; i < 4; ++i) {
22376           WordMask[i + NOffset] = Mask[i] + NOffset;
22377           WordMask[i + VOffset] = VMask[i] + VOffset;
22378         }
22379         // Map the word mask through the DWord mask.
22380         int MappedMask[8];
22381         for (int i = 0; i < 8; ++i)
22382           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22383         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
22384         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
22385         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
22386                        std::begin(UnpackLoMask)) ||
22387             std::equal(std::begin(MappedMask), std::end(MappedMask),
22388                        std::begin(UnpackHiMask))) {
22389           // We can replace all three shuffles with an unpack.
22390           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
22391           DCI.AddToWorklist(V.getNode());
22392           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22393                                                 : X86ISD::UNPCKH,
22394                              DL, MVT::v8i16, V, V);
22395         }
22396       }
22397     }
22398
22399     break;
22400
22401   case X86ISD::PSHUFD:
22402     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22403       return NewN;
22404
22405     break;
22406   }
22407
22408   return SDValue();
22409 }
22410
22411 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22412 ///
22413 /// We combine this directly on the abstract vector shuffle nodes so it is
22414 /// easier to generically match. We also insert dummy vector shuffle nodes for
22415 /// the operands which explicitly discard the lanes which are unused by this
22416 /// operation to try to flow through the rest of the combiner the fact that
22417 /// they're unused.
22418 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22419   SDLoc DL(N);
22420   EVT VT = N->getValueType(0);
22421
22422   // We only handle target-independent shuffles.
22423   // FIXME: It would be easy and harmless to use the target shuffle mask
22424   // extraction tool to support more.
22425   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22426     return SDValue();
22427
22428   auto *SVN = cast<ShuffleVectorSDNode>(N);
22429   ArrayRef<int> Mask = SVN->getMask();
22430   SDValue V1 = N->getOperand(0);
22431   SDValue V2 = N->getOperand(1);
22432
22433   // We require the first shuffle operand to be the SUB node, and the second to
22434   // be the ADD node.
22435   // FIXME: We should support the commuted patterns.
22436   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22437     return SDValue();
22438
22439   // If there are other uses of these operations we can't fold them.
22440   if (!V1->hasOneUse() || !V2->hasOneUse())
22441     return SDValue();
22442
22443   // Ensure that both operations have the same operands. Note that we can
22444   // commute the FADD operands.
22445   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22446   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22447       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22448     return SDValue();
22449
22450   // We're looking for blends between FADD and FSUB nodes. We insist on these
22451   // nodes being lined up in a specific expected pattern.
22452   if (!(isShuffleEquivalent(Mask, 0, 3) ||
22453         isShuffleEquivalent(Mask, 0, 5, 2, 7) ||
22454         isShuffleEquivalent(Mask, 0, 9, 2, 11, 4, 13, 6, 15)))
22455     return SDValue();
22456
22457   // Only specific types are legal at this point, assert so we notice if and
22458   // when these change.
22459   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22460           VT == MVT::v4f64) &&
22461          "Unknown vector type encountered!");
22462
22463   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22464 }
22465
22466 /// PerformShuffleCombine - Performs several different shuffle combines.
22467 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22468                                      TargetLowering::DAGCombinerInfo &DCI,
22469                                      const X86Subtarget *Subtarget) {
22470   SDLoc dl(N);
22471   SDValue N0 = N->getOperand(0);
22472   SDValue N1 = N->getOperand(1);
22473   EVT VT = N->getValueType(0);
22474
22475   // Don't create instructions with illegal types after legalize types has run.
22476   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22477   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22478     return SDValue();
22479
22480   // If we have legalized the vector types, look for blends of FADD and FSUB
22481   // nodes that we can fuse into an ADDSUB node.
22482   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22483     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22484       return AddSub;
22485
22486   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22487   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22488       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22489     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22490
22491   // During Type Legalization, when promoting illegal vector types,
22492   // the backend might introduce new shuffle dag nodes and bitcasts.
22493   //
22494   // This code performs the following transformation:
22495   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22496   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22497   //
22498   // We do this only if both the bitcast and the BINOP dag nodes have
22499   // one use. Also, perform this transformation only if the new binary
22500   // operation is legal. This is to avoid introducing dag nodes that
22501   // potentially need to be further expanded (or custom lowered) into a
22502   // less optimal sequence of dag nodes.
22503   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22504       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22505       N0.getOpcode() == ISD::BITCAST) {
22506     SDValue BC0 = N0.getOperand(0);
22507     EVT SVT = BC0.getValueType();
22508     unsigned Opcode = BC0.getOpcode();
22509     unsigned NumElts = VT.getVectorNumElements();
22510
22511     if (BC0.hasOneUse() && SVT.isVector() &&
22512         SVT.getVectorNumElements() * 2 == NumElts &&
22513         TLI.isOperationLegal(Opcode, VT)) {
22514       bool CanFold = false;
22515       switch (Opcode) {
22516       default : break;
22517       case ISD::ADD :
22518       case ISD::FADD :
22519       case ISD::SUB :
22520       case ISD::FSUB :
22521       case ISD::MUL :
22522       case ISD::FMUL :
22523         CanFold = true;
22524       }
22525
22526       unsigned SVTNumElts = SVT.getVectorNumElements();
22527       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22528       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22529         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22530       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22531         CanFold = SVOp->getMaskElt(i) < 0;
22532
22533       if (CanFold) {
22534         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
22535         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
22536         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22537         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22538       }
22539     }
22540   }
22541
22542   // Only handle 128 wide vector from here on.
22543   if (!VT.is128BitVector())
22544     return SDValue();
22545
22546   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22547   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22548   // consecutive, non-overlapping, and in the right order.
22549   SmallVector<SDValue, 16> Elts;
22550   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22551     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22552
22553   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
22554   if (LD.getNode())
22555     return LD;
22556
22557   if (isTargetShuffle(N->getOpcode())) {
22558     SDValue Shuffle =
22559         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22560     if (Shuffle.getNode())
22561       return Shuffle;
22562
22563     // Try recursively combining arbitrary sequences of x86 shuffle
22564     // instructions into higher-order shuffles. We do this after combining
22565     // specific PSHUF instruction sequences into their minimal form so that we
22566     // can evaluate how many specialized shuffle instructions are involved in
22567     // a particular chain.
22568     SmallVector<int, 1> NonceMask; // Just a placeholder.
22569     NonceMask.push_back(0);
22570     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22571                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22572                                       DCI, Subtarget))
22573       return SDValue(); // This routine will use CombineTo to replace N.
22574   }
22575
22576   return SDValue();
22577 }
22578
22579 /// PerformTruncateCombine - Converts truncate operation to
22580 /// a sequence of vector shuffle operations.
22581 /// It is possible when we truncate 256-bit vector to 128-bit vector
22582 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
22583                                       TargetLowering::DAGCombinerInfo &DCI,
22584                                       const X86Subtarget *Subtarget)  {
22585   return SDValue();
22586 }
22587
22588 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22589 /// specific shuffle of a load can be folded into a single element load.
22590 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22591 /// shuffles have been custom lowered so we need to handle those here.
22592 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22593                                          TargetLowering::DAGCombinerInfo &DCI) {
22594   if (DCI.isBeforeLegalizeOps())
22595     return SDValue();
22596
22597   SDValue InVec = N->getOperand(0);
22598   SDValue EltNo = N->getOperand(1);
22599
22600   if (!isa<ConstantSDNode>(EltNo))
22601     return SDValue();
22602
22603   EVT OriginalVT = InVec.getValueType();
22604
22605   if (InVec.getOpcode() == ISD::BITCAST) {
22606     // Don't duplicate a load with other uses.
22607     if (!InVec.hasOneUse())
22608       return SDValue();
22609     EVT BCVT = InVec.getOperand(0).getValueType();
22610     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22611       return SDValue();
22612     InVec = InVec.getOperand(0);
22613   }
22614
22615   EVT CurrentVT = InVec.getValueType();
22616
22617   if (!isTargetShuffle(InVec.getOpcode()))
22618     return SDValue();
22619
22620   // Don't duplicate a load with other uses.
22621   if (!InVec.hasOneUse())
22622     return SDValue();
22623
22624   SmallVector<int, 16> ShuffleMask;
22625   bool UnaryShuffle;
22626   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22627                             ShuffleMask, UnaryShuffle))
22628     return SDValue();
22629
22630   // Select the input vector, guarding against out of range extract vector.
22631   unsigned NumElems = CurrentVT.getVectorNumElements();
22632   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22633   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22634   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22635                                          : InVec.getOperand(1);
22636
22637   // If inputs to shuffle are the same for both ops, then allow 2 uses
22638   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22639
22640   if (LdNode.getOpcode() == ISD::BITCAST) {
22641     // Don't duplicate a load with other uses.
22642     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22643       return SDValue();
22644
22645     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22646     LdNode = LdNode.getOperand(0);
22647   }
22648
22649   if (!ISD::isNormalLoad(LdNode.getNode()))
22650     return SDValue();
22651
22652   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22653
22654   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22655     return SDValue();
22656
22657   EVT EltVT = N->getValueType(0);
22658   // If there's a bitcast before the shuffle, check if the load type and
22659   // alignment is valid.
22660   unsigned Align = LN0->getAlignment();
22661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22662   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
22663       EltVT.getTypeForEVT(*DAG.getContext()));
22664
22665   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22666     return SDValue();
22667
22668   // All checks match so transform back to vector_shuffle so that DAG combiner
22669   // can finish the job
22670   SDLoc dl(N);
22671
22672   // Create shuffle node taking into account the case that its a unary shuffle
22673   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22674                                    : InVec.getOperand(1);
22675   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22676                                  InVec.getOperand(0), Shuffle,
22677                                  &ShuffleMask[0]);
22678   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
22679   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22680                      EltNo);
22681 }
22682
22683 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22684 /// generation and convert it from being a bunch of shuffles and extracts
22685 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22686 /// storing the value and loading scalars back, while for x64 we should
22687 /// use 64-bit extracts and shifts.
22688 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22689                                          TargetLowering::DAGCombinerInfo &DCI) {
22690   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
22691   if (NewOp.getNode())
22692     return NewOp;
22693
22694   SDValue InputVector = N->getOperand(0);
22695
22696   // Detect whether we are trying to convert from mmx to i32 and the bitcast
22697   // from mmx to v2i32 has a single usage.
22698   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
22699       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
22700       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
22701     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22702                        N->getValueType(0),
22703                        InputVector.getNode()->getOperand(0));
22704
22705   // Only operate on vectors of 4 elements, where the alternative shuffling
22706   // gets to be more expensive.
22707   if (InputVector.getValueType() != MVT::v4i32)
22708     return SDValue();
22709
22710   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22711   // single use which is a sign-extend or zero-extend, and all elements are
22712   // used.
22713   SmallVector<SDNode *, 4> Uses;
22714   unsigned ExtractedElements = 0;
22715   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22716        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22717     if (UI.getUse().getResNo() != InputVector.getResNo())
22718       return SDValue();
22719
22720     SDNode *Extract = *UI;
22721     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22722       return SDValue();
22723
22724     if (Extract->getValueType(0) != MVT::i32)
22725       return SDValue();
22726     if (!Extract->hasOneUse())
22727       return SDValue();
22728     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22729         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22730       return SDValue();
22731     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22732       return SDValue();
22733
22734     // Record which element was extracted.
22735     ExtractedElements |=
22736       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22737
22738     Uses.push_back(Extract);
22739   }
22740
22741   // If not all the elements were used, this may not be worthwhile.
22742   if (ExtractedElements != 15)
22743     return SDValue();
22744
22745   // Ok, we've now decided to do the transformation.
22746   // If 64-bit shifts are legal, use the extract-shift sequence,
22747   // otherwise bounce the vector off the cache.
22748   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22749   SDValue Vals[4];
22750   SDLoc dl(InputVector);
22751   
22752   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22753     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
22754     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
22755     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22756       DAG.getConstant(0, VecIdxTy));
22757     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22758       DAG.getConstant(1, VecIdxTy));
22759
22760     SDValue ShAmt = DAG.getConstant(32, 
22761       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
22762     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22763     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22764       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22765     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22766     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22767       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22768   } else {
22769     // Store the value to a temporary stack slot.
22770     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22771     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22772       MachinePointerInfo(), false, false, 0);
22773
22774     EVT ElementType = InputVector.getValueType().getVectorElementType();
22775     unsigned EltSize = ElementType.getSizeInBits() / 8;
22776
22777     // Replace each use (extract) with a load of the appropriate element.
22778     for (unsigned i = 0; i < 4; ++i) {
22779       uint64_t Offset = EltSize * i;
22780       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
22781
22782       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
22783                                        StackPtr, OffsetVal);
22784
22785       // Load the scalar.
22786       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22787                             ScalarAddr, MachinePointerInfo(),
22788                             false, false, false, 0);
22789
22790     }
22791   }
22792
22793   // Replace the extracts
22794   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22795     UE = Uses.end(); UI != UE; ++UI) {
22796     SDNode *Extract = *UI;
22797
22798     SDValue Idx = Extract->getOperand(1);
22799     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22800     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22801   }
22802
22803   // The replacement was made in place; don't return anything.
22804   return SDValue();
22805 }
22806
22807 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22808 static std::pair<unsigned, bool>
22809 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22810                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22811   if (!VT.isVector())
22812     return std::make_pair(0, false);
22813
22814   bool NeedSplit = false;
22815   switch (VT.getSimpleVT().SimpleTy) {
22816   default: return std::make_pair(0, false);
22817   case MVT::v4i64:
22818   case MVT::v2i64:
22819     if (!Subtarget->hasVLX())
22820       return std::make_pair(0, false);
22821     break;
22822   case MVT::v64i8:
22823   case MVT::v32i16:
22824     if (!Subtarget->hasBWI())
22825       return std::make_pair(0, false);
22826     break;
22827   case MVT::v16i32:
22828   case MVT::v8i64:
22829     if (!Subtarget->hasAVX512())
22830       return std::make_pair(0, false);
22831     break;
22832   case MVT::v32i8:
22833   case MVT::v16i16:
22834   case MVT::v8i32:
22835     if (!Subtarget->hasAVX2())
22836       NeedSplit = true;
22837     if (!Subtarget->hasAVX())
22838       return std::make_pair(0, false);
22839     break;
22840   case MVT::v16i8:
22841   case MVT::v8i16:
22842   case MVT::v4i32:
22843     if (!Subtarget->hasSSE2())
22844       return std::make_pair(0, false);
22845   }
22846
22847   // SSE2 has only a small subset of the operations.
22848   bool hasUnsigned = Subtarget->hasSSE41() ||
22849                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22850   bool hasSigned = Subtarget->hasSSE41() ||
22851                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22852
22853   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22854
22855   unsigned Opc = 0;
22856   // Check for x CC y ? x : y.
22857   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22858       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22859     switch (CC) {
22860     default: break;
22861     case ISD::SETULT:
22862     case ISD::SETULE:
22863       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22864     case ISD::SETUGT:
22865     case ISD::SETUGE:
22866       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22867     case ISD::SETLT:
22868     case ISD::SETLE:
22869       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22870     case ISD::SETGT:
22871     case ISD::SETGE:
22872       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22873     }
22874   // Check for x CC y ? y : x -- a min/max with reversed arms.
22875   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22876              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22877     switch (CC) {
22878     default: break;
22879     case ISD::SETULT:
22880     case ISD::SETULE:
22881       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22882     case ISD::SETUGT:
22883     case ISD::SETUGE:
22884       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22885     case ISD::SETLT:
22886     case ISD::SETLE:
22887       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22888     case ISD::SETGT:
22889     case ISD::SETGE:
22890       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22891     }
22892   }
22893
22894   return std::make_pair(Opc, NeedSplit);
22895 }
22896
22897 static SDValue
22898 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22899                                       const X86Subtarget *Subtarget) {
22900   SDLoc dl(N);
22901   SDValue Cond = N->getOperand(0);
22902   SDValue LHS = N->getOperand(1);
22903   SDValue RHS = N->getOperand(2);
22904
22905   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22906     SDValue CondSrc = Cond->getOperand(0);
22907     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22908       Cond = CondSrc->getOperand(0);
22909   }
22910
22911   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22912     return SDValue();
22913
22914   // A vselect where all conditions and data are constants can be optimized into
22915   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22916   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22917       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22918     return SDValue();
22919
22920   unsigned MaskValue = 0;
22921   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22922     return SDValue();
22923
22924   MVT VT = N->getSimpleValueType(0);
22925   unsigned NumElems = VT.getVectorNumElements();
22926   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22927   for (unsigned i = 0; i < NumElems; ++i) {
22928     // Be sure we emit undef where we can.
22929     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22930       ShuffleMask[i] = -1;
22931     else
22932       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22933   }
22934
22935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22936   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22937     return SDValue();
22938   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22939 }
22940
22941 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22942 /// nodes.
22943 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22944                                     TargetLowering::DAGCombinerInfo &DCI,
22945                                     const X86Subtarget *Subtarget) {
22946   SDLoc DL(N);
22947   SDValue Cond = N->getOperand(0);
22948   // Get the LHS/RHS of the select.
22949   SDValue LHS = N->getOperand(1);
22950   SDValue RHS = N->getOperand(2);
22951   EVT VT = LHS.getValueType();
22952   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22953
22954   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22955   // instructions match the semantics of the common C idiom x<y?x:y but not
22956   // x<=y?x:y, because of how they handle negative zero (which can be
22957   // ignored in unsafe-math mode).
22958   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22959       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
22960       (Subtarget->hasSSE2() ||
22961        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22962     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22963
22964     unsigned Opcode = 0;
22965     // Check for x CC y ? x : y.
22966     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22967         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22968       switch (CC) {
22969       default: break;
22970       case ISD::SETULT:
22971         // Converting this to a min would handle NaNs incorrectly, and swapping
22972         // the operands would cause it to handle comparisons between positive
22973         // and negative zero incorrectly.
22974         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22975           if (!DAG.getTarget().Options.UnsafeFPMath &&
22976               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22977             break;
22978           std::swap(LHS, RHS);
22979         }
22980         Opcode = X86ISD::FMIN;
22981         break;
22982       case ISD::SETOLE:
22983         // Converting this to a min would handle comparisons between positive
22984         // and negative zero incorrectly.
22985         if (!DAG.getTarget().Options.UnsafeFPMath &&
22986             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22987           break;
22988         Opcode = X86ISD::FMIN;
22989         break;
22990       case ISD::SETULE:
22991         // Converting this to a min would handle both negative zeros and NaNs
22992         // incorrectly, but we can swap the operands to fix both.
22993         std::swap(LHS, RHS);
22994       case ISD::SETOLT:
22995       case ISD::SETLT:
22996       case ISD::SETLE:
22997         Opcode = X86ISD::FMIN;
22998         break;
22999
23000       case ISD::SETOGE:
23001         // Converting this to a max would handle comparisons between positive
23002         // and negative zero incorrectly.
23003         if (!DAG.getTarget().Options.UnsafeFPMath &&
23004             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23005           break;
23006         Opcode = X86ISD::FMAX;
23007         break;
23008       case ISD::SETUGT:
23009         // Converting this to a max would handle NaNs incorrectly, and swapping
23010         // the operands would cause it to handle comparisons between positive
23011         // and negative zero incorrectly.
23012         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23013           if (!DAG.getTarget().Options.UnsafeFPMath &&
23014               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23015             break;
23016           std::swap(LHS, RHS);
23017         }
23018         Opcode = X86ISD::FMAX;
23019         break;
23020       case ISD::SETUGE:
23021         // Converting this to a max would handle both negative zeros and NaNs
23022         // incorrectly, but we can swap the operands to fix both.
23023         std::swap(LHS, RHS);
23024       case ISD::SETOGT:
23025       case ISD::SETGT:
23026       case ISD::SETGE:
23027         Opcode = X86ISD::FMAX;
23028         break;
23029       }
23030     // Check for x CC y ? y : x -- a min/max with reversed arms.
23031     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23032                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23033       switch (CC) {
23034       default: break;
23035       case ISD::SETOGE:
23036         // Converting this to a min would handle comparisons between positive
23037         // and negative zero incorrectly, and swapping the operands would
23038         // cause it to handle NaNs incorrectly.
23039         if (!DAG.getTarget().Options.UnsafeFPMath &&
23040             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23041           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23042             break;
23043           std::swap(LHS, RHS);
23044         }
23045         Opcode = X86ISD::FMIN;
23046         break;
23047       case ISD::SETUGT:
23048         // Converting this to a min would handle NaNs incorrectly.
23049         if (!DAG.getTarget().Options.UnsafeFPMath &&
23050             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23051           break;
23052         Opcode = X86ISD::FMIN;
23053         break;
23054       case ISD::SETUGE:
23055         // Converting this to a min would handle both negative zeros and NaNs
23056         // incorrectly, but we can swap the operands to fix both.
23057         std::swap(LHS, RHS);
23058       case ISD::SETOGT:
23059       case ISD::SETGT:
23060       case ISD::SETGE:
23061         Opcode = X86ISD::FMIN;
23062         break;
23063
23064       case ISD::SETULT:
23065         // Converting this to a max would handle NaNs incorrectly.
23066         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23067           break;
23068         Opcode = X86ISD::FMAX;
23069         break;
23070       case ISD::SETOLE:
23071         // Converting this to a max would handle comparisons between positive
23072         // and negative zero incorrectly, and swapping the operands would
23073         // cause it to handle NaNs incorrectly.
23074         if (!DAG.getTarget().Options.UnsafeFPMath &&
23075             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23076           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23077             break;
23078           std::swap(LHS, RHS);
23079         }
23080         Opcode = X86ISD::FMAX;
23081         break;
23082       case ISD::SETULE:
23083         // Converting this to a max would handle both negative zeros and NaNs
23084         // incorrectly, but we can swap the operands to fix both.
23085         std::swap(LHS, RHS);
23086       case ISD::SETOLT:
23087       case ISD::SETLT:
23088       case ISD::SETLE:
23089         Opcode = X86ISD::FMAX;
23090         break;
23091       }
23092     }
23093
23094     if (Opcode)
23095       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23096   }
23097
23098   EVT CondVT = Cond.getValueType();
23099   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23100       CondVT.getVectorElementType() == MVT::i1) {
23101     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23102     // lowering on KNL. In this case we convert it to
23103     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23104     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23105     // Since SKX these selects have a proper lowering.
23106     EVT OpVT = LHS.getValueType();
23107     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23108         (OpVT.getVectorElementType() == MVT::i8 ||
23109          OpVT.getVectorElementType() == MVT::i16) &&
23110         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23111       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23112       DCI.AddToWorklist(Cond.getNode());
23113       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23114     }
23115   }
23116   // If this is a select between two integer constants, try to do some
23117   // optimizations.
23118   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23119     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23120       // Don't do this for crazy integer types.
23121       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23122         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23123         // so that TrueC (the true value) is larger than FalseC.
23124         bool NeedsCondInvert = false;
23125
23126         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23127             // Efficiently invertible.
23128             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23129              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23130               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23131           NeedsCondInvert = true;
23132           std::swap(TrueC, FalseC);
23133         }
23134
23135         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23136         if (FalseC->getAPIntValue() == 0 &&
23137             TrueC->getAPIntValue().isPowerOf2()) {
23138           if (NeedsCondInvert) // Invert the condition if needed.
23139             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23140                                DAG.getConstant(1, Cond.getValueType()));
23141
23142           // Zero extend the condition if needed.
23143           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23144
23145           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23146           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23147                              DAG.getConstant(ShAmt, MVT::i8));
23148         }
23149
23150         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23151         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23152           if (NeedsCondInvert) // Invert the condition if needed.
23153             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23154                                DAG.getConstant(1, Cond.getValueType()));
23155
23156           // Zero extend the condition if needed.
23157           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23158                              FalseC->getValueType(0), Cond);
23159           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23160                              SDValue(FalseC, 0));
23161         }
23162
23163         // Optimize cases that will turn into an LEA instruction.  This requires
23164         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23165         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23166           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23167           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23168
23169           bool isFastMultiplier = false;
23170           if (Diff < 10) {
23171             switch ((unsigned char)Diff) {
23172               default: break;
23173               case 1:  // result = add base, cond
23174               case 2:  // result = lea base(    , cond*2)
23175               case 3:  // result = lea base(cond, cond*2)
23176               case 4:  // result = lea base(    , cond*4)
23177               case 5:  // result = lea base(cond, cond*4)
23178               case 8:  // result = lea base(    , cond*8)
23179               case 9:  // result = lea base(cond, cond*8)
23180                 isFastMultiplier = true;
23181                 break;
23182             }
23183           }
23184
23185           if (isFastMultiplier) {
23186             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23187             if (NeedsCondInvert) // Invert the condition if needed.
23188               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23189                                  DAG.getConstant(1, Cond.getValueType()));
23190
23191             // Zero extend the condition if needed.
23192             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23193                                Cond);
23194             // Scale the condition by the difference.
23195             if (Diff != 1)
23196               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23197                                  DAG.getConstant(Diff, Cond.getValueType()));
23198
23199             // Add the base if non-zero.
23200             if (FalseC->getAPIntValue() != 0)
23201               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23202                                  SDValue(FalseC, 0));
23203             return Cond;
23204           }
23205         }
23206       }
23207   }
23208
23209   // Canonicalize max and min:
23210   // (x > y) ? x : y -> (x >= y) ? x : y
23211   // (x < y) ? x : y -> (x <= y) ? x : y
23212   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23213   // the need for an extra compare
23214   // against zero. e.g.
23215   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23216   // subl   %esi, %edi
23217   // testl  %edi, %edi
23218   // movl   $0, %eax
23219   // cmovgl %edi, %eax
23220   // =>
23221   // xorl   %eax, %eax
23222   // subl   %esi, $edi
23223   // cmovsl %eax, %edi
23224   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23225       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23226       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23227     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23228     switch (CC) {
23229     default: break;
23230     case ISD::SETLT:
23231     case ISD::SETGT: {
23232       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23233       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23234                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23235       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23236     }
23237     }
23238   }
23239
23240   // Early exit check
23241   if (!TLI.isTypeLegal(VT))
23242     return SDValue();
23243
23244   // Match VSELECTs into subs with unsigned saturation.
23245   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23246       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23247       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23248        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23249     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23250
23251     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23252     // left side invert the predicate to simplify logic below.
23253     SDValue Other;
23254     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23255       Other = RHS;
23256       CC = ISD::getSetCCInverse(CC, true);
23257     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23258       Other = LHS;
23259     }
23260
23261     if (Other.getNode() && Other->getNumOperands() == 2 &&
23262         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23263       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23264       SDValue CondRHS = Cond->getOperand(1);
23265
23266       // Look for a general sub with unsigned saturation first.
23267       // x >= y ? x-y : 0 --> subus x, y
23268       // x >  y ? x-y : 0 --> subus x, y
23269       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23270           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23271         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23272
23273       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23274         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23275           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23276             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23277               // If the RHS is a constant we have to reverse the const
23278               // canonicalization.
23279               // x > C-1 ? x+-C : 0 --> subus x, C
23280               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23281                   CondRHSConst->getAPIntValue() ==
23282                       (-OpRHSConst->getAPIntValue() - 1))
23283                 return DAG.getNode(
23284                     X86ISD::SUBUS, DL, VT, OpLHS,
23285                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
23286
23287           // Another special case: If C was a sign bit, the sub has been
23288           // canonicalized into a xor.
23289           // FIXME: Would it be better to use computeKnownBits to determine
23290           //        whether it's safe to decanonicalize the xor?
23291           // x s< 0 ? x^C : 0 --> subus x, C
23292           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23293               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23294               OpRHSConst->getAPIntValue().isSignBit())
23295             // Note that we have to rebuild the RHS constant here to ensure we
23296             // don't rely on particular values of undef lanes.
23297             return DAG.getNode(
23298                 X86ISD::SUBUS, DL, VT, OpLHS,
23299                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
23300         }
23301     }
23302   }
23303
23304   // Try to match a min/max vector operation.
23305   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
23306     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
23307     unsigned Opc = ret.first;
23308     bool NeedSplit = ret.second;
23309
23310     if (Opc && NeedSplit) {
23311       unsigned NumElems = VT.getVectorNumElements();
23312       // Extract the LHS vectors
23313       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
23314       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
23315
23316       // Extract the RHS vectors
23317       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
23318       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
23319
23320       // Create min/max for each subvector
23321       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
23322       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
23323
23324       // Merge the result
23325       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
23326     } else if (Opc)
23327       return DAG.getNode(Opc, DL, VT, LHS, RHS);
23328   }
23329
23330   // Simplify vector selection if condition value type matches vselect
23331   // operand type
23332   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23333     assert(Cond.getValueType().isVector() &&
23334            "vector select expects a vector selector!");
23335
23336     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23337     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23338
23339     // Try invert the condition if true value is not all 1s and false value
23340     // is not all 0s.
23341     if (!TValIsAllOnes && !FValIsAllZeros &&
23342         // Check if the selector will be produced by CMPP*/PCMP*
23343         Cond.getOpcode() == ISD::SETCC &&
23344         // Check if SETCC has already been promoted
23345         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
23346       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23347       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23348
23349       if (TValIsAllZeros || FValIsAllOnes) {
23350         SDValue CC = Cond.getOperand(2);
23351         ISD::CondCode NewCC =
23352           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23353                                Cond.getOperand(0).getValueType().isInteger());
23354         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23355         std::swap(LHS, RHS);
23356         TValIsAllOnes = FValIsAllOnes;
23357         FValIsAllZeros = TValIsAllZeros;
23358       }
23359     }
23360
23361     if (TValIsAllOnes || FValIsAllZeros) {
23362       SDValue Ret;
23363
23364       if (TValIsAllOnes && FValIsAllZeros)
23365         Ret = Cond;
23366       else if (TValIsAllOnes)
23367         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
23368                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
23369       else if (FValIsAllZeros)
23370         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23371                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
23372
23373       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
23374     }
23375   }
23376
23377   // If we know that this node is legal then we know that it is going to be
23378   // matched by one of the SSE/AVX BLEND instructions. These instructions only
23379   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
23380   // to simplify previous instructions.
23381   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23382       !DCI.isBeforeLegalize() &&
23383       // We explicitly check against v8i16 and v16i16 because, although
23384       // they're marked as Custom, they might only be legal when Cond is a
23385       // build_vector of constants. This will be taken care in a later
23386       // condition.
23387       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
23388        VT != MVT::v8i16) &&
23389       // Don't optimize vector of constants. Those are handled by
23390       // the generic code and all the bits must be properly set for
23391       // the generic optimizer.
23392       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23393     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23394
23395     // Don't optimize vector selects that map to mask-registers.
23396     if (BitWidth == 1)
23397       return SDValue();
23398
23399     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23400     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23401
23402     APInt KnownZero, KnownOne;
23403     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23404                                           DCI.isBeforeLegalizeOps());
23405     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23406         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23407                                  TLO)) {
23408       // If we changed the computation somewhere in the DAG, this change
23409       // will affect all users of Cond.
23410       // Make sure it is fine and update all the nodes so that we do not
23411       // use the generic VSELECT anymore. Otherwise, we may perform
23412       // wrong optimizations as we messed up with the actual expectation
23413       // for the vector boolean values.
23414       if (Cond != TLO.Old) {
23415         // Check all uses of that condition operand to check whether it will be
23416         // consumed by non-BLEND instructions, which may depend on all bits are
23417         // set properly.
23418         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23419              I != E; ++I)
23420           if (I->getOpcode() != ISD::VSELECT)
23421             // TODO: Add other opcodes eventually lowered into BLEND.
23422             return SDValue();
23423
23424         // Update all the users of the condition, before committing the change,
23425         // so that the VSELECT optimizations that expect the correct vector
23426         // boolean value will not be triggered.
23427         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23428              I != E; ++I)
23429           DAG.ReplaceAllUsesOfValueWith(
23430               SDValue(*I, 0),
23431               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23432                           Cond, I->getOperand(1), I->getOperand(2)));
23433         DCI.CommitTargetLoweringOpt(TLO);
23434         return SDValue();
23435       }
23436       // At this point, only Cond is changed. Change the condition
23437       // just for N to keep the opportunity to optimize all other
23438       // users their own way.
23439       DAG.ReplaceAllUsesOfValueWith(
23440           SDValue(N, 0),
23441           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23442                       TLO.New, N->getOperand(1), N->getOperand(2)));
23443       return SDValue();
23444     }
23445   }
23446
23447   // We should generate an X86ISD::BLENDI from a vselect if its argument
23448   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23449   // constants. This specific pattern gets generated when we split a
23450   // selector for a 512 bit vector in a machine without AVX512 (but with
23451   // 256-bit vectors), during legalization:
23452   //
23453   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23454   //
23455   // Iff we find this pattern and the build_vectors are built from
23456   // constants, we translate the vselect into a shuffle_vector that we
23457   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23458   if ((N->getOpcode() == ISD::VSELECT ||
23459        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23460       !DCI.isBeforeLegalize()) {
23461     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23462     if (Shuffle.getNode())
23463       return Shuffle;
23464   }
23465
23466   return SDValue();
23467 }
23468
23469 // Check whether a boolean test is testing a boolean value generated by
23470 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23471 // code.
23472 //
23473 // Simplify the following patterns:
23474 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23475 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23476 // to (Op EFLAGS Cond)
23477 //
23478 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23479 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23480 // to (Op EFLAGS !Cond)
23481 //
23482 // where Op could be BRCOND or CMOV.
23483 //
23484 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23485   // Quit if not CMP and SUB with its value result used.
23486   if (Cmp.getOpcode() != X86ISD::CMP &&
23487       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23488       return SDValue();
23489
23490   // Quit if not used as a boolean value.
23491   if (CC != X86::COND_E && CC != X86::COND_NE)
23492     return SDValue();
23493
23494   // Check CMP operands. One of them should be 0 or 1 and the other should be
23495   // an SetCC or extended from it.
23496   SDValue Op1 = Cmp.getOperand(0);
23497   SDValue Op2 = Cmp.getOperand(1);
23498
23499   SDValue SetCC;
23500   const ConstantSDNode* C = nullptr;
23501   bool needOppositeCond = (CC == X86::COND_E);
23502   bool checkAgainstTrue = false; // Is it a comparison against 1?
23503
23504   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23505     SetCC = Op2;
23506   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23507     SetCC = Op1;
23508   else // Quit if all operands are not constants.
23509     return SDValue();
23510
23511   if (C->getZExtValue() == 1) {
23512     needOppositeCond = !needOppositeCond;
23513     checkAgainstTrue = true;
23514   } else if (C->getZExtValue() != 0)
23515     // Quit if the constant is neither 0 or 1.
23516     return SDValue();
23517
23518   bool truncatedToBoolWithAnd = false;
23519   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23520   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23521          SetCC.getOpcode() == ISD::TRUNCATE ||
23522          SetCC.getOpcode() == ISD::AND) {
23523     if (SetCC.getOpcode() == ISD::AND) {
23524       int OpIdx = -1;
23525       ConstantSDNode *CS;
23526       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23527           CS->getZExtValue() == 1)
23528         OpIdx = 1;
23529       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23530           CS->getZExtValue() == 1)
23531         OpIdx = 0;
23532       if (OpIdx == -1)
23533         break;
23534       SetCC = SetCC.getOperand(OpIdx);
23535       truncatedToBoolWithAnd = true;
23536     } else
23537       SetCC = SetCC.getOperand(0);
23538   }
23539
23540   switch (SetCC.getOpcode()) {
23541   case X86ISD::SETCC_CARRY:
23542     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23543     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23544     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23545     // truncated to i1 using 'and'.
23546     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23547       break;
23548     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23549            "Invalid use of SETCC_CARRY!");
23550     // FALL THROUGH
23551   case X86ISD::SETCC:
23552     // Set the condition code or opposite one if necessary.
23553     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23554     if (needOppositeCond)
23555       CC = X86::GetOppositeBranchCondition(CC);
23556     return SetCC.getOperand(1);
23557   case X86ISD::CMOV: {
23558     // Check whether false/true value has canonical one, i.e. 0 or 1.
23559     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23560     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23561     // Quit if true value is not a constant.
23562     if (!TVal)
23563       return SDValue();
23564     // Quit if false value is not a constant.
23565     if (!FVal) {
23566       SDValue Op = SetCC.getOperand(0);
23567       // Skip 'zext' or 'trunc' node.
23568       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23569           Op.getOpcode() == ISD::TRUNCATE)
23570         Op = Op.getOperand(0);
23571       // A special case for rdrand/rdseed, where 0 is set if false cond is
23572       // found.
23573       if ((Op.getOpcode() != X86ISD::RDRAND &&
23574            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23575         return SDValue();
23576     }
23577     // Quit if false value is not the constant 0 or 1.
23578     bool FValIsFalse = true;
23579     if (FVal && FVal->getZExtValue() != 0) {
23580       if (FVal->getZExtValue() != 1)
23581         return SDValue();
23582       // If FVal is 1, opposite cond is needed.
23583       needOppositeCond = !needOppositeCond;
23584       FValIsFalse = false;
23585     }
23586     // Quit if TVal is not the constant opposite of FVal.
23587     if (FValIsFalse && TVal->getZExtValue() != 1)
23588       return SDValue();
23589     if (!FValIsFalse && TVal->getZExtValue() != 0)
23590       return SDValue();
23591     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23592     if (needOppositeCond)
23593       CC = X86::GetOppositeBranchCondition(CC);
23594     return SetCC.getOperand(3);
23595   }
23596   }
23597
23598   return SDValue();
23599 }
23600
23601 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23602 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23603                                   TargetLowering::DAGCombinerInfo &DCI,
23604                                   const X86Subtarget *Subtarget) {
23605   SDLoc DL(N);
23606
23607   // If the flag operand isn't dead, don't touch this CMOV.
23608   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23609     return SDValue();
23610
23611   SDValue FalseOp = N->getOperand(0);
23612   SDValue TrueOp = N->getOperand(1);
23613   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23614   SDValue Cond = N->getOperand(3);
23615
23616   if (CC == X86::COND_E || CC == X86::COND_NE) {
23617     switch (Cond.getOpcode()) {
23618     default: break;
23619     case X86ISD::BSR:
23620     case X86ISD::BSF:
23621       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23622       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23623         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23624     }
23625   }
23626
23627   SDValue Flags;
23628
23629   Flags = checkBoolTestSetCCCombine(Cond, CC);
23630   if (Flags.getNode() &&
23631       // Extra check as FCMOV only supports a subset of X86 cond.
23632       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23633     SDValue Ops[] = { FalseOp, TrueOp,
23634                       DAG.getConstant(CC, MVT::i8), Flags };
23635     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23636   }
23637
23638   // If this is a select between two integer constants, try to do some
23639   // optimizations.  Note that the operands are ordered the opposite of SELECT
23640   // operands.
23641   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23642     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23643       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23644       // larger than FalseC (the false value).
23645       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23646         CC = X86::GetOppositeBranchCondition(CC);
23647         std::swap(TrueC, FalseC);
23648         std::swap(TrueOp, FalseOp);
23649       }
23650
23651       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23652       // This is efficient for any integer data type (including i8/i16) and
23653       // shift amount.
23654       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23655         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23656                            DAG.getConstant(CC, MVT::i8), Cond);
23657
23658         // Zero extend the condition if needed.
23659         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23660
23661         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23662         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23663                            DAG.getConstant(ShAmt, MVT::i8));
23664         if (N->getNumValues() == 2)  // Dead flag value?
23665           return DCI.CombineTo(N, Cond, SDValue());
23666         return Cond;
23667       }
23668
23669       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23670       // for any integer data type, including i8/i16.
23671       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23672         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23673                            DAG.getConstant(CC, MVT::i8), Cond);
23674
23675         // Zero extend the condition if needed.
23676         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23677                            FalseC->getValueType(0), Cond);
23678         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23679                            SDValue(FalseC, 0));
23680
23681         if (N->getNumValues() == 2)  // Dead flag value?
23682           return DCI.CombineTo(N, Cond, SDValue());
23683         return Cond;
23684       }
23685
23686       // Optimize cases that will turn into an LEA instruction.  This requires
23687       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23688       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23689         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23690         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23691
23692         bool isFastMultiplier = false;
23693         if (Diff < 10) {
23694           switch ((unsigned char)Diff) {
23695           default: break;
23696           case 1:  // result = add base, cond
23697           case 2:  // result = lea base(    , cond*2)
23698           case 3:  // result = lea base(cond, cond*2)
23699           case 4:  // result = lea base(    , cond*4)
23700           case 5:  // result = lea base(cond, cond*4)
23701           case 8:  // result = lea base(    , cond*8)
23702           case 9:  // result = lea base(cond, cond*8)
23703             isFastMultiplier = true;
23704             break;
23705           }
23706         }
23707
23708         if (isFastMultiplier) {
23709           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23710           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23711                              DAG.getConstant(CC, MVT::i8), Cond);
23712           // Zero extend the condition if needed.
23713           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23714                              Cond);
23715           // Scale the condition by the difference.
23716           if (Diff != 1)
23717             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23718                                DAG.getConstant(Diff, Cond.getValueType()));
23719
23720           // Add the base if non-zero.
23721           if (FalseC->getAPIntValue() != 0)
23722             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23723                                SDValue(FalseC, 0));
23724           if (N->getNumValues() == 2)  // Dead flag value?
23725             return DCI.CombineTo(N, Cond, SDValue());
23726           return Cond;
23727         }
23728       }
23729     }
23730   }
23731
23732   // Handle these cases:
23733   //   (select (x != c), e, c) -> select (x != c), e, x),
23734   //   (select (x == c), c, e) -> select (x == c), x, e)
23735   // where the c is an integer constant, and the "select" is the combination
23736   // of CMOV and CMP.
23737   //
23738   // The rationale for this change is that the conditional-move from a constant
23739   // needs two instructions, however, conditional-move from a register needs
23740   // only one instruction.
23741   //
23742   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23743   //  some instruction-combining opportunities. This opt needs to be
23744   //  postponed as late as possible.
23745   //
23746   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23747     // the DCI.xxxx conditions are provided to postpone the optimization as
23748     // late as possible.
23749
23750     ConstantSDNode *CmpAgainst = nullptr;
23751     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23752         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23753         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23754
23755       if (CC == X86::COND_NE &&
23756           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23757         CC = X86::GetOppositeBranchCondition(CC);
23758         std::swap(TrueOp, FalseOp);
23759       }
23760
23761       if (CC == X86::COND_E &&
23762           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23763         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23764                           DAG.getConstant(CC, MVT::i8), Cond };
23765         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23766       }
23767     }
23768   }
23769
23770   return SDValue();
23771 }
23772
23773 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23774                                                 const X86Subtarget *Subtarget) {
23775   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23776   switch (IntNo) {
23777   default: return SDValue();
23778   // SSE/AVX/AVX2 blend intrinsics.
23779   case Intrinsic::x86_avx2_pblendvb:
23780   case Intrinsic::x86_avx2_pblendw:
23781   case Intrinsic::x86_avx2_pblendd_128:
23782   case Intrinsic::x86_avx2_pblendd_256:
23783     // Don't try to simplify this intrinsic if we don't have AVX2.
23784     if (!Subtarget->hasAVX2())
23785       return SDValue();
23786     // FALL-THROUGH
23787   case Intrinsic::x86_avx_blend_pd_256:
23788   case Intrinsic::x86_avx_blend_ps_256:
23789   case Intrinsic::x86_avx_blendv_pd_256:
23790   case Intrinsic::x86_avx_blendv_ps_256:
23791     // Don't try to simplify this intrinsic if we don't have AVX.
23792     if (!Subtarget->hasAVX())
23793       return SDValue();
23794     // FALL-THROUGH
23795   case Intrinsic::x86_sse41_pblendw:
23796   case Intrinsic::x86_sse41_blendpd:
23797   case Intrinsic::x86_sse41_blendps:
23798   case Intrinsic::x86_sse41_blendvps:
23799   case Intrinsic::x86_sse41_blendvpd:
23800   case Intrinsic::x86_sse41_pblendvb: {
23801     SDValue Op0 = N->getOperand(1);
23802     SDValue Op1 = N->getOperand(2);
23803     SDValue Mask = N->getOperand(3);
23804
23805     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23806     if (!Subtarget->hasSSE41())
23807       return SDValue();
23808
23809     // fold (blend A, A, Mask) -> A
23810     if (Op0 == Op1)
23811       return Op0;
23812     // fold (blend A, B, allZeros) -> A
23813     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23814       return Op0;
23815     // fold (blend A, B, allOnes) -> B
23816     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23817       return Op1;
23818
23819     // Simplify the case where the mask is a constant i32 value.
23820     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23821       if (C->isNullValue())
23822         return Op0;
23823       if (C->isAllOnesValue())
23824         return Op1;
23825     }
23826
23827     return SDValue();
23828   }
23829
23830   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23831   case Intrinsic::x86_sse2_psrai_w:
23832   case Intrinsic::x86_sse2_psrai_d:
23833   case Intrinsic::x86_avx2_psrai_w:
23834   case Intrinsic::x86_avx2_psrai_d:
23835   case Intrinsic::x86_sse2_psra_w:
23836   case Intrinsic::x86_sse2_psra_d:
23837   case Intrinsic::x86_avx2_psra_w:
23838   case Intrinsic::x86_avx2_psra_d: {
23839     SDValue Op0 = N->getOperand(1);
23840     SDValue Op1 = N->getOperand(2);
23841     EVT VT = Op0.getValueType();
23842     assert(VT.isVector() && "Expected a vector type!");
23843
23844     if (isa<BuildVectorSDNode>(Op1))
23845       Op1 = Op1.getOperand(0);
23846
23847     if (!isa<ConstantSDNode>(Op1))
23848       return SDValue();
23849
23850     EVT SVT = VT.getVectorElementType();
23851     unsigned SVTBits = SVT.getSizeInBits();
23852
23853     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23854     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23855     uint64_t ShAmt = C.getZExtValue();
23856
23857     // Don't try to convert this shift into a ISD::SRA if the shift
23858     // count is bigger than or equal to the element size.
23859     if (ShAmt >= SVTBits)
23860       return SDValue();
23861
23862     // Trivial case: if the shift count is zero, then fold this
23863     // into the first operand.
23864     if (ShAmt == 0)
23865       return Op0;
23866
23867     // Replace this packed shift intrinsic with a target independent
23868     // shift dag node.
23869     SDValue Splat = DAG.getConstant(C, VT);
23870     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
23871   }
23872   }
23873 }
23874
23875 /// PerformMulCombine - Optimize a single multiply with constant into two
23876 /// in order to implement it with two cheaper instructions, e.g.
23877 /// LEA + SHL, LEA + LEA.
23878 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23879                                  TargetLowering::DAGCombinerInfo &DCI) {
23880   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23881     return SDValue();
23882
23883   EVT VT = N->getValueType(0);
23884   if (VT != MVT::i64)
23885     return SDValue();
23886
23887   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23888   if (!C)
23889     return SDValue();
23890   uint64_t MulAmt = C->getZExtValue();
23891   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23892     return SDValue();
23893
23894   uint64_t MulAmt1 = 0;
23895   uint64_t MulAmt2 = 0;
23896   if ((MulAmt % 9) == 0) {
23897     MulAmt1 = 9;
23898     MulAmt2 = MulAmt / 9;
23899   } else if ((MulAmt % 5) == 0) {
23900     MulAmt1 = 5;
23901     MulAmt2 = MulAmt / 5;
23902   } else if ((MulAmt % 3) == 0) {
23903     MulAmt1 = 3;
23904     MulAmt2 = MulAmt / 3;
23905   }
23906   if (MulAmt2 &&
23907       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23908     SDLoc DL(N);
23909
23910     if (isPowerOf2_64(MulAmt2) &&
23911         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23912       // If second multiplifer is pow2, issue it first. We want the multiply by
23913       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23914       // is an add.
23915       std::swap(MulAmt1, MulAmt2);
23916
23917     SDValue NewMul;
23918     if (isPowerOf2_64(MulAmt1))
23919       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23920                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
23921     else
23922       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23923                            DAG.getConstant(MulAmt1, VT));
23924
23925     if (isPowerOf2_64(MulAmt2))
23926       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23927                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
23928     else
23929       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23930                            DAG.getConstant(MulAmt2, VT));
23931
23932     // Do not add new nodes to DAG combiner worklist.
23933     DCI.CombineTo(N, NewMul, false);
23934   }
23935   return SDValue();
23936 }
23937
23938 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23939   SDValue N0 = N->getOperand(0);
23940   SDValue N1 = N->getOperand(1);
23941   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23942   EVT VT = N0.getValueType();
23943
23944   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23945   // since the result of setcc_c is all zero's or all ones.
23946   if (VT.isInteger() && !VT.isVector() &&
23947       N1C && N0.getOpcode() == ISD::AND &&
23948       N0.getOperand(1).getOpcode() == ISD::Constant) {
23949     SDValue N00 = N0.getOperand(0);
23950     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23951         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23952           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23953          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23954       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23955       APInt ShAmt = N1C->getAPIntValue();
23956       Mask = Mask.shl(ShAmt);
23957       if (Mask != 0)
23958         return DAG.getNode(ISD::AND, SDLoc(N), VT,
23959                            N00, DAG.getConstant(Mask, VT));
23960     }
23961   }
23962
23963   // Hardware support for vector shifts is sparse which makes us scalarize the
23964   // vector operations in many cases. Also, on sandybridge ADD is faster than
23965   // shl.
23966   // (shl V, 1) -> add V,V
23967   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23968     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23969       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23970       // We shift all of the values by one. In many cases we do not have
23971       // hardware support for this operation. This is better expressed as an ADD
23972       // of two values.
23973       if (N1SplatC->getZExtValue() == 1)
23974         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23975     }
23976
23977   return SDValue();
23978 }
23979
23980 /// \brief Returns a vector of 0s if the node in input is a vector logical
23981 /// shift by a constant amount which is known to be bigger than or equal
23982 /// to the vector element size in bits.
23983 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23984                                       const X86Subtarget *Subtarget) {
23985   EVT VT = N->getValueType(0);
23986
23987   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23988       (!Subtarget->hasInt256() ||
23989        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23990     return SDValue();
23991
23992   SDValue Amt = N->getOperand(1);
23993   SDLoc DL(N);
23994   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23995     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23996       APInt ShiftAmt = AmtSplat->getAPIntValue();
23997       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23998
23999       // SSE2/AVX2 logical shifts always return a vector of 0s
24000       // if the shift amount is bigger than or equal to
24001       // the element size. The constant shift amount will be
24002       // encoded as a 8-bit immediate.
24003       if (ShiftAmt.trunc(8).uge(MaxAmount))
24004         return getZeroVector(VT, Subtarget, DAG, DL);
24005     }
24006
24007   return SDValue();
24008 }
24009
24010 /// PerformShiftCombine - Combine shifts.
24011 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24012                                    TargetLowering::DAGCombinerInfo &DCI,
24013                                    const X86Subtarget *Subtarget) {
24014   if (N->getOpcode() == ISD::SHL) {
24015     SDValue V = PerformSHLCombine(N, DAG);
24016     if (V.getNode()) return V;
24017   }
24018
24019   if (N->getOpcode() != ISD::SRA) {
24020     // Try to fold this logical shift into a zero vector.
24021     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
24022     if (V.getNode()) return V;
24023   }
24024
24025   return SDValue();
24026 }
24027
24028 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24029 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24030 // and friends.  Likewise for OR -> CMPNEQSS.
24031 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24032                             TargetLowering::DAGCombinerInfo &DCI,
24033                             const X86Subtarget *Subtarget) {
24034   unsigned opcode;
24035
24036   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24037   // we're requiring SSE2 for both.
24038   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24039     SDValue N0 = N->getOperand(0);
24040     SDValue N1 = N->getOperand(1);
24041     SDValue CMP0 = N0->getOperand(1);
24042     SDValue CMP1 = N1->getOperand(1);
24043     SDLoc DL(N);
24044
24045     // The SETCCs should both refer to the same CMP.
24046     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24047       return SDValue();
24048
24049     SDValue CMP00 = CMP0->getOperand(0);
24050     SDValue CMP01 = CMP0->getOperand(1);
24051     EVT     VT    = CMP00.getValueType();
24052
24053     if (VT == MVT::f32 || VT == MVT::f64) {
24054       bool ExpectingFlags = false;
24055       // Check for any users that want flags:
24056       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24057            !ExpectingFlags && UI != UE; ++UI)
24058         switch (UI->getOpcode()) {
24059         default:
24060         case ISD::BR_CC:
24061         case ISD::BRCOND:
24062         case ISD::SELECT:
24063           ExpectingFlags = true;
24064           break;
24065         case ISD::CopyToReg:
24066         case ISD::SIGN_EXTEND:
24067         case ISD::ZERO_EXTEND:
24068         case ISD::ANY_EXTEND:
24069           break;
24070         }
24071
24072       if (!ExpectingFlags) {
24073         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24074         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24075
24076         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24077           X86::CondCode tmp = cc0;
24078           cc0 = cc1;
24079           cc1 = tmp;
24080         }
24081
24082         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24083             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24084           // FIXME: need symbolic constants for these magic numbers.
24085           // See X86ATTInstPrinter.cpp:printSSECC().
24086           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24087           if (Subtarget->hasAVX512()) {
24088             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24089                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
24090             if (N->getValueType(0) != MVT::i1)
24091               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24092                                  FSetCC);
24093             return FSetCC;
24094           }
24095           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24096                                               CMP00.getValueType(), CMP00, CMP01,
24097                                               DAG.getConstant(x86cc, MVT::i8));
24098
24099           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24100           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24101
24102           if (is64BitFP && !Subtarget->is64Bit()) {
24103             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24104             // 64-bit integer, since that's not a legal type. Since
24105             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24106             // bits, but can do this little dance to extract the lowest 32 bits
24107             // and work with those going forward.
24108             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24109                                            OnesOrZeroesF);
24110             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
24111                                            Vector64);
24112             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24113                                         Vector32, DAG.getIntPtrConstant(0));
24114             IntVT = MVT::i32;
24115           }
24116
24117           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
24118           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24119                                       DAG.getConstant(1, IntVT));
24120           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
24121           return OneBitOfTruth;
24122         }
24123       }
24124     }
24125   }
24126   return SDValue();
24127 }
24128
24129 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24130 /// so it can be folded inside ANDNP.
24131 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24132   EVT VT = N->getValueType(0);
24133
24134   // Match direct AllOnes for 128 and 256-bit vectors
24135   if (ISD::isBuildVectorAllOnes(N))
24136     return true;
24137
24138   // Look through a bit convert.
24139   if (N->getOpcode() == ISD::BITCAST)
24140     N = N->getOperand(0).getNode();
24141
24142   // Sometimes the operand may come from a insert_subvector building a 256-bit
24143   // allones vector
24144   if (VT.is256BitVector() &&
24145       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24146     SDValue V1 = N->getOperand(0);
24147     SDValue V2 = N->getOperand(1);
24148
24149     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24150         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24151         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24152         ISD::isBuildVectorAllOnes(V2.getNode()))
24153       return true;
24154   }
24155
24156   return false;
24157 }
24158
24159 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24160 // register. In most cases we actually compare or select YMM-sized registers
24161 // and mixing the two types creates horrible code. This method optimizes
24162 // some of the transition sequences.
24163 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24164                                  TargetLowering::DAGCombinerInfo &DCI,
24165                                  const X86Subtarget *Subtarget) {
24166   EVT VT = N->getValueType(0);
24167   if (!VT.is256BitVector())
24168     return SDValue();
24169
24170   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24171           N->getOpcode() == ISD::ZERO_EXTEND ||
24172           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24173
24174   SDValue Narrow = N->getOperand(0);
24175   EVT NarrowVT = Narrow->getValueType(0);
24176   if (!NarrowVT.is128BitVector())
24177     return SDValue();
24178
24179   if (Narrow->getOpcode() != ISD::XOR &&
24180       Narrow->getOpcode() != ISD::AND &&
24181       Narrow->getOpcode() != ISD::OR)
24182     return SDValue();
24183
24184   SDValue N0  = Narrow->getOperand(0);
24185   SDValue N1  = Narrow->getOperand(1);
24186   SDLoc DL(Narrow);
24187
24188   // The Left side has to be a trunc.
24189   if (N0.getOpcode() != ISD::TRUNCATE)
24190     return SDValue();
24191
24192   // The type of the truncated inputs.
24193   EVT WideVT = N0->getOperand(0)->getValueType(0);
24194   if (WideVT != VT)
24195     return SDValue();
24196
24197   // The right side has to be a 'trunc' or a constant vector.
24198   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24199   ConstantSDNode *RHSConstSplat = nullptr;
24200   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24201     RHSConstSplat = RHSBV->getConstantSplatNode();
24202   if (!RHSTrunc && !RHSConstSplat)
24203     return SDValue();
24204
24205   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24206
24207   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24208     return SDValue();
24209
24210   // Set N0 and N1 to hold the inputs to the new wide operation.
24211   N0 = N0->getOperand(0);
24212   if (RHSConstSplat) {
24213     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24214                      SDValue(RHSConstSplat, 0));
24215     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24216     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24217   } else if (RHSTrunc) {
24218     N1 = N1->getOperand(0);
24219   }
24220
24221   // Generate the wide operation.
24222   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24223   unsigned Opcode = N->getOpcode();
24224   switch (Opcode) {
24225   case ISD::ANY_EXTEND:
24226     return Op;
24227   case ISD::ZERO_EXTEND: {
24228     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24229     APInt Mask = APInt::getAllOnesValue(InBits);
24230     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24231     return DAG.getNode(ISD::AND, DL, VT,
24232                        Op, DAG.getConstant(Mask, VT));
24233   }
24234   case ISD::SIGN_EXTEND:
24235     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24236                        Op, DAG.getValueType(NarrowVT));
24237   default:
24238     llvm_unreachable("Unexpected opcode");
24239   }
24240 }
24241
24242 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24243                                  TargetLowering::DAGCombinerInfo &DCI,
24244                                  const X86Subtarget *Subtarget) {
24245   EVT VT = N->getValueType(0);
24246   if (DCI.isBeforeLegalizeOps())
24247     return SDValue();
24248
24249   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24250   if (R.getNode())
24251     return R;
24252
24253   // Create BEXTR instructions
24254   // BEXTR is ((X >> imm) & (2**size-1))
24255   if (VT == MVT::i32 || VT == MVT::i64) {
24256     SDValue N0 = N->getOperand(0);
24257     SDValue N1 = N->getOperand(1);
24258     SDLoc DL(N);
24259
24260     // Check for BEXTR.
24261     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24262         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24263       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24264       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24265       if (MaskNode && ShiftNode) {
24266         uint64_t Mask = MaskNode->getZExtValue();
24267         uint64_t Shift = ShiftNode->getZExtValue();
24268         if (isMask_64(Mask)) {
24269           uint64_t MaskSize = CountPopulation_64(Mask);
24270           if (Shift + MaskSize <= VT.getSizeInBits())
24271             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24272                                DAG.getConstant(Shift | (MaskSize << 8), VT));
24273         }
24274       }
24275     } // BEXTR
24276
24277     return SDValue();
24278   }
24279
24280   // Want to form ANDNP nodes:
24281   // 1) In the hopes of then easily combining them with OR and AND nodes
24282   //    to form PBLEND/PSIGN.
24283   // 2) To match ANDN packed intrinsics
24284   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24285     return SDValue();
24286
24287   SDValue N0 = N->getOperand(0);
24288   SDValue N1 = N->getOperand(1);
24289   SDLoc DL(N);
24290
24291   // Check LHS for vnot
24292   if (N0.getOpcode() == ISD::XOR &&
24293       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24294       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24295     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24296
24297   // Check RHS for vnot
24298   if (N1.getOpcode() == ISD::XOR &&
24299       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24300       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24301     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24302
24303   return SDValue();
24304 }
24305
24306 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24307                                 TargetLowering::DAGCombinerInfo &DCI,
24308                                 const X86Subtarget *Subtarget) {
24309   if (DCI.isBeforeLegalizeOps())
24310     return SDValue();
24311
24312   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24313   if (R.getNode())
24314     return R;
24315
24316   SDValue N0 = N->getOperand(0);
24317   SDValue N1 = N->getOperand(1);
24318   EVT VT = N->getValueType(0);
24319
24320   // look for psign/blend
24321   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24322     if (!Subtarget->hasSSSE3() ||
24323         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24324       return SDValue();
24325
24326     // Canonicalize pandn to RHS
24327     if (N0.getOpcode() == X86ISD::ANDNP)
24328       std::swap(N0, N1);
24329     // or (and (m, y), (pandn m, x))
24330     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24331       SDValue Mask = N1.getOperand(0);
24332       SDValue X    = N1.getOperand(1);
24333       SDValue Y;
24334       if (N0.getOperand(0) == Mask)
24335         Y = N0.getOperand(1);
24336       if (N0.getOperand(1) == Mask)
24337         Y = N0.getOperand(0);
24338
24339       // Check to see if the mask appeared in both the AND and ANDNP and
24340       if (!Y.getNode())
24341         return SDValue();
24342
24343       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24344       // Look through mask bitcast.
24345       if (Mask.getOpcode() == ISD::BITCAST)
24346         Mask = Mask.getOperand(0);
24347       if (X.getOpcode() == ISD::BITCAST)
24348         X = X.getOperand(0);
24349       if (Y.getOpcode() == ISD::BITCAST)
24350         Y = Y.getOperand(0);
24351
24352       EVT MaskVT = Mask.getValueType();
24353
24354       // Validate that the Mask operand is a vector sra node.
24355       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24356       // there is no psrai.b
24357       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24358       unsigned SraAmt = ~0;
24359       if (Mask.getOpcode() == ISD::SRA) {
24360         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24361           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24362             SraAmt = AmtConst->getZExtValue();
24363       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24364         SDValue SraC = Mask.getOperand(1);
24365         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24366       }
24367       if ((SraAmt + 1) != EltBits)
24368         return SDValue();
24369
24370       SDLoc DL(N);
24371
24372       // Now we know we at least have a plendvb with the mask val.  See if
24373       // we can form a psignb/w/d.
24374       // psign = x.type == y.type == mask.type && y = sub(0, x);
24375       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24376           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24377           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24378         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24379                "Unsupported VT for PSIGN");
24380         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24381         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24382       }
24383       // PBLENDVB only available on SSE 4.1
24384       if (!Subtarget->hasSSE41())
24385         return SDValue();
24386
24387       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24388
24389       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
24390       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
24391       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
24392       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24393       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24394     }
24395   }
24396
24397   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24398     return SDValue();
24399
24400   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24401   MachineFunction &MF = DAG.getMachineFunction();
24402   bool OptForSize = MF.getFunction()->getAttributes().
24403     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
24404
24405   // SHLD/SHRD instructions have lower register pressure, but on some
24406   // platforms they have higher latency than the equivalent
24407   // series of shifts/or that would otherwise be generated.
24408   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24409   // have higher latencies and we are not optimizing for size.
24410   if (!OptForSize && Subtarget->isSHLDSlow())
24411     return SDValue();
24412
24413   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24414     std::swap(N0, N1);
24415   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24416     return SDValue();
24417   if (!N0.hasOneUse() || !N1.hasOneUse())
24418     return SDValue();
24419
24420   SDValue ShAmt0 = N0.getOperand(1);
24421   if (ShAmt0.getValueType() != MVT::i8)
24422     return SDValue();
24423   SDValue ShAmt1 = N1.getOperand(1);
24424   if (ShAmt1.getValueType() != MVT::i8)
24425     return SDValue();
24426   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24427     ShAmt0 = ShAmt0.getOperand(0);
24428   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24429     ShAmt1 = ShAmt1.getOperand(0);
24430
24431   SDLoc DL(N);
24432   unsigned Opc = X86ISD::SHLD;
24433   SDValue Op0 = N0.getOperand(0);
24434   SDValue Op1 = N1.getOperand(0);
24435   if (ShAmt0.getOpcode() == ISD::SUB) {
24436     Opc = X86ISD::SHRD;
24437     std::swap(Op0, Op1);
24438     std::swap(ShAmt0, ShAmt1);
24439   }
24440
24441   unsigned Bits = VT.getSizeInBits();
24442   if (ShAmt1.getOpcode() == ISD::SUB) {
24443     SDValue Sum = ShAmt1.getOperand(0);
24444     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24445       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24446       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24447         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24448       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24449         return DAG.getNode(Opc, DL, VT,
24450                            Op0, Op1,
24451                            DAG.getNode(ISD::TRUNCATE, DL,
24452                                        MVT::i8, ShAmt0));
24453     }
24454   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24455     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24456     if (ShAmt0C &&
24457         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24458       return DAG.getNode(Opc, DL, VT,
24459                          N0.getOperand(0), N1.getOperand(0),
24460                          DAG.getNode(ISD::TRUNCATE, DL,
24461                                        MVT::i8, ShAmt0));
24462   }
24463
24464   return SDValue();
24465 }
24466
24467 // Generate NEG and CMOV for integer abs.
24468 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24469   EVT VT = N->getValueType(0);
24470
24471   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24472   // 8-bit integer abs to NEG and CMOV.
24473   if (VT.isInteger() && VT.getSizeInBits() == 8)
24474     return SDValue();
24475
24476   SDValue N0 = N->getOperand(0);
24477   SDValue N1 = N->getOperand(1);
24478   SDLoc DL(N);
24479
24480   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24481   // and change it to SUB and CMOV.
24482   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24483       N0.getOpcode() == ISD::ADD &&
24484       N0.getOperand(1) == N1 &&
24485       N1.getOpcode() == ISD::SRA &&
24486       N1.getOperand(0) == N0.getOperand(0))
24487     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24488       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24489         // Generate SUB & CMOV.
24490         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24491                                   DAG.getConstant(0, VT), N0.getOperand(0));
24492
24493         SDValue Ops[] = { N0.getOperand(0), Neg,
24494                           DAG.getConstant(X86::COND_GE, MVT::i8),
24495                           SDValue(Neg.getNode(), 1) };
24496         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24497       }
24498   return SDValue();
24499 }
24500
24501 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24502 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24503                                  TargetLowering::DAGCombinerInfo &DCI,
24504                                  const X86Subtarget *Subtarget) {
24505   if (DCI.isBeforeLegalizeOps())
24506     return SDValue();
24507
24508   if (Subtarget->hasCMov()) {
24509     SDValue RV = performIntegerAbsCombine(N, DAG);
24510     if (RV.getNode())
24511       return RV;
24512   }
24513
24514   return SDValue();
24515 }
24516
24517 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24518 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24519                                   TargetLowering::DAGCombinerInfo &DCI,
24520                                   const X86Subtarget *Subtarget) {
24521   LoadSDNode *Ld = cast<LoadSDNode>(N);
24522   EVT RegVT = Ld->getValueType(0);
24523   EVT MemVT = Ld->getMemoryVT();
24524   SDLoc dl(Ld);
24525   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24526
24527   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24528   // into two 16-byte operations.
24529   ISD::LoadExtType Ext = Ld->getExtensionType();
24530   unsigned Alignment = Ld->getAlignment();
24531   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24532   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24533       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24534     unsigned NumElems = RegVT.getVectorNumElements();
24535     if (NumElems < 2)
24536       return SDValue();
24537
24538     SDValue Ptr = Ld->getBasePtr();
24539     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
24540
24541     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24542                                   NumElems/2);
24543     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24544                                 Ld->getPointerInfo(), Ld->isVolatile(),
24545                                 Ld->isNonTemporal(), Ld->isInvariant(),
24546                                 Alignment);
24547     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24548     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24549                                 Ld->getPointerInfo(), Ld->isVolatile(),
24550                                 Ld->isNonTemporal(), Ld->isInvariant(),
24551                                 std::min(16U, Alignment));
24552     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24553                              Load1.getValue(1),
24554                              Load2.getValue(1));
24555
24556     SDValue NewVec = DAG.getUNDEF(RegVT);
24557     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24558     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24559     return DCI.CombineTo(N, NewVec, TF, true);
24560   }
24561
24562   return SDValue();
24563 }
24564
24565 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24566 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24567                                    const X86Subtarget *Subtarget) {
24568   StoreSDNode *St = cast<StoreSDNode>(N);
24569   EVT VT = St->getValue().getValueType();
24570   EVT StVT = St->getMemoryVT();
24571   SDLoc dl(St);
24572   SDValue StoredVal = St->getOperand(1);
24573   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24574
24575   // If we are saving a concatenation of two XMM registers and 32-byte stores
24576   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24577   unsigned Alignment = St->getAlignment();
24578   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24579   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24580       StVT == VT && !IsAligned) {
24581     unsigned NumElems = VT.getVectorNumElements();
24582     if (NumElems < 2)
24583       return SDValue();
24584
24585     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24586     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24587
24588     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
24589     SDValue Ptr0 = St->getBasePtr();
24590     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24591
24592     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24593                                 St->getPointerInfo(), St->isVolatile(),
24594                                 St->isNonTemporal(), Alignment);
24595     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24596                                 St->getPointerInfo(), St->isVolatile(),
24597                                 St->isNonTemporal(),
24598                                 std::min(16U, Alignment));
24599     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24600   }
24601
24602   // Optimize trunc store (of multiple scalars) to shuffle and store.
24603   // First, pack all of the elements in one place. Next, store to memory
24604   // in fewer chunks.
24605   if (St->isTruncatingStore() && VT.isVector()) {
24606     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24607     unsigned NumElems = VT.getVectorNumElements();
24608     assert(StVT != VT && "Cannot truncate to the same type");
24609     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24610     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24611
24612     // From, To sizes and ElemCount must be pow of two
24613     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24614     // We are going to use the original vector elt for storing.
24615     // Accumulated smaller vector elements must be a multiple of the store size.
24616     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24617
24618     unsigned SizeRatio  = FromSz / ToSz;
24619
24620     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24621
24622     // Create a type on which we perform the shuffle
24623     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24624             StVT.getScalarType(), NumElems*SizeRatio);
24625
24626     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24627
24628     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
24629     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24630     for (unsigned i = 0; i != NumElems; ++i)
24631       ShuffleVec[i] = i * SizeRatio;
24632
24633     // Can't shuffle using an illegal type.
24634     if (!TLI.isTypeLegal(WideVecVT))
24635       return SDValue();
24636
24637     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24638                                          DAG.getUNDEF(WideVecVT),
24639                                          &ShuffleVec[0]);
24640     // At this point all of the data is stored at the bottom of the
24641     // register. We now need to save it to mem.
24642
24643     // Find the largest store unit
24644     MVT StoreType = MVT::i8;
24645     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
24646          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
24647       MVT Tp = (MVT::SimpleValueType)tp;
24648       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24649         StoreType = Tp;
24650     }
24651
24652     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24653     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24654         (64 <= NumElems * ToSz))
24655       StoreType = MVT::f64;
24656
24657     // Bitcast the original vector into a vector of store-size units
24658     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24659             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24660     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24661     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
24662     SmallVector<SDValue, 8> Chains;
24663     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
24664                                         TLI.getPointerTy());
24665     SDValue Ptr = St->getBasePtr();
24666
24667     // Perform one or more big stores into memory.
24668     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24669       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24670                                    StoreType, ShuffWide,
24671                                    DAG.getIntPtrConstant(i));
24672       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24673                                 St->getPointerInfo(), St->isVolatile(),
24674                                 St->isNonTemporal(), St->getAlignment());
24675       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24676       Chains.push_back(Ch);
24677     }
24678
24679     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24680   }
24681
24682   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24683   // the FP state in cases where an emms may be missing.
24684   // A preferable solution to the general problem is to figure out the right
24685   // places to insert EMMS.  This qualifies as a quick hack.
24686
24687   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24688   if (VT.getSizeInBits() != 64)
24689     return SDValue();
24690
24691   const Function *F = DAG.getMachineFunction().getFunction();
24692   bool NoImplicitFloatOps = F->getAttributes().
24693     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
24694   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
24695                      && Subtarget->hasSSE2();
24696   if ((VT.isVector() ||
24697        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24698       isa<LoadSDNode>(St->getValue()) &&
24699       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24700       St->getChain().hasOneUse() && !St->isVolatile()) {
24701     SDNode* LdVal = St->getValue().getNode();
24702     LoadSDNode *Ld = nullptr;
24703     int TokenFactorIndex = -1;
24704     SmallVector<SDValue, 8> Ops;
24705     SDNode* ChainVal = St->getChain().getNode();
24706     // Must be a store of a load.  We currently handle two cases:  the load
24707     // is a direct child, and it's under an intervening TokenFactor.  It is
24708     // possible to dig deeper under nested TokenFactors.
24709     if (ChainVal == LdVal)
24710       Ld = cast<LoadSDNode>(St->getChain());
24711     else if (St->getValue().hasOneUse() &&
24712              ChainVal->getOpcode() == ISD::TokenFactor) {
24713       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24714         if (ChainVal->getOperand(i).getNode() == LdVal) {
24715           TokenFactorIndex = i;
24716           Ld = cast<LoadSDNode>(St->getValue());
24717         } else
24718           Ops.push_back(ChainVal->getOperand(i));
24719       }
24720     }
24721
24722     if (!Ld || !ISD::isNormalLoad(Ld))
24723       return SDValue();
24724
24725     // If this is not the MMX case, i.e. we are just turning i64 load/store
24726     // into f64 load/store, avoid the transformation if there are multiple
24727     // uses of the loaded value.
24728     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24729       return SDValue();
24730
24731     SDLoc LdDL(Ld);
24732     SDLoc StDL(N);
24733     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24734     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24735     // pair instead.
24736     if (Subtarget->is64Bit() || F64IsLegal) {
24737       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24738       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24739                                   Ld->getPointerInfo(), Ld->isVolatile(),
24740                                   Ld->isNonTemporal(), Ld->isInvariant(),
24741                                   Ld->getAlignment());
24742       SDValue NewChain = NewLd.getValue(1);
24743       if (TokenFactorIndex != -1) {
24744         Ops.push_back(NewChain);
24745         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24746       }
24747       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24748                           St->getPointerInfo(),
24749                           St->isVolatile(), St->isNonTemporal(),
24750                           St->getAlignment());
24751     }
24752
24753     // Otherwise, lower to two pairs of 32-bit loads / stores.
24754     SDValue LoAddr = Ld->getBasePtr();
24755     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24756                                  DAG.getConstant(4, MVT::i32));
24757
24758     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24759                                Ld->getPointerInfo(),
24760                                Ld->isVolatile(), Ld->isNonTemporal(),
24761                                Ld->isInvariant(), Ld->getAlignment());
24762     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24763                                Ld->getPointerInfo().getWithOffset(4),
24764                                Ld->isVolatile(), Ld->isNonTemporal(),
24765                                Ld->isInvariant(),
24766                                MinAlign(Ld->getAlignment(), 4));
24767
24768     SDValue NewChain = LoLd.getValue(1);
24769     if (TokenFactorIndex != -1) {
24770       Ops.push_back(LoLd);
24771       Ops.push_back(HiLd);
24772       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24773     }
24774
24775     LoAddr = St->getBasePtr();
24776     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24777                          DAG.getConstant(4, MVT::i32));
24778
24779     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24780                                 St->getPointerInfo(),
24781                                 St->isVolatile(), St->isNonTemporal(),
24782                                 St->getAlignment());
24783     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24784                                 St->getPointerInfo().getWithOffset(4),
24785                                 St->isVolatile(),
24786                                 St->isNonTemporal(),
24787                                 MinAlign(St->getAlignment(), 4));
24788     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24789   }
24790   return SDValue();
24791 }
24792
24793 /// Return 'true' if this vector operation is "horizontal"
24794 /// and return the operands for the horizontal operation in LHS and RHS.  A
24795 /// horizontal operation performs the binary operation on successive elements
24796 /// of its first operand, then on successive elements of its second operand,
24797 /// returning the resulting values in a vector.  For example, if
24798 ///   A = < float a0, float a1, float a2, float a3 >
24799 /// and
24800 ///   B = < float b0, float b1, float b2, float b3 >
24801 /// then the result of doing a horizontal operation on A and B is
24802 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24803 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24804 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24805 /// set to A, RHS to B, and the routine returns 'true'.
24806 /// Note that the binary operation should have the property that if one of the
24807 /// operands is UNDEF then the result is UNDEF.
24808 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24809   // Look for the following pattern: if
24810   //   A = < float a0, float a1, float a2, float a3 >
24811   //   B = < float b0, float b1, float b2, float b3 >
24812   // and
24813   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24814   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24815   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24816   // which is A horizontal-op B.
24817
24818   // At least one of the operands should be a vector shuffle.
24819   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24820       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24821     return false;
24822
24823   MVT VT = LHS.getSimpleValueType();
24824
24825   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24826          "Unsupported vector type for horizontal add/sub");
24827
24828   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24829   // operate independently on 128-bit lanes.
24830   unsigned NumElts = VT.getVectorNumElements();
24831   unsigned NumLanes = VT.getSizeInBits()/128;
24832   unsigned NumLaneElts = NumElts / NumLanes;
24833   assert((NumLaneElts % 2 == 0) &&
24834          "Vector type should have an even number of elements in each lane");
24835   unsigned HalfLaneElts = NumLaneElts/2;
24836
24837   // View LHS in the form
24838   //   LHS = VECTOR_SHUFFLE A, B, LMask
24839   // If LHS is not a shuffle then pretend it is the shuffle
24840   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24841   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24842   // type VT.
24843   SDValue A, B;
24844   SmallVector<int, 16> LMask(NumElts);
24845   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24846     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24847       A = LHS.getOperand(0);
24848     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24849       B = LHS.getOperand(1);
24850     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24851     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24852   } else {
24853     if (LHS.getOpcode() != ISD::UNDEF)
24854       A = LHS;
24855     for (unsigned i = 0; i != NumElts; ++i)
24856       LMask[i] = i;
24857   }
24858
24859   // Likewise, view RHS in the form
24860   //   RHS = VECTOR_SHUFFLE C, D, RMask
24861   SDValue C, D;
24862   SmallVector<int, 16> RMask(NumElts);
24863   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24864     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24865       C = RHS.getOperand(0);
24866     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24867       D = RHS.getOperand(1);
24868     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24869     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24870   } else {
24871     if (RHS.getOpcode() != ISD::UNDEF)
24872       C = RHS;
24873     for (unsigned i = 0; i != NumElts; ++i)
24874       RMask[i] = i;
24875   }
24876
24877   // Check that the shuffles are both shuffling the same vectors.
24878   if (!(A == C && B == D) && !(A == D && B == C))
24879     return false;
24880
24881   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24882   if (!A.getNode() && !B.getNode())
24883     return false;
24884
24885   // If A and B occur in reverse order in RHS, then "swap" them (which means
24886   // rewriting the mask).
24887   if (A != C)
24888     CommuteVectorShuffleMask(RMask, NumElts);
24889
24890   // At this point LHS and RHS are equivalent to
24891   //   LHS = VECTOR_SHUFFLE A, B, LMask
24892   //   RHS = VECTOR_SHUFFLE A, B, RMask
24893   // Check that the masks correspond to performing a horizontal operation.
24894   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24895     for (unsigned i = 0; i != NumLaneElts; ++i) {
24896       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24897
24898       // Ignore any UNDEF components.
24899       if (LIdx < 0 || RIdx < 0 ||
24900           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24901           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24902         continue;
24903
24904       // Check that successive elements are being operated on.  If not, this is
24905       // not a horizontal operation.
24906       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24907       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24908       if (!(LIdx == Index && RIdx == Index + 1) &&
24909           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24910         return false;
24911     }
24912   }
24913
24914   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24915   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24916   return true;
24917 }
24918
24919 /// Do target-specific dag combines on floating point adds.
24920 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24921                                   const X86Subtarget *Subtarget) {
24922   EVT VT = N->getValueType(0);
24923   SDValue LHS = N->getOperand(0);
24924   SDValue RHS = N->getOperand(1);
24925
24926   // Try to synthesize horizontal adds from adds of shuffles.
24927   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24928        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24929       isHorizontalBinOp(LHS, RHS, true))
24930     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24931   return SDValue();
24932 }
24933
24934 /// Do target-specific dag combines on floating point subs.
24935 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24936                                   const X86Subtarget *Subtarget) {
24937   EVT VT = N->getValueType(0);
24938   SDValue LHS = N->getOperand(0);
24939   SDValue RHS = N->getOperand(1);
24940
24941   // Try to synthesize horizontal subs from subs of shuffles.
24942   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24943        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24944       isHorizontalBinOp(LHS, RHS, false))
24945     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24946   return SDValue();
24947 }
24948
24949 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24950 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24951   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24952   // F[X]OR(0.0, x) -> x
24953   // F[X]OR(x, 0.0) -> x
24954   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24955     if (C->getValueAPF().isPosZero())
24956       return N->getOperand(1);
24957   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24958     if (C->getValueAPF().isPosZero())
24959       return N->getOperand(0);
24960   return SDValue();
24961 }
24962
24963 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24964 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24965   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24966
24967   // Only perform optimizations if UnsafeMath is used.
24968   if (!DAG.getTarget().Options.UnsafeFPMath)
24969     return SDValue();
24970
24971   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24972   // into FMINC and FMAXC, which are Commutative operations.
24973   unsigned NewOp = 0;
24974   switch (N->getOpcode()) {
24975     default: llvm_unreachable("unknown opcode");
24976     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24977     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24978   }
24979
24980   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24981                      N->getOperand(0), N->getOperand(1));
24982 }
24983
24984 /// Do target-specific dag combines on X86ISD::FAND nodes.
24985 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24986   // FAND(0.0, x) -> 0.0
24987   // FAND(x, 0.0) -> 0.0
24988   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24989     if (C->getValueAPF().isPosZero())
24990       return N->getOperand(0);
24991   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24992     if (C->getValueAPF().isPosZero())
24993       return N->getOperand(1);
24994   return SDValue();
24995 }
24996
24997 /// Do target-specific dag combines on X86ISD::FANDN nodes
24998 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24999   // FANDN(x, 0.0) -> 0.0
25000   // FANDN(0.0, x) -> x
25001   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25002     if (C->getValueAPF().isPosZero())
25003       return N->getOperand(1);
25004   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25005     if (C->getValueAPF().isPosZero())
25006       return N->getOperand(1);
25007   return SDValue();
25008 }
25009
25010 static SDValue PerformBTCombine(SDNode *N,
25011                                 SelectionDAG &DAG,
25012                                 TargetLowering::DAGCombinerInfo &DCI) {
25013   // BT ignores high bits in the bit index operand.
25014   SDValue Op1 = N->getOperand(1);
25015   if (Op1.hasOneUse()) {
25016     unsigned BitWidth = Op1.getValueSizeInBits();
25017     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25018     APInt KnownZero, KnownOne;
25019     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25020                                           !DCI.isBeforeLegalizeOps());
25021     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25022     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25023         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25024       DCI.CommitTargetLoweringOpt(TLO);
25025   }
25026   return SDValue();
25027 }
25028
25029 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25030   SDValue Op = N->getOperand(0);
25031   if (Op.getOpcode() == ISD::BITCAST)
25032     Op = Op.getOperand(0);
25033   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25034   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25035       VT.getVectorElementType().getSizeInBits() ==
25036       OpVT.getVectorElementType().getSizeInBits()) {
25037     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25038   }
25039   return SDValue();
25040 }
25041
25042 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25043                                                const X86Subtarget *Subtarget) {
25044   EVT VT = N->getValueType(0);
25045   if (!VT.isVector())
25046     return SDValue();
25047
25048   SDValue N0 = N->getOperand(0);
25049   SDValue N1 = N->getOperand(1);
25050   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25051   SDLoc dl(N);
25052
25053   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25054   // both SSE and AVX2 since there is no sign-extended shift right
25055   // operation on a vector with 64-bit elements.
25056   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25057   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25058   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25059       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25060     SDValue N00 = N0.getOperand(0);
25061
25062     // EXTLOAD has a better solution on AVX2,
25063     // it may be replaced with X86ISD::VSEXT node.
25064     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25065       if (!ISD::isNormalLoad(N00.getNode()))
25066         return SDValue();
25067
25068     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25069         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25070                                   N00, N1);
25071       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25072     }
25073   }
25074   return SDValue();
25075 }
25076
25077 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25078                                   TargetLowering::DAGCombinerInfo &DCI,
25079                                   const X86Subtarget *Subtarget) {
25080   SDValue N0 = N->getOperand(0);
25081   EVT VT = N->getValueType(0);
25082
25083   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25084   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25085   // This exposes the sext to the sdivrem lowering, so that it directly extends
25086   // from AH (which we otherwise need to do contortions to access).
25087   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25088       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
25089     SDLoc dl(N);
25090     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25091     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
25092                             N0.getOperand(0), N0.getOperand(1));
25093     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25094     return R.getValue(1);
25095   }
25096
25097   if (!DCI.isBeforeLegalizeOps())
25098     return SDValue();
25099
25100   if (!Subtarget->hasFp256())
25101     return SDValue();
25102
25103   if (VT.isVector() && VT.getSizeInBits() == 256) {
25104     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
25105     if (R.getNode())
25106       return R;
25107   }
25108
25109   return SDValue();
25110 }
25111
25112 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25113                                  const X86Subtarget* Subtarget) {
25114   SDLoc dl(N);
25115   EVT VT = N->getValueType(0);
25116
25117   // Let legalize expand this if it isn't a legal type yet.
25118   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25119     return SDValue();
25120
25121   EVT ScalarVT = VT.getScalarType();
25122   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25123       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
25124     return SDValue();
25125
25126   SDValue A = N->getOperand(0);
25127   SDValue B = N->getOperand(1);
25128   SDValue C = N->getOperand(2);
25129
25130   bool NegA = (A.getOpcode() == ISD::FNEG);
25131   bool NegB = (B.getOpcode() == ISD::FNEG);
25132   bool NegC = (C.getOpcode() == ISD::FNEG);
25133
25134   // Negative multiplication when NegA xor NegB
25135   bool NegMul = (NegA != NegB);
25136   if (NegA)
25137     A = A.getOperand(0);
25138   if (NegB)
25139     B = B.getOperand(0);
25140   if (NegC)
25141     C = C.getOperand(0);
25142
25143   unsigned Opcode;
25144   if (!NegMul)
25145     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25146   else
25147     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25148
25149   return DAG.getNode(Opcode, dl, VT, A, B, C);
25150 }
25151
25152 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25153                                   TargetLowering::DAGCombinerInfo &DCI,
25154                                   const X86Subtarget *Subtarget) {
25155   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25156   //           (and (i32 x86isd::setcc_carry), 1)
25157   // This eliminates the zext. This transformation is necessary because
25158   // ISD::SETCC is always legalized to i8.
25159   SDLoc dl(N);
25160   SDValue N0 = N->getOperand(0);
25161   EVT VT = N->getValueType(0);
25162
25163   if (N0.getOpcode() == ISD::AND &&
25164       N0.hasOneUse() &&
25165       N0.getOperand(0).hasOneUse()) {
25166     SDValue N00 = N0.getOperand(0);
25167     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25168       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25169       if (!C || C->getZExtValue() != 1)
25170         return SDValue();
25171       return DAG.getNode(ISD::AND, dl, VT,
25172                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25173                                      N00.getOperand(0), N00.getOperand(1)),
25174                          DAG.getConstant(1, VT));
25175     }
25176   }
25177
25178   if (N0.getOpcode() == ISD::TRUNCATE &&
25179       N0.hasOneUse() &&
25180       N0.getOperand(0).hasOneUse()) {
25181     SDValue N00 = N0.getOperand(0);
25182     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25183       return DAG.getNode(ISD::AND, dl, VT,
25184                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25185                                      N00.getOperand(0), N00.getOperand(1)),
25186                          DAG.getConstant(1, VT));
25187     }
25188   }
25189   if (VT.is256BitVector()) {
25190     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
25191     if (R.getNode())
25192       return R;
25193   }
25194
25195   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25196   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25197   // This exposes the zext to the udivrem lowering, so that it directly extends
25198   // from AH (which we otherwise need to do contortions to access).
25199   if (N0.getOpcode() == ISD::UDIVREM &&
25200       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25201       (VT == MVT::i32 || VT == MVT::i64)) {
25202     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25203     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25204                             N0.getOperand(0), N0.getOperand(1));
25205     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25206     return R.getValue(1);
25207   }
25208
25209   return SDValue();
25210 }
25211
25212 // Optimize x == -y --> x+y == 0
25213 //          x != -y --> x+y != 0
25214 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25215                                       const X86Subtarget* Subtarget) {
25216   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25217   SDValue LHS = N->getOperand(0);
25218   SDValue RHS = N->getOperand(1);
25219   EVT VT = N->getValueType(0);
25220   SDLoc DL(N);
25221
25222   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25223     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25224       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25225         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25226                                    LHS.getValueType(), RHS, LHS.getOperand(1));
25227         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25228                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25229       }
25230   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25231     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25232       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25233         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25234                                    RHS.getValueType(), LHS, RHS.getOperand(1));
25235         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25236                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25237       }
25238
25239   if (VT.getScalarType() == MVT::i1) {
25240     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25241       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25242     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
25243     if (!IsSEXT0 && !IsVZero0)
25244       return SDValue();
25245     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
25246       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25247     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25248
25249     if (!IsSEXT1 && !IsVZero1)
25250       return SDValue();
25251
25252     if (IsSEXT0 && IsVZero1) {
25253       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
25254       if (CC == ISD::SETEQ)
25255         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25256       return LHS.getOperand(0);
25257     }
25258     if (IsSEXT1 && IsVZero0) {
25259       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
25260       if (CC == ISD::SETEQ)
25261         return DAG.getNOT(DL, RHS.getOperand(0), VT);
25262       return RHS.getOperand(0);
25263     }
25264   }
25265
25266   return SDValue();
25267 }
25268
25269 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25270                                       const X86Subtarget *Subtarget) {
25271   SDLoc dl(N);
25272   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25273   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25274          "X86insertps is only defined for v4x32");
25275
25276   SDValue Ld = N->getOperand(1);
25277   if (MayFoldLoad(Ld)) {
25278     // Extract the countS bits from the immediate so we can get the proper
25279     // address when narrowing the vector load to a specific element.
25280     // When the second source op is a memory address, interps doesn't use
25281     // countS and just gets an f32 from that address.
25282     unsigned DestIndex =
25283         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25284     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25285   } else
25286     return SDValue();
25287
25288   // Create this as a scalar to vector to match the instruction pattern.
25289   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25290   // countS bits are ignored when loading from memory on insertps, which
25291   // means we don't need to explicitly set them to 0.
25292   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25293                      LoadScalarToVector, N->getOperand(2));
25294 }
25295
25296 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25297 // as "sbb reg,reg", since it can be extended without zext and produces
25298 // an all-ones bit which is more useful than 0/1 in some cases.
25299 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25300                                MVT VT) {
25301   if (VT == MVT::i8)
25302     return DAG.getNode(ISD::AND, DL, VT,
25303                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25304                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
25305                        DAG.getConstant(1, VT));
25306   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25307   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25308                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25309                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
25310 }
25311
25312 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25313 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25314                                    TargetLowering::DAGCombinerInfo &DCI,
25315                                    const X86Subtarget *Subtarget) {
25316   SDLoc DL(N);
25317   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25318   SDValue EFLAGS = N->getOperand(1);
25319
25320   if (CC == X86::COND_A) {
25321     // Try to convert COND_A into COND_B in an attempt to facilitate
25322     // materializing "setb reg".
25323     //
25324     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25325     // cannot take an immediate as its first operand.
25326     //
25327     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25328         EFLAGS.getValueType().isInteger() &&
25329         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25330       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25331                                    EFLAGS.getNode()->getVTList(),
25332                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25333       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25334       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25335     }
25336   }
25337
25338   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25339   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25340   // cases.
25341   if (CC == X86::COND_B)
25342     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25343
25344   SDValue Flags;
25345
25346   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25347   if (Flags.getNode()) {
25348     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25349     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25350   }
25351
25352   return SDValue();
25353 }
25354
25355 // Optimize branch condition evaluation.
25356 //
25357 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25358                                     TargetLowering::DAGCombinerInfo &DCI,
25359                                     const X86Subtarget *Subtarget) {
25360   SDLoc DL(N);
25361   SDValue Chain = N->getOperand(0);
25362   SDValue Dest = N->getOperand(1);
25363   SDValue EFLAGS = N->getOperand(3);
25364   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25365
25366   SDValue Flags;
25367
25368   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25369   if (Flags.getNode()) {
25370     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25371     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25372                        Flags);
25373   }
25374
25375   return SDValue();
25376 }
25377
25378 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25379                                                          SelectionDAG &DAG) {
25380   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25381   // optimize away operation when it's from a constant.
25382   //
25383   // The general transformation is:
25384   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25385   //       AND(VECTOR_CMP(x,y), constant2)
25386   //    constant2 = UNARYOP(constant)
25387
25388   // Early exit if this isn't a vector operation, the operand of the
25389   // unary operation isn't a bitwise AND, or if the sizes of the operations
25390   // aren't the same.
25391   EVT VT = N->getValueType(0);
25392   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25393       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25394       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25395     return SDValue();
25396
25397   // Now check that the other operand of the AND is a constant. We could
25398   // make the transformation for non-constant splats as well, but it's unclear
25399   // that would be a benefit as it would not eliminate any operations, just
25400   // perform one more step in scalar code before moving to the vector unit.
25401   if (BuildVectorSDNode *BV =
25402           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25403     // Bail out if the vector isn't a constant.
25404     if (!BV->isConstant())
25405       return SDValue();
25406
25407     // Everything checks out. Build up the new and improved node.
25408     SDLoc DL(N);
25409     EVT IntVT = BV->getValueType(0);
25410     // Create a new constant of the appropriate type for the transformed
25411     // DAG.
25412     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25413     // The AND node needs bitcasts to/from an integer vector type around it.
25414     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
25415     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25416                                  N->getOperand(0)->getOperand(0), MaskConst);
25417     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
25418     return Res;
25419   }
25420
25421   return SDValue();
25422 }
25423
25424 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25425                                         const X86TargetLowering *XTLI) {
25426   // First try to optimize away the conversion entirely when it's
25427   // conditionally from a constant. Vectors only.
25428   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
25429   if (Res != SDValue())
25430     return Res;
25431
25432   // Now move on to more general possibilities.
25433   SDValue Op0 = N->getOperand(0);
25434   EVT InVT = Op0->getValueType(0);
25435
25436   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
25437   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
25438     SDLoc dl(N);
25439     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
25440     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25441     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
25442   }
25443
25444   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25445   // a 32-bit target where SSE doesn't support i64->FP operations.
25446   if (Op0.getOpcode() == ISD::LOAD) {
25447     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25448     EVT VT = Ld->getValueType(0);
25449     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
25450         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25451         !XTLI->getSubtarget()->is64Bit() &&
25452         VT == MVT::i64) {
25453       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
25454                                           Ld->getChain(), Op0, DAG);
25455       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25456       return FILDChain;
25457     }
25458   }
25459   return SDValue();
25460 }
25461
25462 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25463 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25464                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25465   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25466   // the result is either zero or one (depending on the input carry bit).
25467   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25468   if (X86::isZeroNode(N->getOperand(0)) &&
25469       X86::isZeroNode(N->getOperand(1)) &&
25470       // We don't have a good way to replace an EFLAGS use, so only do this when
25471       // dead right now.
25472       SDValue(N, 1).use_empty()) {
25473     SDLoc DL(N);
25474     EVT VT = N->getValueType(0);
25475     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
25476     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25477                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25478                                            DAG.getConstant(X86::COND_B,MVT::i8),
25479                                            N->getOperand(2)),
25480                                DAG.getConstant(1, VT));
25481     return DCI.CombineTo(N, Res1, CarryOut);
25482   }
25483
25484   return SDValue();
25485 }
25486
25487 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25488 //      (add Y, (setne X, 0)) -> sbb -1, Y
25489 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25490 //      (sub (setne X, 0), Y) -> adc -1, Y
25491 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25492   SDLoc DL(N);
25493
25494   // Look through ZExts.
25495   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25496   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25497     return SDValue();
25498
25499   SDValue SetCC = Ext.getOperand(0);
25500   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25501     return SDValue();
25502
25503   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25504   if (CC != X86::COND_E && CC != X86::COND_NE)
25505     return SDValue();
25506
25507   SDValue Cmp = SetCC.getOperand(1);
25508   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25509       !X86::isZeroNode(Cmp.getOperand(1)) ||
25510       !Cmp.getOperand(0).getValueType().isInteger())
25511     return SDValue();
25512
25513   SDValue CmpOp0 = Cmp.getOperand(0);
25514   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25515                                DAG.getConstant(1, CmpOp0.getValueType()));
25516
25517   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25518   if (CC == X86::COND_NE)
25519     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25520                        DL, OtherVal.getValueType(), OtherVal,
25521                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
25522   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25523                      DL, OtherVal.getValueType(), OtherVal,
25524                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
25525 }
25526
25527 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25528 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25529                                  const X86Subtarget *Subtarget) {
25530   EVT VT = N->getValueType(0);
25531   SDValue Op0 = N->getOperand(0);
25532   SDValue Op1 = N->getOperand(1);
25533
25534   // Try to synthesize horizontal adds from adds of shuffles.
25535   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25536        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25537       isHorizontalBinOp(Op0, Op1, true))
25538     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25539
25540   return OptimizeConditionalInDecrement(N, DAG);
25541 }
25542
25543 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25544                                  const X86Subtarget *Subtarget) {
25545   SDValue Op0 = N->getOperand(0);
25546   SDValue Op1 = N->getOperand(1);
25547
25548   // X86 can't encode an immediate LHS of a sub. See if we can push the
25549   // negation into a preceding instruction.
25550   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25551     // If the RHS of the sub is a XOR with one use and a constant, invert the
25552     // immediate. Then add one to the LHS of the sub so we can turn
25553     // X-Y -> X+~Y+1, saving one register.
25554     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25555         isa<ConstantSDNode>(Op1.getOperand(1))) {
25556       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25557       EVT VT = Op0.getValueType();
25558       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25559                                    Op1.getOperand(0),
25560                                    DAG.getConstant(~XorC, VT));
25561       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25562                          DAG.getConstant(C->getAPIntValue()+1, VT));
25563     }
25564   }
25565
25566   // Try to synthesize horizontal adds from adds of shuffles.
25567   EVT VT = N->getValueType(0);
25568   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25569        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25570       isHorizontalBinOp(Op0, Op1, true))
25571     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25572
25573   return OptimizeConditionalInDecrement(N, DAG);
25574 }
25575
25576 /// performVZEXTCombine - Performs build vector combines
25577 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25578                                    TargetLowering::DAGCombinerInfo &DCI,
25579                                    const X86Subtarget *Subtarget) {
25580   SDLoc DL(N);
25581   MVT VT = N->getSimpleValueType(0);
25582   SDValue Op = N->getOperand(0);
25583   MVT OpVT = Op.getSimpleValueType();
25584   MVT OpEltVT = OpVT.getVectorElementType();
25585   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25586
25587   // (vzext (bitcast (vzext (x)) -> (vzext x)
25588   SDValue V = Op;
25589   while (V.getOpcode() == ISD::BITCAST)
25590     V = V.getOperand(0);
25591
25592   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25593     MVT InnerVT = V.getSimpleValueType();
25594     MVT InnerEltVT = InnerVT.getVectorElementType();
25595
25596     // If the element sizes match exactly, we can just do one larger vzext. This
25597     // is always an exact type match as vzext operates on integer types.
25598     if (OpEltVT == InnerEltVT) {
25599       assert(OpVT == InnerVT && "Types must match for vzext!");
25600       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25601     }
25602
25603     // The only other way we can combine them is if only a single element of the
25604     // inner vzext is used in the input to the outer vzext.
25605     if (InnerEltVT.getSizeInBits() < InputBits)
25606       return SDValue();
25607
25608     // In this case, the inner vzext is completely dead because we're going to
25609     // only look at bits inside of the low element. Just do the outer vzext on
25610     // a bitcast of the input to the inner.
25611     return DAG.getNode(X86ISD::VZEXT, DL, VT,
25612                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
25613   }
25614
25615   // Check if we can bypass extracting and re-inserting an element of an input
25616   // vector. Essentialy:
25617   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25618   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25619       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25620       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25621     SDValue ExtractedV = V.getOperand(0);
25622     SDValue OrigV = ExtractedV.getOperand(0);
25623     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25624       if (ExtractIdx->getZExtValue() == 0) {
25625         MVT OrigVT = OrigV.getSimpleValueType();
25626         // Extract a subvector if necessary...
25627         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25628           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25629           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25630                                     OrigVT.getVectorNumElements() / Ratio);
25631           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25632                               DAG.getIntPtrConstant(0));
25633         }
25634         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
25635         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25636       }
25637   }
25638
25639   return SDValue();
25640 }
25641
25642 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25643                                              DAGCombinerInfo &DCI) const {
25644   SelectionDAG &DAG = DCI.DAG;
25645   switch (N->getOpcode()) {
25646   default: break;
25647   case ISD::EXTRACT_VECTOR_ELT:
25648     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25649   case ISD::VSELECT:
25650   case ISD::SELECT:
25651   case X86ISD::SHRUNKBLEND:
25652     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25653   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25654   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25655   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25656   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25657   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25658   case ISD::SHL:
25659   case ISD::SRA:
25660   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25661   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25662   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25663   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25664   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25665   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25666   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
25667   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25668   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25669   case X86ISD::FXOR:
25670   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25671   case X86ISD::FMIN:
25672   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25673   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25674   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25675   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25676   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25677   case ISD::ANY_EXTEND:
25678   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25679   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25680   case ISD::SIGN_EXTEND_INREG:
25681     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25682   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
25683   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25684   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25685   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25686   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25687   case X86ISD::SHUFP:       // Handle all target specific shuffles
25688   case X86ISD::PALIGNR:
25689   case X86ISD::UNPCKH:
25690   case X86ISD::UNPCKL:
25691   case X86ISD::MOVHLPS:
25692   case X86ISD::MOVLHPS:
25693   case X86ISD::PSHUFB:
25694   case X86ISD::PSHUFD:
25695   case X86ISD::PSHUFHW:
25696   case X86ISD::PSHUFLW:
25697   case X86ISD::MOVSS:
25698   case X86ISD::MOVSD:
25699   case X86ISD::VPERMILPI:
25700   case X86ISD::VPERM2X128:
25701   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25702   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25703   case ISD::INTRINSIC_WO_CHAIN:
25704     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25705   case X86ISD::INSERTPS:
25706     return PerformINSERTPSCombine(N, DAG, Subtarget);
25707   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
25708   }
25709
25710   return SDValue();
25711 }
25712
25713 /// isTypeDesirableForOp - Return true if the target has native support for
25714 /// the specified value type and it is 'desirable' to use the type for the
25715 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25716 /// instruction encodings are longer and some i16 instructions are slow.
25717 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25718   if (!isTypeLegal(VT))
25719     return false;
25720   if (VT != MVT::i16)
25721     return true;
25722
25723   switch (Opc) {
25724   default:
25725     return true;
25726   case ISD::LOAD:
25727   case ISD::SIGN_EXTEND:
25728   case ISD::ZERO_EXTEND:
25729   case ISD::ANY_EXTEND:
25730   case ISD::SHL:
25731   case ISD::SRL:
25732   case ISD::SUB:
25733   case ISD::ADD:
25734   case ISD::MUL:
25735   case ISD::AND:
25736   case ISD::OR:
25737   case ISD::XOR:
25738     return false;
25739   }
25740 }
25741
25742 /// IsDesirableToPromoteOp - This method query the target whether it is
25743 /// beneficial for dag combiner to promote the specified node. If true, it
25744 /// should return the desired promotion type by reference.
25745 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25746   EVT VT = Op.getValueType();
25747   if (VT != MVT::i16)
25748     return false;
25749
25750   bool Promote = false;
25751   bool Commute = false;
25752   switch (Op.getOpcode()) {
25753   default: break;
25754   case ISD::LOAD: {
25755     LoadSDNode *LD = cast<LoadSDNode>(Op);
25756     // If the non-extending load has a single use and it's not live out, then it
25757     // might be folded.
25758     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25759                                                      Op.hasOneUse()*/) {
25760       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25761              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25762         // The only case where we'd want to promote LOAD (rather then it being
25763         // promoted as an operand is when it's only use is liveout.
25764         if (UI->getOpcode() != ISD::CopyToReg)
25765           return false;
25766       }
25767     }
25768     Promote = true;
25769     break;
25770   }
25771   case ISD::SIGN_EXTEND:
25772   case ISD::ZERO_EXTEND:
25773   case ISD::ANY_EXTEND:
25774     Promote = true;
25775     break;
25776   case ISD::SHL:
25777   case ISD::SRL: {
25778     SDValue N0 = Op.getOperand(0);
25779     // Look out for (store (shl (load), x)).
25780     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25781       return false;
25782     Promote = true;
25783     break;
25784   }
25785   case ISD::ADD:
25786   case ISD::MUL:
25787   case ISD::AND:
25788   case ISD::OR:
25789   case ISD::XOR:
25790     Commute = true;
25791     // fallthrough
25792   case ISD::SUB: {
25793     SDValue N0 = Op.getOperand(0);
25794     SDValue N1 = Op.getOperand(1);
25795     if (!Commute && MayFoldLoad(N1))
25796       return false;
25797     // Avoid disabling potential load folding opportunities.
25798     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25799       return false;
25800     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25801       return false;
25802     Promote = true;
25803   }
25804   }
25805
25806   PVT = MVT::i32;
25807   return Promote;
25808 }
25809
25810 //===----------------------------------------------------------------------===//
25811 //                           X86 Inline Assembly Support
25812 //===----------------------------------------------------------------------===//
25813
25814 namespace {
25815   // Helper to match a string separated by whitespace.
25816   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
25817     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
25818
25819     for (unsigned i = 0, e = args.size(); i != e; ++i) {
25820       StringRef piece(*args[i]);
25821       if (!s.startswith(piece)) // Check if the piece matches.
25822         return false;
25823
25824       s = s.substr(piece.size());
25825       StringRef::size_type pos = s.find_first_not_of(" \t");
25826       if (pos == 0) // We matched a prefix.
25827         return false;
25828
25829       s = s.substr(pos);
25830     }
25831
25832     return s.empty();
25833   }
25834   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
25835 }
25836
25837 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25838
25839   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25840     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25841         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25842         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25843
25844       if (AsmPieces.size() == 3)
25845         return true;
25846       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25847         return true;
25848     }
25849   }
25850   return false;
25851 }
25852
25853 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25854   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25855
25856   std::string AsmStr = IA->getAsmString();
25857
25858   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25859   if (!Ty || Ty->getBitWidth() % 16 != 0)
25860     return false;
25861
25862   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25863   SmallVector<StringRef, 4> AsmPieces;
25864   SplitString(AsmStr, AsmPieces, ";\n");
25865
25866   switch (AsmPieces.size()) {
25867   default: return false;
25868   case 1:
25869     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25870     // we will turn this bswap into something that will be lowered to logical
25871     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25872     // lower so don't worry about this.
25873     // bswap $0
25874     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
25875         matchAsm(AsmPieces[0], "bswapl", "$0") ||
25876         matchAsm(AsmPieces[0], "bswapq", "$0") ||
25877         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
25878         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
25879         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
25880       // No need to check constraints, nothing other than the equivalent of
25881       // "=r,0" would be valid here.
25882       return IntrinsicLowering::LowerToByteSwap(CI);
25883     }
25884
25885     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25886     if (CI->getType()->isIntegerTy(16) &&
25887         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25888         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
25889          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
25890       AsmPieces.clear();
25891       const std::string &ConstraintsStr = IA->getConstraintString();
25892       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25893       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25894       if (clobbersFlagRegisters(AsmPieces))
25895         return IntrinsicLowering::LowerToByteSwap(CI);
25896     }
25897     break;
25898   case 3:
25899     if (CI->getType()->isIntegerTy(32) &&
25900         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25901         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
25902         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
25903         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
25904       AsmPieces.clear();
25905       const std::string &ConstraintsStr = IA->getConstraintString();
25906       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25907       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25908       if (clobbersFlagRegisters(AsmPieces))
25909         return IntrinsicLowering::LowerToByteSwap(CI);
25910     }
25911
25912     if (CI->getType()->isIntegerTy(64)) {
25913       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25914       if (Constraints.size() >= 2 &&
25915           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25916           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25917         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25918         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
25919             matchAsm(AsmPieces[1], "bswap", "%edx") &&
25920             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
25921           return IntrinsicLowering::LowerToByteSwap(CI);
25922       }
25923     }
25924     break;
25925   }
25926   return false;
25927 }
25928
25929 /// getConstraintType - Given a constraint letter, return the type of
25930 /// constraint it is for this target.
25931 X86TargetLowering::ConstraintType
25932 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
25933   if (Constraint.size() == 1) {
25934     switch (Constraint[0]) {
25935     case 'R':
25936     case 'q':
25937     case 'Q':
25938     case 'f':
25939     case 't':
25940     case 'u':
25941     case 'y':
25942     case 'x':
25943     case 'Y':
25944     case 'l':
25945       return C_RegisterClass;
25946     case 'a':
25947     case 'b':
25948     case 'c':
25949     case 'd':
25950     case 'S':
25951     case 'D':
25952     case 'A':
25953       return C_Register;
25954     case 'I':
25955     case 'J':
25956     case 'K':
25957     case 'L':
25958     case 'M':
25959     case 'N':
25960     case 'G':
25961     case 'C':
25962     case 'e':
25963     case 'Z':
25964       return C_Other;
25965     default:
25966       break;
25967     }
25968   }
25969   return TargetLowering::getConstraintType(Constraint);
25970 }
25971
25972 /// Examine constraint type and operand type and determine a weight value.
25973 /// This object must already have been set up with the operand type
25974 /// and the current alternative constraint selected.
25975 TargetLowering::ConstraintWeight
25976   X86TargetLowering::getSingleConstraintMatchWeight(
25977     AsmOperandInfo &info, const char *constraint) const {
25978   ConstraintWeight weight = CW_Invalid;
25979   Value *CallOperandVal = info.CallOperandVal;
25980     // If we don't have a value, we can't do a match,
25981     // but allow it at the lowest weight.
25982   if (!CallOperandVal)
25983     return CW_Default;
25984   Type *type = CallOperandVal->getType();
25985   // Look at the constraint type.
25986   switch (*constraint) {
25987   default:
25988     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25989   case 'R':
25990   case 'q':
25991   case 'Q':
25992   case 'a':
25993   case 'b':
25994   case 'c':
25995   case 'd':
25996   case 'S':
25997   case 'D':
25998   case 'A':
25999     if (CallOperandVal->getType()->isIntegerTy())
26000       weight = CW_SpecificReg;
26001     break;
26002   case 'f':
26003   case 't':
26004   case 'u':
26005     if (type->isFloatingPointTy())
26006       weight = CW_SpecificReg;
26007     break;
26008   case 'y':
26009     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26010       weight = CW_SpecificReg;
26011     break;
26012   case 'x':
26013   case 'Y':
26014     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26015         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26016       weight = CW_Register;
26017     break;
26018   case 'I':
26019     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26020       if (C->getZExtValue() <= 31)
26021         weight = CW_Constant;
26022     }
26023     break;
26024   case 'J':
26025     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26026       if (C->getZExtValue() <= 63)
26027         weight = CW_Constant;
26028     }
26029     break;
26030   case 'K':
26031     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26032       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26033         weight = CW_Constant;
26034     }
26035     break;
26036   case 'L':
26037     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26038       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26039         weight = CW_Constant;
26040     }
26041     break;
26042   case 'M':
26043     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26044       if (C->getZExtValue() <= 3)
26045         weight = CW_Constant;
26046     }
26047     break;
26048   case 'N':
26049     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26050       if (C->getZExtValue() <= 0xff)
26051         weight = CW_Constant;
26052     }
26053     break;
26054   case 'G':
26055   case 'C':
26056     if (dyn_cast<ConstantFP>(CallOperandVal)) {
26057       weight = CW_Constant;
26058     }
26059     break;
26060   case 'e':
26061     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26062       if ((C->getSExtValue() >= -0x80000000LL) &&
26063           (C->getSExtValue() <= 0x7fffffffLL))
26064         weight = CW_Constant;
26065     }
26066     break;
26067   case 'Z':
26068     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26069       if (C->getZExtValue() <= 0xffffffff)
26070         weight = CW_Constant;
26071     }
26072     break;
26073   }
26074   return weight;
26075 }
26076
26077 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26078 /// with another that has more specific requirements based on the type of the
26079 /// corresponding operand.
26080 const char *X86TargetLowering::
26081 LowerXConstraint(EVT ConstraintVT) const {
26082   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26083   // 'f' like normal targets.
26084   if (ConstraintVT.isFloatingPoint()) {
26085     if (Subtarget->hasSSE2())
26086       return "Y";
26087     if (Subtarget->hasSSE1())
26088       return "x";
26089   }
26090
26091   return TargetLowering::LowerXConstraint(ConstraintVT);
26092 }
26093
26094 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26095 /// vector.  If it is invalid, don't add anything to Ops.
26096 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26097                                                      std::string &Constraint,
26098                                                      std::vector<SDValue>&Ops,
26099                                                      SelectionDAG &DAG) const {
26100   SDValue Result;
26101
26102   // Only support length 1 constraints for now.
26103   if (Constraint.length() > 1) return;
26104
26105   char ConstraintLetter = Constraint[0];
26106   switch (ConstraintLetter) {
26107   default: break;
26108   case 'I':
26109     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26110       if (C->getZExtValue() <= 31) {
26111         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26112         break;
26113       }
26114     }
26115     return;
26116   case 'J':
26117     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26118       if (C->getZExtValue() <= 63) {
26119         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26120         break;
26121       }
26122     }
26123     return;
26124   case 'K':
26125     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26126       if (isInt<8>(C->getSExtValue())) {
26127         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26128         break;
26129       }
26130     }
26131     return;
26132   case 'N':
26133     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26134       if (C->getZExtValue() <= 255) {
26135         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26136         break;
26137       }
26138     }
26139     return;
26140   case 'e': {
26141     // 32-bit signed value
26142     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26143       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26144                                            C->getSExtValue())) {
26145         // Widen to 64 bits here to get it sign extended.
26146         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
26147         break;
26148       }
26149     // FIXME gcc accepts some relocatable values here too, but only in certain
26150     // memory models; it's complicated.
26151     }
26152     return;
26153   }
26154   case 'Z': {
26155     // 32-bit unsigned value
26156     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26157       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26158                                            C->getZExtValue())) {
26159         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
26160         break;
26161       }
26162     }
26163     // FIXME gcc accepts some relocatable values here too, but only in certain
26164     // memory models; it's complicated.
26165     return;
26166   }
26167   case 'i': {
26168     // Literal immediates are always ok.
26169     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26170       // Widen to 64 bits here to get it sign extended.
26171       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
26172       break;
26173     }
26174
26175     // In any sort of PIC mode addresses need to be computed at runtime by
26176     // adding in a register or some sort of table lookup.  These can't
26177     // be used as immediates.
26178     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26179       return;
26180
26181     // If we are in non-pic codegen mode, we allow the address of a global (with
26182     // an optional displacement) to be used with 'i'.
26183     GlobalAddressSDNode *GA = nullptr;
26184     int64_t Offset = 0;
26185
26186     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26187     while (1) {
26188       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26189         Offset += GA->getOffset();
26190         break;
26191       } else if (Op.getOpcode() == ISD::ADD) {
26192         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26193           Offset += C->getZExtValue();
26194           Op = Op.getOperand(0);
26195           continue;
26196         }
26197       } else if (Op.getOpcode() == ISD::SUB) {
26198         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26199           Offset += -C->getZExtValue();
26200           Op = Op.getOperand(0);
26201           continue;
26202         }
26203       }
26204
26205       // Otherwise, this isn't something we can handle, reject it.
26206       return;
26207     }
26208
26209     const GlobalValue *GV = GA->getGlobal();
26210     // If we require an extra load to get this address, as in PIC mode, we
26211     // can't accept it.
26212     if (isGlobalStubReference(
26213             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26214       return;
26215
26216     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26217                                         GA->getValueType(0), Offset);
26218     break;
26219   }
26220   }
26221
26222   if (Result.getNode()) {
26223     Ops.push_back(Result);
26224     return;
26225   }
26226   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26227 }
26228
26229 std::pair<unsigned, const TargetRegisterClass*>
26230 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
26231                                                 MVT VT) const {
26232   // First, see if this is a constraint that directly corresponds to an LLVM
26233   // register class.
26234   if (Constraint.size() == 1) {
26235     // GCC Constraint Letters
26236     switch (Constraint[0]) {
26237     default: break;
26238       // TODO: Slight differences here in allocation order and leaving
26239       // RIP in the class. Do they matter any more here than they do
26240       // in the normal allocation?
26241     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26242       if (Subtarget->is64Bit()) {
26243         if (VT == MVT::i32 || VT == MVT::f32)
26244           return std::make_pair(0U, &X86::GR32RegClass);
26245         if (VT == MVT::i16)
26246           return std::make_pair(0U, &X86::GR16RegClass);
26247         if (VT == MVT::i8 || VT == MVT::i1)
26248           return std::make_pair(0U, &X86::GR8RegClass);
26249         if (VT == MVT::i64 || VT == MVT::f64)
26250           return std::make_pair(0U, &X86::GR64RegClass);
26251         break;
26252       }
26253       // 32-bit fallthrough
26254     case 'Q':   // Q_REGS
26255       if (VT == MVT::i32 || VT == MVT::f32)
26256         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26257       if (VT == MVT::i16)
26258         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26259       if (VT == MVT::i8 || VT == MVT::i1)
26260         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26261       if (VT == MVT::i64)
26262         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26263       break;
26264     case 'r':   // GENERAL_REGS
26265     case 'l':   // INDEX_REGS
26266       if (VT == MVT::i8 || VT == MVT::i1)
26267         return std::make_pair(0U, &X86::GR8RegClass);
26268       if (VT == MVT::i16)
26269         return std::make_pair(0U, &X86::GR16RegClass);
26270       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26271         return std::make_pair(0U, &X86::GR32RegClass);
26272       return std::make_pair(0U, &X86::GR64RegClass);
26273     case 'R':   // LEGACY_REGS
26274       if (VT == MVT::i8 || VT == MVT::i1)
26275         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26276       if (VT == MVT::i16)
26277         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26278       if (VT == MVT::i32 || !Subtarget->is64Bit())
26279         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26280       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26281     case 'f':  // FP Stack registers.
26282       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26283       // value to the correct fpstack register class.
26284       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26285         return std::make_pair(0U, &X86::RFP32RegClass);
26286       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26287         return std::make_pair(0U, &X86::RFP64RegClass);
26288       return std::make_pair(0U, &X86::RFP80RegClass);
26289     case 'y':   // MMX_REGS if MMX allowed.
26290       if (!Subtarget->hasMMX()) break;
26291       return std::make_pair(0U, &X86::VR64RegClass);
26292     case 'Y':   // SSE_REGS if SSE2 allowed
26293       if (!Subtarget->hasSSE2()) break;
26294       // FALL THROUGH.
26295     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26296       if (!Subtarget->hasSSE1()) break;
26297
26298       switch (VT.SimpleTy) {
26299       default: break;
26300       // Scalar SSE types.
26301       case MVT::f32:
26302       case MVT::i32:
26303         return std::make_pair(0U, &X86::FR32RegClass);
26304       case MVT::f64:
26305       case MVT::i64:
26306         return std::make_pair(0U, &X86::FR64RegClass);
26307       // Vector types.
26308       case MVT::v16i8:
26309       case MVT::v8i16:
26310       case MVT::v4i32:
26311       case MVT::v2i64:
26312       case MVT::v4f32:
26313       case MVT::v2f64:
26314         return std::make_pair(0U, &X86::VR128RegClass);
26315       // AVX types.
26316       case MVT::v32i8:
26317       case MVT::v16i16:
26318       case MVT::v8i32:
26319       case MVT::v4i64:
26320       case MVT::v8f32:
26321       case MVT::v4f64:
26322         return std::make_pair(0U, &X86::VR256RegClass);
26323       case MVT::v8f64:
26324       case MVT::v16f32:
26325       case MVT::v16i32:
26326       case MVT::v8i64:
26327         return std::make_pair(0U, &X86::VR512RegClass);
26328       }
26329       break;
26330     }
26331   }
26332
26333   // Use the default implementation in TargetLowering to convert the register
26334   // constraint into a member of a register class.
26335   std::pair<unsigned, const TargetRegisterClass*> Res;
26336   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
26337
26338   // Not found as a standard register?
26339   if (!Res.second) {
26340     // Map st(0) -> st(7) -> ST0
26341     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26342         tolower(Constraint[1]) == 's' &&
26343         tolower(Constraint[2]) == 't' &&
26344         Constraint[3] == '(' &&
26345         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26346         Constraint[5] == ')' &&
26347         Constraint[6] == '}') {
26348
26349       Res.first = X86::FP0+Constraint[4]-'0';
26350       Res.second = &X86::RFP80RegClass;
26351       return Res;
26352     }
26353
26354     // GCC allows "st(0)" to be called just plain "st".
26355     if (StringRef("{st}").equals_lower(Constraint)) {
26356       Res.first = X86::FP0;
26357       Res.second = &X86::RFP80RegClass;
26358       return Res;
26359     }
26360
26361     // flags -> EFLAGS
26362     if (StringRef("{flags}").equals_lower(Constraint)) {
26363       Res.first = X86::EFLAGS;
26364       Res.second = &X86::CCRRegClass;
26365       return Res;
26366     }
26367
26368     // 'A' means EAX + EDX.
26369     if (Constraint == "A") {
26370       Res.first = X86::EAX;
26371       Res.second = &X86::GR32_ADRegClass;
26372       return Res;
26373     }
26374     return Res;
26375   }
26376
26377   // Otherwise, check to see if this is a register class of the wrong value
26378   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26379   // turn into {ax},{dx}.
26380   if (Res.second->hasType(VT))
26381     return Res;   // Correct type already, nothing to do.
26382
26383   // All of the single-register GCC register classes map their values onto
26384   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
26385   // really want an 8-bit or 32-bit register, map to the appropriate register
26386   // class and return the appropriate register.
26387   if (Res.second == &X86::GR16RegClass) {
26388     if (VT == MVT::i8 || VT == MVT::i1) {
26389       unsigned DestReg = 0;
26390       switch (Res.first) {
26391       default: break;
26392       case X86::AX: DestReg = X86::AL; break;
26393       case X86::DX: DestReg = X86::DL; break;
26394       case X86::CX: DestReg = X86::CL; break;
26395       case X86::BX: DestReg = X86::BL; break;
26396       }
26397       if (DestReg) {
26398         Res.first = DestReg;
26399         Res.second = &X86::GR8RegClass;
26400       }
26401     } else if (VT == MVT::i32 || VT == MVT::f32) {
26402       unsigned DestReg = 0;
26403       switch (Res.first) {
26404       default: break;
26405       case X86::AX: DestReg = X86::EAX; break;
26406       case X86::DX: DestReg = X86::EDX; break;
26407       case X86::CX: DestReg = X86::ECX; break;
26408       case X86::BX: DestReg = X86::EBX; break;
26409       case X86::SI: DestReg = X86::ESI; break;
26410       case X86::DI: DestReg = X86::EDI; break;
26411       case X86::BP: DestReg = X86::EBP; break;
26412       case X86::SP: DestReg = X86::ESP; break;
26413       }
26414       if (DestReg) {
26415         Res.first = DestReg;
26416         Res.second = &X86::GR32RegClass;
26417       }
26418     } else if (VT == MVT::i64 || VT == MVT::f64) {
26419       unsigned DestReg = 0;
26420       switch (Res.first) {
26421       default: break;
26422       case X86::AX: DestReg = X86::RAX; break;
26423       case X86::DX: DestReg = X86::RDX; break;
26424       case X86::CX: DestReg = X86::RCX; break;
26425       case X86::BX: DestReg = X86::RBX; break;
26426       case X86::SI: DestReg = X86::RSI; break;
26427       case X86::DI: DestReg = X86::RDI; break;
26428       case X86::BP: DestReg = X86::RBP; break;
26429       case X86::SP: DestReg = X86::RSP; break;
26430       }
26431       if (DestReg) {
26432         Res.first = DestReg;
26433         Res.second = &X86::GR64RegClass;
26434       }
26435     }
26436   } else if (Res.second == &X86::FR32RegClass ||
26437              Res.second == &X86::FR64RegClass ||
26438              Res.second == &X86::VR128RegClass ||
26439              Res.second == &X86::VR256RegClass ||
26440              Res.second == &X86::FR32XRegClass ||
26441              Res.second == &X86::FR64XRegClass ||
26442              Res.second == &X86::VR128XRegClass ||
26443              Res.second == &X86::VR256XRegClass ||
26444              Res.second == &X86::VR512RegClass) {
26445     // Handle references to XMM physical registers that got mapped into the
26446     // wrong class.  This can happen with constraints like {xmm0} where the
26447     // target independent register mapper will just pick the first match it can
26448     // find, ignoring the required type.
26449
26450     if (VT == MVT::f32 || VT == MVT::i32)
26451       Res.second = &X86::FR32RegClass;
26452     else if (VT == MVT::f64 || VT == MVT::i64)
26453       Res.second = &X86::FR64RegClass;
26454     else if (X86::VR128RegClass.hasType(VT))
26455       Res.second = &X86::VR128RegClass;
26456     else if (X86::VR256RegClass.hasType(VT))
26457       Res.second = &X86::VR256RegClass;
26458     else if (X86::VR512RegClass.hasType(VT))
26459       Res.second = &X86::VR512RegClass;
26460   }
26461
26462   return Res;
26463 }
26464
26465 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
26466                                             Type *Ty) const {
26467   // Scaling factors are not free at all.
26468   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26469   // will take 2 allocations in the out of order engine instead of 1
26470   // for plain addressing mode, i.e. inst (reg1).
26471   // E.g.,
26472   // vaddps (%rsi,%drx), %ymm0, %ymm1
26473   // Requires two allocations (one for the load, one for the computation)
26474   // whereas:
26475   // vaddps (%rsi), %ymm0, %ymm1
26476   // Requires just 1 allocation, i.e., freeing allocations for other operations
26477   // and having less micro operations to execute.
26478   //
26479   // For some X86 architectures, this is even worse because for instance for
26480   // stores, the complex addressing mode forces the instruction to use the
26481   // "load" ports instead of the dedicated "store" port.
26482   // E.g., on Haswell:
26483   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26484   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26485   if (isLegalAddressingMode(AM, Ty))
26486     // Scale represents reg2 * scale, thus account for 1
26487     // as soon as we use a second register.
26488     return AM.Scale != 0;
26489   return -1;
26490 }
26491
26492 bool X86TargetLowering::isTargetFTOL() const {
26493   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26494 }