Revert "[CodeGenPrepare] Move sign/zero extensions near loads using type promotion."
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallBitVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/VariadicFunction.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
54 #include <bitset>
55 #include <numeric>
56 #include <cctype>
57 using namespace llvm;
58
59 #define DEBUG_TYPE "x86-isel"
60
61 STATISTIC(NumTailCalls, "Number of tail calls");
62
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64     "x86-experimental-vector-widening-legalization", cl::init(false),
65     cl::desc("Enable an experimental vector type legalization through widening "
66              "rather than promotion."),
67     cl::Hidden);
68
69 static cl::opt<bool> ExperimentalVectorShuffleLowering(
70     "x86-experimental-vector-shuffle-lowering", cl::init(true),
71     cl::desc("Enable an experimental vector shuffle lowering code path."),
72     cl::Hidden);
73
74 static cl::opt<int> ReciprocalEstimateRefinementSteps(
75     "x86-recip-refinement-steps", cl::init(1),
76     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
77              "result of the hardware reciprocal estimate instruction."),
78     cl::NotHidden);
79
80 // Forward declarations.
81 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
82                        SDValue V2);
83
84 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
85                                 SelectionDAG &DAG, SDLoc dl,
86                                 unsigned vectorWidth) {
87   assert((vectorWidth == 128 || vectorWidth == 256) &&
88          "Unsupported vector width");
89   EVT VT = Vec.getValueType();
90   EVT ElVT = VT.getVectorElementType();
91   unsigned Factor = VT.getSizeInBits()/vectorWidth;
92   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
93                                   VT.getVectorNumElements()/Factor);
94
95   // Extract from UNDEF is UNDEF.
96   if (Vec.getOpcode() == ISD::UNDEF)
97     return DAG.getUNDEF(ResultVT);
98
99   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
100   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
101
102   // This is the index of the first element of the vectorWidth-bit chunk
103   // we want.
104   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
105                                * ElemsPerChunk);
106
107   // If the input is a buildvector just emit a smaller one.
108   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
109     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
110                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
111                                     ElemsPerChunk));
112
113   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
114   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
115 }
116
117 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
118 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
119 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
120 /// instructions or a simple subregister reference. Idx is an index in the
121 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
122 /// lowering EXTRACT_VECTOR_ELT operations easier.
123 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
124                                    SelectionDAG &DAG, SDLoc dl) {
125   assert((Vec.getValueType().is256BitVector() ||
126           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
127   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
128 }
129
130 /// Generate a DAG to grab 256-bits from a 512-bit vector.
131 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
132                                    SelectionDAG &DAG, SDLoc dl) {
133   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
134   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
135 }
136
137 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
138                                unsigned IdxVal, SelectionDAG &DAG,
139                                SDLoc dl, unsigned vectorWidth) {
140   assert((vectorWidth == 128 || vectorWidth == 256) &&
141          "Unsupported vector width");
142   // Inserting UNDEF is Result
143   if (Vec.getOpcode() == ISD::UNDEF)
144     return Result;
145   EVT VT = Vec.getValueType();
146   EVT ElVT = VT.getVectorElementType();
147   EVT ResultVT = Result.getValueType();
148
149   // Insert the relevant vectorWidth bits.
150   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
151
152   // This is the index of the first element of the vectorWidth-bit chunk
153   // we want.
154   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
155                                * ElemsPerChunk);
156
157   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
158   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
159 }
160
161 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
162 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
163 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
164 /// simple superregister reference.  Idx is an index in the 128 bits
165 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
166 /// lowering INSERT_VECTOR_ELT operations easier.
167 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
168                                   SelectionDAG &DAG,SDLoc dl) {
169   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
170   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
171 }
172
173 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
174                                   SelectionDAG &DAG, SDLoc dl) {
175   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
176   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
177 }
178
179 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
180 /// instructions. This is used because creating CONCAT_VECTOR nodes of
181 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
182 /// large BUILD_VECTORS.
183 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
184                                    unsigned NumElems, SelectionDAG &DAG,
185                                    SDLoc dl) {
186   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
187   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
188 }
189
190 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
191                                    unsigned NumElems, SelectionDAG &DAG,
192                                    SDLoc dl) {
193   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
194   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
195 }
196
197 // FIXME: This should stop caching the target machine as soon as
198 // we can remove resetOperationActions et al.
199 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM)
200     : TargetLowering(TM) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasSSE2();
203   X86ScalarSSEf32 = Subtarget->hasSSE1();
204   TD = getDataLayout();
205
206   resetOperationActions();
207 }
208
209 void X86TargetLowering::resetOperationActions() {
210   const TargetMachine &TM = getTargetMachine();
211   static bool FirstTimeThrough = true;
212
213   // If none of the target options have changed, then we don't need to reset the
214   // operation actions.
215   if (!FirstTimeThrough && TO == TM.Options) return;
216
217   if (!FirstTimeThrough) {
218     // Reinitialize the actions.
219     initActions();
220     FirstTimeThrough = false;
221   }
222
223   TO = TM.Options;
224
225   // Set up the TargetLowering object.
226   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227
228   // X86 is weird. It always uses i8 for shift amounts and setcc results.
229   setBooleanContents(ZeroOrOneBooleanContent);
230   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232
233   // For 64-bit, since we have so many registers, use the ILP scheduler.
234   // For 32-bit, use the register pressure specific scheduling.
235   // For Atom, always use ILP scheduling.
236   if (Subtarget->isAtom())
237     setSchedulingPreference(Sched::ILP);
238   else if (Subtarget->is64Bit())
239     setSchedulingPreference(Sched::ILP);
240   else
241     setSchedulingPreference(Sched::RegPressure);
242   const X86RegisterInfo *RegInfo =
243       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
244   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245
246   // Bypass expensive divides on Atom when compiling with O2.
247   if (TM.getOptLevel() >= CodeGenOpt::Default) {
248     if (Subtarget->hasSlowDivide32())
249       addBypassSlowDiv(32, 8);
250     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
251       addBypassSlowDiv(64, 16);
252   }
253
254   if (Subtarget->isTargetKnownWindowsMSVC()) {
255     // Setup Windows compiler runtime calls.
256     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258     setLibcallName(RTLIB::SREM_I64, "_allrem");
259     setLibcallName(RTLIB::UREM_I64, "_aullrem");
260     setLibcallName(RTLIB::MUL_I64, "_allmul");
261     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266
267     // The _ftol2 runtime function has an unusual calling conv, which
268     // is modeled by a special pseudo-instruction.
269     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
270     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
273   }
274
275   if (Subtarget->isTargetDarwin()) {
276     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277     setUseUnderscoreSetJmp(false);
278     setUseUnderscoreLongJmp(false);
279   } else if (Subtarget->isTargetWindowsGNU()) {
280     // MS runtime is weird: it exports _setjmp, but longjmp!
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(false);
283   } else {
284     setUseUnderscoreSetJmp(true);
285     setUseUnderscoreLongJmp(true);
286   }
287
288   // Set up the register classes.
289   addRegisterClass(MVT::i8, &X86::GR8RegClass);
290   addRegisterClass(MVT::i16, &X86::GR16RegClass);
291   addRegisterClass(MVT::i32, &X86::GR32RegClass);
292   if (Subtarget->is64Bit())
293     addRegisterClass(MVT::i64, &X86::GR64RegClass);
294
295   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296
297   // We don't accept any truncstore of integer registers.
298   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
304
305   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
306
307   // SETOEQ and SETUNE require checking two conditions.
308   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314
315   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316   // operation.
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
318   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
319   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
320
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
323     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
324   } else if (!TM.Options.UseSoftFloat) {
325     // We have an algorithm for SSE2->double, and we turn this into a
326     // 64-bit FILD followed by conditional FADD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
328     // We have an algorithm for SSE2, and we turn this into a 64-bit
329     // FILD for other targets.
330     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
331   }
332
333   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334   // this operation.
335   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
336   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
337
338   if (!TM.Options.UseSoftFloat) {
339     // SSE has no i16 to fp conversion, only i32
340     if (X86ScalarSSEf32) {
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
342       // f32 and f64 cases are Legal, f80 case is not
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     } else {
345       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
346       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
347     }
348   } else {
349     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
350     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
351   }
352
353   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
354   // are Legal, f80 is custom lowered.
355   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
356   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
357
358   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359   // this operation.
360   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
361   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
362
363   if (X86ScalarSSEf32) {
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
365     // f32 and f64 cases are Legal, f80 case is not
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   } else {
368     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
369     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
370   }
371
372   // Handle FP_TO_UINT by promoting the destination to a larger signed
373   // conversion.
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
375   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
376   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
377
378   if (Subtarget->is64Bit()) {
379     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
380     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
381   } else if (!TM.Options.UseSoftFloat) {
382     // Since AVX is a superset of SSE3, only check for SSE here.
383     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384       // Expand FP_TO_UINT into a select.
385       // FIXME: We would like to use a Custom expander here eventually to do
386       // the optimal thing for SSE vs. the default expansion in the legalizer.
387       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
388     else
389       // With SSE3 we can use fisttpll to convert to a signed i64; without
390       // SSE, we're stuck with a fistpll.
391       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
392   }
393
394   if (isTargetFTOL()) {
395     // Use the _ftol2 runtime function, which has a pseudo-instruction
396     // to handle its weird calling convention.
397     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
398   }
399
400   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401   if (!X86ScalarSSEf64) {
402     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
403     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
404     if (Subtarget->is64Bit()) {
405       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
406       // Without SSE, i64->f64 goes through memory.
407       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
408     }
409   }
410
411   // Scalar integer divide and remainder are lowered to use operations that
412   // produce two results, to match the available instructions. This exposes
413   // the two-result form to trivial CSE, which is able to combine x/y and x%y
414   // into a single instruction.
415   //
416   // Scalar integer multiply-high is also lowered to use two-result
417   // operations, to match the available instructions. However, plain multiply
418   // (low) operations are left as Legal, as there are single-result
419   // instructions for this in x86. Using the two-result multiply instructions
420   // when both high and low results are needed must be arranged by dagcombine.
421   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422     MVT VT = IntVTs[i];
423     setOperationAction(ISD::MULHS, VT, Expand);
424     setOperationAction(ISD::MULHU, VT, Expand);
425     setOperationAction(ISD::SDIV, VT, Expand);
426     setOperationAction(ISD::UDIV, VT, Expand);
427     setOperationAction(ISD::SREM, VT, Expand);
428     setOperationAction(ISD::UREM, VT, Expand);
429
430     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431     setOperationAction(ISD::ADDC, VT, Custom);
432     setOperationAction(ISD::ADDE, VT, Custom);
433     setOperationAction(ISD::SUBC, VT, Custom);
434     setOperationAction(ISD::SUBE, VT, Custom);
435   }
436
437   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
438   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
439   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
444   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
445   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
446   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
447   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
448   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
449   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
450   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
451   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
452   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
453   if (Subtarget->is64Bit())
454     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
455   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
456   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
457   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
458   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
459   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
460   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
461   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
462   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
463
464   // Promote the i8 variants and force them on up to i32 which has a shorter
465   // encoding.
466   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
467   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
468   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
469   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
470   if (Subtarget->hasBMI()) {
471     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
472     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
473     if (Subtarget->is64Bit())
474       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
475   } else {
476     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
477     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
478     if (Subtarget->is64Bit())
479       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
480   }
481
482   if (Subtarget->hasLZCNT()) {
483     // When promoting the i8 variants, force them to i32 for a shorter
484     // encoding.
485     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
486     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
488     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
491     if (Subtarget->is64Bit())
492       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
493   } else {
494     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
495     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
496     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
497     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
498     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
500     if (Subtarget->is64Bit()) {
501       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
502       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
503     }
504   }
505
506   // Special handling for half-precision floating point conversions.
507   // If we don't have F16C support, then lower half float conversions
508   // into library calls.
509   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
510     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
511     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
512   }
513
514   // There's never any support for operations beyond MVT::f32.
515   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
516   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
517   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
518   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
519
520   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
521   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
522   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
523   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
524
525   if (Subtarget->hasPOPCNT()) {
526     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
527   } else {
528     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
529     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
530     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
531     if (Subtarget->is64Bit())
532       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
533   }
534
535   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
536
537   if (!Subtarget->hasMOVBE())
538     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
539
540   // These should be promoted to a larger select which is supported.
541   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
542   // X86 wants to expand cmov itself.
543   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
544   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
545   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
546   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
547   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
548   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
549   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
550   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
551   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
552   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
553   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
554   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
555   if (Subtarget->is64Bit()) {
556     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
557     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
558   }
559   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
560   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
561   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
562   // support continuation, user-level threading, and etc.. As a result, no
563   // other SjLj exception interfaces are implemented and please don't build
564   // your own exception handling based on them.
565   // LLVM/Clang supports zero-cost DWARF exception handling.
566   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
567   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
568
569   // Darwin ABI issue.
570   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
571   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
572   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
573   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
574   if (Subtarget->is64Bit())
575     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
576   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
577   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
578   if (Subtarget->is64Bit()) {
579     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
580     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
581     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
582     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
583     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
584   }
585   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
586   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
587   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
588   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
589   if (Subtarget->is64Bit()) {
590     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
591     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
592     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
593   }
594
595   if (Subtarget->hasSSE1())
596     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
597
598   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
599
600   // Expand certain atomics
601   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
602     MVT VT = IntVTs[i];
603     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
604     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
605     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
606   }
607
608   if (Subtarget->hasCmpxchg16b()) {
609     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
610   }
611
612   // FIXME - use subtarget debug flags
613   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
614       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
615     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
616   }
617
618   if (Subtarget->is64Bit()) {
619     setExceptionPointerRegister(X86::RAX);
620     setExceptionSelectorRegister(X86::RDX);
621   } else {
622     setExceptionPointerRegister(X86::EAX);
623     setExceptionSelectorRegister(X86::EDX);
624   }
625   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
626   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
627
628   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
629   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
630
631   setOperationAction(ISD::TRAP, MVT::Other, Legal);
632   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
633
634   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
635   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
636   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
637   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
638     // TargetInfo::X86_64ABIBuiltinVaList
639     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
640     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
641   } else {
642     // TargetInfo::CharPtrBuiltinVaList
643     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
644     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
645   }
646
647   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
648   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
649
650   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
651
652   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
653     // f32 and f64 use SSE.
654     // Set up the FP register classes.
655     addRegisterClass(MVT::f32, &X86::FR32RegClass);
656     addRegisterClass(MVT::f64, &X86::FR64RegClass);
657
658     // Use ANDPD to simulate FABS.
659     setOperationAction(ISD::FABS , MVT::f64, Custom);
660     setOperationAction(ISD::FABS , MVT::f32, Custom);
661
662     // Use XORP to simulate FNEG.
663     setOperationAction(ISD::FNEG , MVT::f64, Custom);
664     setOperationAction(ISD::FNEG , MVT::f32, Custom);
665
666     // Use ANDPD and ORPD to simulate FCOPYSIGN.
667     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
668     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
669
670     // Lower this to FGETSIGNx86 plus an AND.
671     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
672     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
673
674     // We don't support sin/cos/fmod
675     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
676     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
677     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
678     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
679     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
680     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
681
682     // Expand FP immediates into loads from the stack, except for the special
683     // cases we handle.
684     addLegalFPImmediate(APFloat(+0.0)); // xorpd
685     addLegalFPImmediate(APFloat(+0.0f)); // xorps
686   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
687     // Use SSE for f32, x87 for f64.
688     // Set up the FP register classes.
689     addRegisterClass(MVT::f32, &X86::FR32RegClass);
690     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
691
692     // Use ANDPS to simulate FABS.
693     setOperationAction(ISD::FABS , MVT::f32, Custom);
694
695     // Use XORP to simulate FNEG.
696     setOperationAction(ISD::FNEG , MVT::f32, Custom);
697
698     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
699
700     // Use ANDPS and ORPS to simulate FCOPYSIGN.
701     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
702     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
703
704     // We don't support sin/cos/fmod
705     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
706     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
707     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
708
709     // Special cases we handle for FP constants.
710     addLegalFPImmediate(APFloat(+0.0f)); // xorps
711     addLegalFPImmediate(APFloat(+0.0)); // FLD0
712     addLegalFPImmediate(APFloat(+1.0)); // FLD1
713     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
714     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
715
716     if (!TM.Options.UnsafeFPMath) {
717       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
718       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
719       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
720     }
721   } else if (!TM.Options.UseSoftFloat) {
722     // f32 and f64 in x87.
723     // Set up the FP register classes.
724     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
725     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
726
727     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
728     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
729     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
730     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
731
732     if (!TM.Options.UnsafeFPMath) {
733       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
734       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
735       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
736       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
737       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
738       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
739     }
740     addLegalFPImmediate(APFloat(+0.0)); // FLD0
741     addLegalFPImmediate(APFloat(+1.0)); // FLD1
742     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
743     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
744     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
745     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
746     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
747     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
748   }
749
750   // We don't support FMA.
751   setOperationAction(ISD::FMA, MVT::f64, Expand);
752   setOperationAction(ISD::FMA, MVT::f32, Expand);
753
754   // Long double always uses X87.
755   if (!TM.Options.UseSoftFloat) {
756     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
757     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
758     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
759     {
760       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
761       addLegalFPImmediate(TmpFlt);  // FLD0
762       TmpFlt.changeSign();
763       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
764
765       bool ignored;
766       APFloat TmpFlt2(+1.0);
767       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
768                       &ignored);
769       addLegalFPImmediate(TmpFlt2);  // FLD1
770       TmpFlt2.changeSign();
771       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
772     }
773
774     if (!TM.Options.UnsafeFPMath) {
775       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
776       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
777       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
778     }
779
780     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
781     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
782     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
783     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
784     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
785     setOperationAction(ISD::FMA, MVT::f80, Expand);
786   }
787
788   // Always use a library call for pow.
789   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
790   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
791   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
792
793   setOperationAction(ISD::FLOG, MVT::f80, Expand);
794   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
795   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
796   setOperationAction(ISD::FEXP, MVT::f80, Expand);
797   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
798   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
799   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
800
801   // First set operation action for all vector types to either promote
802   // (for widening) or expand (for scalarization). Then we will selectively
803   // turn on ones that can be effectively codegen'd.
804   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
805            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
806     MVT VT = (MVT::SimpleValueType)i;
807     setOperationAction(ISD::ADD , VT, Expand);
808     setOperationAction(ISD::SUB , VT, Expand);
809     setOperationAction(ISD::FADD, VT, Expand);
810     setOperationAction(ISD::FNEG, VT, Expand);
811     setOperationAction(ISD::FSUB, VT, Expand);
812     setOperationAction(ISD::MUL , VT, Expand);
813     setOperationAction(ISD::FMUL, VT, Expand);
814     setOperationAction(ISD::SDIV, VT, Expand);
815     setOperationAction(ISD::UDIV, VT, Expand);
816     setOperationAction(ISD::FDIV, VT, Expand);
817     setOperationAction(ISD::SREM, VT, Expand);
818     setOperationAction(ISD::UREM, VT, Expand);
819     setOperationAction(ISD::LOAD, VT, Expand);
820     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
821     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
822     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
823     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
824     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
825     setOperationAction(ISD::FABS, VT, Expand);
826     setOperationAction(ISD::FSIN, VT, Expand);
827     setOperationAction(ISD::FSINCOS, VT, Expand);
828     setOperationAction(ISD::FCOS, VT, Expand);
829     setOperationAction(ISD::FSINCOS, VT, Expand);
830     setOperationAction(ISD::FREM, VT, Expand);
831     setOperationAction(ISD::FMA,  VT, Expand);
832     setOperationAction(ISD::FPOWI, VT, Expand);
833     setOperationAction(ISD::FSQRT, VT, Expand);
834     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
835     setOperationAction(ISD::FFLOOR, VT, Expand);
836     setOperationAction(ISD::FCEIL, VT, Expand);
837     setOperationAction(ISD::FTRUNC, VT, Expand);
838     setOperationAction(ISD::FRINT, VT, Expand);
839     setOperationAction(ISD::FNEARBYINT, VT, Expand);
840     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
841     setOperationAction(ISD::MULHS, VT, Expand);
842     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
843     setOperationAction(ISD::MULHU, VT, Expand);
844     setOperationAction(ISD::SDIVREM, VT, Expand);
845     setOperationAction(ISD::UDIVREM, VT, Expand);
846     setOperationAction(ISD::FPOW, VT, Expand);
847     setOperationAction(ISD::CTPOP, VT, Expand);
848     setOperationAction(ISD::CTTZ, VT, Expand);
849     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
850     setOperationAction(ISD::CTLZ, VT, Expand);
851     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
852     setOperationAction(ISD::SHL, VT, Expand);
853     setOperationAction(ISD::SRA, VT, Expand);
854     setOperationAction(ISD::SRL, VT, Expand);
855     setOperationAction(ISD::ROTL, VT, Expand);
856     setOperationAction(ISD::ROTR, VT, Expand);
857     setOperationAction(ISD::BSWAP, VT, Expand);
858     setOperationAction(ISD::SETCC, VT, Expand);
859     setOperationAction(ISD::FLOG, VT, Expand);
860     setOperationAction(ISD::FLOG2, VT, Expand);
861     setOperationAction(ISD::FLOG10, VT, Expand);
862     setOperationAction(ISD::FEXP, VT, Expand);
863     setOperationAction(ISD::FEXP2, VT, Expand);
864     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
865     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
866     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
867     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
868     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
869     setOperationAction(ISD::TRUNCATE, VT, Expand);
870     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
871     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
872     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
873     setOperationAction(ISD::VSELECT, VT, Expand);
874     setOperationAction(ISD::SELECT_CC, VT, Expand);
875     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
876              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
877       setTruncStoreAction(VT,
878                           (MVT::SimpleValueType)InnerVT, Expand);
879     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
880     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
881
882     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
883     // we have to deal with them whether we ask for Expansion or not. Setting
884     // Expand causes its own optimisation problems though, so leave them legal.
885     if (VT.getVectorElementType() == MVT::i1)
886       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
887   }
888
889   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
890   // with -msoft-float, disable use of MMX as well.
891   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
892     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
893     // No operations on x86mmx supported, everything uses intrinsics.
894   }
895
896   // MMX-sized vectors (other than x86mmx) are expected to be expanded
897   // into smaller operations.
898   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
899   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
900   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
901   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
902   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
903   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
904   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
905   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
906   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
907   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
908   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
909   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
910   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
911   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
912   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
913   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
914   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
915   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
916   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
917   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
918   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
919   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
920   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
921   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
922   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
923   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
924   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
925   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
926   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
927
928   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
929     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
930
931     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
932     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
933     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
934     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
935     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
936     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
937     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
938     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
939     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
940     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
942     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
943     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
944   }
945
946   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
947     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
948
949     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
950     // registers cannot be used even for integer operations.
951     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
952     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
953     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
954     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
955
956     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
957     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
958     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
959     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
960     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
961     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
962     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
963     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
964     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
965     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
966     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
967     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
968     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
969     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
971     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
972     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
973     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
974     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
975     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
976     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
977     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
978
979     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
980     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
981     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
982     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
983
984     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
985     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
989
990     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
991     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
992       MVT VT = (MVT::SimpleValueType)i;
993       // Do not attempt to custom lower non-power-of-2 vectors
994       if (!isPowerOf2_32(VT.getVectorNumElements()))
995         continue;
996       // Do not attempt to custom lower non-128-bit vectors
997       if (!VT.is128BitVector())
998         continue;
999       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1000       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1001       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1002     }
1003
1004     // We support custom legalizing of sext and anyext loads for specific
1005     // memory vector types which we can load as a scalar (or sequence of
1006     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1007     // loads these must work with a single scalar load.
1008     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1009     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1010     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1011     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1012     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1013     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1014     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1015     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1016     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1017
1018     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1019     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1020     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1021     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1022     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1023     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1024
1025     if (Subtarget->is64Bit()) {
1026       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1027       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1028     }
1029
1030     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1031     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1032       MVT VT = (MVT::SimpleValueType)i;
1033
1034       // Do not attempt to promote non-128-bit vectors
1035       if (!VT.is128BitVector())
1036         continue;
1037
1038       setOperationAction(ISD::AND,    VT, Promote);
1039       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1040       setOperationAction(ISD::OR,     VT, Promote);
1041       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1042       setOperationAction(ISD::XOR,    VT, Promote);
1043       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1044       setOperationAction(ISD::LOAD,   VT, Promote);
1045       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1046       setOperationAction(ISD::SELECT, VT, Promote);
1047       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1048     }
1049
1050     // Custom lower v2i64 and v2f64 selects.
1051     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1052     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1053     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1054     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1055
1056     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1057     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1058
1059     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1060     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1061     // As there is no 64-bit GPR available, we need build a special custom
1062     // sequence to convert from v2i32 to v2f32.
1063     if (!Subtarget->is64Bit())
1064       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1065
1066     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1067     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1068
1069     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1070
1071     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1072     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1073     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1074   }
1075
1076   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1077     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1078     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1079     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1080     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1081     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1082     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1083     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1084     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1085     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1086     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1087
1088     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1089     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1090     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1091     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1092     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1093     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1094     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1095     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1096     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1097     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1098
1099     // FIXME: Do we need to handle scalar-to-vector here?
1100     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1101
1102     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1103     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1104     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1105     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1106     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1107     // There is no BLENDI for byte vectors. We don't need to custom lower
1108     // some vselects for now.
1109     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1110
1111     // SSE41 brings specific instructions for doing vector sign extend even in
1112     // cases where we don't have SRA.
1113     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1114     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1115     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1116
1117     // i8 and i16 vectors are custom because the source register and source
1118     // source memory operand types are not the same width.  f32 vectors are
1119     // custom since the immediate controlling the insert encodes additional
1120     // information.
1121     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1122     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1123     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1124     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1125
1126     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1127     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1128     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1129     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1130
1131     // FIXME: these should be Legal, but that's only for the case where
1132     // the index is constant.  For now custom expand to deal with that.
1133     if (Subtarget->is64Bit()) {
1134       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1135       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1136     }
1137   }
1138
1139   if (Subtarget->hasSSE2()) {
1140     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1141     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1142
1143     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1144     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1145
1146     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1147     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1148
1149     // In the customized shift lowering, the legal cases in AVX2 will be
1150     // recognized.
1151     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1152     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1153
1154     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1155     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1156
1157     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1158   }
1159
1160   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1161     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1162     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1163     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1164     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1165     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1166     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1167
1168     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1169     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1170     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1171
1172     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1173     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1174     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1175     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1176     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1177     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1178     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1179     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1180     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1181     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1182     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1183     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1184
1185     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1186     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1187     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1188     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1189     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1190     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1191     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1192     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1193     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1194     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1195     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1196     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1197
1198     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1199     // even though v8i16 is a legal type.
1200     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1201     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1202     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1203
1204     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1205     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1206     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1207
1208     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1209     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1210
1211     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1212
1213     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1214     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1215
1216     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1217     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1218
1219     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1220     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1221
1222     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1223     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1224     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1225     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1226
1227     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1228     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1229     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1230
1231     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1232     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1233     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1234     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1235
1236     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1237     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1238     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1239     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1240     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1241     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1242     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1243     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1244     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1245     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1246     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1247     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1248
1249     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1250       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1251       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1252       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1253       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1254       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1255       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1256     }
1257
1258     if (Subtarget->hasInt256()) {
1259       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1260       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1261       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1262       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1263
1264       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1265       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1266       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1267       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1268
1269       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1270       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1271       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1272       // Don't lower v32i8 because there is no 128-bit byte mul
1273
1274       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1275       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1276       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1277       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1278
1279       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1280       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1281
1282       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1283       // when we have a 256bit-wide blend with immediate.
1284       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1285     } else {
1286       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1287       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1288       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1289       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1290
1291       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1292       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1293       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1294       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1295
1296       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1297       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1298       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1299       // Don't lower v32i8 because there is no 128-bit byte mul
1300     }
1301
1302     // In the customized shift lowering, the legal cases in AVX2 will be
1303     // recognized.
1304     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1305     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1306
1307     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1308     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1309
1310     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1311
1312     // Custom lower several nodes for 256-bit types.
1313     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1314              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1315       MVT VT = (MVT::SimpleValueType)i;
1316
1317       // Extract subvector is special because the value type
1318       // (result) is 128-bit but the source is 256-bit wide.
1319       if (VT.is128BitVector()) {
1320         if (VT.getScalarSizeInBits() >= 32) {
1321           setOperationAction(ISD::MLOAD,  VT, Custom);
1322           setOperationAction(ISD::MSTORE, VT, Custom);
1323         }
1324         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1325       }
1326       // Do not attempt to custom lower other non-256-bit vectors
1327       if (!VT.is256BitVector())
1328         continue;
1329
1330       if (VT.getScalarSizeInBits() >= 32) {
1331         setOperationAction(ISD::MLOAD,  VT, Legal);
1332         setOperationAction(ISD::MSTORE, VT, Legal);
1333       }
1334       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1335       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1336       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1337       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1338       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1339       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1340       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1341     }
1342
1343     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1344     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1345       MVT VT = (MVT::SimpleValueType)i;
1346
1347       // Do not attempt to promote non-256-bit vectors
1348       if (!VT.is256BitVector())
1349         continue;
1350
1351       setOperationAction(ISD::AND,    VT, Promote);
1352       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1353       setOperationAction(ISD::OR,     VT, Promote);
1354       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1355       setOperationAction(ISD::XOR,    VT, Promote);
1356       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1357       setOperationAction(ISD::LOAD,   VT, Promote);
1358       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1359       setOperationAction(ISD::SELECT, VT, Promote);
1360       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1361     }
1362   }
1363
1364   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1365     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1366     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1369
1370     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1371     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1372     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1373
1374     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1375     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1376     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1377     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1378     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1379     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1380     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1385
1386     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1387     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1391     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1392
1393     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1394     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1398     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1399     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1400     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1401
1402     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1403     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1405     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1406     if (Subtarget->is64Bit()) {
1407       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1408       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1410       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1411     }
1412     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1413     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1416     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1417     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1419     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1420     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1421     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1422     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1423     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1424     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1425     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1426
1427     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1431     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1432     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1433     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1434     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1438     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1439     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1440
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1445     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1446     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1447
1448     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1449     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1450
1451     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1452
1453     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1454     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1455     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1456     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1457     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1458     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1460     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1461     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1462
1463     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1464     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1465
1466     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1467     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1468
1469     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1470
1471     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1472     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1473
1474     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1475     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1476
1477     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1478     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1479
1480     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1482     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1483     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1484     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1485     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1486
1487     if (Subtarget->hasCDI()) {
1488       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1489       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1490     }
1491
1492     // Custom lower several nodes.
1493     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1494              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1495       MVT VT = (MVT::SimpleValueType)i;
1496
1497       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1498       // Extract subvector is special because the value type
1499       // (result) is 256/128-bit but the source is 512-bit wide.
1500       if (VT.is128BitVector() || VT.is256BitVector()) {
1501         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1502         if ( EltSize >= 32) {
1503           setOperationAction(ISD::MLOAD,   VT, Legal);
1504           setOperationAction(ISD::MSTORE,  VT, Legal);
1505         }
1506       }
1507       if (VT.getVectorElementType() == MVT::i1)
1508         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1509
1510       // Do not attempt to custom lower other non-512-bit vectors
1511       if (!VT.is512BitVector())
1512         continue;
1513
1514       if ( EltSize >= 32) {
1515         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1516         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1517         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1518         setOperationAction(ISD::VSELECT,             VT, Legal);
1519         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1520         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1521         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1522         setOperationAction(ISD::MLOAD,               VT, Legal);
1523         setOperationAction(ISD::MSTORE,              VT, Legal);
1524       }
1525     }
1526     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1527       MVT VT = (MVT::SimpleValueType)i;
1528
1529       // Do not attempt to promote non-256-bit vectors.
1530       if (!VT.is512BitVector())
1531         continue;
1532
1533       setOperationAction(ISD::SELECT, VT, Promote);
1534       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1535     }
1536   }// has  AVX-512
1537
1538   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1539     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1540     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1541
1542     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1543     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1544
1545     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1546     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1547     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1548     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1549     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1550     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1551     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1552     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1553     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1554
1555     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1556       const MVT VT = (MVT::SimpleValueType)i;
1557
1558       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1559
1560       // Do not attempt to promote non-256-bit vectors.
1561       if (!VT.is512BitVector())
1562         continue;
1563
1564       if (EltSize < 32) {
1565         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1566         setOperationAction(ISD::VSELECT,             VT, Legal);
1567       }
1568     }
1569   }
1570
1571   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1572     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1573     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1574
1575     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1576     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1577     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Legal);
1578
1579     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1580     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1581     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1582     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1583     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1584     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1585   }
1586
1587   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1588   // of this type with custom code.
1589   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1590            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1591     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1592                        Custom);
1593   }
1594
1595   // We want to custom lower some of our intrinsics.
1596   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1597   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1598   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1599   if (!Subtarget->is64Bit())
1600     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1601
1602   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1603   // handle type legalization for these operations here.
1604   //
1605   // FIXME: We really should do custom legalization for addition and
1606   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1607   // than generic legalization for 64-bit multiplication-with-overflow, though.
1608   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1609     // Add/Sub/Mul with overflow operations are custom lowered.
1610     MVT VT = IntVTs[i];
1611     setOperationAction(ISD::SADDO, VT, Custom);
1612     setOperationAction(ISD::UADDO, VT, Custom);
1613     setOperationAction(ISD::SSUBO, VT, Custom);
1614     setOperationAction(ISD::USUBO, VT, Custom);
1615     setOperationAction(ISD::SMULO, VT, Custom);
1616     setOperationAction(ISD::UMULO, VT, Custom);
1617   }
1618
1619
1620   if (!Subtarget->is64Bit()) {
1621     // These libcalls are not available in 32-bit.
1622     setLibcallName(RTLIB::SHL_I128, nullptr);
1623     setLibcallName(RTLIB::SRL_I128, nullptr);
1624     setLibcallName(RTLIB::SRA_I128, nullptr);
1625   }
1626
1627   // Combine sin / cos into one node or libcall if possible.
1628   if (Subtarget->hasSinCos()) {
1629     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1630     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1631     if (Subtarget->isTargetDarwin()) {
1632       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1633       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1634       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1635       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1636     }
1637   }
1638
1639   if (Subtarget->isTargetWin64()) {
1640     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1641     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1642     setOperationAction(ISD::SREM, MVT::i128, Custom);
1643     setOperationAction(ISD::UREM, MVT::i128, Custom);
1644     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1645     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1646   }
1647
1648   // We have target-specific dag combine patterns for the following nodes:
1649   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1650   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1651   setTargetDAGCombine(ISD::VSELECT);
1652   setTargetDAGCombine(ISD::SELECT);
1653   setTargetDAGCombine(ISD::SHL);
1654   setTargetDAGCombine(ISD::SRA);
1655   setTargetDAGCombine(ISD::SRL);
1656   setTargetDAGCombine(ISD::OR);
1657   setTargetDAGCombine(ISD::AND);
1658   setTargetDAGCombine(ISD::ADD);
1659   setTargetDAGCombine(ISD::FADD);
1660   setTargetDAGCombine(ISD::FSUB);
1661   setTargetDAGCombine(ISD::FMA);
1662   setTargetDAGCombine(ISD::SUB);
1663   setTargetDAGCombine(ISD::LOAD);
1664   setTargetDAGCombine(ISD::STORE);
1665   setTargetDAGCombine(ISD::ZERO_EXTEND);
1666   setTargetDAGCombine(ISD::ANY_EXTEND);
1667   setTargetDAGCombine(ISD::SIGN_EXTEND);
1668   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1669   setTargetDAGCombine(ISD::TRUNCATE);
1670   setTargetDAGCombine(ISD::SINT_TO_FP);
1671   setTargetDAGCombine(ISD::SETCC);
1672   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1673   setTargetDAGCombine(ISD::BUILD_VECTOR);
1674   if (Subtarget->is64Bit())
1675     setTargetDAGCombine(ISD::MUL);
1676   setTargetDAGCombine(ISD::XOR);
1677
1678   computeRegisterProperties();
1679
1680   // On Darwin, -Os means optimize for size without hurting performance,
1681   // do not reduce the limit.
1682   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1683   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1684   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1685   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1686   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1687   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1688   setPrefLoopAlignment(4); // 2^4 bytes.
1689
1690   // Predictable cmov don't hurt on atom because it's in-order.
1691   PredictableSelectIsExpensive = !Subtarget->isAtom();
1692
1693   setPrefFunctionAlignment(4); // 2^4 bytes.
1694
1695   verifyIntrinsicTables();
1696 }
1697
1698 // This has so far only been implemented for 64-bit MachO.
1699 bool X86TargetLowering::useLoadStackGuardNode() const {
1700   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1701 }
1702
1703 TargetLoweringBase::LegalizeTypeAction
1704 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1705   if (ExperimentalVectorWideningLegalization &&
1706       VT.getVectorNumElements() != 1 &&
1707       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1708     return TypeWidenVector;
1709
1710   return TargetLoweringBase::getPreferredVectorAction(VT);
1711 }
1712
1713 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1714   if (!VT.isVector())
1715     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1716
1717   const unsigned NumElts = VT.getVectorNumElements();
1718   const EVT EltVT = VT.getVectorElementType();
1719   if (VT.is512BitVector()) {
1720     if (Subtarget->hasAVX512())
1721       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1722           EltVT == MVT::f32 || EltVT == MVT::f64)
1723         switch(NumElts) {
1724         case  8: return MVT::v8i1;
1725         case 16: return MVT::v16i1;
1726       }
1727     if (Subtarget->hasBWI())
1728       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1729         switch(NumElts) {
1730         case 32: return MVT::v32i1;
1731         case 64: return MVT::v64i1;
1732       }
1733   }
1734
1735   if (VT.is256BitVector() || VT.is128BitVector()) {
1736     if (Subtarget->hasVLX())
1737       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1738           EltVT == MVT::f32 || EltVT == MVT::f64)
1739         switch(NumElts) {
1740         case 2: return MVT::v2i1;
1741         case 4: return MVT::v4i1;
1742         case 8: return MVT::v8i1;
1743       }
1744     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1745       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1746         switch(NumElts) {
1747         case  8: return MVT::v8i1;
1748         case 16: return MVT::v16i1;
1749         case 32: return MVT::v32i1;
1750       }
1751   }
1752
1753   return VT.changeVectorElementTypeToInteger();
1754 }
1755
1756 /// Helper for getByValTypeAlignment to determine
1757 /// the desired ByVal argument alignment.
1758 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1759   if (MaxAlign == 16)
1760     return;
1761   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1762     if (VTy->getBitWidth() == 128)
1763       MaxAlign = 16;
1764   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1765     unsigned EltAlign = 0;
1766     getMaxByValAlign(ATy->getElementType(), EltAlign);
1767     if (EltAlign > MaxAlign)
1768       MaxAlign = EltAlign;
1769   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1770     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1771       unsigned EltAlign = 0;
1772       getMaxByValAlign(STy->getElementType(i), EltAlign);
1773       if (EltAlign > MaxAlign)
1774         MaxAlign = EltAlign;
1775       if (MaxAlign == 16)
1776         break;
1777     }
1778   }
1779 }
1780
1781 /// Return the desired alignment for ByVal aggregate
1782 /// function arguments in the caller parameter area. For X86, aggregates
1783 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1784 /// are at 4-byte boundaries.
1785 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1786   if (Subtarget->is64Bit()) {
1787     // Max of 8 and alignment of type.
1788     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1789     if (TyAlign > 8)
1790       return TyAlign;
1791     return 8;
1792   }
1793
1794   unsigned Align = 4;
1795   if (Subtarget->hasSSE1())
1796     getMaxByValAlign(Ty, Align);
1797   return Align;
1798 }
1799
1800 /// Returns the target specific optimal type for load
1801 /// and store operations as a result of memset, memcpy, and memmove
1802 /// lowering. If DstAlign is zero that means it's safe to destination
1803 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1804 /// means there isn't a need to check it against alignment requirement,
1805 /// probably because the source does not need to be loaded. If 'IsMemset' is
1806 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1807 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1808 /// source is constant so it does not need to be loaded.
1809 /// It returns EVT::Other if the type should be determined using generic
1810 /// target-independent logic.
1811 EVT
1812 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1813                                        unsigned DstAlign, unsigned SrcAlign,
1814                                        bool IsMemset, bool ZeroMemset,
1815                                        bool MemcpyStrSrc,
1816                                        MachineFunction &MF) const {
1817   const Function *F = MF.getFunction();
1818   if ((!IsMemset || ZeroMemset) &&
1819       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1820                                        Attribute::NoImplicitFloat)) {
1821     if (Size >= 16 &&
1822         (Subtarget->isUnalignedMemAccessFast() ||
1823          ((DstAlign == 0 || DstAlign >= 16) &&
1824           (SrcAlign == 0 || SrcAlign >= 16)))) {
1825       if (Size >= 32) {
1826         if (Subtarget->hasInt256())
1827           return MVT::v8i32;
1828         if (Subtarget->hasFp256())
1829           return MVT::v8f32;
1830       }
1831       if (Subtarget->hasSSE2())
1832         return MVT::v4i32;
1833       if (Subtarget->hasSSE1())
1834         return MVT::v4f32;
1835     } else if (!MemcpyStrSrc && Size >= 8 &&
1836                !Subtarget->is64Bit() &&
1837                Subtarget->hasSSE2()) {
1838       // Do not use f64 to lower memcpy if source is string constant. It's
1839       // better to use i32 to avoid the loads.
1840       return MVT::f64;
1841     }
1842   }
1843   if (Subtarget->is64Bit() && Size >= 8)
1844     return MVT::i64;
1845   return MVT::i32;
1846 }
1847
1848 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1849   if (VT == MVT::f32)
1850     return X86ScalarSSEf32;
1851   else if (VT == MVT::f64)
1852     return X86ScalarSSEf64;
1853   return true;
1854 }
1855
1856 bool
1857 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1858                                                   unsigned,
1859                                                   unsigned,
1860                                                   bool *Fast) const {
1861   if (Fast)
1862     *Fast = Subtarget->isUnalignedMemAccessFast();
1863   return true;
1864 }
1865
1866 /// Return the entry encoding for a jump table in the
1867 /// current function.  The returned value is a member of the
1868 /// MachineJumpTableInfo::JTEntryKind enum.
1869 unsigned X86TargetLowering::getJumpTableEncoding() const {
1870   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1871   // symbol.
1872   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1873       Subtarget->isPICStyleGOT())
1874     return MachineJumpTableInfo::EK_Custom32;
1875
1876   // Otherwise, use the normal jump table encoding heuristics.
1877   return TargetLowering::getJumpTableEncoding();
1878 }
1879
1880 const MCExpr *
1881 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1882                                              const MachineBasicBlock *MBB,
1883                                              unsigned uid,MCContext &Ctx) const{
1884   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1885          Subtarget->isPICStyleGOT());
1886   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1887   // entries.
1888   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1889                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1890 }
1891
1892 /// Returns relocation base for the given PIC jumptable.
1893 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1894                                                     SelectionDAG &DAG) const {
1895   if (!Subtarget->is64Bit())
1896     // This doesn't have SDLoc associated with it, but is not really the
1897     // same as a Register.
1898     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1899   return Table;
1900 }
1901
1902 /// This returns the relocation base for the given PIC jumptable,
1903 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1904 const MCExpr *X86TargetLowering::
1905 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1906                              MCContext &Ctx) const {
1907   // X86-64 uses RIP relative addressing based on the jump table label.
1908   if (Subtarget->isPICStyleRIPRel())
1909     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1910
1911   // Otherwise, the reference is relative to the PIC base.
1912   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1913 }
1914
1915 // FIXME: Why this routine is here? Move to RegInfo!
1916 std::pair<const TargetRegisterClass*, uint8_t>
1917 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1918   const TargetRegisterClass *RRC = nullptr;
1919   uint8_t Cost = 1;
1920   switch (VT.SimpleTy) {
1921   default:
1922     return TargetLowering::findRepresentativeClass(VT);
1923   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1924     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1925     break;
1926   case MVT::x86mmx:
1927     RRC = &X86::VR64RegClass;
1928     break;
1929   case MVT::f32: case MVT::f64:
1930   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1931   case MVT::v4f32: case MVT::v2f64:
1932   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1933   case MVT::v4f64:
1934     RRC = &X86::VR128RegClass;
1935     break;
1936   }
1937   return std::make_pair(RRC, Cost);
1938 }
1939
1940 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1941                                                unsigned &Offset) const {
1942   if (!Subtarget->isTargetLinux())
1943     return false;
1944
1945   if (Subtarget->is64Bit()) {
1946     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1947     Offset = 0x28;
1948     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1949       AddressSpace = 256;
1950     else
1951       AddressSpace = 257;
1952   } else {
1953     // %gs:0x14 on i386
1954     Offset = 0x14;
1955     AddressSpace = 256;
1956   }
1957   return true;
1958 }
1959
1960 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1961                                             unsigned DestAS) const {
1962   assert(SrcAS != DestAS && "Expected different address spaces!");
1963
1964   return SrcAS < 256 && DestAS < 256;
1965 }
1966
1967 //===----------------------------------------------------------------------===//
1968 //               Return Value Calling Convention Implementation
1969 //===----------------------------------------------------------------------===//
1970
1971 #include "X86GenCallingConv.inc"
1972
1973 bool
1974 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1975                                   MachineFunction &MF, bool isVarArg,
1976                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1977                         LLVMContext &Context) const {
1978   SmallVector<CCValAssign, 16> RVLocs;
1979   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1980   return CCInfo.CheckReturn(Outs, RetCC_X86);
1981 }
1982
1983 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1984   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1985   return ScratchRegs;
1986 }
1987
1988 SDValue
1989 X86TargetLowering::LowerReturn(SDValue Chain,
1990                                CallingConv::ID CallConv, bool isVarArg,
1991                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1992                                const SmallVectorImpl<SDValue> &OutVals,
1993                                SDLoc dl, SelectionDAG &DAG) const {
1994   MachineFunction &MF = DAG.getMachineFunction();
1995   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1996
1997   SmallVector<CCValAssign, 16> RVLocs;
1998   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1999   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2000
2001   SDValue Flag;
2002   SmallVector<SDValue, 6> RetOps;
2003   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2004   // Operand #1 = Bytes To Pop
2005   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2006                    MVT::i16));
2007
2008   // Copy the result values into the output registers.
2009   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2010     CCValAssign &VA = RVLocs[i];
2011     assert(VA.isRegLoc() && "Can only return in registers!");
2012     SDValue ValToCopy = OutVals[i];
2013     EVT ValVT = ValToCopy.getValueType();
2014
2015     // Promote values to the appropriate types.
2016     if (VA.getLocInfo() == CCValAssign::SExt)
2017       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2018     else if (VA.getLocInfo() == CCValAssign::ZExt)
2019       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2020     else if (VA.getLocInfo() == CCValAssign::AExt)
2021       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2022     else if (VA.getLocInfo() == CCValAssign::BCvt)
2023       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2024
2025     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2026            "Unexpected FP-extend for return value.");
2027
2028     // If this is x86-64, and we disabled SSE, we can't return FP values,
2029     // or SSE or MMX vectors.
2030     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2031          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2032           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2033       report_fatal_error("SSE register return with SSE disabled");
2034     }
2035     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2036     // llvm-gcc has never done it right and no one has noticed, so this
2037     // should be OK for now.
2038     if (ValVT == MVT::f64 &&
2039         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2040       report_fatal_error("SSE2 register return with SSE2 disabled");
2041
2042     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2043     // the RET instruction and handled by the FP Stackifier.
2044     if (VA.getLocReg() == X86::FP0 ||
2045         VA.getLocReg() == X86::FP1) {
2046       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2047       // change the value to the FP stack register class.
2048       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2049         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2050       RetOps.push_back(ValToCopy);
2051       // Don't emit a copytoreg.
2052       continue;
2053     }
2054
2055     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2056     // which is returned in RAX / RDX.
2057     if (Subtarget->is64Bit()) {
2058       if (ValVT == MVT::x86mmx) {
2059         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2060           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2061           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2062                                   ValToCopy);
2063           // If we don't have SSE2 available, convert to v4f32 so the generated
2064           // register is legal.
2065           if (!Subtarget->hasSSE2())
2066             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2067         }
2068       }
2069     }
2070
2071     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2072     Flag = Chain.getValue(1);
2073     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2074   }
2075
2076   // The x86-64 ABIs require that for returning structs by value we copy
2077   // the sret argument into %rax/%eax (depending on ABI) for the return.
2078   // Win32 requires us to put the sret argument to %eax as well.
2079   // We saved the argument into a virtual register in the entry block,
2080   // so now we copy the value out and into %rax/%eax.
2081   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2082       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2083     MachineFunction &MF = DAG.getMachineFunction();
2084     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2085     unsigned Reg = FuncInfo->getSRetReturnReg();
2086     assert(Reg &&
2087            "SRetReturnReg should have been set in LowerFormalArguments().");
2088     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2089
2090     unsigned RetValReg
2091         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2092           X86::RAX : X86::EAX;
2093     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2094     Flag = Chain.getValue(1);
2095
2096     // RAX/EAX now acts like a return value.
2097     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2098   }
2099
2100   RetOps[0] = Chain;  // Update chain.
2101
2102   // Add the flag if we have it.
2103   if (Flag.getNode())
2104     RetOps.push_back(Flag);
2105
2106   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2107 }
2108
2109 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2110   if (N->getNumValues() != 1)
2111     return false;
2112   if (!N->hasNUsesOfValue(1, 0))
2113     return false;
2114
2115   SDValue TCChain = Chain;
2116   SDNode *Copy = *N->use_begin();
2117   if (Copy->getOpcode() == ISD::CopyToReg) {
2118     // If the copy has a glue operand, we conservatively assume it isn't safe to
2119     // perform a tail call.
2120     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2121       return false;
2122     TCChain = Copy->getOperand(0);
2123   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2124     return false;
2125
2126   bool HasRet = false;
2127   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2128        UI != UE; ++UI) {
2129     if (UI->getOpcode() != X86ISD::RET_FLAG)
2130       return false;
2131     // If we are returning more than one value, we can definitely
2132     // not make a tail call see PR19530
2133     if (UI->getNumOperands() > 4)
2134       return false;
2135     if (UI->getNumOperands() == 4 &&
2136         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2137       return false;
2138     HasRet = true;
2139   }
2140
2141   if (!HasRet)
2142     return false;
2143
2144   Chain = TCChain;
2145   return true;
2146 }
2147
2148 EVT
2149 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2150                                             ISD::NodeType ExtendKind) const {
2151   MVT ReturnMVT;
2152   // TODO: Is this also valid on 32-bit?
2153   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2154     ReturnMVT = MVT::i8;
2155   else
2156     ReturnMVT = MVT::i32;
2157
2158   EVT MinVT = getRegisterType(Context, ReturnMVT);
2159   return VT.bitsLT(MinVT) ? MinVT : VT;
2160 }
2161
2162 /// Lower the result values of a call into the
2163 /// appropriate copies out of appropriate physical registers.
2164 ///
2165 SDValue
2166 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2167                                    CallingConv::ID CallConv, bool isVarArg,
2168                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2169                                    SDLoc dl, SelectionDAG &DAG,
2170                                    SmallVectorImpl<SDValue> &InVals) const {
2171
2172   // Assign locations to each value returned by this call.
2173   SmallVector<CCValAssign, 16> RVLocs;
2174   bool Is64Bit = Subtarget->is64Bit();
2175   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2176                  *DAG.getContext());
2177   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2178
2179   // Copy all of the result registers out of their specified physreg.
2180   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2181     CCValAssign &VA = RVLocs[i];
2182     EVT CopyVT = VA.getValVT();
2183
2184     // If this is x86-64, and we disabled SSE, we can't return FP values
2185     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2186         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2187       report_fatal_error("SSE register return with SSE disabled");
2188     }
2189
2190     // If we prefer to use the value in xmm registers, copy it out as f80 and
2191     // use a truncate to move it from fp stack reg to xmm reg.
2192     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2193         isScalarFPTypeInSSEReg(VA.getValVT()))
2194       CopyVT = MVT::f80;
2195
2196     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2197                                CopyVT, InFlag).getValue(1);
2198     SDValue Val = Chain.getValue(0);
2199
2200     if (CopyVT != VA.getValVT())
2201       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2202                         // This truncation won't change the value.
2203                         DAG.getIntPtrConstant(1));
2204
2205     InFlag = Chain.getValue(2);
2206     InVals.push_back(Val);
2207   }
2208
2209   return Chain;
2210 }
2211
2212 //===----------------------------------------------------------------------===//
2213 //                C & StdCall & Fast Calling Convention implementation
2214 //===----------------------------------------------------------------------===//
2215 //  StdCall calling convention seems to be standard for many Windows' API
2216 //  routines and around. It differs from C calling convention just a little:
2217 //  callee should clean up the stack, not caller. Symbols should be also
2218 //  decorated in some fancy way :) It doesn't support any vector arguments.
2219 //  For info on fast calling convention see Fast Calling Convention (tail call)
2220 //  implementation LowerX86_32FastCCCallTo.
2221
2222 /// CallIsStructReturn - Determines whether a call uses struct return
2223 /// semantics.
2224 enum StructReturnType {
2225   NotStructReturn,
2226   RegStructReturn,
2227   StackStructReturn
2228 };
2229 static StructReturnType
2230 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2231   if (Outs.empty())
2232     return NotStructReturn;
2233
2234   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2235   if (!Flags.isSRet())
2236     return NotStructReturn;
2237   if (Flags.isInReg())
2238     return RegStructReturn;
2239   return StackStructReturn;
2240 }
2241
2242 /// Determines whether a function uses struct return semantics.
2243 static StructReturnType
2244 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2245   if (Ins.empty())
2246     return NotStructReturn;
2247
2248   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2249   if (!Flags.isSRet())
2250     return NotStructReturn;
2251   if (Flags.isInReg())
2252     return RegStructReturn;
2253   return StackStructReturn;
2254 }
2255
2256 /// Make a copy of an aggregate at address specified by "Src" to address
2257 /// "Dst" with size and alignment information specified by the specific
2258 /// parameter attribute. The copy will be passed as a byval function parameter.
2259 static SDValue
2260 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2261                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2262                           SDLoc dl) {
2263   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2264
2265   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2266                        /*isVolatile*/false, /*AlwaysInline=*/true,
2267                        MachinePointerInfo(), MachinePointerInfo());
2268 }
2269
2270 /// Return true if the calling convention is one that
2271 /// supports tail call optimization.
2272 static bool IsTailCallConvention(CallingConv::ID CC) {
2273   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2274           CC == CallingConv::HiPE);
2275 }
2276
2277 /// \brief Return true if the calling convention is a C calling convention.
2278 static bool IsCCallConvention(CallingConv::ID CC) {
2279   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2280           CC == CallingConv::X86_64_SysV);
2281 }
2282
2283 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2284   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2285     return false;
2286
2287   CallSite CS(CI);
2288   CallingConv::ID CalleeCC = CS.getCallingConv();
2289   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2290     return false;
2291
2292   return true;
2293 }
2294
2295 /// Return true if the function is being made into
2296 /// a tailcall target by changing its ABI.
2297 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2298                                    bool GuaranteedTailCallOpt) {
2299   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2300 }
2301
2302 SDValue
2303 X86TargetLowering::LowerMemArgument(SDValue Chain,
2304                                     CallingConv::ID CallConv,
2305                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2306                                     SDLoc dl, SelectionDAG &DAG,
2307                                     const CCValAssign &VA,
2308                                     MachineFrameInfo *MFI,
2309                                     unsigned i) const {
2310   // Create the nodes corresponding to a load from this parameter slot.
2311   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2312   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2313       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2314   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2315   EVT ValVT;
2316
2317   // If value is passed by pointer we have address passed instead of the value
2318   // itself.
2319   if (VA.getLocInfo() == CCValAssign::Indirect)
2320     ValVT = VA.getLocVT();
2321   else
2322     ValVT = VA.getValVT();
2323
2324   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2325   // changed with more analysis.
2326   // In case of tail call optimization mark all arguments mutable. Since they
2327   // could be overwritten by lowering of arguments in case of a tail call.
2328   if (Flags.isByVal()) {
2329     unsigned Bytes = Flags.getByValSize();
2330     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2331     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2332     return DAG.getFrameIndex(FI, getPointerTy());
2333   } else {
2334     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2335                                     VA.getLocMemOffset(), isImmutable);
2336     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2337     return DAG.getLoad(ValVT, dl, Chain, FIN,
2338                        MachinePointerInfo::getFixedStack(FI),
2339                        false, false, false, 0);
2340   }
2341 }
2342
2343 // FIXME: Get this from tablegen.
2344 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2345                                                 const X86Subtarget *Subtarget) {
2346   assert(Subtarget->is64Bit());
2347
2348   if (Subtarget->isCallingConvWin64(CallConv)) {
2349     static const MCPhysReg GPR64ArgRegsWin64[] = {
2350       X86::RCX, X86::RDX, X86::R8,  X86::R9
2351     };
2352     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2353   }
2354
2355   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2356     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2357   };
2358   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2359 }
2360
2361 // FIXME: Get this from tablegen.
2362 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2363                                                 CallingConv::ID CallConv,
2364                                                 const X86Subtarget *Subtarget) {
2365   assert(Subtarget->is64Bit());
2366   if (Subtarget->isCallingConvWin64(CallConv)) {
2367     // The XMM registers which might contain var arg parameters are shadowed
2368     // in their paired GPR.  So we only need to save the GPR to their home
2369     // slots.
2370     // TODO: __vectorcall will change this.
2371     return None;
2372   }
2373
2374   const Function *Fn = MF.getFunction();
2375   bool NoImplicitFloatOps = Fn->getAttributes().
2376       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2377   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2378          "SSE register cannot be used when SSE is disabled!");
2379   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2380       !Subtarget->hasSSE1())
2381     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2382     // registers.
2383     return None;
2384
2385   static const MCPhysReg XMMArgRegs64Bit[] = {
2386     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2387     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2388   };
2389   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2390 }
2391
2392 SDValue
2393 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2394                                         CallingConv::ID CallConv,
2395                                         bool isVarArg,
2396                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2397                                         SDLoc dl,
2398                                         SelectionDAG &DAG,
2399                                         SmallVectorImpl<SDValue> &InVals)
2400                                           const {
2401   MachineFunction &MF = DAG.getMachineFunction();
2402   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2403
2404   const Function* Fn = MF.getFunction();
2405   if (Fn->hasExternalLinkage() &&
2406       Subtarget->isTargetCygMing() &&
2407       Fn->getName() == "main")
2408     FuncInfo->setForceFramePointer(true);
2409
2410   MachineFrameInfo *MFI = MF.getFrameInfo();
2411   bool Is64Bit = Subtarget->is64Bit();
2412   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2413
2414   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2415          "Var args not supported with calling convention fastcc, ghc or hipe");
2416
2417   // Assign locations to all of the incoming arguments.
2418   SmallVector<CCValAssign, 16> ArgLocs;
2419   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2420
2421   // Allocate shadow area for Win64
2422   if (IsWin64)
2423     CCInfo.AllocateStack(32, 8);
2424
2425   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2426
2427   unsigned LastVal = ~0U;
2428   SDValue ArgValue;
2429   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2430     CCValAssign &VA = ArgLocs[i];
2431     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2432     // places.
2433     assert(VA.getValNo() != LastVal &&
2434            "Don't support value assigned to multiple locs yet");
2435     (void)LastVal;
2436     LastVal = VA.getValNo();
2437
2438     if (VA.isRegLoc()) {
2439       EVT RegVT = VA.getLocVT();
2440       const TargetRegisterClass *RC;
2441       if (RegVT == MVT::i32)
2442         RC = &X86::GR32RegClass;
2443       else if (Is64Bit && RegVT == MVT::i64)
2444         RC = &X86::GR64RegClass;
2445       else if (RegVT == MVT::f32)
2446         RC = &X86::FR32RegClass;
2447       else if (RegVT == MVT::f64)
2448         RC = &X86::FR64RegClass;
2449       else if (RegVT.is512BitVector())
2450         RC = &X86::VR512RegClass;
2451       else if (RegVT.is256BitVector())
2452         RC = &X86::VR256RegClass;
2453       else if (RegVT.is128BitVector())
2454         RC = &X86::VR128RegClass;
2455       else if (RegVT == MVT::x86mmx)
2456         RC = &X86::VR64RegClass;
2457       else if (RegVT == MVT::i1)
2458         RC = &X86::VK1RegClass;
2459       else if (RegVT == MVT::v8i1)
2460         RC = &X86::VK8RegClass;
2461       else if (RegVT == MVT::v16i1)
2462         RC = &X86::VK16RegClass;
2463       else if (RegVT == MVT::v32i1)
2464         RC = &X86::VK32RegClass;
2465       else if (RegVT == MVT::v64i1)
2466         RC = &X86::VK64RegClass;
2467       else
2468         llvm_unreachable("Unknown argument type!");
2469
2470       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2471       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2472
2473       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2474       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2475       // right size.
2476       if (VA.getLocInfo() == CCValAssign::SExt)
2477         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2478                                DAG.getValueType(VA.getValVT()));
2479       else if (VA.getLocInfo() == CCValAssign::ZExt)
2480         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2481                                DAG.getValueType(VA.getValVT()));
2482       else if (VA.getLocInfo() == CCValAssign::BCvt)
2483         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2484
2485       if (VA.isExtInLoc()) {
2486         // Handle MMX values passed in XMM regs.
2487         if (RegVT.isVector())
2488           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2489         else
2490           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2491       }
2492     } else {
2493       assert(VA.isMemLoc());
2494       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2495     }
2496
2497     // If value is passed via pointer - do a load.
2498     if (VA.getLocInfo() == CCValAssign::Indirect)
2499       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2500                              MachinePointerInfo(), false, false, false, 0);
2501
2502     InVals.push_back(ArgValue);
2503   }
2504
2505   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2506     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2507       // The x86-64 ABIs require that for returning structs by value we copy
2508       // the sret argument into %rax/%eax (depending on ABI) for the return.
2509       // Win32 requires us to put the sret argument to %eax as well.
2510       // Save the argument into a virtual register so that we can access it
2511       // from the return points.
2512       if (Ins[i].Flags.isSRet()) {
2513         unsigned Reg = FuncInfo->getSRetReturnReg();
2514         if (!Reg) {
2515           MVT PtrTy = getPointerTy();
2516           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2517           FuncInfo->setSRetReturnReg(Reg);
2518         }
2519         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2520         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2521         break;
2522       }
2523     }
2524   }
2525
2526   unsigned StackSize = CCInfo.getNextStackOffset();
2527   // Align stack specially for tail calls.
2528   if (FuncIsMadeTailCallSafe(CallConv,
2529                              MF.getTarget().Options.GuaranteedTailCallOpt))
2530     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2531
2532   // If the function takes variable number of arguments, make a frame index for
2533   // the start of the first vararg value... for expansion of llvm.va_start. We
2534   // can skip this if there are no va_start calls.
2535   if (MFI->hasVAStart() &&
2536       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2537                    CallConv != CallingConv::X86_ThisCall))) {
2538     FuncInfo->setVarArgsFrameIndex(
2539         MFI->CreateFixedObject(1, StackSize, true));
2540   }
2541
2542   // 64-bit calling conventions support varargs and register parameters, so we
2543   // have to do extra work to spill them in the prologue or forward them to
2544   // musttail calls.
2545   if (Is64Bit && isVarArg &&
2546       (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2547     // Find the first unallocated argument registers.
2548     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2549     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2550     unsigned NumIntRegs =
2551         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2552     unsigned NumXMMRegs =
2553         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2554     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2555            "SSE register cannot be used when SSE is disabled!");
2556
2557     // Gather all the live in physical registers.
2558     SmallVector<SDValue, 6> LiveGPRs;
2559     SmallVector<SDValue, 8> LiveXMMRegs;
2560     SDValue ALVal;
2561     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2562       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2563       LiveGPRs.push_back(
2564           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2565     }
2566     if (!ArgXMMs.empty()) {
2567       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2568       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2569       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2570         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2571         LiveXMMRegs.push_back(
2572             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2573       }
2574     }
2575
2576     // Store them to the va_list returned by va_start.
2577     if (MFI->hasVAStart()) {
2578       if (IsWin64) {
2579         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2580         // Get to the caller-allocated home save location.  Add 8 to account
2581         // for the return address.
2582         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2583         FuncInfo->setRegSaveFrameIndex(
2584           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2585         // Fixup to set vararg frame on shadow area (4 x i64).
2586         if (NumIntRegs < 4)
2587           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2588       } else {
2589         // For X86-64, if there are vararg parameters that are passed via
2590         // registers, then we must store them to their spots on the stack so
2591         // they may be loaded by deferencing the result of va_next.
2592         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2593         FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2594         FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2595             ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2596       }
2597
2598       // Store the integer parameter registers.
2599       SmallVector<SDValue, 8> MemOps;
2600       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2601                                         getPointerTy());
2602       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2603       for (SDValue Val : LiveGPRs) {
2604         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2605                                   DAG.getIntPtrConstant(Offset));
2606         SDValue Store =
2607           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2608                        MachinePointerInfo::getFixedStack(
2609                          FuncInfo->getRegSaveFrameIndex(), Offset),
2610                        false, false, 0);
2611         MemOps.push_back(Store);
2612         Offset += 8;
2613       }
2614
2615       if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2616         // Now store the XMM (fp + vector) parameter registers.
2617         SmallVector<SDValue, 12> SaveXMMOps;
2618         SaveXMMOps.push_back(Chain);
2619         SaveXMMOps.push_back(ALVal);
2620         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2621                                FuncInfo->getRegSaveFrameIndex()));
2622         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2623                                FuncInfo->getVarArgsFPOffset()));
2624         SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2625                           LiveXMMRegs.end());
2626         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2627                                      MVT::Other, SaveXMMOps));
2628       }
2629
2630       if (!MemOps.empty())
2631         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2632     } else {
2633       // Add all GPRs, al, and XMMs to the list of forwards.  We will add then
2634       // to the liveout set on a musttail call.
2635       assert(MFI->hasMustTailInVarArgFunc());
2636       auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2637       typedef X86MachineFunctionInfo::Forward Forward;
2638
2639       for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2640         unsigned VReg =
2641             MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2642         Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2643         Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2644       }
2645
2646       if (!ArgXMMs.empty()) {
2647         unsigned ALVReg =
2648             MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2649         Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2650         Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2651
2652         for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2653           unsigned VReg =
2654               MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2655           Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2656           Forwards.push_back(
2657               Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2658         }
2659       }
2660     }
2661   }
2662
2663   // Some CCs need callee pop.
2664   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2665                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2666     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2667   } else {
2668     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2669     // If this is an sret function, the return should pop the hidden pointer.
2670     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2671         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2672         argsAreStructReturn(Ins) == StackStructReturn)
2673       FuncInfo->setBytesToPopOnReturn(4);
2674   }
2675
2676   if (!Is64Bit) {
2677     // RegSaveFrameIndex is X86-64 only.
2678     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2679     if (CallConv == CallingConv::X86_FastCall ||
2680         CallConv == CallingConv::X86_ThisCall)
2681       // fastcc functions can't have varargs.
2682       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2683   }
2684
2685   FuncInfo->setArgumentStackSize(StackSize);
2686
2687   return Chain;
2688 }
2689
2690 SDValue
2691 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2692                                     SDValue StackPtr, SDValue Arg,
2693                                     SDLoc dl, SelectionDAG &DAG,
2694                                     const CCValAssign &VA,
2695                                     ISD::ArgFlagsTy Flags) const {
2696   unsigned LocMemOffset = VA.getLocMemOffset();
2697   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2698   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2699   if (Flags.isByVal())
2700     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2701
2702   return DAG.getStore(Chain, dl, Arg, PtrOff,
2703                       MachinePointerInfo::getStack(LocMemOffset),
2704                       false, false, 0);
2705 }
2706
2707 /// Emit a load of return address if tail call
2708 /// optimization is performed and it is required.
2709 SDValue
2710 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2711                                            SDValue &OutRetAddr, SDValue Chain,
2712                                            bool IsTailCall, bool Is64Bit,
2713                                            int FPDiff, SDLoc dl) const {
2714   // Adjust the Return address stack slot.
2715   EVT VT = getPointerTy();
2716   OutRetAddr = getReturnAddressFrameIndex(DAG);
2717
2718   // Load the "old" Return address.
2719   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2720                            false, false, false, 0);
2721   return SDValue(OutRetAddr.getNode(), 1);
2722 }
2723
2724 /// Emit a store of the return address if tail call
2725 /// optimization is performed and it is required (FPDiff!=0).
2726 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2727                                         SDValue Chain, SDValue RetAddrFrIdx,
2728                                         EVT PtrVT, unsigned SlotSize,
2729                                         int FPDiff, SDLoc dl) {
2730   // Store the return address to the appropriate stack slot.
2731   if (!FPDiff) return Chain;
2732   // Calculate the new stack slot for the return address.
2733   int NewReturnAddrFI =
2734     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2735                                          false);
2736   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2737   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2738                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2739                        false, false, 0);
2740   return Chain;
2741 }
2742
2743 SDValue
2744 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2745                              SmallVectorImpl<SDValue> &InVals) const {
2746   SelectionDAG &DAG                     = CLI.DAG;
2747   SDLoc &dl                             = CLI.DL;
2748   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2749   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2750   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2751   SDValue Chain                         = CLI.Chain;
2752   SDValue Callee                        = CLI.Callee;
2753   CallingConv::ID CallConv              = CLI.CallConv;
2754   bool &isTailCall                      = CLI.IsTailCall;
2755   bool isVarArg                         = CLI.IsVarArg;
2756
2757   MachineFunction &MF = DAG.getMachineFunction();
2758   bool Is64Bit        = Subtarget->is64Bit();
2759   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2760   StructReturnType SR = callIsStructReturn(Outs);
2761   bool IsSibcall      = false;
2762   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2763
2764   if (MF.getTarget().Options.DisableTailCalls)
2765     isTailCall = false;
2766
2767   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2768   if (IsMustTail) {
2769     // Force this to be a tail call.  The verifier rules are enough to ensure
2770     // that we can lower this successfully without moving the return address
2771     // around.
2772     isTailCall = true;
2773   } else if (isTailCall) {
2774     // Check if it's really possible to do a tail call.
2775     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2776                     isVarArg, SR != NotStructReturn,
2777                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2778                     Outs, OutVals, Ins, DAG);
2779
2780     // Sibcalls are automatically detected tailcalls which do not require
2781     // ABI changes.
2782     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2783       IsSibcall = true;
2784
2785     if (isTailCall)
2786       ++NumTailCalls;
2787   }
2788
2789   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2790          "Var args not supported with calling convention fastcc, ghc or hipe");
2791
2792   // Analyze operands of the call, assigning locations to each operand.
2793   SmallVector<CCValAssign, 16> ArgLocs;
2794   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2795
2796   // Allocate shadow area for Win64
2797   if (IsWin64)
2798     CCInfo.AllocateStack(32, 8);
2799
2800   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2801
2802   // Get a count of how many bytes are to be pushed on the stack.
2803   unsigned NumBytes = CCInfo.getNextStackOffset();
2804   if (IsSibcall)
2805     // This is a sibcall. The memory operands are available in caller's
2806     // own caller's stack.
2807     NumBytes = 0;
2808   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2809            IsTailCallConvention(CallConv))
2810     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2811
2812   int FPDiff = 0;
2813   if (isTailCall && !IsSibcall && !IsMustTail) {
2814     // Lower arguments at fp - stackoffset + fpdiff.
2815     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2816
2817     FPDiff = NumBytesCallerPushed - NumBytes;
2818
2819     // Set the delta of movement of the returnaddr stackslot.
2820     // But only set if delta is greater than previous delta.
2821     if (FPDiff < X86Info->getTCReturnAddrDelta())
2822       X86Info->setTCReturnAddrDelta(FPDiff);
2823   }
2824
2825   unsigned NumBytesToPush = NumBytes;
2826   unsigned NumBytesToPop = NumBytes;
2827
2828   // If we have an inalloca argument, all stack space has already been allocated
2829   // for us and be right at the top of the stack.  We don't support multiple
2830   // arguments passed in memory when using inalloca.
2831   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2832     NumBytesToPush = 0;
2833     if (!ArgLocs.back().isMemLoc())
2834       report_fatal_error("cannot use inalloca attribute on a register "
2835                          "parameter");
2836     if (ArgLocs.back().getLocMemOffset() != 0)
2837       report_fatal_error("any parameter with the inalloca attribute must be "
2838                          "the only memory argument");
2839   }
2840
2841   if (!IsSibcall)
2842     Chain = DAG.getCALLSEQ_START(
2843         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2844
2845   SDValue RetAddrFrIdx;
2846   // Load return address for tail calls.
2847   if (isTailCall && FPDiff)
2848     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2849                                     Is64Bit, FPDiff, dl);
2850
2851   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2852   SmallVector<SDValue, 8> MemOpChains;
2853   SDValue StackPtr;
2854
2855   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2856   // of tail call optimization arguments are handle later.
2857   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2858       DAG.getSubtarget().getRegisterInfo());
2859   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2860     // Skip inalloca arguments, they have already been written.
2861     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2862     if (Flags.isInAlloca())
2863       continue;
2864
2865     CCValAssign &VA = ArgLocs[i];
2866     EVT RegVT = VA.getLocVT();
2867     SDValue Arg = OutVals[i];
2868     bool isByVal = Flags.isByVal();
2869
2870     // Promote the value if needed.
2871     switch (VA.getLocInfo()) {
2872     default: llvm_unreachable("Unknown loc info!");
2873     case CCValAssign::Full: break;
2874     case CCValAssign::SExt:
2875       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2876       break;
2877     case CCValAssign::ZExt:
2878       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2879       break;
2880     case CCValAssign::AExt:
2881       if (RegVT.is128BitVector()) {
2882         // Special case: passing MMX values in XMM registers.
2883         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2884         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2885         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2886       } else
2887         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2888       break;
2889     case CCValAssign::BCvt:
2890       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2891       break;
2892     case CCValAssign::Indirect: {
2893       // Store the argument.
2894       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2895       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2896       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2897                            MachinePointerInfo::getFixedStack(FI),
2898                            false, false, 0);
2899       Arg = SpillSlot;
2900       break;
2901     }
2902     }
2903
2904     if (VA.isRegLoc()) {
2905       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2906       if (isVarArg && IsWin64) {
2907         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2908         // shadow reg if callee is a varargs function.
2909         unsigned ShadowReg = 0;
2910         switch (VA.getLocReg()) {
2911         case X86::XMM0: ShadowReg = X86::RCX; break;
2912         case X86::XMM1: ShadowReg = X86::RDX; break;
2913         case X86::XMM2: ShadowReg = X86::R8; break;
2914         case X86::XMM3: ShadowReg = X86::R9; break;
2915         }
2916         if (ShadowReg)
2917           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2918       }
2919     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2920       assert(VA.isMemLoc());
2921       if (!StackPtr.getNode())
2922         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2923                                       getPointerTy());
2924       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2925                                              dl, DAG, VA, Flags));
2926     }
2927   }
2928
2929   if (!MemOpChains.empty())
2930     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2931
2932   if (Subtarget->isPICStyleGOT()) {
2933     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2934     // GOT pointer.
2935     if (!isTailCall) {
2936       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2937                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2938     } else {
2939       // If we are tail calling and generating PIC/GOT style code load the
2940       // address of the callee into ECX. The value in ecx is used as target of
2941       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2942       // for tail calls on PIC/GOT architectures. Normally we would just put the
2943       // address of GOT into ebx and then call target@PLT. But for tail calls
2944       // ebx would be restored (since ebx is callee saved) before jumping to the
2945       // target@PLT.
2946
2947       // Note: The actual moving to ECX is done further down.
2948       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2949       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2950           !G->getGlobal()->hasProtectedVisibility())
2951         Callee = LowerGlobalAddress(Callee, DAG);
2952       else if (isa<ExternalSymbolSDNode>(Callee))
2953         Callee = LowerExternalSymbol(Callee, DAG);
2954     }
2955   }
2956
2957   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2958     // From AMD64 ABI document:
2959     // For calls that may call functions that use varargs or stdargs
2960     // (prototype-less calls or calls to functions containing ellipsis (...) in
2961     // the declaration) %al is used as hidden argument to specify the number
2962     // of SSE registers used. The contents of %al do not need to match exactly
2963     // the number of registers, but must be an ubound on the number of SSE
2964     // registers used and is in the range 0 - 8 inclusive.
2965
2966     // Count the number of XMM registers allocated.
2967     static const MCPhysReg XMMArgRegs[] = {
2968       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2969       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2970     };
2971     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2972     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2973            && "SSE registers cannot be used when SSE is disabled");
2974
2975     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2976                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2977   }
2978
2979   if (Is64Bit && isVarArg && IsMustTail) {
2980     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2981     for (const auto &F : Forwards) {
2982       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2983       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2984     }
2985   }
2986
2987   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2988   // don't need this because the eligibility check rejects calls that require
2989   // shuffling arguments passed in memory.
2990   if (!IsSibcall && isTailCall) {
2991     // Force all the incoming stack arguments to be loaded from the stack
2992     // before any new outgoing arguments are stored to the stack, because the
2993     // outgoing stack slots may alias the incoming argument stack slots, and
2994     // the alias isn't otherwise explicit. This is slightly more conservative
2995     // than necessary, because it means that each store effectively depends
2996     // on every argument instead of just those arguments it would clobber.
2997     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2998
2999     SmallVector<SDValue, 8> MemOpChains2;
3000     SDValue FIN;
3001     int FI = 0;
3002     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3003       CCValAssign &VA = ArgLocs[i];
3004       if (VA.isRegLoc())
3005         continue;
3006       assert(VA.isMemLoc());
3007       SDValue Arg = OutVals[i];
3008       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3009       // Skip inalloca arguments.  They don't require any work.
3010       if (Flags.isInAlloca())
3011         continue;
3012       // Create frame index.
3013       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3014       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3015       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3016       FIN = DAG.getFrameIndex(FI, getPointerTy());
3017
3018       if (Flags.isByVal()) {
3019         // Copy relative to framepointer.
3020         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3021         if (!StackPtr.getNode())
3022           StackPtr = DAG.getCopyFromReg(Chain, dl,
3023                                         RegInfo->getStackRegister(),
3024                                         getPointerTy());
3025         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3026
3027         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3028                                                          ArgChain,
3029                                                          Flags, DAG, dl));
3030       } else {
3031         // Store relative to framepointer.
3032         MemOpChains2.push_back(
3033           DAG.getStore(ArgChain, dl, Arg, FIN,
3034                        MachinePointerInfo::getFixedStack(FI),
3035                        false, false, 0));
3036       }
3037     }
3038
3039     if (!MemOpChains2.empty())
3040       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3041
3042     // Store the return address to the appropriate stack slot.
3043     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3044                                      getPointerTy(), RegInfo->getSlotSize(),
3045                                      FPDiff, dl);
3046   }
3047
3048   // Build a sequence of copy-to-reg nodes chained together with token chain
3049   // and flag operands which copy the outgoing args into registers.
3050   SDValue InFlag;
3051   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3052     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3053                              RegsToPass[i].second, InFlag);
3054     InFlag = Chain.getValue(1);
3055   }
3056
3057   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3058     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3059     // In the 64-bit large code model, we have to make all calls
3060     // through a register, since the call instruction's 32-bit
3061     // pc-relative offset may not be large enough to hold the whole
3062     // address.
3063   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3064     // If the callee is a GlobalAddress node (quite common, every direct call
3065     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3066     // it.
3067
3068     // We should use extra load for direct calls to dllimported functions in
3069     // non-JIT mode.
3070     const GlobalValue *GV = G->getGlobal();
3071     if (!GV->hasDLLImportStorageClass()) {
3072       unsigned char OpFlags = 0;
3073       bool ExtraLoad = false;
3074       unsigned WrapperKind = ISD::DELETED_NODE;
3075
3076       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3077       // external symbols most go through the PLT in PIC mode.  If the symbol
3078       // has hidden or protected visibility, or if it is static or local, then
3079       // we don't need to use the PLT - we can directly call it.
3080       if (Subtarget->isTargetELF() &&
3081           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3082           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3083         OpFlags = X86II::MO_PLT;
3084       } else if (Subtarget->isPICStyleStubAny() &&
3085                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3086                  (!Subtarget->getTargetTriple().isMacOSX() ||
3087                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3088         // PC-relative references to external symbols should go through $stub,
3089         // unless we're building with the leopard linker or later, which
3090         // automatically synthesizes these stubs.
3091         OpFlags = X86II::MO_DARWIN_STUB;
3092       } else if (Subtarget->isPICStyleRIPRel() &&
3093                  isa<Function>(GV) &&
3094                  cast<Function>(GV)->getAttributes().
3095                    hasAttribute(AttributeSet::FunctionIndex,
3096                                 Attribute::NonLazyBind)) {
3097         // If the function is marked as non-lazy, generate an indirect call
3098         // which loads from the GOT directly. This avoids runtime overhead
3099         // at the cost of eager binding (and one extra byte of encoding).
3100         OpFlags = X86II::MO_GOTPCREL;
3101         WrapperKind = X86ISD::WrapperRIP;
3102         ExtraLoad = true;
3103       }
3104
3105       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3106                                           G->getOffset(), OpFlags);
3107
3108       // Add a wrapper if needed.
3109       if (WrapperKind != ISD::DELETED_NODE)
3110         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3111       // Add extra indirection if needed.
3112       if (ExtraLoad)
3113         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3114                              MachinePointerInfo::getGOT(),
3115                              false, false, false, 0);
3116     }
3117   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3118     unsigned char OpFlags = 0;
3119
3120     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3121     // external symbols should go through the PLT.
3122     if (Subtarget->isTargetELF() &&
3123         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3124       OpFlags = X86II::MO_PLT;
3125     } else if (Subtarget->isPICStyleStubAny() &&
3126                (!Subtarget->getTargetTriple().isMacOSX() ||
3127                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3128       // PC-relative references to external symbols should go through $stub,
3129       // unless we're building with the leopard linker or later, which
3130       // automatically synthesizes these stubs.
3131       OpFlags = X86II::MO_DARWIN_STUB;
3132     }
3133
3134     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3135                                          OpFlags);
3136   } else if (Subtarget->isTarget64BitILP32() && Callee->getValueType(0) == MVT::i32) {
3137     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3138     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3139   }
3140
3141   // Returns a chain & a flag for retval copy to use.
3142   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3143   SmallVector<SDValue, 8> Ops;
3144
3145   if (!IsSibcall && isTailCall) {
3146     Chain = DAG.getCALLSEQ_END(Chain,
3147                                DAG.getIntPtrConstant(NumBytesToPop, true),
3148                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3149     InFlag = Chain.getValue(1);
3150   }
3151
3152   Ops.push_back(Chain);
3153   Ops.push_back(Callee);
3154
3155   if (isTailCall)
3156     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3157
3158   // Add argument registers to the end of the list so that they are known live
3159   // into the call.
3160   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3161     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3162                                   RegsToPass[i].second.getValueType()));
3163
3164   // Add a register mask operand representing the call-preserved registers.
3165   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3166   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3167   assert(Mask && "Missing call preserved mask for calling convention");
3168   Ops.push_back(DAG.getRegisterMask(Mask));
3169
3170   if (InFlag.getNode())
3171     Ops.push_back(InFlag);
3172
3173   if (isTailCall) {
3174     // We used to do:
3175     //// If this is the first return lowered for this function, add the regs
3176     //// to the liveout set for the function.
3177     // This isn't right, although it's probably harmless on x86; liveouts
3178     // should be computed from returns not tail calls.  Consider a void
3179     // function making a tail call to a function returning int.
3180     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3181   }
3182
3183   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3184   InFlag = Chain.getValue(1);
3185
3186   // Create the CALLSEQ_END node.
3187   unsigned NumBytesForCalleeToPop;
3188   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3189                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3190     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3191   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3192            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3193            SR == StackStructReturn)
3194     // If this is a call to a struct-return function, the callee
3195     // pops the hidden struct pointer, so we have to push it back.
3196     // This is common for Darwin/X86, Linux & Mingw32 targets.
3197     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3198     NumBytesForCalleeToPop = 4;
3199   else
3200     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3201
3202   // Returns a flag for retval copy to use.
3203   if (!IsSibcall) {
3204     Chain = DAG.getCALLSEQ_END(Chain,
3205                                DAG.getIntPtrConstant(NumBytesToPop, true),
3206                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3207                                                      true),
3208                                InFlag, dl);
3209     InFlag = Chain.getValue(1);
3210   }
3211
3212   // Handle result values, copying them out of physregs into vregs that we
3213   // return.
3214   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3215                          Ins, dl, DAG, InVals);
3216 }
3217
3218 //===----------------------------------------------------------------------===//
3219 //                Fast Calling Convention (tail call) implementation
3220 //===----------------------------------------------------------------------===//
3221
3222 //  Like std call, callee cleans arguments, convention except that ECX is
3223 //  reserved for storing the tail called function address. Only 2 registers are
3224 //  free for argument passing (inreg). Tail call optimization is performed
3225 //  provided:
3226 //                * tailcallopt is enabled
3227 //                * caller/callee are fastcc
3228 //  On X86_64 architecture with GOT-style position independent code only local
3229 //  (within module) calls are supported at the moment.
3230 //  To keep the stack aligned according to platform abi the function
3231 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3232 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3233 //  If a tail called function callee has more arguments than the caller the
3234 //  caller needs to make sure that there is room to move the RETADDR to. This is
3235 //  achieved by reserving an area the size of the argument delta right after the
3236 //  original RETADDR, but before the saved framepointer or the spilled registers
3237 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3238 //  stack layout:
3239 //    arg1
3240 //    arg2
3241 //    RETADDR
3242 //    [ new RETADDR
3243 //      move area ]
3244 //    (possible EBP)
3245 //    ESI
3246 //    EDI
3247 //    local1 ..
3248
3249 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3250 /// for a 16 byte align requirement.
3251 unsigned
3252 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3253                                                SelectionDAG& DAG) const {
3254   MachineFunction &MF = DAG.getMachineFunction();
3255   const TargetMachine &TM = MF.getTarget();
3256   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3257       TM.getSubtargetImpl()->getRegisterInfo());
3258   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3259   unsigned StackAlignment = TFI.getStackAlignment();
3260   uint64_t AlignMask = StackAlignment - 1;
3261   int64_t Offset = StackSize;
3262   unsigned SlotSize = RegInfo->getSlotSize();
3263   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3264     // Number smaller than 12 so just add the difference.
3265     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3266   } else {
3267     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3268     Offset = ((~AlignMask) & Offset) + StackAlignment +
3269       (StackAlignment-SlotSize);
3270   }
3271   return Offset;
3272 }
3273
3274 /// MatchingStackOffset - Return true if the given stack call argument is
3275 /// already available in the same position (relatively) of the caller's
3276 /// incoming argument stack.
3277 static
3278 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3279                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3280                          const X86InstrInfo *TII) {
3281   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3282   int FI = INT_MAX;
3283   if (Arg.getOpcode() == ISD::CopyFromReg) {
3284     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3285     if (!TargetRegisterInfo::isVirtualRegister(VR))
3286       return false;
3287     MachineInstr *Def = MRI->getVRegDef(VR);
3288     if (!Def)
3289       return false;
3290     if (!Flags.isByVal()) {
3291       if (!TII->isLoadFromStackSlot(Def, FI))
3292         return false;
3293     } else {
3294       unsigned Opcode = Def->getOpcode();
3295       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3296           Def->getOperand(1).isFI()) {
3297         FI = Def->getOperand(1).getIndex();
3298         Bytes = Flags.getByValSize();
3299       } else
3300         return false;
3301     }
3302   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3303     if (Flags.isByVal())
3304       // ByVal argument is passed in as a pointer but it's now being
3305       // dereferenced. e.g.
3306       // define @foo(%struct.X* %A) {
3307       //   tail call @bar(%struct.X* byval %A)
3308       // }
3309       return false;
3310     SDValue Ptr = Ld->getBasePtr();
3311     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3312     if (!FINode)
3313       return false;
3314     FI = FINode->getIndex();
3315   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3316     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3317     FI = FINode->getIndex();
3318     Bytes = Flags.getByValSize();
3319   } else
3320     return false;
3321
3322   assert(FI != INT_MAX);
3323   if (!MFI->isFixedObjectIndex(FI))
3324     return false;
3325   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3326 }
3327
3328 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3329 /// for tail call optimization. Targets which want to do tail call
3330 /// optimization should implement this function.
3331 bool
3332 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3333                                                      CallingConv::ID CalleeCC,
3334                                                      bool isVarArg,
3335                                                      bool isCalleeStructRet,
3336                                                      bool isCallerStructRet,
3337                                                      Type *RetTy,
3338                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3339                                     const SmallVectorImpl<SDValue> &OutVals,
3340                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3341                                                      SelectionDAG &DAG) const {
3342   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3343     return false;
3344
3345   // If -tailcallopt is specified, make fastcc functions tail-callable.
3346   const MachineFunction &MF = DAG.getMachineFunction();
3347   const Function *CallerF = MF.getFunction();
3348
3349   // If the function return type is x86_fp80 and the callee return type is not,
3350   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3351   // perform a tailcall optimization here.
3352   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3353     return false;
3354
3355   CallingConv::ID CallerCC = CallerF->getCallingConv();
3356   bool CCMatch = CallerCC == CalleeCC;
3357   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3358   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3359
3360   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3361     if (IsTailCallConvention(CalleeCC) && CCMatch)
3362       return true;
3363     return false;
3364   }
3365
3366   // Look for obvious safe cases to perform tail call optimization that do not
3367   // require ABI changes. This is what gcc calls sibcall.
3368
3369   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3370   // emit a special epilogue.
3371   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3372       DAG.getSubtarget().getRegisterInfo());
3373   if (RegInfo->needsStackRealignment(MF))
3374     return false;
3375
3376   // Also avoid sibcall optimization if either caller or callee uses struct
3377   // return semantics.
3378   if (isCalleeStructRet || isCallerStructRet)
3379     return false;
3380
3381   // An stdcall/thiscall caller is expected to clean up its arguments; the
3382   // callee isn't going to do that.
3383   // FIXME: this is more restrictive than needed. We could produce a tailcall
3384   // when the stack adjustment matches. For example, with a thiscall that takes
3385   // only one argument.
3386   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3387                    CallerCC == CallingConv::X86_ThisCall))
3388     return false;
3389
3390   // Do not sibcall optimize vararg calls unless all arguments are passed via
3391   // registers.
3392   if (isVarArg && !Outs.empty()) {
3393
3394     // Optimizing for varargs on Win64 is unlikely to be safe without
3395     // additional testing.
3396     if (IsCalleeWin64 || IsCallerWin64)
3397       return false;
3398
3399     SmallVector<CCValAssign, 16> ArgLocs;
3400     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3401                    *DAG.getContext());
3402
3403     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3404     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3405       if (!ArgLocs[i].isRegLoc())
3406         return false;
3407   }
3408
3409   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3410   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3411   // this into a sibcall.
3412   bool Unused = false;
3413   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3414     if (!Ins[i].Used) {
3415       Unused = true;
3416       break;
3417     }
3418   }
3419   if (Unused) {
3420     SmallVector<CCValAssign, 16> RVLocs;
3421     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3422                    *DAG.getContext());
3423     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3424     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3425       CCValAssign &VA = RVLocs[i];
3426       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3427         return false;
3428     }
3429   }
3430
3431   // If the calling conventions do not match, then we'd better make sure the
3432   // results are returned in the same way as what the caller expects.
3433   if (!CCMatch) {
3434     SmallVector<CCValAssign, 16> RVLocs1;
3435     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3436                     *DAG.getContext());
3437     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3438
3439     SmallVector<CCValAssign, 16> RVLocs2;
3440     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3441                     *DAG.getContext());
3442     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3443
3444     if (RVLocs1.size() != RVLocs2.size())
3445       return false;
3446     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3447       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3448         return false;
3449       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3450         return false;
3451       if (RVLocs1[i].isRegLoc()) {
3452         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3453           return false;
3454       } else {
3455         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3456           return false;
3457       }
3458     }
3459   }
3460
3461   // If the callee takes no arguments then go on to check the results of the
3462   // call.
3463   if (!Outs.empty()) {
3464     // Check if stack adjustment is needed. For now, do not do this if any
3465     // argument is passed on the stack.
3466     SmallVector<CCValAssign, 16> ArgLocs;
3467     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3468                    *DAG.getContext());
3469
3470     // Allocate shadow area for Win64
3471     if (IsCalleeWin64)
3472       CCInfo.AllocateStack(32, 8);
3473
3474     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3475     if (CCInfo.getNextStackOffset()) {
3476       MachineFunction &MF = DAG.getMachineFunction();
3477       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3478         return false;
3479
3480       // Check if the arguments are already laid out in the right way as
3481       // the caller's fixed stack objects.
3482       MachineFrameInfo *MFI = MF.getFrameInfo();
3483       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3484       const X86InstrInfo *TII =
3485           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3486       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3487         CCValAssign &VA = ArgLocs[i];
3488         SDValue Arg = OutVals[i];
3489         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3490         if (VA.getLocInfo() == CCValAssign::Indirect)
3491           return false;
3492         if (!VA.isRegLoc()) {
3493           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3494                                    MFI, MRI, TII))
3495             return false;
3496         }
3497       }
3498     }
3499
3500     // If the tailcall address may be in a register, then make sure it's
3501     // possible to register allocate for it. In 32-bit, the call address can
3502     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3503     // callee-saved registers are restored. These happen to be the same
3504     // registers used to pass 'inreg' arguments so watch out for those.
3505     if (!Subtarget->is64Bit() &&
3506         ((!isa<GlobalAddressSDNode>(Callee) &&
3507           !isa<ExternalSymbolSDNode>(Callee)) ||
3508          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3509       unsigned NumInRegs = 0;
3510       // In PIC we need an extra register to formulate the address computation
3511       // for the callee.
3512       unsigned MaxInRegs =
3513         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3514
3515       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3516         CCValAssign &VA = ArgLocs[i];
3517         if (!VA.isRegLoc())
3518           continue;
3519         unsigned Reg = VA.getLocReg();
3520         switch (Reg) {
3521         default: break;
3522         case X86::EAX: case X86::EDX: case X86::ECX:
3523           if (++NumInRegs == MaxInRegs)
3524             return false;
3525           break;
3526         }
3527       }
3528     }
3529   }
3530
3531   return true;
3532 }
3533
3534 FastISel *
3535 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3536                                   const TargetLibraryInfo *libInfo) const {
3537   return X86::createFastISel(funcInfo, libInfo);
3538 }
3539
3540 //===----------------------------------------------------------------------===//
3541 //                           Other Lowering Hooks
3542 //===----------------------------------------------------------------------===//
3543
3544 static bool MayFoldLoad(SDValue Op) {
3545   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3546 }
3547
3548 static bool MayFoldIntoStore(SDValue Op) {
3549   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3550 }
3551
3552 static bool isTargetShuffle(unsigned Opcode) {
3553   switch(Opcode) {
3554   default: return false;
3555   case X86ISD::BLENDI:
3556   case X86ISD::PSHUFB:
3557   case X86ISD::PSHUFD:
3558   case X86ISD::PSHUFHW:
3559   case X86ISD::PSHUFLW:
3560   case X86ISD::SHUFP:
3561   case X86ISD::PALIGNR:
3562   case X86ISD::MOVLHPS:
3563   case X86ISD::MOVLHPD:
3564   case X86ISD::MOVHLPS:
3565   case X86ISD::MOVLPS:
3566   case X86ISD::MOVLPD:
3567   case X86ISD::MOVSHDUP:
3568   case X86ISD::MOVSLDUP:
3569   case X86ISD::MOVDDUP:
3570   case X86ISD::MOVSS:
3571   case X86ISD::MOVSD:
3572   case X86ISD::UNPCKL:
3573   case X86ISD::UNPCKH:
3574   case X86ISD::VPERMILPI:
3575   case X86ISD::VPERM2X128:
3576   case X86ISD::VPERMI:
3577     return true;
3578   }
3579 }
3580
3581 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3582                                     SDValue V1, SelectionDAG &DAG) {
3583   switch(Opc) {
3584   default: llvm_unreachable("Unknown x86 shuffle node");
3585   case X86ISD::MOVSHDUP:
3586   case X86ISD::MOVSLDUP:
3587   case X86ISD::MOVDDUP:
3588     return DAG.getNode(Opc, dl, VT, V1);
3589   }
3590 }
3591
3592 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3593                                     SDValue V1, unsigned TargetMask,
3594                                     SelectionDAG &DAG) {
3595   switch(Opc) {
3596   default: llvm_unreachable("Unknown x86 shuffle node");
3597   case X86ISD::PSHUFD:
3598   case X86ISD::PSHUFHW:
3599   case X86ISD::PSHUFLW:
3600   case X86ISD::VPERMILPI:
3601   case X86ISD::VPERMI:
3602     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3603   }
3604 }
3605
3606 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3607                                     SDValue V1, SDValue V2, unsigned TargetMask,
3608                                     SelectionDAG &DAG) {
3609   switch(Opc) {
3610   default: llvm_unreachable("Unknown x86 shuffle node");
3611   case X86ISD::PALIGNR:
3612   case X86ISD::VALIGN:
3613   case X86ISD::SHUFP:
3614   case X86ISD::VPERM2X128:
3615     return DAG.getNode(Opc, dl, VT, V1, V2,
3616                        DAG.getConstant(TargetMask, MVT::i8));
3617   }
3618 }
3619
3620 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3621                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3622   switch(Opc) {
3623   default: llvm_unreachable("Unknown x86 shuffle node");
3624   case X86ISD::MOVLHPS:
3625   case X86ISD::MOVLHPD:
3626   case X86ISD::MOVHLPS:
3627   case X86ISD::MOVLPS:
3628   case X86ISD::MOVLPD:
3629   case X86ISD::MOVSS:
3630   case X86ISD::MOVSD:
3631   case X86ISD::UNPCKL:
3632   case X86ISD::UNPCKH:
3633     return DAG.getNode(Opc, dl, VT, V1, V2);
3634   }
3635 }
3636
3637 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3638   MachineFunction &MF = DAG.getMachineFunction();
3639   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3640       DAG.getSubtarget().getRegisterInfo());
3641   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3642   int ReturnAddrIndex = FuncInfo->getRAIndex();
3643
3644   if (ReturnAddrIndex == 0) {
3645     // Set up a frame object for the return address.
3646     unsigned SlotSize = RegInfo->getSlotSize();
3647     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3648                                                            -(int64_t)SlotSize,
3649                                                            false);
3650     FuncInfo->setRAIndex(ReturnAddrIndex);
3651   }
3652
3653   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3654 }
3655
3656 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3657                                        bool hasSymbolicDisplacement) {
3658   // Offset should fit into 32 bit immediate field.
3659   if (!isInt<32>(Offset))
3660     return false;
3661
3662   // If we don't have a symbolic displacement - we don't have any extra
3663   // restrictions.
3664   if (!hasSymbolicDisplacement)
3665     return true;
3666
3667   // FIXME: Some tweaks might be needed for medium code model.
3668   if (M != CodeModel::Small && M != CodeModel::Kernel)
3669     return false;
3670
3671   // For small code model we assume that latest object is 16MB before end of 31
3672   // bits boundary. We may also accept pretty large negative constants knowing
3673   // that all objects are in the positive half of address space.
3674   if (M == CodeModel::Small && Offset < 16*1024*1024)
3675     return true;
3676
3677   // For kernel code model we know that all object resist in the negative half
3678   // of 32bits address space. We may not accept negative offsets, since they may
3679   // be just off and we may accept pretty large positive ones.
3680   if (M == CodeModel::Kernel && Offset >= 0)
3681     return true;
3682
3683   return false;
3684 }
3685
3686 /// isCalleePop - Determines whether the callee is required to pop its
3687 /// own arguments. Callee pop is necessary to support tail calls.
3688 bool X86::isCalleePop(CallingConv::ID CallingConv,
3689                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3690   switch (CallingConv) {
3691   default:
3692     return false;
3693   case CallingConv::X86_StdCall:
3694   case CallingConv::X86_FastCall:
3695   case CallingConv::X86_ThisCall:
3696     return !is64Bit;
3697   case CallingConv::Fast:
3698   case CallingConv::GHC:
3699   case CallingConv::HiPE:
3700     if (IsVarArg)
3701       return false;
3702     return TailCallOpt;
3703   }
3704 }
3705
3706 /// \brief Return true if the condition is an unsigned comparison operation.
3707 static bool isX86CCUnsigned(unsigned X86CC) {
3708   switch (X86CC) {
3709   default: llvm_unreachable("Invalid integer condition!");
3710   case X86::COND_E:     return true;
3711   case X86::COND_G:     return false;
3712   case X86::COND_GE:    return false;
3713   case X86::COND_L:     return false;
3714   case X86::COND_LE:    return false;
3715   case X86::COND_NE:    return true;
3716   case X86::COND_B:     return true;
3717   case X86::COND_A:     return true;
3718   case X86::COND_BE:    return true;
3719   case X86::COND_AE:    return true;
3720   }
3721   llvm_unreachable("covered switch fell through?!");
3722 }
3723
3724 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3725 /// specific condition code, returning the condition code and the LHS/RHS of the
3726 /// comparison to make.
3727 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3728                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3729   if (!isFP) {
3730     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3731       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3732         // X > -1   -> X == 0, jump !sign.
3733         RHS = DAG.getConstant(0, RHS.getValueType());
3734         return X86::COND_NS;
3735       }
3736       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3737         // X < 0   -> X == 0, jump on sign.
3738         return X86::COND_S;
3739       }
3740       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3741         // X < 1   -> X <= 0
3742         RHS = DAG.getConstant(0, RHS.getValueType());
3743         return X86::COND_LE;
3744       }
3745     }
3746
3747     switch (SetCCOpcode) {
3748     default: llvm_unreachable("Invalid integer condition!");
3749     case ISD::SETEQ:  return X86::COND_E;
3750     case ISD::SETGT:  return X86::COND_G;
3751     case ISD::SETGE:  return X86::COND_GE;
3752     case ISD::SETLT:  return X86::COND_L;
3753     case ISD::SETLE:  return X86::COND_LE;
3754     case ISD::SETNE:  return X86::COND_NE;
3755     case ISD::SETULT: return X86::COND_B;
3756     case ISD::SETUGT: return X86::COND_A;
3757     case ISD::SETULE: return X86::COND_BE;
3758     case ISD::SETUGE: return X86::COND_AE;
3759     }
3760   }
3761
3762   // First determine if it is required or is profitable to flip the operands.
3763
3764   // If LHS is a foldable load, but RHS is not, flip the condition.
3765   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3766       !ISD::isNON_EXTLoad(RHS.getNode())) {
3767     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3768     std::swap(LHS, RHS);
3769   }
3770
3771   switch (SetCCOpcode) {
3772   default: break;
3773   case ISD::SETOLT:
3774   case ISD::SETOLE:
3775   case ISD::SETUGT:
3776   case ISD::SETUGE:
3777     std::swap(LHS, RHS);
3778     break;
3779   }
3780
3781   // On a floating point condition, the flags are set as follows:
3782   // ZF  PF  CF   op
3783   //  0 | 0 | 0 | X > Y
3784   //  0 | 0 | 1 | X < Y
3785   //  1 | 0 | 0 | X == Y
3786   //  1 | 1 | 1 | unordered
3787   switch (SetCCOpcode) {
3788   default: llvm_unreachable("Condcode should be pre-legalized away");
3789   case ISD::SETUEQ:
3790   case ISD::SETEQ:   return X86::COND_E;
3791   case ISD::SETOLT:              // flipped
3792   case ISD::SETOGT:
3793   case ISD::SETGT:   return X86::COND_A;
3794   case ISD::SETOLE:              // flipped
3795   case ISD::SETOGE:
3796   case ISD::SETGE:   return X86::COND_AE;
3797   case ISD::SETUGT:              // flipped
3798   case ISD::SETULT:
3799   case ISD::SETLT:   return X86::COND_B;
3800   case ISD::SETUGE:              // flipped
3801   case ISD::SETULE:
3802   case ISD::SETLE:   return X86::COND_BE;
3803   case ISD::SETONE:
3804   case ISD::SETNE:   return X86::COND_NE;
3805   case ISD::SETUO:   return X86::COND_P;
3806   case ISD::SETO:    return X86::COND_NP;
3807   case ISD::SETOEQ:
3808   case ISD::SETUNE:  return X86::COND_INVALID;
3809   }
3810 }
3811
3812 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3813 /// code. Current x86 isa includes the following FP cmov instructions:
3814 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3815 static bool hasFPCMov(unsigned X86CC) {
3816   switch (X86CC) {
3817   default:
3818     return false;
3819   case X86::COND_B:
3820   case X86::COND_BE:
3821   case X86::COND_E:
3822   case X86::COND_P:
3823   case X86::COND_A:
3824   case X86::COND_AE:
3825   case X86::COND_NE:
3826   case X86::COND_NP:
3827     return true;
3828   }
3829 }
3830
3831 /// isFPImmLegal - Returns true if the target can instruction select the
3832 /// specified FP immediate natively. If false, the legalizer will
3833 /// materialize the FP immediate as a load from a constant pool.
3834 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3835   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3836     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3837       return true;
3838   }
3839   return false;
3840 }
3841
3842 /// \brief Returns true if it is beneficial to convert a load of a constant
3843 /// to just the constant itself.
3844 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3845                                                           Type *Ty) const {
3846   assert(Ty->isIntegerTy());
3847
3848   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3849   if (BitSize == 0 || BitSize > 64)
3850     return false;
3851   return true;
3852 }
3853
3854 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3855 /// the specified range (L, H].
3856 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3857   return (Val < 0) || (Val >= Low && Val < Hi);
3858 }
3859
3860 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3861 /// specified value.
3862 static bool isUndefOrEqual(int Val, int CmpVal) {
3863   return (Val < 0 || Val == CmpVal);
3864 }
3865
3866 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3867 /// from position Pos and ending in Pos+Size, falls within the specified
3868 /// sequential range (L, L+Pos]. or is undef.
3869 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3870                                        unsigned Pos, unsigned Size, int Low) {
3871   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3872     if (!isUndefOrEqual(Mask[i], Low))
3873       return false;
3874   return true;
3875 }
3876
3877 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3878 /// is suitable for input to PSHUFD. That is, it doesn't reference the other
3879 /// operand - by default will match for first operand.
3880 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT,
3881                          bool TestSecondOperand = false) {
3882   if (VT != MVT::v4f32 && VT != MVT::v4i32 &&
3883       VT != MVT::v2f64 && VT != MVT::v2i64)
3884     return false;
3885
3886   unsigned NumElems = VT.getVectorNumElements();
3887   unsigned Lo = TestSecondOperand ? NumElems : 0;
3888   unsigned Hi = Lo + NumElems;
3889
3890   for (unsigned i = 0; i < NumElems; ++i)
3891     if (!isUndefOrInRange(Mask[i], (int)Lo, (int)Hi))
3892       return false;
3893
3894   return true;
3895 }
3896
3897 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3898 /// is suitable for input to PSHUFHW.
3899 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3900   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3901     return false;
3902
3903   // Lower quadword copied in order or undef.
3904   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3905     return false;
3906
3907   // Upper quadword shuffled.
3908   for (unsigned i = 4; i != 8; ++i)
3909     if (!isUndefOrInRange(Mask[i], 4, 8))
3910       return false;
3911
3912   if (VT == MVT::v16i16) {
3913     // Lower quadword copied in order or undef.
3914     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3915       return false;
3916
3917     // Upper quadword shuffled.
3918     for (unsigned i = 12; i != 16; ++i)
3919       if (!isUndefOrInRange(Mask[i], 12, 16))
3920         return false;
3921   }
3922
3923   return true;
3924 }
3925
3926 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3927 /// is suitable for input to PSHUFLW.
3928 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3929   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3930     return false;
3931
3932   // Upper quadword copied in order.
3933   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3934     return false;
3935
3936   // Lower quadword shuffled.
3937   for (unsigned i = 0; i != 4; ++i)
3938     if (!isUndefOrInRange(Mask[i], 0, 4))
3939       return false;
3940
3941   if (VT == MVT::v16i16) {
3942     // Upper quadword copied in order.
3943     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3944       return false;
3945
3946     // Lower quadword shuffled.
3947     for (unsigned i = 8; i != 12; ++i)
3948       if (!isUndefOrInRange(Mask[i], 8, 12))
3949         return false;
3950   }
3951
3952   return true;
3953 }
3954
3955 /// \brief Return true if the mask specifies a shuffle of elements that is
3956 /// suitable for input to intralane (palignr) or interlane (valign) vector
3957 /// right-shift.
3958 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3959   unsigned NumElts = VT.getVectorNumElements();
3960   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3961   unsigned NumLaneElts = NumElts/NumLanes;
3962
3963   // Do not handle 64-bit element shuffles with palignr.
3964   if (NumLaneElts == 2)
3965     return false;
3966
3967   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3968     unsigned i;
3969     for (i = 0; i != NumLaneElts; ++i) {
3970       if (Mask[i+l] >= 0)
3971         break;
3972     }
3973
3974     // Lane is all undef, go to next lane
3975     if (i == NumLaneElts)
3976       continue;
3977
3978     int Start = Mask[i+l];
3979
3980     // Make sure its in this lane in one of the sources
3981     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3982         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3983       return false;
3984
3985     // If not lane 0, then we must match lane 0
3986     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3987       return false;
3988
3989     // Correct second source to be contiguous with first source
3990     if (Start >= (int)NumElts)
3991       Start -= NumElts - NumLaneElts;
3992
3993     // Make sure we're shifting in the right direction.
3994     if (Start <= (int)(i+l))
3995       return false;
3996
3997     Start -= i;
3998
3999     // Check the rest of the elements to see if they are consecutive.
4000     for (++i; i != NumLaneElts; ++i) {
4001       int Idx = Mask[i+l];
4002
4003       // Make sure its in this lane
4004       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
4005           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
4006         return false;
4007
4008       // If not lane 0, then we must match lane 0
4009       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
4010         return false;
4011
4012       if (Idx >= (int)NumElts)
4013         Idx -= NumElts - NumLaneElts;
4014
4015       if (!isUndefOrEqual(Idx, Start+i))
4016         return false;
4017
4018     }
4019   }
4020
4021   return true;
4022 }
4023
4024 /// \brief Return true if the node specifies a shuffle of elements that is
4025 /// suitable for input to PALIGNR.
4026 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4027                           const X86Subtarget *Subtarget) {
4028   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4029       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4030       VT.is512BitVector())
4031     // FIXME: Add AVX512BW.
4032     return false;
4033
4034   return isAlignrMask(Mask, VT, false);
4035 }
4036
4037 /// \brief Return true if the node specifies a shuffle of elements that is
4038 /// suitable for input to VALIGN.
4039 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4040                           const X86Subtarget *Subtarget) {
4041   // FIXME: Add AVX512VL.
4042   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4043     return false;
4044   return isAlignrMask(Mask, VT, true);
4045 }
4046
4047 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4048 /// the two vector operands have swapped position.
4049 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4050                                      unsigned NumElems) {
4051   for (unsigned i = 0; i != NumElems; ++i) {
4052     int idx = Mask[i];
4053     if (idx < 0)
4054       continue;
4055     else if (idx < (int)NumElems)
4056       Mask[i] = idx + NumElems;
4057     else
4058       Mask[i] = idx - NumElems;
4059   }
4060 }
4061
4062 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4063 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4064 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4065 /// reverse of what x86 shuffles want.
4066 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4067
4068   unsigned NumElems = VT.getVectorNumElements();
4069   unsigned NumLanes = VT.getSizeInBits()/128;
4070   unsigned NumLaneElems = NumElems/NumLanes;
4071
4072   if (NumLaneElems != 2 && NumLaneElems != 4)
4073     return false;
4074
4075   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4076   bool symetricMaskRequired =
4077     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4078
4079   // VSHUFPSY divides the resulting vector into 4 chunks.
4080   // The sources are also splitted into 4 chunks, and each destination
4081   // chunk must come from a different source chunk.
4082   //
4083   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4084   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4085   //
4086   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4087   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4088   //
4089   // VSHUFPDY divides the resulting vector into 4 chunks.
4090   // The sources are also splitted into 4 chunks, and each destination
4091   // chunk must come from a different source chunk.
4092   //
4093   //  SRC1 =>      X3       X2       X1       X0
4094   //  SRC2 =>      Y3       Y2       Y1       Y0
4095   //
4096   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4097   //
4098   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4099   unsigned HalfLaneElems = NumLaneElems/2;
4100   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4101     for (unsigned i = 0; i != NumLaneElems; ++i) {
4102       int Idx = Mask[i+l];
4103       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4104       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4105         return false;
4106       // For VSHUFPSY, the mask of the second half must be the same as the
4107       // first but with the appropriate offsets. This works in the same way as
4108       // VPERMILPS works with masks.
4109       if (!symetricMaskRequired || Idx < 0)
4110         continue;
4111       if (MaskVal[i] < 0) {
4112         MaskVal[i] = Idx - l;
4113         continue;
4114       }
4115       if ((signed)(Idx - l) != MaskVal[i])
4116         return false;
4117     }
4118   }
4119
4120   return true;
4121 }
4122
4123 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4124 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4125 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4126   if (!VT.is128BitVector())
4127     return false;
4128
4129   unsigned NumElems = VT.getVectorNumElements();
4130
4131   if (NumElems != 4)
4132     return false;
4133
4134   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4135   return isUndefOrEqual(Mask[0], 6) &&
4136          isUndefOrEqual(Mask[1], 7) &&
4137          isUndefOrEqual(Mask[2], 2) &&
4138          isUndefOrEqual(Mask[3], 3);
4139 }
4140
4141 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4142 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4143 /// <2, 3, 2, 3>
4144 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4145   if (!VT.is128BitVector())
4146     return false;
4147
4148   unsigned NumElems = VT.getVectorNumElements();
4149
4150   if (NumElems != 4)
4151     return false;
4152
4153   return isUndefOrEqual(Mask[0], 2) &&
4154          isUndefOrEqual(Mask[1], 3) &&
4155          isUndefOrEqual(Mask[2], 2) &&
4156          isUndefOrEqual(Mask[3], 3);
4157 }
4158
4159 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4160 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4161 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4162   if (!VT.is128BitVector())
4163     return false;
4164
4165   unsigned NumElems = VT.getVectorNumElements();
4166
4167   if (NumElems != 2 && NumElems != 4)
4168     return false;
4169
4170   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4171     if (!isUndefOrEqual(Mask[i], i + NumElems))
4172       return false;
4173
4174   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4175     if (!isUndefOrEqual(Mask[i], i))
4176       return false;
4177
4178   return true;
4179 }
4180
4181 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4182 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4183 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4184   if (!VT.is128BitVector())
4185     return false;
4186
4187   unsigned NumElems = VT.getVectorNumElements();
4188
4189   if (NumElems != 2 && NumElems != 4)
4190     return false;
4191
4192   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4193     if (!isUndefOrEqual(Mask[i], i))
4194       return false;
4195
4196   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4197     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4198       return false;
4199
4200   return true;
4201 }
4202
4203 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4204 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4205 /// i. e: If all but one element come from the same vector.
4206 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4207   // TODO: Deal with AVX's VINSERTPS
4208   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4209     return false;
4210
4211   unsigned CorrectPosV1 = 0;
4212   unsigned CorrectPosV2 = 0;
4213   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4214     if (Mask[i] == -1) {
4215       ++CorrectPosV1;
4216       ++CorrectPosV2;
4217       continue;
4218     }
4219
4220     if (Mask[i] == i)
4221       ++CorrectPosV1;
4222     else if (Mask[i] == i + 4)
4223       ++CorrectPosV2;
4224   }
4225
4226   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4227     // We have 3 elements (undefs count as elements from any vector) from one
4228     // vector, and one from another.
4229     return true;
4230
4231   return false;
4232 }
4233
4234 //
4235 // Some special combinations that can be optimized.
4236 //
4237 static
4238 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4239                                SelectionDAG &DAG) {
4240   MVT VT = SVOp->getSimpleValueType(0);
4241   SDLoc dl(SVOp);
4242
4243   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4244     return SDValue();
4245
4246   ArrayRef<int> Mask = SVOp->getMask();
4247
4248   // These are the special masks that may be optimized.
4249   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4250   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4251   bool MatchEvenMask = true;
4252   bool MatchOddMask  = true;
4253   for (int i=0; i<8; ++i) {
4254     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4255       MatchEvenMask = false;
4256     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4257       MatchOddMask = false;
4258   }
4259
4260   if (!MatchEvenMask && !MatchOddMask)
4261     return SDValue();
4262
4263   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4264
4265   SDValue Op0 = SVOp->getOperand(0);
4266   SDValue Op1 = SVOp->getOperand(1);
4267
4268   if (MatchEvenMask) {
4269     // Shift the second operand right to 32 bits.
4270     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4271     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4272   } else {
4273     // Shift the first operand left to 32 bits.
4274     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4275     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4276   }
4277   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4278   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4279 }
4280
4281 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4282 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4283 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4284                          bool HasInt256, bool V2IsSplat = false) {
4285
4286   assert(VT.getSizeInBits() >= 128 &&
4287          "Unsupported vector type for unpckl");
4288
4289   unsigned NumElts = VT.getVectorNumElements();
4290   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4291       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4292     return false;
4293
4294   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4295          "Unsupported vector type for unpckh");
4296
4297   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4298   unsigned NumLanes = VT.getSizeInBits()/128;
4299   unsigned NumLaneElts = NumElts/NumLanes;
4300
4301   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4302     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4303       int BitI  = Mask[l+i];
4304       int BitI1 = Mask[l+i+1];
4305       if (!isUndefOrEqual(BitI, j))
4306         return false;
4307       if (V2IsSplat) {
4308         if (!isUndefOrEqual(BitI1, NumElts))
4309           return false;
4310       } else {
4311         if (!isUndefOrEqual(BitI1, j + NumElts))
4312           return false;
4313       }
4314     }
4315   }
4316
4317   return true;
4318 }
4319
4320 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4321 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4322 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4323                          bool HasInt256, bool V2IsSplat = false) {
4324   assert(VT.getSizeInBits() >= 128 &&
4325          "Unsupported vector type for unpckh");
4326
4327   unsigned NumElts = VT.getVectorNumElements();
4328   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4329       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4330     return false;
4331
4332   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4333          "Unsupported vector type for unpckh");
4334
4335   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4336   unsigned NumLanes = VT.getSizeInBits()/128;
4337   unsigned NumLaneElts = NumElts/NumLanes;
4338
4339   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4340     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4341       int BitI  = Mask[l+i];
4342       int BitI1 = Mask[l+i+1];
4343       if (!isUndefOrEqual(BitI, j))
4344         return false;
4345       if (V2IsSplat) {
4346         if (isUndefOrEqual(BitI1, NumElts))
4347           return false;
4348       } else {
4349         if (!isUndefOrEqual(BitI1, j+NumElts))
4350           return false;
4351       }
4352     }
4353   }
4354   return true;
4355 }
4356
4357 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4358 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4359 /// <0, 0, 1, 1>
4360 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4361   unsigned NumElts = VT.getVectorNumElements();
4362   bool Is256BitVec = VT.is256BitVector();
4363
4364   if (VT.is512BitVector())
4365     return false;
4366   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4367          "Unsupported vector type for unpckh");
4368
4369   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4370       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4371     return false;
4372
4373   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4374   // FIXME: Need a better way to get rid of this, there's no latency difference
4375   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4376   // the former later. We should also remove the "_undef" special mask.
4377   if (NumElts == 4 && Is256BitVec)
4378     return false;
4379
4380   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4381   // independently on 128-bit lanes.
4382   unsigned NumLanes = VT.getSizeInBits()/128;
4383   unsigned NumLaneElts = NumElts/NumLanes;
4384
4385   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4386     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4387       int BitI  = Mask[l+i];
4388       int BitI1 = Mask[l+i+1];
4389
4390       if (!isUndefOrEqual(BitI, j))
4391         return false;
4392       if (!isUndefOrEqual(BitI1, j))
4393         return false;
4394     }
4395   }
4396
4397   return true;
4398 }
4399
4400 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4401 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4402 /// <2, 2, 3, 3>
4403 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4404   unsigned NumElts = VT.getVectorNumElements();
4405
4406   if (VT.is512BitVector())
4407     return false;
4408
4409   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4410          "Unsupported vector type for unpckh");
4411
4412   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4413       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4414     return false;
4415
4416   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4417   // independently on 128-bit lanes.
4418   unsigned NumLanes = VT.getSizeInBits()/128;
4419   unsigned NumLaneElts = NumElts/NumLanes;
4420
4421   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4422     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4423       int BitI  = Mask[l+i];
4424       int BitI1 = Mask[l+i+1];
4425       if (!isUndefOrEqual(BitI, j))
4426         return false;
4427       if (!isUndefOrEqual(BitI1, j))
4428         return false;
4429     }
4430   }
4431   return true;
4432 }
4433
4434 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4435 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4436 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4437   if (!VT.is512BitVector())
4438     return false;
4439
4440   unsigned NumElts = VT.getVectorNumElements();
4441   unsigned HalfSize = NumElts/2;
4442   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4443     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4444       *Imm = 1;
4445       return true;
4446     }
4447   }
4448   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4449     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4450       *Imm = 0;
4451       return true;
4452     }
4453   }
4454   return false;
4455 }
4456
4457 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4458 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4459 /// MOVSD, and MOVD, i.e. setting the lowest element.
4460 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4461   if (VT.getVectorElementType().getSizeInBits() < 32)
4462     return false;
4463   if (!VT.is128BitVector())
4464     return false;
4465
4466   unsigned NumElts = VT.getVectorNumElements();
4467
4468   if (!isUndefOrEqual(Mask[0], NumElts))
4469     return false;
4470
4471   for (unsigned i = 1; i != NumElts; ++i)
4472     if (!isUndefOrEqual(Mask[i], i))
4473       return false;
4474
4475   return true;
4476 }
4477
4478 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4479 /// as permutations between 128-bit chunks or halves. As an example: this
4480 /// shuffle bellow:
4481 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4482 /// The first half comes from the second half of V1 and the second half from the
4483 /// the second half of V2.
4484 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4485   if (!HasFp256 || !VT.is256BitVector())
4486     return false;
4487
4488   // The shuffle result is divided into half A and half B. In total the two
4489   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4490   // B must come from C, D, E or F.
4491   unsigned HalfSize = VT.getVectorNumElements()/2;
4492   bool MatchA = false, MatchB = false;
4493
4494   // Check if A comes from one of C, D, E, F.
4495   for (unsigned Half = 0; Half != 4; ++Half) {
4496     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4497       MatchA = true;
4498       break;
4499     }
4500   }
4501
4502   // Check if B comes from one of C, D, E, F.
4503   for (unsigned Half = 0; Half != 4; ++Half) {
4504     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4505       MatchB = true;
4506       break;
4507     }
4508   }
4509
4510   return MatchA && MatchB;
4511 }
4512
4513 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4514 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4515 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4516   MVT VT = SVOp->getSimpleValueType(0);
4517
4518   unsigned HalfSize = VT.getVectorNumElements()/2;
4519
4520   unsigned FstHalf = 0, SndHalf = 0;
4521   for (unsigned i = 0; i < HalfSize; ++i) {
4522     if (SVOp->getMaskElt(i) > 0) {
4523       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4524       break;
4525     }
4526   }
4527   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4528     if (SVOp->getMaskElt(i) > 0) {
4529       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4530       break;
4531     }
4532   }
4533
4534   return (FstHalf | (SndHalf << 4));
4535 }
4536
4537 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4538 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4539   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4540   if (EltSize < 32)
4541     return false;
4542
4543   unsigned NumElts = VT.getVectorNumElements();
4544   Imm8 = 0;
4545   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4546     for (unsigned i = 0; i != NumElts; ++i) {
4547       if (Mask[i] < 0)
4548         continue;
4549       Imm8 |= Mask[i] << (i*2);
4550     }
4551     return true;
4552   }
4553
4554   unsigned LaneSize = 4;
4555   SmallVector<int, 4> MaskVal(LaneSize, -1);
4556
4557   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4558     for (unsigned i = 0; i != LaneSize; ++i) {
4559       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4560         return false;
4561       if (Mask[i+l] < 0)
4562         continue;
4563       if (MaskVal[i] < 0) {
4564         MaskVal[i] = Mask[i+l] - l;
4565         Imm8 |= MaskVal[i] << (i*2);
4566         continue;
4567       }
4568       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4569         return false;
4570     }
4571   }
4572   return true;
4573 }
4574
4575 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4576 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4577 /// Note that VPERMIL mask matching is different depending whether theunderlying
4578 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4579 /// to the same elements of the low, but to the higher half of the source.
4580 /// In VPERMILPD the two lanes could be shuffled independently of each other
4581 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4582 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4583   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4584   if (VT.getSizeInBits() < 256 || EltSize < 32)
4585     return false;
4586   bool symetricMaskRequired = (EltSize == 32);
4587   unsigned NumElts = VT.getVectorNumElements();
4588
4589   unsigned NumLanes = VT.getSizeInBits()/128;
4590   unsigned LaneSize = NumElts/NumLanes;
4591   // 2 or 4 elements in one lane
4592
4593   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4594   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4595     for (unsigned i = 0; i != LaneSize; ++i) {
4596       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4597         return false;
4598       if (symetricMaskRequired) {
4599         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4600           ExpectedMaskVal[i] = Mask[i+l] - l;
4601           continue;
4602         }
4603         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4604           return false;
4605       }
4606     }
4607   }
4608   return true;
4609 }
4610
4611 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4612 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4613 /// element of vector 2 and the other elements to come from vector 1 in order.
4614 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4615                                bool V2IsSplat = false, bool V2IsUndef = false) {
4616   if (!VT.is128BitVector())
4617     return false;
4618
4619   unsigned NumOps = VT.getVectorNumElements();
4620   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4621     return false;
4622
4623   if (!isUndefOrEqual(Mask[0], 0))
4624     return false;
4625
4626   for (unsigned i = 1; i != NumOps; ++i)
4627     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4628           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4629           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4630       return false;
4631
4632   return true;
4633 }
4634
4635 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4636 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4637 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4638 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4639                            const X86Subtarget *Subtarget) {
4640   if (!Subtarget->hasSSE3())
4641     return false;
4642
4643   unsigned NumElems = VT.getVectorNumElements();
4644
4645   if ((VT.is128BitVector() && NumElems != 4) ||
4646       (VT.is256BitVector() && NumElems != 8) ||
4647       (VT.is512BitVector() && NumElems != 16))
4648     return false;
4649
4650   // "i+1" is the value the indexed mask element must have
4651   for (unsigned i = 0; i != NumElems; i += 2)
4652     if (!isUndefOrEqual(Mask[i], i+1) ||
4653         !isUndefOrEqual(Mask[i+1], i+1))
4654       return false;
4655
4656   return true;
4657 }
4658
4659 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4660 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4661 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4662 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4663                            const X86Subtarget *Subtarget) {
4664   if (!Subtarget->hasSSE3())
4665     return false;
4666
4667   unsigned NumElems = VT.getVectorNumElements();
4668
4669   if ((VT.is128BitVector() && NumElems != 4) ||
4670       (VT.is256BitVector() && NumElems != 8) ||
4671       (VT.is512BitVector() && NumElems != 16))
4672     return false;
4673
4674   // "i" is the value the indexed mask element must have
4675   for (unsigned i = 0; i != NumElems; i += 2)
4676     if (!isUndefOrEqual(Mask[i], i) ||
4677         !isUndefOrEqual(Mask[i+1], i))
4678       return false;
4679
4680   return true;
4681 }
4682
4683 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4684 /// specifies a shuffle of elements that is suitable for input to 256-bit
4685 /// version of MOVDDUP.
4686 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4687   if (!HasFp256 || !VT.is256BitVector())
4688     return false;
4689
4690   unsigned NumElts = VT.getVectorNumElements();
4691   if (NumElts != 4)
4692     return false;
4693
4694   for (unsigned i = 0; i != NumElts/2; ++i)
4695     if (!isUndefOrEqual(Mask[i], 0))
4696       return false;
4697   for (unsigned i = NumElts/2; i != NumElts; ++i)
4698     if (!isUndefOrEqual(Mask[i], NumElts/2))
4699       return false;
4700   return true;
4701 }
4702
4703 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4704 /// specifies a shuffle of elements that is suitable for input to 128-bit
4705 /// version of MOVDDUP.
4706 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4707   if (!VT.is128BitVector())
4708     return false;
4709
4710   unsigned e = VT.getVectorNumElements() / 2;
4711   for (unsigned i = 0; i != e; ++i)
4712     if (!isUndefOrEqual(Mask[i], i))
4713       return false;
4714   for (unsigned i = 0; i != e; ++i)
4715     if (!isUndefOrEqual(Mask[e+i], i))
4716       return false;
4717   return true;
4718 }
4719
4720 /// isVEXTRACTIndex - Return true if the specified
4721 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4722 /// suitable for instruction that extract 128 or 256 bit vectors
4723 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4724   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4725   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4726     return false;
4727
4728   // The index should be aligned on a vecWidth-bit boundary.
4729   uint64_t Index =
4730     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4731
4732   MVT VT = N->getSimpleValueType(0);
4733   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4734   bool Result = (Index * ElSize) % vecWidth == 0;
4735
4736   return Result;
4737 }
4738
4739 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4740 /// operand specifies a subvector insert that is suitable for input to
4741 /// insertion of 128 or 256-bit subvectors
4742 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4743   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4744   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4745     return false;
4746   // The index should be aligned on a vecWidth-bit boundary.
4747   uint64_t Index =
4748     cast<ConstantSDNode>(N->getOperand(2).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 bool X86::isVINSERT128Index(SDNode *N) {
4758   return isVINSERTIndex(N, 128);
4759 }
4760
4761 bool X86::isVINSERT256Index(SDNode *N) {
4762   return isVINSERTIndex(N, 256);
4763 }
4764
4765 bool X86::isVEXTRACT128Index(SDNode *N) {
4766   return isVEXTRACTIndex(N, 128);
4767 }
4768
4769 bool X86::isVEXTRACT256Index(SDNode *N) {
4770   return isVEXTRACTIndex(N, 256);
4771 }
4772
4773 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4774 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4775 /// Handles 128-bit and 256-bit.
4776 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4777   MVT VT = N->getSimpleValueType(0);
4778
4779   assert((VT.getSizeInBits() >= 128) &&
4780          "Unsupported vector type for PSHUF/SHUFP");
4781
4782   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4783   // independently on 128-bit lanes.
4784   unsigned NumElts = VT.getVectorNumElements();
4785   unsigned NumLanes = VT.getSizeInBits()/128;
4786   unsigned NumLaneElts = NumElts/NumLanes;
4787
4788   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4789          "Only supports 2, 4 or 8 elements per lane");
4790
4791   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4792   unsigned Mask = 0;
4793   for (unsigned i = 0; i != NumElts; ++i) {
4794     int Elt = N->getMaskElt(i);
4795     if (Elt < 0) continue;
4796     Elt &= NumLaneElts - 1;
4797     unsigned ShAmt = (i << Shift) % 8;
4798     Mask |= Elt << ShAmt;
4799   }
4800
4801   return Mask;
4802 }
4803
4804 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4805 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4806 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4807   MVT VT = N->getSimpleValueType(0);
4808
4809   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4810          "Unsupported vector type for PSHUFHW");
4811
4812   unsigned NumElts = VT.getVectorNumElements();
4813
4814   unsigned Mask = 0;
4815   for (unsigned l = 0; l != NumElts; l += 8) {
4816     // 8 nodes per lane, but we only care about the last 4.
4817     for (unsigned i = 0; i < 4; ++i) {
4818       int Elt = N->getMaskElt(l+i+4);
4819       if (Elt < 0) continue;
4820       Elt &= 0x3; // only 2-bits.
4821       Mask |= Elt << (i * 2);
4822     }
4823   }
4824
4825   return Mask;
4826 }
4827
4828 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4829 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4830 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4831   MVT VT = N->getSimpleValueType(0);
4832
4833   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4834          "Unsupported vector type for PSHUFHW");
4835
4836   unsigned NumElts = VT.getVectorNumElements();
4837
4838   unsigned Mask = 0;
4839   for (unsigned l = 0; l != NumElts; l += 8) {
4840     // 8 nodes per lane, but we only care about the first 4.
4841     for (unsigned i = 0; i < 4; ++i) {
4842       int Elt = N->getMaskElt(l+i);
4843       if (Elt < 0) continue;
4844       Elt &= 0x3; // only 2-bits
4845       Mask |= Elt << (i * 2);
4846     }
4847   }
4848
4849   return Mask;
4850 }
4851
4852 /// \brief Return the appropriate immediate to shuffle the specified
4853 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4854 /// VALIGN (if Interlane is true) instructions.
4855 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4856                                            bool InterLane) {
4857   MVT VT = SVOp->getSimpleValueType(0);
4858   unsigned EltSize = InterLane ? 1 :
4859     VT.getVectorElementType().getSizeInBits() >> 3;
4860
4861   unsigned NumElts = VT.getVectorNumElements();
4862   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4863   unsigned NumLaneElts = NumElts/NumLanes;
4864
4865   int Val = 0;
4866   unsigned i;
4867   for (i = 0; i != NumElts; ++i) {
4868     Val = SVOp->getMaskElt(i);
4869     if (Val >= 0)
4870       break;
4871   }
4872   if (Val >= (int)NumElts)
4873     Val -= NumElts - NumLaneElts;
4874
4875   assert(Val - i > 0 && "PALIGNR imm should be positive");
4876   return (Val - i) * EltSize;
4877 }
4878
4879 /// \brief Return the appropriate immediate to shuffle the specified
4880 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4881 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4882   return getShuffleAlignrImmediate(SVOp, false);
4883 }
4884
4885 /// \brief Return the appropriate immediate to shuffle the specified
4886 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4887 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4888   return getShuffleAlignrImmediate(SVOp, true);
4889 }
4890
4891
4892 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4893   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4894   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4895     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4896
4897   uint64_t Index =
4898     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4899
4900   MVT VecVT = N->getOperand(0).getSimpleValueType();
4901   MVT ElVT = VecVT.getVectorElementType();
4902
4903   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4904   return Index / NumElemsPerChunk;
4905 }
4906
4907 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4908   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4909   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4910     llvm_unreachable("Illegal insert subvector for VINSERT");
4911
4912   uint64_t Index =
4913     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4914
4915   MVT VecVT = N->getSimpleValueType(0);
4916   MVT ElVT = VecVT.getVectorElementType();
4917
4918   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4919   return Index / NumElemsPerChunk;
4920 }
4921
4922 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4923 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4924 /// and VINSERTI128 instructions.
4925 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4926   return getExtractVEXTRACTImmediate(N, 128);
4927 }
4928
4929 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4930 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4931 /// and VINSERTI64x4 instructions.
4932 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4933   return getExtractVEXTRACTImmediate(N, 256);
4934 }
4935
4936 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4937 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4938 /// and VINSERTI128 instructions.
4939 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4940   return getInsertVINSERTImmediate(N, 128);
4941 }
4942
4943 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4944 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4945 /// and VINSERTI64x4 instructions.
4946 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4947   return getInsertVINSERTImmediate(N, 256);
4948 }
4949
4950 /// isZero - Returns true if Elt is a constant integer zero
4951 static bool isZero(SDValue V) {
4952   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4953   return C && C->isNullValue();
4954 }
4955
4956 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4957 /// constant +0.0.
4958 bool X86::isZeroNode(SDValue Elt) {
4959   if (isZero(Elt))
4960     return true;
4961   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4962     return CFP->getValueAPF().isPosZero();
4963   return false;
4964 }
4965
4966 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4967 /// match movhlps. The lower half elements should come from upper half of
4968 /// V1 (and in order), and the upper half elements should come from the upper
4969 /// half of V2 (and in order).
4970 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4971   if (!VT.is128BitVector())
4972     return false;
4973   if (VT.getVectorNumElements() != 4)
4974     return false;
4975   for (unsigned i = 0, e = 2; i != e; ++i)
4976     if (!isUndefOrEqual(Mask[i], i+2))
4977       return false;
4978   for (unsigned i = 2; i != 4; ++i)
4979     if (!isUndefOrEqual(Mask[i], i+4))
4980       return false;
4981   return true;
4982 }
4983
4984 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4985 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4986 /// required.
4987 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4988   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4989     return false;
4990   N = N->getOperand(0).getNode();
4991   if (!ISD::isNON_EXTLoad(N))
4992     return false;
4993   if (LD)
4994     *LD = cast<LoadSDNode>(N);
4995   return true;
4996 }
4997
4998 // Test whether the given value is a vector value which will be legalized
4999 // into a load.
5000 static bool WillBeConstantPoolLoad(SDNode *N) {
5001   if (N->getOpcode() != ISD::BUILD_VECTOR)
5002     return false;
5003
5004   // Check for any non-constant elements.
5005   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5006     switch (N->getOperand(i).getNode()->getOpcode()) {
5007     case ISD::UNDEF:
5008     case ISD::ConstantFP:
5009     case ISD::Constant:
5010       break;
5011     default:
5012       return false;
5013     }
5014
5015   // Vectors of all-zeros and all-ones are materialized with special
5016   // instructions rather than being loaded.
5017   return !ISD::isBuildVectorAllZeros(N) &&
5018          !ISD::isBuildVectorAllOnes(N);
5019 }
5020
5021 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5022 /// match movlp{s|d}. The lower half elements should come from lower half of
5023 /// V1 (and in order), and the upper half elements should come from the upper
5024 /// half of V2 (and in order). And since V1 will become the source of the
5025 /// MOVLP, it must be either a vector load or a scalar load to vector.
5026 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5027                                ArrayRef<int> Mask, MVT VT) {
5028   if (!VT.is128BitVector())
5029     return false;
5030
5031   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5032     return false;
5033   // Is V2 is a vector load, don't do this transformation. We will try to use
5034   // load folding shufps op.
5035   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5036     return false;
5037
5038   unsigned NumElems = VT.getVectorNumElements();
5039
5040   if (NumElems != 2 && NumElems != 4)
5041     return false;
5042   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5043     if (!isUndefOrEqual(Mask[i], i))
5044       return false;
5045   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5046     if (!isUndefOrEqual(Mask[i], i+NumElems))
5047       return false;
5048   return true;
5049 }
5050
5051 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5052 /// to an zero vector.
5053 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5054 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5055   SDValue V1 = N->getOperand(0);
5056   SDValue V2 = N->getOperand(1);
5057   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5058   for (unsigned i = 0; i != NumElems; ++i) {
5059     int Idx = N->getMaskElt(i);
5060     if (Idx >= (int)NumElems) {
5061       unsigned Opc = V2.getOpcode();
5062       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5063         continue;
5064       if (Opc != ISD::BUILD_VECTOR ||
5065           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5066         return false;
5067     } else if (Idx >= 0) {
5068       unsigned Opc = V1.getOpcode();
5069       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5070         continue;
5071       if (Opc != ISD::BUILD_VECTOR ||
5072           !X86::isZeroNode(V1.getOperand(Idx)))
5073         return false;
5074     }
5075   }
5076   return true;
5077 }
5078
5079 /// getZeroVector - Returns a vector of specified type with all zero elements.
5080 ///
5081 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5082                              SelectionDAG &DAG, SDLoc dl) {
5083   assert(VT.isVector() && "Expected a vector type");
5084
5085   // Always build SSE zero vectors as <4 x i32> bitcasted
5086   // to their dest type. This ensures they get CSE'd.
5087   SDValue Vec;
5088   if (VT.is128BitVector()) {  // SSE
5089     if (Subtarget->hasSSE2()) {  // SSE2
5090       SDValue Cst = DAG.getConstant(0, MVT::i32);
5091       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5092     } else { // SSE1
5093       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5094       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5095     }
5096   } else if (VT.is256BitVector()) { // AVX
5097     if (Subtarget->hasInt256()) { // AVX2
5098       SDValue Cst = DAG.getConstant(0, MVT::i32);
5099       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5100       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5101     } else {
5102       // 256-bit logic and arithmetic instructions in AVX are all
5103       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5104       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5105       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5106       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5107     }
5108   } else if (VT.is512BitVector()) { // AVX-512
5109       SDValue Cst = DAG.getConstant(0, MVT::i32);
5110       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5111                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5112       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5113   } else if (VT.getScalarType() == MVT::i1) {
5114     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5115     SDValue Cst = DAG.getConstant(0, MVT::i1);
5116     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5117     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5118   } else
5119     llvm_unreachable("Unexpected vector type");
5120
5121   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5122 }
5123
5124 /// getOnesVector - Returns a vector of specified type with all bits set.
5125 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5126 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5127 /// Then bitcast to their original type, ensuring they get CSE'd.
5128 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5129                              SDLoc dl) {
5130   assert(VT.isVector() && "Expected a vector type");
5131
5132   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
5133   SDValue Vec;
5134   if (VT.is256BitVector()) {
5135     if (HasInt256) { // AVX2
5136       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5137       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5138     } else { // AVX
5139       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5140       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5141     }
5142   } else if (VT.is128BitVector()) {
5143     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5144   } else
5145     llvm_unreachable("Unexpected vector type");
5146
5147   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5148 }
5149
5150 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5151 /// that point to V2 points to its first element.
5152 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5153   for (unsigned i = 0; i != NumElems; ++i) {
5154     if (Mask[i] > (int)NumElems) {
5155       Mask[i] = NumElems;
5156     }
5157   }
5158 }
5159
5160 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5161 /// operation of specified width.
5162 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5163                        SDValue V2) {
5164   unsigned NumElems = VT.getVectorNumElements();
5165   SmallVector<int, 8> Mask;
5166   Mask.push_back(NumElems);
5167   for (unsigned i = 1; i != NumElems; ++i)
5168     Mask.push_back(i);
5169   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5170 }
5171
5172 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5173 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5174                           SDValue V2) {
5175   unsigned NumElems = VT.getVectorNumElements();
5176   SmallVector<int, 8> Mask;
5177   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5178     Mask.push_back(i);
5179     Mask.push_back(i + NumElems);
5180   }
5181   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5182 }
5183
5184 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5185 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5186                           SDValue V2) {
5187   unsigned NumElems = VT.getVectorNumElements();
5188   SmallVector<int, 8> Mask;
5189   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5190     Mask.push_back(i + Half);
5191     Mask.push_back(i + NumElems + Half);
5192   }
5193   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5194 }
5195
5196 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5197 // a generic shuffle instruction because the target has no such instructions.
5198 // Generate shuffles which repeat i16 and i8 several times until they can be
5199 // represented by v4f32 and then be manipulated by target suported shuffles.
5200 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5201   MVT VT = V.getSimpleValueType();
5202   int NumElems = VT.getVectorNumElements();
5203   SDLoc dl(V);
5204
5205   while (NumElems > 4) {
5206     if (EltNo < NumElems/2) {
5207       V = getUnpackl(DAG, dl, VT, V, V);
5208     } else {
5209       V = getUnpackh(DAG, dl, VT, V, V);
5210       EltNo -= NumElems/2;
5211     }
5212     NumElems >>= 1;
5213   }
5214   return V;
5215 }
5216
5217 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5218 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5219   MVT VT = V.getSimpleValueType();
5220   SDLoc dl(V);
5221
5222   if (VT.is128BitVector()) {
5223     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5224     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5225     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5226                              &SplatMask[0]);
5227   } else if (VT.is256BitVector()) {
5228     // To use VPERMILPS to splat scalars, the second half of indicies must
5229     // refer to the higher part, which is a duplication of the lower one,
5230     // because VPERMILPS can only handle in-lane permutations.
5231     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5232                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5233
5234     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5235     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5236                              &SplatMask[0]);
5237   } else
5238     llvm_unreachable("Vector size not supported");
5239
5240   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5241 }
5242
5243 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5244 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5245   MVT SrcVT = SV->getSimpleValueType(0);
5246   SDValue V1 = SV->getOperand(0);
5247   SDLoc dl(SV);
5248
5249   int EltNo = SV->getSplatIndex();
5250   int NumElems = SrcVT.getVectorNumElements();
5251   bool Is256BitVec = SrcVT.is256BitVector();
5252
5253   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5254          "Unknown how to promote splat for type");
5255
5256   // Extract the 128-bit part containing the splat element and update
5257   // the splat element index when it refers to the higher register.
5258   if (Is256BitVec) {
5259     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5260     if (EltNo >= NumElems/2)
5261       EltNo -= NumElems/2;
5262   }
5263
5264   // All i16 and i8 vector types can't be used directly by a generic shuffle
5265   // instruction because the target has no such instruction. Generate shuffles
5266   // which repeat i16 and i8 several times until they fit in i32, and then can
5267   // be manipulated by target suported shuffles.
5268   MVT EltVT = SrcVT.getVectorElementType();
5269   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5270     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5271
5272   // Recreate the 256-bit vector and place the same 128-bit vector
5273   // into the low and high part. This is necessary because we want
5274   // to use VPERM* to shuffle the vectors
5275   if (Is256BitVec) {
5276     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5277   }
5278
5279   return getLegalSplat(DAG, V1, EltNo);
5280 }
5281
5282 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5283 /// vector of zero or undef vector.  This produces a shuffle where the low
5284 /// element of V2 is swizzled into the zero/undef vector, landing at element
5285 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5286 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5287                                            bool IsZero,
5288                                            const X86Subtarget *Subtarget,
5289                                            SelectionDAG &DAG) {
5290   MVT VT = V2.getSimpleValueType();
5291   SDValue V1 = IsZero
5292     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5293   unsigned NumElems = VT.getVectorNumElements();
5294   SmallVector<int, 16> MaskVec;
5295   for (unsigned i = 0; i != NumElems; ++i)
5296     // If this is the insertion idx, put the low elt of V2 here.
5297     MaskVec.push_back(i == Idx ? NumElems : i);
5298   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5299 }
5300
5301 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5302 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5303 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5304 /// shuffles which use a single input multiple times, and in those cases it will
5305 /// adjust the mask to only have indices within that single input.
5306 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5307                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5308   unsigned NumElems = VT.getVectorNumElements();
5309   SDValue ImmN;
5310
5311   IsUnary = false;
5312   bool IsFakeUnary = false;
5313   switch(N->getOpcode()) {
5314   case X86ISD::BLENDI:
5315     ImmN = N->getOperand(N->getNumOperands()-1);
5316     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5317     break;
5318   case X86ISD::SHUFP:
5319     ImmN = N->getOperand(N->getNumOperands()-1);
5320     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5321     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5322     break;
5323   case X86ISD::UNPCKH:
5324     DecodeUNPCKHMask(VT, Mask);
5325     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5326     break;
5327   case X86ISD::UNPCKL:
5328     DecodeUNPCKLMask(VT, Mask);
5329     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5330     break;
5331   case X86ISD::MOVHLPS:
5332     DecodeMOVHLPSMask(NumElems, Mask);
5333     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5334     break;
5335   case X86ISD::MOVLHPS:
5336     DecodeMOVLHPSMask(NumElems, Mask);
5337     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5338     break;
5339   case X86ISD::PALIGNR:
5340     ImmN = N->getOperand(N->getNumOperands()-1);
5341     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5342     break;
5343   case X86ISD::PSHUFD:
5344   case X86ISD::VPERMILPI:
5345     ImmN = N->getOperand(N->getNumOperands()-1);
5346     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5347     IsUnary = true;
5348     break;
5349   case X86ISD::PSHUFHW:
5350     ImmN = N->getOperand(N->getNumOperands()-1);
5351     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5352     IsUnary = true;
5353     break;
5354   case X86ISD::PSHUFLW:
5355     ImmN = N->getOperand(N->getNumOperands()-1);
5356     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5357     IsUnary = true;
5358     break;
5359   case X86ISD::PSHUFB: {
5360     IsUnary = true;
5361     SDValue MaskNode = N->getOperand(1);
5362     while (MaskNode->getOpcode() == ISD::BITCAST)
5363       MaskNode = MaskNode->getOperand(0);
5364
5365     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5366       // If we have a build-vector, then things are easy.
5367       EVT VT = MaskNode.getValueType();
5368       assert(VT.isVector() &&
5369              "Can't produce a non-vector with a build_vector!");
5370       if (!VT.isInteger())
5371         return false;
5372
5373       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5374
5375       SmallVector<uint64_t, 32> RawMask;
5376       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5377         SDValue Op = MaskNode->getOperand(i);
5378         if (Op->getOpcode() == ISD::UNDEF) {
5379           RawMask.push_back((uint64_t)SM_SentinelUndef);
5380           continue;
5381         }
5382         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5383         if (!CN)
5384           return false;
5385         APInt MaskElement = CN->getAPIntValue();
5386
5387         // We now have to decode the element which could be any integer size and
5388         // extract each byte of it.
5389         for (int j = 0; j < NumBytesPerElement; ++j) {
5390           // Note that this is x86 and so always little endian: the low byte is
5391           // the first byte of the mask.
5392           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5393           MaskElement = MaskElement.lshr(8);
5394         }
5395       }
5396       DecodePSHUFBMask(RawMask, Mask);
5397       break;
5398     }
5399
5400     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5401     if (!MaskLoad)
5402       return false;
5403
5404     SDValue Ptr = MaskLoad->getBasePtr();
5405     if (Ptr->getOpcode() == X86ISD::Wrapper)
5406       Ptr = Ptr->getOperand(0);
5407
5408     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5409     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5410       return false;
5411
5412     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5413       // FIXME: Support AVX-512 here.
5414       Type *Ty = C->getType();
5415       if (!Ty->isVectorTy() || (Ty->getVectorNumElements() != 16 &&
5416                                 Ty->getVectorNumElements() != 32))
5417         return false;
5418
5419       DecodePSHUFBMask(C, Mask);
5420       break;
5421     }
5422
5423     return false;
5424   }
5425   case X86ISD::VPERMI:
5426     ImmN = N->getOperand(N->getNumOperands()-1);
5427     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5428     IsUnary = true;
5429     break;
5430   case X86ISD::MOVSS:
5431   case X86ISD::MOVSD: {
5432     // The index 0 always comes from the first element of the second source,
5433     // this is why MOVSS and MOVSD are used in the first place. The other
5434     // elements come from the other positions of the first source vector
5435     Mask.push_back(NumElems);
5436     for (unsigned i = 1; i != NumElems; ++i) {
5437       Mask.push_back(i);
5438     }
5439     break;
5440   }
5441   case X86ISD::VPERM2X128:
5442     ImmN = N->getOperand(N->getNumOperands()-1);
5443     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5444     if (Mask.empty()) return false;
5445     break;
5446   case X86ISD::MOVSLDUP:
5447     DecodeMOVSLDUPMask(VT, Mask);
5448     break;
5449   case X86ISD::MOVSHDUP:
5450     DecodeMOVSHDUPMask(VT, Mask);
5451     break;
5452   case X86ISD::MOVDDUP:
5453   case X86ISD::MOVLHPD:
5454   case X86ISD::MOVLPD:
5455   case X86ISD::MOVLPS:
5456     // Not yet implemented
5457     return false;
5458   default: llvm_unreachable("unknown target shuffle node");
5459   }
5460
5461   // If we have a fake unary shuffle, the shuffle mask is spread across two
5462   // inputs that are actually the same node. Re-map the mask to always point
5463   // into the first input.
5464   if (IsFakeUnary)
5465     for (int &M : Mask)
5466       if (M >= (int)Mask.size())
5467         M -= Mask.size();
5468
5469   return true;
5470 }
5471
5472 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5473 /// element of the result of the vector shuffle.
5474 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5475                                    unsigned Depth) {
5476   if (Depth == 6)
5477     return SDValue();  // Limit search depth.
5478
5479   SDValue V = SDValue(N, 0);
5480   EVT VT = V.getValueType();
5481   unsigned Opcode = V.getOpcode();
5482
5483   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5484   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5485     int Elt = SV->getMaskElt(Index);
5486
5487     if (Elt < 0)
5488       return DAG.getUNDEF(VT.getVectorElementType());
5489
5490     unsigned NumElems = VT.getVectorNumElements();
5491     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5492                                          : SV->getOperand(1);
5493     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5494   }
5495
5496   // Recurse into target specific vector shuffles to find scalars.
5497   if (isTargetShuffle(Opcode)) {
5498     MVT ShufVT = V.getSimpleValueType();
5499     unsigned NumElems = ShufVT.getVectorNumElements();
5500     SmallVector<int, 16> ShuffleMask;
5501     bool IsUnary;
5502
5503     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5504       return SDValue();
5505
5506     int Elt = ShuffleMask[Index];
5507     if (Elt < 0)
5508       return DAG.getUNDEF(ShufVT.getVectorElementType());
5509
5510     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5511                                          : N->getOperand(1);
5512     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5513                                Depth+1);
5514   }
5515
5516   // Actual nodes that may contain scalar elements
5517   if (Opcode == ISD::BITCAST) {
5518     V = V.getOperand(0);
5519     EVT SrcVT = V.getValueType();
5520     unsigned NumElems = VT.getVectorNumElements();
5521
5522     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5523       return SDValue();
5524   }
5525
5526   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5527     return (Index == 0) ? V.getOperand(0)
5528                         : DAG.getUNDEF(VT.getVectorElementType());
5529
5530   if (V.getOpcode() == ISD::BUILD_VECTOR)
5531     return V.getOperand(Index);
5532
5533   return SDValue();
5534 }
5535
5536 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5537 /// shuffle operation which come from a consecutively from a zero. The
5538 /// search can start in two different directions, from left or right.
5539 /// We count undefs as zeros until PreferredNum is reached.
5540 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5541                                          unsigned NumElems, bool ZerosFromLeft,
5542                                          SelectionDAG &DAG,
5543                                          unsigned PreferredNum = -1U) {
5544   unsigned NumZeros = 0;
5545   for (unsigned i = 0; i != NumElems; ++i) {
5546     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5547     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5548     if (!Elt.getNode())
5549       break;
5550
5551     if (X86::isZeroNode(Elt))
5552       ++NumZeros;
5553     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5554       NumZeros = std::min(NumZeros + 1, PreferredNum);
5555     else
5556       break;
5557   }
5558
5559   return NumZeros;
5560 }
5561
5562 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5563 /// correspond consecutively to elements from one of the vector operands,
5564 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5565 static
5566 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5567                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5568                               unsigned NumElems, unsigned &OpNum) {
5569   bool SeenV1 = false;
5570   bool SeenV2 = false;
5571
5572   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5573     int Idx = SVOp->getMaskElt(i);
5574     // Ignore undef indicies
5575     if (Idx < 0)
5576       continue;
5577
5578     if (Idx < (int)NumElems)
5579       SeenV1 = true;
5580     else
5581       SeenV2 = true;
5582
5583     // Only accept consecutive elements from the same vector
5584     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5585       return false;
5586   }
5587
5588   OpNum = SeenV1 ? 0 : 1;
5589   return true;
5590 }
5591
5592 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5593 /// logical left shift of a vector.
5594 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5595                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5596   unsigned NumElems =
5597     SVOp->getSimpleValueType(0).getVectorNumElements();
5598   unsigned NumZeros = getNumOfConsecutiveZeros(
5599       SVOp, NumElems, false /* check zeros from right */, DAG,
5600       SVOp->getMaskElt(0));
5601   unsigned OpSrc;
5602
5603   if (!NumZeros)
5604     return false;
5605
5606   // Considering the elements in the mask that are not consecutive zeros,
5607   // check if they consecutively come from only one of the source vectors.
5608   //
5609   //               V1 = {X, A, B, C}     0
5610   //                         \  \  \    /
5611   //   vector_shuffle V1, V2 <1, 2, 3, X>
5612   //
5613   if (!isShuffleMaskConsecutive(SVOp,
5614             0,                   // Mask Start Index
5615             NumElems-NumZeros,   // Mask End Index(exclusive)
5616             NumZeros,            // Where to start looking in the src vector
5617             NumElems,            // Number of elements in vector
5618             OpSrc))              // Which source operand ?
5619     return false;
5620
5621   isLeft = false;
5622   ShAmt = NumZeros;
5623   ShVal = SVOp->getOperand(OpSrc);
5624   return true;
5625 }
5626
5627 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5628 /// logical left shift of a vector.
5629 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5630                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5631   unsigned NumElems =
5632     SVOp->getSimpleValueType(0).getVectorNumElements();
5633   unsigned NumZeros = getNumOfConsecutiveZeros(
5634       SVOp, NumElems, true /* check zeros from left */, DAG,
5635       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5636   unsigned OpSrc;
5637
5638   if (!NumZeros)
5639     return false;
5640
5641   // Considering the elements in the mask that are not consecutive zeros,
5642   // check if they consecutively come from only one of the source vectors.
5643   //
5644   //                           0    { A, B, X, X } = V2
5645   //                          / \    /  /
5646   //   vector_shuffle V1, V2 <X, X, 4, 5>
5647   //
5648   if (!isShuffleMaskConsecutive(SVOp,
5649             NumZeros,     // Mask Start Index
5650             NumElems,     // Mask End Index(exclusive)
5651             0,            // Where to start looking in the src vector
5652             NumElems,     // Number of elements in vector
5653             OpSrc))       // Which source operand ?
5654     return false;
5655
5656   isLeft = true;
5657   ShAmt = NumZeros;
5658   ShVal = SVOp->getOperand(OpSrc);
5659   return true;
5660 }
5661
5662 /// isVectorShift - Returns true if the shuffle can be implemented as a
5663 /// logical left or right shift of a vector.
5664 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5665                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5666   // Although the logic below support any bitwidth size, there are no
5667   // shift instructions which handle more than 128-bit vectors.
5668   if (!SVOp->getSimpleValueType(0).is128BitVector())
5669     return false;
5670
5671   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5672       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5673     return true;
5674
5675   return false;
5676 }
5677
5678 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5679 ///
5680 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5681                                        unsigned NumNonZero, unsigned NumZero,
5682                                        SelectionDAG &DAG,
5683                                        const X86Subtarget* Subtarget,
5684                                        const TargetLowering &TLI) {
5685   if (NumNonZero > 8)
5686     return SDValue();
5687
5688   SDLoc dl(Op);
5689   SDValue V;
5690   bool First = true;
5691   for (unsigned i = 0; i < 16; ++i) {
5692     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5693     if (ThisIsNonZero && First) {
5694       if (NumZero)
5695         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5696       else
5697         V = DAG.getUNDEF(MVT::v8i16);
5698       First = false;
5699     }
5700
5701     if ((i & 1) != 0) {
5702       SDValue ThisElt, LastElt;
5703       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5704       if (LastIsNonZero) {
5705         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5706                               MVT::i16, Op.getOperand(i-1));
5707       }
5708       if (ThisIsNonZero) {
5709         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5710         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5711                               ThisElt, DAG.getConstant(8, MVT::i8));
5712         if (LastIsNonZero)
5713           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5714       } else
5715         ThisElt = LastElt;
5716
5717       if (ThisElt.getNode())
5718         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5719                         DAG.getIntPtrConstant(i/2));
5720     }
5721   }
5722
5723   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5724 }
5725
5726 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5727 ///
5728 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5729                                      unsigned NumNonZero, unsigned NumZero,
5730                                      SelectionDAG &DAG,
5731                                      const X86Subtarget* Subtarget,
5732                                      const TargetLowering &TLI) {
5733   if (NumNonZero > 4)
5734     return SDValue();
5735
5736   SDLoc dl(Op);
5737   SDValue V;
5738   bool First = true;
5739   for (unsigned i = 0; i < 8; ++i) {
5740     bool isNonZero = (NonZeros & (1 << i)) != 0;
5741     if (isNonZero) {
5742       if (First) {
5743         if (NumZero)
5744           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5745         else
5746           V = DAG.getUNDEF(MVT::v8i16);
5747         First = false;
5748       }
5749       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5750                       MVT::v8i16, V, Op.getOperand(i),
5751                       DAG.getIntPtrConstant(i));
5752     }
5753   }
5754
5755   return V;
5756 }
5757
5758 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5759 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5760                                      const X86Subtarget *Subtarget,
5761                                      const TargetLowering &TLI) {
5762   // Find all zeroable elements.
5763   bool Zeroable[4];
5764   for (int i=0; i < 4; ++i) {
5765     SDValue Elt = Op->getOperand(i);
5766     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5767   }
5768   assert(std::count_if(&Zeroable[0], &Zeroable[4],
5769                        [](bool M) { return !M; }) > 1 &&
5770          "We expect at least two non-zero elements!");
5771
5772   // We only know how to deal with build_vector nodes where elements are either
5773   // zeroable or extract_vector_elt with constant index.
5774   SDValue FirstNonZero;
5775   unsigned FirstNonZeroIdx;
5776   for (unsigned i=0; i < 4; ++i) {
5777     if (Zeroable[i])
5778       continue;
5779     SDValue Elt = Op->getOperand(i);
5780     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5781         !isa<ConstantSDNode>(Elt.getOperand(1)))
5782       return SDValue();
5783     // Make sure that this node is extracting from a 128-bit vector.
5784     MVT VT = Elt.getOperand(0).getSimpleValueType();
5785     if (!VT.is128BitVector())
5786       return SDValue();
5787     if (!FirstNonZero.getNode()) {
5788       FirstNonZero = Elt;
5789       FirstNonZeroIdx = i;
5790     }
5791   }
5792
5793   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5794   SDValue V1 = FirstNonZero.getOperand(0);
5795   MVT VT = V1.getSimpleValueType();
5796
5797   // See if this build_vector can be lowered as a blend with zero.
5798   SDValue Elt;
5799   unsigned EltMaskIdx, EltIdx;
5800   int Mask[4];
5801   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5802     if (Zeroable[EltIdx]) {
5803       // The zero vector will be on the right hand side.
5804       Mask[EltIdx] = EltIdx+4;
5805       continue;
5806     }
5807
5808     Elt = Op->getOperand(EltIdx);
5809     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5810     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5811     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5812       break;
5813     Mask[EltIdx] = EltIdx;
5814   }
5815
5816   if (EltIdx == 4) {
5817     // Let the shuffle legalizer deal with blend operations.
5818     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5819     if (V1.getSimpleValueType() != VT)
5820       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5821     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5822   }
5823
5824   // See if we can lower this build_vector to a INSERTPS.
5825   if (!Subtarget->hasSSE41())
5826     return SDValue();
5827
5828   SDValue V2 = Elt.getOperand(0);
5829   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5830     V1 = SDValue();
5831
5832   bool CanFold = true;
5833   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5834     if (Zeroable[i])
5835       continue;
5836
5837     SDValue Current = Op->getOperand(i);
5838     SDValue SrcVector = Current->getOperand(0);
5839     if (!V1.getNode())
5840       V1 = SrcVector;
5841     CanFold = SrcVector == V1 &&
5842       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5843   }
5844
5845   if (!CanFold)
5846     return SDValue();
5847
5848   assert(V1.getNode() && "Expected at least two non-zero elements!");
5849   if (V1.getSimpleValueType() != MVT::v4f32)
5850     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5851   if (V2.getSimpleValueType() != MVT::v4f32)
5852     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5853
5854   // Ok, we can emit an INSERTPS instruction.
5855   unsigned ZMask = 0;
5856   for (int i = 0; i < 4; ++i)
5857     if (Zeroable[i])
5858       ZMask |= 1 << i;
5859
5860   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5861   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5862   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
5863                                DAG.getIntPtrConstant(InsertPSMask));
5864   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
5865 }
5866
5867 /// getVShift - Return a vector logical shift node.
5868 ///
5869 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5870                          unsigned NumBits, SelectionDAG &DAG,
5871                          const TargetLowering &TLI, SDLoc dl) {
5872   assert(VT.is128BitVector() && "Unknown type for VShift");
5873   EVT ShVT = MVT::v2i64;
5874   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5875   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5876   return DAG.getNode(ISD::BITCAST, dl, VT,
5877                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5878                              DAG.getConstant(NumBits,
5879                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5880 }
5881
5882 static SDValue
5883 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5884
5885   // Check if the scalar load can be widened into a vector load. And if
5886   // the address is "base + cst" see if the cst can be "absorbed" into
5887   // the shuffle mask.
5888   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5889     SDValue Ptr = LD->getBasePtr();
5890     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5891       return SDValue();
5892     EVT PVT = LD->getValueType(0);
5893     if (PVT != MVT::i32 && PVT != MVT::f32)
5894       return SDValue();
5895
5896     int FI = -1;
5897     int64_t Offset = 0;
5898     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5899       FI = FINode->getIndex();
5900       Offset = 0;
5901     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5902                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5903       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5904       Offset = Ptr.getConstantOperandVal(1);
5905       Ptr = Ptr.getOperand(0);
5906     } else {
5907       return SDValue();
5908     }
5909
5910     // FIXME: 256-bit vector instructions don't require a strict alignment,
5911     // improve this code to support it better.
5912     unsigned RequiredAlign = VT.getSizeInBits()/8;
5913     SDValue Chain = LD->getChain();
5914     // Make sure the stack object alignment is at least 16 or 32.
5915     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5916     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5917       if (MFI->isFixedObjectIndex(FI)) {
5918         // Can't change the alignment. FIXME: It's possible to compute
5919         // the exact stack offset and reference FI + adjust offset instead.
5920         // If someone *really* cares about this. That's the way to implement it.
5921         return SDValue();
5922       } else {
5923         MFI->setObjectAlignment(FI, RequiredAlign);
5924       }
5925     }
5926
5927     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5928     // Ptr + (Offset & ~15).
5929     if (Offset < 0)
5930       return SDValue();
5931     if ((Offset % RequiredAlign) & 3)
5932       return SDValue();
5933     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5934     if (StartOffset)
5935       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5936                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5937
5938     int EltNo = (Offset - StartOffset) >> 2;
5939     unsigned NumElems = VT.getVectorNumElements();
5940
5941     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5942     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5943                              LD->getPointerInfo().getWithOffset(StartOffset),
5944                              false, false, false, 0);
5945
5946     SmallVector<int, 8> Mask;
5947     for (unsigned i = 0; i != NumElems; ++i)
5948       Mask.push_back(EltNo);
5949
5950     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5951   }
5952
5953   return SDValue();
5954 }
5955
5956 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5957 /// vector of type 'VT', see if the elements can be replaced by a single large
5958 /// load which has the same value as a build_vector whose operands are 'elts'.
5959 ///
5960 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5961 ///
5962 /// FIXME: we'd also like to handle the case where the last elements are zero
5963 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5964 /// There's even a handy isZeroNode for that purpose.
5965 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5966                                         SDLoc &DL, SelectionDAG &DAG,
5967                                         bool isAfterLegalize) {
5968   EVT EltVT = VT.getVectorElementType();
5969   unsigned NumElems = Elts.size();
5970
5971   LoadSDNode *LDBase = nullptr;
5972   unsigned LastLoadedElt = -1U;
5973
5974   // For each element in the initializer, see if we've found a load or an undef.
5975   // If we don't find an initial load element, or later load elements are
5976   // non-consecutive, bail out.
5977   for (unsigned i = 0; i < NumElems; ++i) {
5978     SDValue Elt = Elts[i];
5979
5980     if (!Elt.getNode() ||
5981         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5982       return SDValue();
5983     if (!LDBase) {
5984       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5985         return SDValue();
5986       LDBase = cast<LoadSDNode>(Elt.getNode());
5987       LastLoadedElt = i;
5988       continue;
5989     }
5990     if (Elt.getOpcode() == ISD::UNDEF)
5991       continue;
5992
5993     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5994     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5995       return SDValue();
5996     LastLoadedElt = i;
5997   }
5998
5999   // If we have found an entire vector of loads and undefs, then return a large
6000   // load of the entire vector width starting at the base pointer.  If we found
6001   // consecutive loads for the low half, generate a vzext_load node.
6002   if (LastLoadedElt == NumElems - 1) {
6003
6004     if (isAfterLegalize &&
6005         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
6006       return SDValue();
6007
6008     SDValue NewLd = SDValue();
6009
6010     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
6011       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6012                           LDBase->getPointerInfo(),
6013                           LDBase->isVolatile(), LDBase->isNonTemporal(),
6014                           LDBase->isInvariant(), 0);
6015     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6016                         LDBase->getPointerInfo(),
6017                         LDBase->isVolatile(), LDBase->isNonTemporal(),
6018                         LDBase->isInvariant(), LDBase->getAlignment());
6019
6020     if (LDBase->hasAnyUseOfValue(1)) {
6021       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6022                                      SDValue(LDBase, 1),
6023                                      SDValue(NewLd.getNode(), 1));
6024       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6025       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6026                              SDValue(NewLd.getNode(), 1));
6027     }
6028
6029     return NewLd;
6030   }
6031   
6032   //TODO: The code below fires only for for loading the low v2i32 / v2f32
6033   //of a v4i32 / v4f32. It's probably worth generalizing.
6034   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
6035       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
6036     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
6037     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
6038     SDValue ResNode =
6039         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
6040                                 LDBase->getPointerInfo(),
6041                                 LDBase->getAlignment(),
6042                                 false/*isVolatile*/, true/*ReadMem*/,
6043                                 false/*WriteMem*/);
6044
6045     // Make sure the newly-created LOAD is in the same position as LDBase in
6046     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
6047     // update uses of LDBase's output chain to use the TokenFactor.
6048     if (LDBase->hasAnyUseOfValue(1)) {
6049       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6050                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
6051       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6052       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6053                              SDValue(ResNode.getNode(), 1));
6054     }
6055
6056     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
6057   }
6058   return SDValue();
6059 }
6060
6061 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6062 /// to generate a splat value for the following cases:
6063 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6064 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6065 /// a scalar load, or a constant.
6066 /// The VBROADCAST node is returned when a pattern is found,
6067 /// or SDValue() otherwise.
6068 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6069                                     SelectionDAG &DAG) {
6070   // VBROADCAST requires AVX.
6071   // TODO: Splats could be generated for non-AVX CPUs using SSE
6072   // instructions, but there's less potential gain for only 128-bit vectors.
6073   if (!Subtarget->hasAVX())
6074     return SDValue();
6075
6076   MVT VT = Op.getSimpleValueType();
6077   SDLoc dl(Op);
6078
6079   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6080          "Unsupported vector type for broadcast.");
6081
6082   SDValue Ld;
6083   bool ConstSplatVal;
6084
6085   switch (Op.getOpcode()) {
6086     default:
6087       // Unknown pattern found.
6088       return SDValue();
6089
6090     case ISD::BUILD_VECTOR: {
6091       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6092       BitVector UndefElements;
6093       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6094
6095       // We need a splat of a single value to use broadcast, and it doesn't
6096       // make any sense if the value is only in one element of the vector.
6097       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6098         return SDValue();
6099
6100       Ld = Splat;
6101       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6102                        Ld.getOpcode() == ISD::ConstantFP);
6103
6104       // Make sure that all of the users of a non-constant load are from the
6105       // BUILD_VECTOR node.
6106       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6107         return SDValue();
6108       break;
6109     }
6110
6111     case ISD::VECTOR_SHUFFLE: {
6112       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6113
6114       // Shuffles must have a splat mask where the first element is
6115       // broadcasted.
6116       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6117         return SDValue();
6118
6119       SDValue Sc = Op.getOperand(0);
6120       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6121           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6122
6123         if (!Subtarget->hasInt256())
6124           return SDValue();
6125
6126         // Use the register form of the broadcast instruction available on AVX2.
6127         if (VT.getSizeInBits() >= 256)
6128           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6129         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6130       }
6131
6132       Ld = Sc.getOperand(0);
6133       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6134                        Ld.getOpcode() == ISD::ConstantFP);
6135
6136       // The scalar_to_vector node and the suspected
6137       // load node must have exactly one user.
6138       // Constants may have multiple users.
6139
6140       // AVX-512 has register version of the broadcast
6141       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6142         Ld.getValueType().getSizeInBits() >= 32;
6143       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6144           !hasRegVer))
6145         return SDValue();
6146       break;
6147     }
6148   }
6149
6150   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6151   bool IsGE256 = (VT.getSizeInBits() >= 256);
6152
6153   // When optimizing for size, generate up to 5 extra bytes for a broadcast
6154   // instruction to save 8 or more bytes of constant pool data.
6155   // TODO: If multiple splats are generated to load the same constant,
6156   // it may be detrimental to overall size. There needs to be a way to detect
6157   // that condition to know if this is truly a size win.
6158   const Function *F = DAG.getMachineFunction().getFunction();
6159   bool OptForSize = F->getAttributes().
6160     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6161
6162   // Handle broadcasting a single constant scalar from the constant pool
6163   // into a vector.
6164   // On Sandybridge (no AVX2), it is still better to load a constant vector
6165   // from the constant pool and not to broadcast it from a scalar.
6166   // But override that restriction when optimizing for size.
6167   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
6168   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
6169     EVT CVT = Ld.getValueType();
6170     assert(!CVT.isVector() && "Must not broadcast a vector type");
6171
6172     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
6173     // For size optimization, also splat v2f64 and v2i64, and for size opt
6174     // with AVX2, also splat i8 and i16.
6175     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
6176     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6177         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
6178       const Constant *C = nullptr;
6179       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6180         C = CI->getConstantIntValue();
6181       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6182         C = CF->getConstantFPValue();
6183
6184       assert(C && "Invalid constant type");
6185
6186       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6187       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6188       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6189       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6190                        MachinePointerInfo::getConstantPool(),
6191                        false, false, false, Alignment);
6192
6193       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6194     }
6195   }
6196
6197   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6198
6199   // Handle AVX2 in-register broadcasts.
6200   if (!IsLoad && Subtarget->hasInt256() &&
6201       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6202     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6203
6204   // The scalar source must be a normal load.
6205   if (!IsLoad)
6206     return SDValue();
6207
6208   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6209     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6210
6211   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6212   // double since there is no vbroadcastsd xmm
6213   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6214     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6215       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6216   }
6217
6218   // Unsupported broadcast.
6219   return SDValue();
6220 }
6221
6222 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6223 /// underlying vector and index.
6224 ///
6225 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6226 /// index.
6227 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6228                                          SDValue ExtIdx) {
6229   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6230   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6231     return Idx;
6232
6233   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6234   // lowered this:
6235   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6236   // to:
6237   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6238   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6239   //                           undef)
6240   //                       Constant<0>)
6241   // In this case the vector is the extract_subvector expression and the index
6242   // is 2, as specified by the shuffle.
6243   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6244   SDValue ShuffleVec = SVOp->getOperand(0);
6245   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6246   assert(ShuffleVecVT.getVectorElementType() ==
6247          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6248
6249   int ShuffleIdx = SVOp->getMaskElt(Idx);
6250   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6251     ExtractedFromVec = ShuffleVec;
6252     return ShuffleIdx;
6253   }
6254   return Idx;
6255 }
6256
6257 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6258   MVT VT = Op.getSimpleValueType();
6259
6260   // Skip if insert_vec_elt is not supported.
6261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6262   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6263     return SDValue();
6264
6265   SDLoc DL(Op);
6266   unsigned NumElems = Op.getNumOperands();
6267
6268   SDValue VecIn1;
6269   SDValue VecIn2;
6270   SmallVector<unsigned, 4> InsertIndices;
6271   SmallVector<int, 8> Mask(NumElems, -1);
6272
6273   for (unsigned i = 0; i != NumElems; ++i) {
6274     unsigned Opc = Op.getOperand(i).getOpcode();
6275
6276     if (Opc == ISD::UNDEF)
6277       continue;
6278
6279     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6280       // Quit if more than 1 elements need inserting.
6281       if (InsertIndices.size() > 1)
6282         return SDValue();
6283
6284       InsertIndices.push_back(i);
6285       continue;
6286     }
6287
6288     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6289     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6290     // Quit if non-constant index.
6291     if (!isa<ConstantSDNode>(ExtIdx))
6292       return SDValue();
6293     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6294
6295     // Quit if extracted from vector of different type.
6296     if (ExtractedFromVec.getValueType() != VT)
6297       return SDValue();
6298
6299     if (!VecIn1.getNode())
6300       VecIn1 = ExtractedFromVec;
6301     else if (VecIn1 != ExtractedFromVec) {
6302       if (!VecIn2.getNode())
6303         VecIn2 = ExtractedFromVec;
6304       else if (VecIn2 != ExtractedFromVec)
6305         // Quit if more than 2 vectors to shuffle
6306         return SDValue();
6307     }
6308
6309     if (ExtractedFromVec == VecIn1)
6310       Mask[i] = Idx;
6311     else if (ExtractedFromVec == VecIn2)
6312       Mask[i] = Idx + NumElems;
6313   }
6314
6315   if (!VecIn1.getNode())
6316     return SDValue();
6317
6318   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6319   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6320   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6321     unsigned Idx = InsertIndices[i];
6322     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6323                      DAG.getIntPtrConstant(Idx));
6324   }
6325
6326   return NV;
6327 }
6328
6329 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6330 SDValue
6331 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6332
6333   MVT VT = Op.getSimpleValueType();
6334   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6335          "Unexpected type in LowerBUILD_VECTORvXi1!");
6336
6337   SDLoc dl(Op);
6338   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6339     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6340     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6341     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6342   }
6343
6344   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6345     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6346     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6347     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6348   }
6349
6350   bool AllContants = true;
6351   uint64_t Immediate = 0;
6352   int NonConstIdx = -1;
6353   bool IsSplat = true;
6354   unsigned NumNonConsts = 0;
6355   unsigned NumConsts = 0;
6356   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6357     SDValue In = Op.getOperand(idx);
6358     if (In.getOpcode() == ISD::UNDEF)
6359       continue;
6360     if (!isa<ConstantSDNode>(In)) {
6361       AllContants = false;
6362       NonConstIdx = idx;
6363       NumNonConsts++;
6364     } else {
6365       NumConsts++;
6366       if (cast<ConstantSDNode>(In)->getZExtValue())
6367       Immediate |= (1ULL << idx);
6368     }
6369     if (In != Op.getOperand(0))
6370       IsSplat = false;
6371   }
6372
6373   if (AllContants) {
6374     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6375       DAG.getConstant(Immediate, MVT::i16));
6376     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6377                        DAG.getIntPtrConstant(0));
6378   }
6379
6380   if (NumNonConsts == 1 && NonConstIdx != 0) {
6381     SDValue DstVec;
6382     if (NumConsts) {
6383       SDValue VecAsImm = DAG.getConstant(Immediate,
6384                                          MVT::getIntegerVT(VT.getSizeInBits()));
6385       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6386     }
6387     else
6388       DstVec = DAG.getUNDEF(VT);
6389     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6390                        Op.getOperand(NonConstIdx),
6391                        DAG.getIntPtrConstant(NonConstIdx));
6392   }
6393   if (!IsSplat && (NonConstIdx != 0))
6394     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6395   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6396   SDValue Select;
6397   if (IsSplat)
6398     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6399                           DAG.getConstant(-1, SelectVT),
6400                           DAG.getConstant(0, SelectVT));
6401   else
6402     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6403                          DAG.getConstant((Immediate | 1), SelectVT),
6404                          DAG.getConstant(Immediate, SelectVT));
6405   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6406 }
6407
6408 /// \brief Return true if \p N implements a horizontal binop and return the
6409 /// operands for the horizontal binop into V0 and V1.
6410 ///
6411 /// This is a helper function of PerformBUILD_VECTORCombine.
6412 /// This function checks that the build_vector \p N in input implements a
6413 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6414 /// operation to match.
6415 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6416 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6417 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6418 /// arithmetic sub.
6419 ///
6420 /// This function only analyzes elements of \p N whose indices are
6421 /// in range [BaseIdx, LastIdx).
6422 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6423                               SelectionDAG &DAG,
6424                               unsigned BaseIdx, unsigned LastIdx,
6425                               SDValue &V0, SDValue &V1) {
6426   EVT VT = N->getValueType(0);
6427
6428   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6429   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6430          "Invalid Vector in input!");
6431
6432   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6433   bool CanFold = true;
6434   unsigned ExpectedVExtractIdx = BaseIdx;
6435   unsigned NumElts = LastIdx - BaseIdx;
6436   V0 = DAG.getUNDEF(VT);
6437   V1 = DAG.getUNDEF(VT);
6438
6439   // Check if N implements a horizontal binop.
6440   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6441     SDValue Op = N->getOperand(i + BaseIdx);
6442
6443     // Skip UNDEFs.
6444     if (Op->getOpcode() == ISD::UNDEF) {
6445       // Update the expected vector extract index.
6446       if (i * 2 == NumElts)
6447         ExpectedVExtractIdx = BaseIdx;
6448       ExpectedVExtractIdx += 2;
6449       continue;
6450     }
6451
6452     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6453
6454     if (!CanFold)
6455       break;
6456
6457     SDValue Op0 = Op.getOperand(0);
6458     SDValue Op1 = Op.getOperand(1);
6459
6460     // Try to match the following pattern:
6461     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6462     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6463         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6464         Op0.getOperand(0) == Op1.getOperand(0) &&
6465         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6466         isa<ConstantSDNode>(Op1.getOperand(1)));
6467     if (!CanFold)
6468       break;
6469
6470     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6471     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6472
6473     if (i * 2 < NumElts) {
6474       if (V0.getOpcode() == ISD::UNDEF)
6475         V0 = Op0.getOperand(0);
6476     } else {
6477       if (V1.getOpcode() == ISD::UNDEF)
6478         V1 = Op0.getOperand(0);
6479       if (i * 2 == NumElts)
6480         ExpectedVExtractIdx = BaseIdx;
6481     }
6482
6483     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6484     if (I0 == ExpectedVExtractIdx)
6485       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6486     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6487       // Try to match the following dag sequence:
6488       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6489       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6490     } else
6491       CanFold = false;
6492
6493     ExpectedVExtractIdx += 2;
6494   }
6495
6496   return CanFold;
6497 }
6498
6499 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6500 /// a concat_vector.
6501 ///
6502 /// This is a helper function of PerformBUILD_VECTORCombine.
6503 /// This function expects two 256-bit vectors called V0 and V1.
6504 /// At first, each vector is split into two separate 128-bit vectors.
6505 /// Then, the resulting 128-bit vectors are used to implement two
6506 /// horizontal binary operations.
6507 ///
6508 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6509 ///
6510 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6511 /// the two new horizontal binop.
6512 /// When Mode is set, the first horizontal binop dag node would take as input
6513 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6514 /// horizontal binop dag node would take as input the lower 128-bit of V1
6515 /// and the upper 128-bit of V1.
6516 ///   Example:
6517 ///     HADD V0_LO, V0_HI
6518 ///     HADD V1_LO, V1_HI
6519 ///
6520 /// Otherwise, the first horizontal binop dag node takes as input the lower
6521 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6522 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6523 ///   Example:
6524 ///     HADD V0_LO, V1_LO
6525 ///     HADD V0_HI, V1_HI
6526 ///
6527 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6528 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6529 /// the upper 128-bits of the result.
6530 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6531                                      SDLoc DL, SelectionDAG &DAG,
6532                                      unsigned X86Opcode, bool Mode,
6533                                      bool isUndefLO, bool isUndefHI) {
6534   EVT VT = V0.getValueType();
6535   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6536          "Invalid nodes in input!");
6537
6538   unsigned NumElts = VT.getVectorNumElements();
6539   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6540   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6541   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6542   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6543   EVT NewVT = V0_LO.getValueType();
6544
6545   SDValue LO = DAG.getUNDEF(NewVT);
6546   SDValue HI = DAG.getUNDEF(NewVT);
6547
6548   if (Mode) {
6549     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6550     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6551       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6552     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6553       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6554   } else {
6555     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6556     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6557                        V1_LO->getOpcode() != ISD::UNDEF))
6558       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6559
6560     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6561                        V1_HI->getOpcode() != ISD::UNDEF))
6562       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6563   }
6564
6565   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6566 }
6567
6568 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6569 /// sequence of 'vadd + vsub + blendi'.
6570 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6571                            const X86Subtarget *Subtarget) {
6572   SDLoc DL(BV);
6573   EVT VT = BV->getValueType(0);
6574   unsigned NumElts = VT.getVectorNumElements();
6575   SDValue InVec0 = DAG.getUNDEF(VT);
6576   SDValue InVec1 = DAG.getUNDEF(VT);
6577
6578   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6579           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6580
6581   // Odd-numbered elements in the input build vector are obtained from
6582   // adding two integer/float elements.
6583   // Even-numbered elements in the input build vector are obtained from
6584   // subtracting two integer/float elements.
6585   unsigned ExpectedOpcode = ISD::FSUB;
6586   unsigned NextExpectedOpcode = ISD::FADD;
6587   bool AddFound = false;
6588   bool SubFound = false;
6589
6590   for (unsigned i = 0, e = NumElts; i != e; i++) {
6591     SDValue Op = BV->getOperand(i);
6592
6593     // Skip 'undef' values.
6594     unsigned Opcode = Op.getOpcode();
6595     if (Opcode == ISD::UNDEF) {
6596       std::swap(ExpectedOpcode, NextExpectedOpcode);
6597       continue;
6598     }
6599
6600     // Early exit if we found an unexpected opcode.
6601     if (Opcode != ExpectedOpcode)
6602       return SDValue();
6603
6604     SDValue Op0 = Op.getOperand(0);
6605     SDValue Op1 = Op.getOperand(1);
6606
6607     // Try to match the following pattern:
6608     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6609     // Early exit if we cannot match that sequence.
6610     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6611         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6612         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6613         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6614         Op0.getOperand(1) != Op1.getOperand(1))
6615       return SDValue();
6616
6617     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6618     if (I0 != i)
6619       return SDValue();
6620
6621     // We found a valid add/sub node. Update the information accordingly.
6622     if (i & 1)
6623       AddFound = true;
6624     else
6625       SubFound = true;
6626
6627     // Update InVec0 and InVec1.
6628     if (InVec0.getOpcode() == ISD::UNDEF)
6629       InVec0 = Op0.getOperand(0);
6630     if (InVec1.getOpcode() == ISD::UNDEF)
6631       InVec1 = Op1.getOperand(0);
6632
6633     // Make sure that operands in input to each add/sub node always
6634     // come from a same pair of vectors.
6635     if (InVec0 != Op0.getOperand(0)) {
6636       if (ExpectedOpcode == ISD::FSUB)
6637         return SDValue();
6638
6639       // FADD is commutable. Try to commute the operands
6640       // and then test again.
6641       std::swap(Op0, Op1);
6642       if (InVec0 != Op0.getOperand(0))
6643         return SDValue();
6644     }
6645
6646     if (InVec1 != Op1.getOperand(0))
6647       return SDValue();
6648
6649     // Update the pair of expected opcodes.
6650     std::swap(ExpectedOpcode, NextExpectedOpcode);
6651   }
6652
6653   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6654   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6655       InVec1.getOpcode() != ISD::UNDEF)
6656     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6657
6658   return SDValue();
6659 }
6660
6661 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6662                                           const X86Subtarget *Subtarget) {
6663   SDLoc DL(N);
6664   EVT VT = N->getValueType(0);
6665   unsigned NumElts = VT.getVectorNumElements();
6666   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6667   SDValue InVec0, InVec1;
6668
6669   // Try to match an ADDSUB.
6670   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6671       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6672     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6673     if (Value.getNode())
6674       return Value;
6675   }
6676
6677   // Try to match horizontal ADD/SUB.
6678   unsigned NumUndefsLO = 0;
6679   unsigned NumUndefsHI = 0;
6680   unsigned Half = NumElts/2;
6681
6682   // Count the number of UNDEF operands in the build_vector in input.
6683   for (unsigned i = 0, e = Half; i != e; ++i)
6684     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6685       NumUndefsLO++;
6686
6687   for (unsigned i = Half, e = NumElts; i != e; ++i)
6688     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6689       NumUndefsHI++;
6690
6691   // Early exit if this is either a build_vector of all UNDEFs or all the
6692   // operands but one are UNDEF.
6693   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6694     return SDValue();
6695
6696   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6697     // Try to match an SSE3 float HADD/HSUB.
6698     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6699       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6700
6701     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6702       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6703   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6704     // Try to match an SSSE3 integer HADD/HSUB.
6705     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6706       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6707
6708     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6709       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6710   }
6711
6712   if (!Subtarget->hasAVX())
6713     return SDValue();
6714
6715   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6716     // Try to match an AVX horizontal add/sub of packed single/double
6717     // precision floating point values from 256-bit vectors.
6718     SDValue InVec2, InVec3;
6719     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6720         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6721         ((InVec0.getOpcode() == ISD::UNDEF ||
6722           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6723         ((InVec1.getOpcode() == ISD::UNDEF ||
6724           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6725       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6726
6727     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6728         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6729         ((InVec0.getOpcode() == ISD::UNDEF ||
6730           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6731         ((InVec1.getOpcode() == ISD::UNDEF ||
6732           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6733       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6734   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6735     // Try to match an AVX2 horizontal add/sub of signed integers.
6736     SDValue InVec2, InVec3;
6737     unsigned X86Opcode;
6738     bool CanFold = true;
6739
6740     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6741         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6742         ((InVec0.getOpcode() == ISD::UNDEF ||
6743           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6744         ((InVec1.getOpcode() == ISD::UNDEF ||
6745           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6746       X86Opcode = X86ISD::HADD;
6747     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6748         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6749         ((InVec0.getOpcode() == ISD::UNDEF ||
6750           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6751         ((InVec1.getOpcode() == ISD::UNDEF ||
6752           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6753       X86Opcode = X86ISD::HSUB;
6754     else
6755       CanFold = false;
6756
6757     if (CanFold) {
6758       // Fold this build_vector into a single horizontal add/sub.
6759       // Do this only if the target has AVX2.
6760       if (Subtarget->hasAVX2())
6761         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6762
6763       // Do not try to expand this build_vector into a pair of horizontal
6764       // add/sub if we can emit a pair of scalar add/sub.
6765       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6766         return SDValue();
6767
6768       // Convert this build_vector into a pair of horizontal binop followed by
6769       // a concat vector.
6770       bool isUndefLO = NumUndefsLO == Half;
6771       bool isUndefHI = NumUndefsHI == Half;
6772       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6773                                    isUndefLO, isUndefHI);
6774     }
6775   }
6776
6777   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6778        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6779     unsigned X86Opcode;
6780     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6781       X86Opcode = X86ISD::HADD;
6782     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6783       X86Opcode = X86ISD::HSUB;
6784     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6785       X86Opcode = X86ISD::FHADD;
6786     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6787       X86Opcode = X86ISD::FHSUB;
6788     else
6789       return SDValue();
6790
6791     // Don't try to expand this build_vector into a pair of horizontal add/sub
6792     // if we can simply emit a pair of scalar add/sub.
6793     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6794       return SDValue();
6795
6796     // Convert this build_vector into two horizontal add/sub followed by
6797     // a concat vector.
6798     bool isUndefLO = NumUndefsLO == Half;
6799     bool isUndefHI = NumUndefsHI == Half;
6800     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6801                                  isUndefLO, isUndefHI);
6802   }
6803
6804   return SDValue();
6805 }
6806
6807 SDValue
6808 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6809   SDLoc dl(Op);
6810
6811   MVT VT = Op.getSimpleValueType();
6812   MVT ExtVT = VT.getVectorElementType();
6813   unsigned NumElems = Op.getNumOperands();
6814
6815   // Generate vectors for predicate vectors.
6816   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6817     return LowerBUILD_VECTORvXi1(Op, DAG);
6818
6819   // Vectors containing all zeros can be matched by pxor and xorps later
6820   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6821     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6822     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6823     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6824       return Op;
6825
6826     return getZeroVector(VT, Subtarget, DAG, dl);
6827   }
6828
6829   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6830   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6831   // vpcmpeqd on 256-bit vectors.
6832   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6833     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6834       return Op;
6835
6836     if (!VT.is512BitVector())
6837       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6838   }
6839
6840   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6841   if (Broadcast.getNode())
6842     return Broadcast;
6843
6844   unsigned EVTBits = ExtVT.getSizeInBits();
6845
6846   unsigned NumZero  = 0;
6847   unsigned NumNonZero = 0;
6848   unsigned NonZeros = 0;
6849   bool IsAllConstants = true;
6850   SmallSet<SDValue, 8> Values;
6851   for (unsigned i = 0; i < NumElems; ++i) {
6852     SDValue Elt = Op.getOperand(i);
6853     if (Elt.getOpcode() == ISD::UNDEF)
6854       continue;
6855     Values.insert(Elt);
6856     if (Elt.getOpcode() != ISD::Constant &&
6857         Elt.getOpcode() != ISD::ConstantFP)
6858       IsAllConstants = false;
6859     if (X86::isZeroNode(Elt))
6860       NumZero++;
6861     else {
6862       NonZeros |= (1 << i);
6863       NumNonZero++;
6864     }
6865   }
6866
6867   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6868   if (NumNonZero == 0)
6869     return DAG.getUNDEF(VT);
6870
6871   // Special case for single non-zero, non-undef, element.
6872   if (NumNonZero == 1) {
6873     unsigned Idx = countTrailingZeros(NonZeros);
6874     SDValue Item = Op.getOperand(Idx);
6875
6876     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6877     // the value are obviously zero, truncate the value to i32 and do the
6878     // insertion that way.  Only do this if the value is non-constant or if the
6879     // value is a constant being inserted into element 0.  It is cheaper to do
6880     // a constant pool load than it is to do a movd + shuffle.
6881     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6882         (!IsAllConstants || Idx == 0)) {
6883       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6884         // Handle SSE only.
6885         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6886         EVT VecVT = MVT::v4i32;
6887         unsigned VecElts = 4;
6888
6889         // Truncate the value (which may itself be a constant) to i32, and
6890         // convert it to a vector with movd (S2V+shuffle to zero extend).
6891         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6892         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6893
6894         // If using the new shuffle lowering, just directly insert this.
6895         if (ExperimentalVectorShuffleLowering)
6896           return DAG.getNode(
6897               ISD::BITCAST, dl, VT,
6898               getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6899
6900         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6901
6902         // Now we have our 32-bit value zero extended in the low element of
6903         // a vector.  If Idx != 0, swizzle it into place.
6904         if (Idx != 0) {
6905           SmallVector<int, 4> Mask;
6906           Mask.push_back(Idx);
6907           for (unsigned i = 1; i != VecElts; ++i)
6908             Mask.push_back(i);
6909           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6910                                       &Mask[0]);
6911         }
6912         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6913       }
6914     }
6915
6916     // If we have a constant or non-constant insertion into the low element of
6917     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6918     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6919     // depending on what the source datatype is.
6920     if (Idx == 0) {
6921       if (NumZero == 0)
6922         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6923
6924       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6925           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6926         if (VT.is256BitVector() || VT.is512BitVector()) {
6927           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6928           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6929                              Item, DAG.getIntPtrConstant(0));
6930         }
6931         assert(VT.is128BitVector() && "Expected an SSE value type!");
6932         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6933         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6934         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6935       }
6936
6937       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6938         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6939         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6940         if (VT.is256BitVector()) {
6941           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6942           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6943         } else {
6944           assert(VT.is128BitVector() && "Expected an SSE value type!");
6945           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6946         }
6947         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6948       }
6949     }
6950
6951     // Is it a vector logical left shift?
6952     if (NumElems == 2 && Idx == 1 &&
6953         X86::isZeroNode(Op.getOperand(0)) &&
6954         !X86::isZeroNode(Op.getOperand(1))) {
6955       unsigned NumBits = VT.getSizeInBits();
6956       return getVShift(true, VT,
6957                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6958                                    VT, Op.getOperand(1)),
6959                        NumBits/2, DAG, *this, dl);
6960     }
6961
6962     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6963       return SDValue();
6964
6965     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6966     // is a non-constant being inserted into an element other than the low one,
6967     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6968     // movd/movss) to move this into the low element, then shuffle it into
6969     // place.
6970     if (EVTBits == 32) {
6971       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6972
6973       // If using the new shuffle lowering, just directly insert this.
6974       if (ExperimentalVectorShuffleLowering)
6975         return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6976
6977       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6978       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6979       SmallVector<int, 8> MaskVec;
6980       for (unsigned i = 0; i != NumElems; ++i)
6981         MaskVec.push_back(i == Idx ? 0 : 1);
6982       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6983     }
6984   }
6985
6986   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6987   if (Values.size() == 1) {
6988     if (EVTBits == 32) {
6989       // Instead of a shuffle like this:
6990       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6991       // Check if it's possible to issue this instead.
6992       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6993       unsigned Idx = countTrailingZeros(NonZeros);
6994       SDValue Item = Op.getOperand(Idx);
6995       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6996         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6997     }
6998     return SDValue();
6999   }
7000
7001   // A vector full of immediates; various special cases are already
7002   // handled, so this is best done with a single constant-pool load.
7003   if (IsAllConstants)
7004     return SDValue();
7005
7006   // For AVX-length vectors, see if we can use a vector load to get all of the
7007   // elements, otherwise build the individual 128-bit pieces and use
7008   // shuffles to put them in place.
7009   if (VT.is256BitVector() || VT.is512BitVector()) {
7010     SmallVector<SDValue, 64> V;
7011     for (unsigned i = 0; i != NumElems; ++i)
7012       V.push_back(Op.getOperand(i));
7013
7014     // Check for a build vector of consecutive loads.
7015     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
7016       return LD;
7017     
7018     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
7019
7020     // Build both the lower and upper subvector.
7021     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7022                                 makeArrayRef(&V[0], NumElems/2));
7023     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7024                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
7025
7026     // Recreate the wider vector with the lower and upper part.
7027     if (VT.is256BitVector())
7028       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7029     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7030   }
7031
7032   // Let legalizer expand 2-wide build_vectors.
7033   if (EVTBits == 64) {
7034     if (NumNonZero == 1) {
7035       // One half is zero or undef.
7036       unsigned Idx = countTrailingZeros(NonZeros);
7037       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
7038                                  Op.getOperand(Idx));
7039       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
7040     }
7041     return SDValue();
7042   }
7043
7044   // If element VT is < 32 bits, convert it to inserts into a zero vector.
7045   if (EVTBits == 8 && NumElems == 16) {
7046     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
7047                                         Subtarget, *this);
7048     if (V.getNode()) return V;
7049   }
7050
7051   if (EVTBits == 16 && NumElems == 8) {
7052     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
7053                                       Subtarget, *this);
7054     if (V.getNode()) return V;
7055   }
7056
7057   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
7058   if (EVTBits == 32 && NumElems == 4) {
7059     SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
7060     if (V.getNode())
7061       return V;
7062   }
7063
7064   // If element VT is == 32 bits, turn it into a number of shuffles.
7065   SmallVector<SDValue, 8> V(NumElems);
7066   if (NumElems == 4 && NumZero > 0) {
7067     for (unsigned i = 0; i < 4; ++i) {
7068       bool isZero = !(NonZeros & (1 << i));
7069       if (isZero)
7070         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7071       else
7072         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7073     }
7074
7075     for (unsigned i = 0; i < 2; ++i) {
7076       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7077         default: break;
7078         case 0:
7079           V[i] = V[i*2];  // Must be a zero vector.
7080           break;
7081         case 1:
7082           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7083           break;
7084         case 2:
7085           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7086           break;
7087         case 3:
7088           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7089           break;
7090       }
7091     }
7092
7093     bool Reverse1 = (NonZeros & 0x3) == 2;
7094     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7095     int MaskVec[] = {
7096       Reverse1 ? 1 : 0,
7097       Reverse1 ? 0 : 1,
7098       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7099       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7100     };
7101     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7102   }
7103
7104   if (Values.size() > 1 && VT.is128BitVector()) {
7105     // Check for a build vector of consecutive loads.
7106     for (unsigned i = 0; i < NumElems; ++i)
7107       V[i] = Op.getOperand(i);
7108
7109     // Check for elements which are consecutive loads.
7110     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7111     if (LD.getNode())
7112       return LD;
7113
7114     // Check for a build vector from mostly shuffle plus few inserting.
7115     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7116     if (Sh.getNode())
7117       return Sh;
7118
7119     // For SSE 4.1, use insertps to put the high elements into the low element.
7120     if (getSubtarget()->hasSSE41()) {
7121       SDValue Result;
7122       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7123         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7124       else
7125         Result = DAG.getUNDEF(VT);
7126
7127       for (unsigned i = 1; i < NumElems; ++i) {
7128         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7129         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7130                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7131       }
7132       return Result;
7133     }
7134
7135     // Otherwise, expand into a number of unpckl*, start by extending each of
7136     // our (non-undef) elements to the full vector width with the element in the
7137     // bottom slot of the vector (which generates no code for SSE).
7138     for (unsigned i = 0; i < NumElems; ++i) {
7139       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7140         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7141       else
7142         V[i] = DAG.getUNDEF(VT);
7143     }
7144
7145     // Next, we iteratively mix elements, e.g. for v4f32:
7146     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7147     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7148     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7149     unsigned EltStride = NumElems >> 1;
7150     while (EltStride != 0) {
7151       for (unsigned i = 0; i < EltStride; ++i) {
7152         // If V[i+EltStride] is undef and this is the first round of mixing,
7153         // then it is safe to just drop this shuffle: V[i] is already in the
7154         // right place, the one element (since it's the first round) being
7155         // inserted as undef can be dropped.  This isn't safe for successive
7156         // rounds because they will permute elements within both vectors.
7157         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7158             EltStride == NumElems/2)
7159           continue;
7160
7161         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7162       }
7163       EltStride >>= 1;
7164     }
7165     return V[0];
7166   }
7167   return SDValue();
7168 }
7169
7170 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7171 // to create 256-bit vectors from two other 128-bit ones.
7172 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7173   SDLoc dl(Op);
7174   MVT ResVT = Op.getSimpleValueType();
7175
7176   assert((ResVT.is256BitVector() ||
7177           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7178
7179   SDValue V1 = Op.getOperand(0);
7180   SDValue V2 = Op.getOperand(1);
7181   unsigned NumElems = ResVT.getVectorNumElements();
7182   if(ResVT.is256BitVector())
7183     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7184
7185   if (Op.getNumOperands() == 4) {
7186     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7187                                 ResVT.getVectorNumElements()/2);
7188     SDValue V3 = Op.getOperand(2);
7189     SDValue V4 = Op.getOperand(3);
7190     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7191       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7192   }
7193   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7194 }
7195
7196 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7197   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7198   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7199          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7200           Op.getNumOperands() == 4)));
7201
7202   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7203   // from two other 128-bit ones.
7204
7205   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7206   return LowerAVXCONCAT_VECTORS(Op, DAG);
7207 }
7208
7209
7210 //===----------------------------------------------------------------------===//
7211 // Vector shuffle lowering
7212 //
7213 // This is an experimental code path for lowering vector shuffles on x86. It is
7214 // designed to handle arbitrary vector shuffles and blends, gracefully
7215 // degrading performance as necessary. It works hard to recognize idiomatic
7216 // shuffles and lower them to optimal instruction patterns without leaving
7217 // a framework that allows reasonably efficient handling of all vector shuffle
7218 // patterns.
7219 //===----------------------------------------------------------------------===//
7220
7221 /// \brief Tiny helper function to identify a no-op mask.
7222 ///
7223 /// This is a somewhat boring predicate function. It checks whether the mask
7224 /// array input, which is assumed to be a single-input shuffle mask of the kind
7225 /// used by the X86 shuffle instructions (not a fully general
7226 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7227 /// in-place shuffle are 'no-op's.
7228 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7229   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7230     if (Mask[i] != -1 && Mask[i] != i)
7231       return false;
7232   return true;
7233 }
7234
7235 /// \brief Helper function to classify a mask as a single-input mask.
7236 ///
7237 /// This isn't a generic single-input test because in the vector shuffle
7238 /// lowering we canonicalize single inputs to be the first input operand. This
7239 /// means we can more quickly test for a single input by only checking whether
7240 /// an input from the second operand exists. We also assume that the size of
7241 /// mask corresponds to the size of the input vectors which isn't true in the
7242 /// fully general case.
7243 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7244   for (int M : Mask)
7245     if (M >= (int)Mask.size())
7246       return false;
7247   return true;
7248 }
7249
7250 /// \brief Test whether there are elements crossing 128-bit lanes in this
7251 /// shuffle mask.
7252 ///
7253 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
7254 /// and we routinely test for these.
7255 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
7256   int LaneSize = 128 / VT.getScalarSizeInBits();
7257   int Size = Mask.size();
7258   for (int i = 0; i < Size; ++i)
7259     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
7260       return true;
7261   return false;
7262 }
7263
7264 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
7265 ///
7266 /// This checks a shuffle mask to see if it is performing the same
7267 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
7268 /// that it is also not lane-crossing. It may however involve a blend from the
7269 /// same lane of a second vector.
7270 ///
7271 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
7272 /// non-trivial to compute in the face of undef lanes. The representation is
7273 /// *not* suitable for use with existing 128-bit shuffles as it will contain
7274 /// entries from both V1 and V2 inputs to the wider mask.
7275 static bool
7276 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
7277                                 SmallVectorImpl<int> &RepeatedMask) {
7278   int LaneSize = 128 / VT.getScalarSizeInBits();
7279   RepeatedMask.resize(LaneSize, -1);
7280   int Size = Mask.size();
7281   for (int i = 0; i < Size; ++i) {
7282     if (Mask[i] < 0)
7283       continue;
7284     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
7285       // This entry crosses lanes, so there is no way to model this shuffle.
7286       return false;
7287
7288     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
7289     if (RepeatedMask[i % LaneSize] == -1)
7290       // This is the first non-undef entry in this slot of a 128-bit lane.
7291       RepeatedMask[i % LaneSize] =
7292           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
7293     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
7294       // Found a mismatch with the repeated mask.
7295       return false;
7296   }
7297   return true;
7298 }
7299
7300 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7301 // 2013 will allow us to use it as a non-type template parameter.
7302 namespace {
7303
7304 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7305 ///
7306 /// See its documentation for details.
7307 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7308   if (Mask.size() != Args.size())
7309     return false;
7310   for (int i = 0, e = Mask.size(); i < e; ++i) {
7311     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7312     if (Mask[i] != -1 && Mask[i] != *Args[i])
7313       return false;
7314   }
7315   return true;
7316 }
7317
7318 } // namespace
7319
7320 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7321 /// arguments.
7322 ///
7323 /// This is a fast way to test a shuffle mask against a fixed pattern:
7324 ///
7325 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7326 ///
7327 /// It returns true if the mask is exactly as wide as the argument list, and
7328 /// each element of the mask is either -1 (signifying undef) or the value given
7329 /// in the argument.
7330 static const VariadicFunction1<
7331     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7332
7333 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7334 ///
7335 /// This helper function produces an 8-bit shuffle immediate corresponding to
7336 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7337 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7338 /// example.
7339 ///
7340 /// NB: We rely heavily on "undef" masks preserving the input lane.
7341 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7342                                           SelectionDAG &DAG) {
7343   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7344   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7345   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7346   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7347   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7348
7349   unsigned Imm = 0;
7350   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7351   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7352   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7353   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7354   return DAG.getConstant(Imm, MVT::i8);
7355 }
7356
7357 /// \brief Try to emit a blend instruction for a shuffle.
7358 ///
7359 /// This doesn't do any checks for the availability of instructions for blending
7360 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7361 /// be matched in the backend with the type given. What it does check for is
7362 /// that the shuffle mask is in fact a blend.
7363 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7364                                          SDValue V2, ArrayRef<int> Mask,
7365                                          const X86Subtarget *Subtarget,
7366                                          SelectionDAG &DAG) {
7367
7368   unsigned BlendMask = 0;
7369   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7370     if (Mask[i] >= Size) {
7371       if (Mask[i] != i + Size)
7372         return SDValue(); // Shuffled V2 input!
7373       BlendMask |= 1u << i;
7374       continue;
7375     }
7376     if (Mask[i] >= 0 && Mask[i] != i)
7377       return SDValue(); // Shuffled V1 input!
7378   }
7379   switch (VT.SimpleTy) {
7380   case MVT::v2f64:
7381   case MVT::v4f32:
7382   case MVT::v4f64:
7383   case MVT::v8f32:
7384     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7385                        DAG.getConstant(BlendMask, MVT::i8));
7386
7387   case MVT::v4i64:
7388   case MVT::v8i32:
7389     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7390     // FALLTHROUGH
7391   case MVT::v2i64:
7392   case MVT::v4i32:
7393     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7394     // that instruction.
7395     if (Subtarget->hasAVX2()) {
7396       // Scale the blend by the number of 32-bit dwords per element.
7397       int Scale =  VT.getScalarSizeInBits() / 32;
7398       BlendMask = 0;
7399       for (int i = 0, Size = Mask.size(); i < Size; ++i)
7400         if (Mask[i] >= Size)
7401           for (int j = 0; j < Scale; ++j)
7402             BlendMask |= 1u << (i * Scale + j);
7403
7404       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7405       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
7406       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
7407       return DAG.getNode(ISD::BITCAST, DL, VT,
7408                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7409                                      DAG.getConstant(BlendMask, MVT::i8)));
7410     }
7411     // FALLTHROUGH
7412   case MVT::v8i16: {
7413     // For integer shuffles we need to expand the mask and cast the inputs to
7414     // v8i16s prior to blending.
7415     int Scale = 8 / VT.getVectorNumElements();
7416     BlendMask = 0;
7417     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7418       if (Mask[i] >= Size)
7419         for (int j = 0; j < Scale; ++j)
7420           BlendMask |= 1u << (i * Scale + j);
7421
7422     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
7423     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
7424     return DAG.getNode(ISD::BITCAST, DL, VT,
7425                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7426                                    DAG.getConstant(BlendMask, MVT::i8)));
7427   }
7428
7429   case MVT::v16i16: {
7430     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7431     SmallVector<int, 8> RepeatedMask;
7432     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7433       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7434       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7435       BlendMask = 0;
7436       for (int i = 0; i < 8; ++i)
7437         if (RepeatedMask[i] >= 16)
7438           BlendMask |= 1u << i;
7439       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7440                          DAG.getConstant(BlendMask, MVT::i8));
7441     }
7442   }
7443     // FALLTHROUGH
7444   case MVT::v32i8: {
7445     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7446     // Scale the blend by the number of bytes per element.
7447     int Scale =  VT.getScalarSizeInBits() / 8;
7448     assert(Mask.size() * Scale == 32 && "Not a 256-bit vector!");
7449
7450     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7451     // mix of LLVM's code generator and the x86 backend. We tell the code
7452     // generator that boolean values in the elements of an x86 vector register
7453     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7454     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7455     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7456     // of the element (the remaining are ignored) and 0 in that high bit would
7457     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7458     // the LLVM model for boolean values in vector elements gets the relevant
7459     // bit set, it is set backwards and over constrained relative to x86's
7460     // actual model.
7461     SDValue VSELECTMask[32];
7462     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7463       for (int j = 0; j < Scale; ++j)
7464         VSELECTMask[Scale * i + j] =
7465             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7466                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8);
7467
7468     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1);
7469     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V2);
7470     return DAG.getNode(
7471         ISD::BITCAST, DL, VT,
7472         DAG.getNode(ISD::VSELECT, DL, MVT::v32i8,
7473                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, VSELECTMask),
7474                     V1, V2));
7475   }
7476
7477   default:
7478     llvm_unreachable("Not a supported integer vector type!");
7479   }
7480 }
7481
7482 /// \brief Generic routine to lower a shuffle and blend as a decomposed set of
7483 /// unblended shuffles followed by an unshuffled blend.
7484 ///
7485 /// This matches the extremely common pattern for handling combined
7486 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7487 /// operations.
7488 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7489                                                           SDValue V1,
7490                                                           SDValue V2,
7491                                                           ArrayRef<int> Mask,
7492                                                           SelectionDAG &DAG) {
7493   // Shuffle the input elements into the desired positions in V1 and V2 and
7494   // blend them together.
7495   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7496   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7497   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7498   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7499     if (Mask[i] >= 0 && Mask[i] < Size) {
7500       V1Mask[i] = Mask[i];
7501       BlendMask[i] = i;
7502     } else if (Mask[i] >= Size) {
7503       V2Mask[i] = Mask[i] - Size;
7504       BlendMask[i] = i + Size;
7505     }
7506
7507   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7508   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7509   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7510 }
7511
7512 /// \brief Try to lower a vector shuffle as a byte rotation.
7513 ///
7514 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7515 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7516 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7517 /// try to generically lower a vector shuffle through such an pattern. It
7518 /// does not check for the profitability of lowering either as PALIGNR or
7519 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7520 /// This matches shuffle vectors that look like:
7521 ///
7522 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7523 ///
7524 /// Essentially it concatenates V1 and V2, shifts right by some number of
7525 /// elements, and takes the low elements as the result. Note that while this is
7526 /// specified as a *right shift* because x86 is little-endian, it is a *left
7527 /// rotate* of the vector lanes.
7528 ///
7529 /// Note that this only handles 128-bit vector widths currently.
7530 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7531                                               SDValue V2,
7532                                               ArrayRef<int> Mask,
7533                                               const X86Subtarget *Subtarget,
7534                                               SelectionDAG &DAG) {
7535   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7536
7537   // We need to detect various ways of spelling a rotation:
7538   //   [11, 12, 13, 14, 15,  0,  1,  2]
7539   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7540   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7541   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7542   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7543   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7544   int Rotation = 0;
7545   SDValue Lo, Hi;
7546   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7547     if (Mask[i] == -1)
7548       continue;
7549     assert(Mask[i] >= 0 && "Only -1 is a valid negative mask element!");
7550
7551     // Based on the mod-Size value of this mask element determine where
7552     // a rotated vector would have started.
7553     int StartIdx = i - (Mask[i] % Size);
7554     if (StartIdx == 0)
7555       // The identity rotation isn't interesting, stop.
7556       return SDValue();
7557
7558     // If we found the tail of a vector the rotation must be the missing
7559     // front. If we found the head of a vector, it must be how much of the head.
7560     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
7561
7562     if (Rotation == 0)
7563       Rotation = CandidateRotation;
7564     else if (Rotation != CandidateRotation)
7565       // The rotations don't match, so we can't match this mask.
7566       return SDValue();
7567
7568     // Compute which value this mask is pointing at.
7569     SDValue MaskV = Mask[i] < Size ? V1 : V2;
7570
7571     // Compute which of the two target values this index should be assigned to.
7572     // This reflects whether the high elements are remaining or the low elements
7573     // are remaining.
7574     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7575
7576     // Either set up this value if we've not encountered it before, or check
7577     // that it remains consistent.
7578     if (!TargetV)
7579       TargetV = MaskV;
7580     else if (TargetV != MaskV)
7581       // This may be a rotation, but it pulls from the inputs in some
7582       // unsupported interleaving.
7583       return SDValue();
7584   }
7585
7586   // Check that we successfully analyzed the mask, and normalize the results.
7587   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7588   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7589   if (!Lo)
7590     Lo = Hi;
7591   else if (!Hi)
7592     Hi = Lo;
7593
7594   assert(VT.getSizeInBits() == 128 &&
7595          "Rotate-based lowering only supports 128-bit lowering!");
7596   assert(Mask.size() <= 16 &&
7597          "Can shuffle at most 16 bytes in a 128-bit vector!");
7598
7599   // The actual rotate instruction rotates bytes, so we need to scale the
7600   // rotation based on how many bytes are in the vector.
7601   int Scale = 16 / Mask.size();
7602
7603   // SSSE3 targets can use the palignr instruction
7604   if (Subtarget->hasSSSE3()) {
7605     // Cast the inputs to v16i8 to match PALIGNR.
7606     Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Lo);
7607     Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Hi);
7608
7609     return DAG.getNode(ISD::BITCAST, DL, VT,
7610                        DAG.getNode(X86ISD::PALIGNR, DL, MVT::v16i8, Hi, Lo,
7611                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
7612   }
7613
7614   // Default SSE2 implementation
7615   int LoByteShift = 16 - Rotation * Scale;
7616   int HiByteShift = Rotation * Scale;
7617
7618   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7619   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
7620   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
7621
7622   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7623                                 DAG.getConstant(8 * LoByteShift, MVT::i8));
7624   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7625                                 DAG.getConstant(8 * HiByteShift, MVT::i8));
7626   return DAG.getNode(ISD::BITCAST, DL, VT,
7627                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7628 }
7629
7630 /// \brief Compute whether each element of a shuffle is zeroable.
7631 ///
7632 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7633 /// Either it is an undef element in the shuffle mask, the element of the input
7634 /// referenced is undef, or the element of the input referenced is known to be
7635 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7636 /// as many lanes with this technique as possible to simplify the remaining
7637 /// shuffle.
7638 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
7639                                                      SDValue V1, SDValue V2) {
7640   SmallBitVector Zeroable(Mask.size(), false);
7641
7642   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7643   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7644
7645   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7646     int M = Mask[i];
7647     // Handle the easy cases.
7648     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7649       Zeroable[i] = true;
7650       continue;
7651     }
7652
7653     // If this is an index into a build_vector node, dig out the input value and
7654     // use it.
7655     SDValue V = M < Size ? V1 : V2;
7656     if (V.getOpcode() != ISD::BUILD_VECTOR)
7657       continue;
7658
7659     SDValue Input = V.getOperand(M % Size);
7660     // The UNDEF opcode check really should be dead code here, but not quite
7661     // worth asserting on (it isn't invalid, just unexpected).
7662     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
7663       Zeroable[i] = true;
7664   }
7665
7666   return Zeroable;
7667 }
7668
7669 /// \brief Try to lower a vector shuffle as a byte shift (shifts in zeros).
7670 ///
7671 /// Attempts to match a shuffle mask against the PSRLDQ and PSLLDQ SSE2
7672 /// byte-shift instructions. The mask must consist of a shifted sequential
7673 /// shuffle from one of the input vectors and zeroable elements for the
7674 /// remaining 'shifted in' elements.
7675 ///
7676 /// Note that this only handles 128-bit vector widths currently.
7677 static SDValue lowerVectorShuffleAsByteShift(SDLoc DL, MVT VT, SDValue V1,
7678                                              SDValue V2, ArrayRef<int> Mask,
7679                                              SelectionDAG &DAG) {
7680   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7681
7682   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7683
7684   int Size = Mask.size();
7685   int Scale = 16 / Size;
7686
7687   auto isSequential = [](int Base, int StartIndex, int EndIndex, int MaskOffset,
7688                          ArrayRef<int> Mask) {
7689     for (int i = StartIndex; i < EndIndex; i++) {
7690       if (Mask[i] < 0)
7691         continue;
7692       if (i + Base != Mask[i] - MaskOffset)
7693         return false;
7694     }
7695     return true;
7696   };
7697
7698   for (int Shift = 1; Shift < Size; Shift++) {
7699     int ByteShift = Shift * Scale;
7700
7701     // PSRLDQ : (little-endian) right byte shift
7702     // [ 5,  6,  7, zz, zz, zz, zz, zz]
7703     // [ -1, 5,  6,  7, zz, zz, zz, zz]
7704     // [  1, 2, -1, -1, -1, -1, zz, zz]
7705     bool ZeroableRight = true;
7706     for (int i = Size - Shift; i < Size; i++) {
7707       ZeroableRight &= Zeroable[i];
7708     }
7709
7710     if (ZeroableRight) {
7711       bool ValidShiftRight1 = isSequential(Shift, 0, Size - Shift, 0, Mask);
7712       bool ValidShiftRight2 = isSequential(Shift, 0, Size - Shift, Size, Mask);
7713
7714       if (ValidShiftRight1 || ValidShiftRight2) {
7715         // Cast the inputs to v2i64 to match PSRLDQ.
7716         SDValue &TargetV = ValidShiftRight1 ? V1 : V2;
7717         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7718         SDValue Shifted = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, V,
7719                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7720         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7721       }
7722     }
7723
7724     // PSLLDQ : (little-endian) left byte shift
7725     // [ zz,  0,  1,  2,  3,  4,  5,  6]
7726     // [ zz, zz, -1, -1,  2,  3,  4, -1]
7727     // [ zz, zz, zz, zz, zz, zz, -1,  1]
7728     bool ZeroableLeft = true;
7729     for (int i = 0; i < Shift; i++) {
7730       ZeroableLeft &= Zeroable[i];
7731     }
7732
7733     if (ZeroableLeft) {
7734       bool ValidShiftLeft1 = isSequential(-Shift, Shift, Size, 0, Mask);
7735       bool ValidShiftLeft2 = isSequential(-Shift, Shift, Size, Size, Mask);
7736
7737       if (ValidShiftLeft1 || ValidShiftLeft2) {
7738         // Cast the inputs to v2i64 to match PSLLDQ.
7739         SDValue &TargetV = ValidShiftLeft1 ? V1 : V2;
7740         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7741         SDValue Shifted = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, V,
7742                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7743         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7744       }
7745     }
7746   }
7747
7748   return SDValue();
7749 }
7750
7751 /// \brief Lower a vector shuffle as a zero or any extension.
7752 ///
7753 /// Given a specific number of elements, element bit width, and extension
7754 /// stride, produce either a zero or any extension based on the available
7755 /// features of the subtarget.
7756 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7757     SDLoc DL, MVT VT, int NumElements, int Scale, bool AnyExt, SDValue InputV,
7758     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7759   assert(Scale > 1 && "Need a scale to extend.");
7760   int EltBits = VT.getSizeInBits() / NumElements;
7761   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7762          "Only 8, 16, and 32 bit elements can be extended.");
7763   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7764
7765   // Found a valid zext mask! Try various lowering strategies based on the
7766   // input type and available ISA extensions.
7767   if (Subtarget->hasSSE41()) {
7768     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7769     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7770                                  NumElements / Scale);
7771     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7772     return DAG.getNode(ISD::BITCAST, DL, VT,
7773                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7774   }
7775
7776   // For any extends we can cheat for larger element sizes and use shuffle
7777   // instructions that can fold with a load and/or copy.
7778   if (AnyExt && EltBits == 32) {
7779     int PSHUFDMask[4] = {0, -1, 1, -1};
7780     return DAG.getNode(
7781         ISD::BITCAST, DL, VT,
7782         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7783                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7784                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7785   }
7786   if (AnyExt && EltBits == 16 && Scale > 2) {
7787     int PSHUFDMask[4] = {0, -1, 0, -1};
7788     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7789                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7790                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
7791     int PSHUFHWMask[4] = {1, -1, -1, -1};
7792     return DAG.getNode(
7793         ISD::BITCAST, DL, VT,
7794         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7795                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
7796                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
7797   }
7798
7799   // If this would require more than 2 unpack instructions to expand, use
7800   // pshufb when available. We can only use more than 2 unpack instructions
7801   // when zero extending i8 elements which also makes it easier to use pshufb.
7802   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7803     assert(NumElements == 16 && "Unexpected byte vector width!");
7804     SDValue PSHUFBMask[16];
7805     for (int i = 0; i < 16; ++i)
7806       PSHUFBMask[i] =
7807           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
7808     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
7809     return DAG.getNode(ISD::BITCAST, DL, VT,
7810                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7811                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
7812                                                MVT::v16i8, PSHUFBMask)));
7813   }
7814
7815   // Otherwise emit a sequence of unpacks.
7816   do {
7817     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7818     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7819                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7820     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7821     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7822     Scale /= 2;
7823     EltBits *= 2;
7824     NumElements /= 2;
7825   } while (Scale > 1);
7826   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
7827 }
7828
7829 /// \brief Try to lower a vector shuffle as a zero extension on any micrarch.
7830 ///
7831 /// This routine will try to do everything in its power to cleverly lower
7832 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7833 /// check for the profitability of this lowering,  it tries to aggressively
7834 /// match this pattern. It will use all of the micro-architectural details it
7835 /// can to emit an efficient lowering. It handles both blends with all-zero
7836 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7837 /// masking out later).
7838 ///
7839 /// The reason we have dedicated lowering for zext-style shuffles is that they
7840 /// are both incredibly common and often quite performance sensitive.
7841 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7842     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7843     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7844   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7845
7846   int Bits = VT.getSizeInBits();
7847   int NumElements = Mask.size();
7848
7849   // Define a helper function to check a particular ext-scale and lower to it if
7850   // valid.
7851   auto Lower = [&](int Scale) -> SDValue {
7852     SDValue InputV;
7853     bool AnyExt = true;
7854     for (int i = 0; i < NumElements; ++i) {
7855       if (Mask[i] == -1)
7856         continue; // Valid anywhere but doesn't tell us anything.
7857       if (i % Scale != 0) {
7858         // Each of the extend elements needs to be zeroable.
7859         if (!Zeroable[i])
7860           return SDValue();
7861
7862         // We no lorger are in the anyext case.
7863         AnyExt = false;
7864         continue;
7865       }
7866
7867       // Each of the base elements needs to be consecutive indices into the
7868       // same input vector.
7869       SDValue V = Mask[i] < NumElements ? V1 : V2;
7870       if (!InputV)
7871         InputV = V;
7872       else if (InputV != V)
7873         return SDValue(); // Flip-flopping inputs.
7874
7875       if (Mask[i] % NumElements != i / Scale)
7876         return SDValue(); // Non-consecutive strided elemenst.
7877     }
7878
7879     // If we fail to find an input, we have a zero-shuffle which should always
7880     // have already been handled.
7881     // FIXME: Maybe handle this here in case during blending we end up with one?
7882     if (!InputV)
7883       return SDValue();
7884
7885     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7886         DL, VT, NumElements, Scale, AnyExt, InputV, Subtarget, DAG);
7887   };
7888
7889   // The widest scale possible for extending is to a 64-bit integer.
7890   assert(Bits % 64 == 0 &&
7891          "The number of bits in a vector must be divisible by 64 on x86!");
7892   int NumExtElements = Bits / 64;
7893
7894   // Each iteration, try extending the elements half as much, but into twice as
7895   // many elements.
7896   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7897     assert(NumElements % NumExtElements == 0 &&
7898            "The input vector size must be divisble by the extended size.");
7899     if (SDValue V = Lower(NumElements / NumExtElements))
7900       return V;
7901   }
7902
7903   // No viable ext lowering found.
7904   return SDValue();
7905 }
7906
7907 /// \brief Try to get a scalar value for a specific element of a vector.
7908 ///
7909 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7910 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7911                                               SelectionDAG &DAG) {
7912   MVT VT = V.getSimpleValueType();
7913   MVT EltVT = VT.getVectorElementType();
7914   while (V.getOpcode() == ISD::BITCAST)
7915     V = V.getOperand(0);
7916   // If the bitcasts shift the element size, we can't extract an equivalent
7917   // element from it.
7918   MVT NewVT = V.getSimpleValueType();
7919   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7920     return SDValue();
7921
7922   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7923       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
7924     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
7925
7926   return SDValue();
7927 }
7928
7929 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7930 ///
7931 /// This is particularly important because the set of instructions varies
7932 /// significantly based on whether the operand is a load or not.
7933 static bool isShuffleFoldableLoad(SDValue V) {
7934   while (V.getOpcode() == ISD::BITCAST)
7935     V = V.getOperand(0);
7936
7937   return ISD::isNON_EXTLoad(V.getNode());
7938 }
7939
7940 /// \brief Try to lower insertion of a single element into a zero vector.
7941 ///
7942 /// This is a common pattern that we have especially efficient patterns to lower
7943 /// across all subtarget feature sets.
7944 static SDValue lowerVectorShuffleAsElementInsertion(
7945     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7946     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7947   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7948   MVT ExtVT = VT;
7949   MVT EltVT = VT.getVectorElementType();
7950
7951   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7952                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7953                 Mask.begin();
7954   bool IsV1Zeroable = true;
7955   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7956     if (i != V2Index && !Zeroable[i]) {
7957       IsV1Zeroable = false;
7958       break;
7959     }
7960
7961   // Check for a single input from a SCALAR_TO_VECTOR node.
7962   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7963   // all the smarts here sunk into that routine. However, the current
7964   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7965   // vector shuffle lowering is dead.
7966   if (SDValue V2S = getScalarValueForVectorElement(
7967           V2, Mask[V2Index] - Mask.size(), DAG)) {
7968     // We need to zext the scalar if it is smaller than an i32.
7969     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7970     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7971       // Using zext to expand a narrow element won't work for non-zero
7972       // insertions.
7973       if (!IsV1Zeroable)
7974         return SDValue();
7975
7976       // Zero-extend directly to i32.
7977       ExtVT = MVT::v4i32;
7978       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7979     }
7980     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7981   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7982              EltVT == MVT::i16) {
7983     // Either not inserting from the low element of the input or the input
7984     // element size is too small to use VZEXT_MOVL to clear the high bits.
7985     return SDValue();
7986   }
7987
7988   if (!IsV1Zeroable) {
7989     // If V1 can't be treated as a zero vector we have fewer options to lower
7990     // this. We can't support integer vectors or non-zero targets cheaply, and
7991     // the V1 elements can't be permuted in any way.
7992     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7993     if (!VT.isFloatingPoint() || V2Index != 0)
7994       return SDValue();
7995     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7996     V1Mask[V2Index] = -1;
7997     if (!isNoopShuffleMask(V1Mask))
7998       return SDValue();
7999     // This is essentially a special case blend operation, but if we have
8000     // general purpose blend operations, they are always faster. Bail and let
8001     // the rest of the lowering handle these as blends.
8002     if (Subtarget->hasSSE41())
8003       return SDValue();
8004
8005     // Otherwise, use MOVSD or MOVSS.
8006     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8007            "Only two types of floating point element types to handle!");
8008     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8009                        ExtVT, V1, V2);
8010   }
8011
8012   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8013   if (ExtVT != VT)
8014     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8015
8016   if (V2Index != 0) {
8017     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8018     // the desired position. Otherwise it is more efficient to do a vector
8019     // shift left. We know that we can do a vector shift left because all
8020     // the inputs are zero.
8021     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8022       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8023       V2Shuffle[V2Index] = 0;
8024       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8025     } else {
8026       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
8027       V2 = DAG.getNode(
8028           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8029           DAG.getConstant(
8030               V2Index * EltVT.getSizeInBits(),
8031               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
8032       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8033     }
8034   }
8035   return V2;
8036 }
8037
8038 /// \brief Try to lower broadcast of a single element.
8039 ///
8040 /// For convenience, this code also bundles all of the subtarget feature set
8041 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8042 /// a convenient way to factor it out.
8043 static SDValue lowerVectorShuffleAsBroadcast(MVT VT, SDLoc DL, SDValue V,
8044                                              ArrayRef<int> Mask,
8045                                              const X86Subtarget *Subtarget,
8046                                              SelectionDAG &DAG) {
8047   if (!Subtarget->hasAVX())
8048     return SDValue();
8049   if (VT.isInteger() && !Subtarget->hasAVX2())
8050     return SDValue();
8051
8052   // Check that the mask is a broadcast.
8053   int BroadcastIdx = -1;
8054   for (int M : Mask)
8055     if (M >= 0 && BroadcastIdx == -1)
8056       BroadcastIdx = M;
8057     else if (M >= 0 && M != BroadcastIdx)
8058       return SDValue();
8059
8060   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8061                                             "a sorted mask where the broadcast "
8062                                             "comes from V1.");
8063
8064   // Go up the chain of (vector) values to try and find a scalar load that
8065   // we can combine with the broadcast.
8066   for (;;) {
8067     switch (V.getOpcode()) {
8068     case ISD::CONCAT_VECTORS: {
8069       int OperandSize = Mask.size() / V.getNumOperands();
8070       V = V.getOperand(BroadcastIdx / OperandSize);
8071       BroadcastIdx %= OperandSize;
8072       continue;
8073     }
8074
8075     case ISD::INSERT_SUBVECTOR: {
8076       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8077       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8078       if (!ConstantIdx)
8079         break;
8080
8081       int BeginIdx = (int)ConstantIdx->getZExtValue();
8082       int EndIdx =
8083           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
8084       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8085         BroadcastIdx -= BeginIdx;
8086         V = VInner;
8087       } else {
8088         V = VOuter;
8089       }
8090       continue;
8091     }
8092     }
8093     break;
8094   }
8095
8096   // Check if this is a broadcast of a scalar. We special case lowering
8097   // for scalars so that we can more effectively fold with loads.
8098   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8099       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8100     V = V.getOperand(BroadcastIdx);
8101
8102     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
8103     // AVX2.
8104     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8105       return SDValue();
8106   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8107     // We can't broadcast from a vector register w/o AVX2, and we can only
8108     // broadcast from the zero-element of a vector register.
8109     return SDValue();
8110   }
8111
8112   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8113 }
8114
8115 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8116 ///
8117 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8118 /// support for floating point shuffles but not integer shuffles. These
8119 /// instructions will incur a domain crossing penalty on some chips though so
8120 /// it is better to avoid lowering through this for integer vectors where
8121 /// possible.
8122 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8123                                        const X86Subtarget *Subtarget,
8124                                        SelectionDAG &DAG) {
8125   SDLoc DL(Op);
8126   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8127   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8128   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8129   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8130   ArrayRef<int> Mask = SVOp->getMask();
8131   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8132
8133   if (isSingleInputShuffleMask(Mask)) {
8134     // Straight shuffle of a single input vector. Simulate this by using the
8135     // single input as both of the "inputs" to this instruction..
8136     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8137
8138     if (Subtarget->hasAVX()) {
8139       // If we have AVX, we can use VPERMILPS which will allow folding a load
8140       // into the shuffle.
8141       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8142                          DAG.getConstant(SHUFPDMask, MVT::i8));
8143     }
8144
8145     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
8146                        DAG.getConstant(SHUFPDMask, MVT::i8));
8147   }
8148   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8149   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8150
8151   // Use dedicated unpack instructions for masks that match their pattern.
8152   if (isShuffleEquivalent(Mask, 0, 2))
8153     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8154   if (isShuffleEquivalent(Mask, 1, 3))
8155     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8156
8157   // If we have a single input, insert that into V1 if we can do so cheaply.
8158   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8159     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8160             MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
8161       return Insertion;
8162     // Try inverting the insertion since for v2 masks it is easy to do and we
8163     // can't reliably sort the mask one way or the other.
8164     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8165                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8166     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8167             MVT::v2f64, DL, V2, V1, InverseMask, Subtarget, DAG))
8168       return Insertion;
8169   }
8170
8171   // Try to use one of the special instruction patterns to handle two common
8172   // blend patterns if a zero-blend above didn't work.
8173   if (isShuffleEquivalent(Mask, 0, 3) || isShuffleEquivalent(Mask, 1, 3))
8174     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8175       // We can either use a special instruction to load over the low double or
8176       // to move just the low double.
8177       return DAG.getNode(
8178           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8179           DL, MVT::v2f64, V2,
8180           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8181
8182   if (Subtarget->hasSSE41())
8183     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8184                                                   Subtarget, DAG))
8185       return Blend;
8186
8187   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8188   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
8189                      DAG.getConstant(SHUFPDMask, MVT::i8));
8190 }
8191
8192 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8193 ///
8194 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8195 /// the integer unit to minimize domain crossing penalties. However, for blends
8196 /// it falls back to the floating point shuffle operation with appropriate bit
8197 /// casting.
8198 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8199                                        const X86Subtarget *Subtarget,
8200                                        SelectionDAG &DAG) {
8201   SDLoc DL(Op);
8202   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8203   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8204   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8205   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8206   ArrayRef<int> Mask = SVOp->getMask();
8207   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8208
8209   if (isSingleInputShuffleMask(Mask)) {
8210     // Check for being able to broadcast a single element.
8211     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v2i64, DL, V1,
8212                                                           Mask, Subtarget, DAG))
8213       return Broadcast;
8214
8215     // Straight shuffle of a single input vector. For everything from SSE2
8216     // onward this has a single fast instruction with no scary immediates.
8217     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8218     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
8219     int WidenedMask[4] = {
8220         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8221         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8222     return DAG.getNode(
8223         ISD::BITCAST, DL, MVT::v2i64,
8224         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
8225                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
8226   }
8227
8228   // Try to use byte shift instructions.
8229   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8230           DL, MVT::v2i64, V1, V2, Mask, DAG))
8231     return Shift;
8232
8233   // If we have a single input from V2 insert that into V1 if we can do so
8234   // cheaply.
8235   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8236     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8237             MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
8238       return Insertion;
8239     // Try inverting the insertion since for v2 masks it is easy to do and we
8240     // can't reliably sort the mask one way or the other.
8241     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8242                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8243     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8244             MVT::v2i64, DL, V2, V1, InverseMask, Subtarget, DAG))
8245       return Insertion;
8246   }
8247
8248   // Use dedicated unpack instructions for masks that match their pattern.
8249   if (isShuffleEquivalent(Mask, 0, 2))
8250     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8251   if (isShuffleEquivalent(Mask, 1, 3))
8252     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8253
8254   if (Subtarget->hasSSE41())
8255     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8256                                                   Subtarget, DAG))
8257       return Blend;
8258
8259   // Try to use byte rotation instructions.
8260   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8261   if (Subtarget->hasSSSE3())
8262     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8263             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8264       return Rotate;
8265
8266   // We implement this with SHUFPD which is pretty lame because it will likely
8267   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8268   // However, all the alternatives are still more cycles and newer chips don't
8269   // have this problem. It would be really nice if x86 had better shuffles here.
8270   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
8271   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
8272   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
8273                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8274 }
8275
8276 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8277 ///
8278 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8279 /// It makes no assumptions about whether this is the *best* lowering, it simply
8280 /// uses it.
8281 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8282                                             ArrayRef<int> Mask, SDValue V1,
8283                                             SDValue V2, SelectionDAG &DAG) {
8284   SDValue LowV = V1, HighV = V2;
8285   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8286
8287   int NumV2Elements =
8288       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8289
8290   if (NumV2Elements == 1) {
8291     int V2Index =
8292         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8293         Mask.begin();
8294
8295     // Compute the index adjacent to V2Index and in the same half by toggling
8296     // the low bit.
8297     int V2AdjIndex = V2Index ^ 1;
8298
8299     if (Mask[V2AdjIndex] == -1) {
8300       // Handles all the cases where we have a single V2 element and an undef.
8301       // This will only ever happen in the high lanes because we commute the
8302       // vector otherwise.
8303       if (V2Index < 2)
8304         std::swap(LowV, HighV);
8305       NewMask[V2Index] -= 4;
8306     } else {
8307       // Handle the case where the V2 element ends up adjacent to a V1 element.
8308       // To make this work, blend them together as the first step.
8309       int V1Index = V2AdjIndex;
8310       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8311       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8312                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8313
8314       // Now proceed to reconstruct the final blend as we have the necessary
8315       // high or low half formed.
8316       if (V2Index < 2) {
8317         LowV = V2;
8318         HighV = V1;
8319       } else {
8320         HighV = V2;
8321       }
8322       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8323       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8324     }
8325   } else if (NumV2Elements == 2) {
8326     if (Mask[0] < 4 && Mask[1] < 4) {
8327       // Handle the easy case where we have V1 in the low lanes and V2 in the
8328       // high lanes.
8329       NewMask[2] -= 4;
8330       NewMask[3] -= 4;
8331     } else if (Mask[2] < 4 && Mask[3] < 4) {
8332       // We also handle the reversed case because this utility may get called
8333       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8334       // arrange things in the right direction.
8335       NewMask[0] -= 4;
8336       NewMask[1] -= 4;
8337       HighV = V1;
8338       LowV = V2;
8339     } else {
8340       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8341       // trying to place elements directly, just blend them and set up the final
8342       // shuffle to place them.
8343
8344       // The first two blend mask elements are for V1, the second two are for
8345       // V2.
8346       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8347                           Mask[2] < 4 ? Mask[2] : Mask[3],
8348                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8349                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8350       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8351                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8352
8353       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8354       // a blend.
8355       LowV = HighV = V1;
8356       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8357       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8358       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8359       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8360     }
8361   }
8362   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8363                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
8364 }
8365
8366 /// \brief Lower 4-lane 32-bit floating point shuffles.
8367 ///
8368 /// Uses instructions exclusively from the floating point unit to minimize
8369 /// domain crossing penalties, as these are sufficient to implement all v4f32
8370 /// shuffles.
8371 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8372                                        const X86Subtarget *Subtarget,
8373                                        SelectionDAG &DAG) {
8374   SDLoc DL(Op);
8375   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8376   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8377   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8378   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8379   ArrayRef<int> Mask = SVOp->getMask();
8380   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8381
8382   int NumV2Elements =
8383       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8384
8385   if (NumV2Elements == 0) {
8386     // Check for being able to broadcast a single element.
8387     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f32, DL, V1,
8388                                                           Mask, Subtarget, DAG))
8389       return Broadcast;
8390
8391     if (Subtarget->hasAVX()) {
8392       // If we have AVX, we can use VPERMILPS which will allow folding a load
8393       // into the shuffle.
8394       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8395                          getV4X86ShuffleImm8ForMask(Mask, DAG));
8396     }
8397
8398     // Otherwise, use a straight shuffle of a single input vector. We pass the
8399     // input vector to both operands to simulate this with a SHUFPS.
8400     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8401                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8402   }
8403
8404   // Use dedicated unpack instructions for masks that match their pattern.
8405   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8406     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8407   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8408     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8409
8410   // There are special ways we can lower some single-element blends. However, we
8411   // have custom ways we can lower more complex single-element blends below that
8412   // we defer to if both this and BLENDPS fail to match, so restrict this to
8413   // when the V2 input is targeting element 0 of the mask -- that is the fast
8414   // case here.
8415   if (NumV2Elements == 1 && Mask[0] >= 4)
8416     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
8417                                                          Mask, Subtarget, DAG))
8418       return V;
8419
8420   if (Subtarget->hasSSE41())
8421     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8422                                                   Subtarget, DAG))
8423       return Blend;
8424
8425   // Check for whether we can use INSERTPS to perform the blend. We only use
8426   // INSERTPS when the V1 elements are already in the correct locations
8427   // because otherwise we can just always use two SHUFPS instructions which
8428   // are much smaller to encode than a SHUFPS and an INSERTPS.
8429   if (NumV2Elements == 1 && Subtarget->hasSSE41()) {
8430     int V2Index =
8431         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8432         Mask.begin();
8433
8434     // When using INSERTPS we can zero any lane of the destination. Collect
8435     // the zero inputs into a mask and drop them from the lanes of V1 which
8436     // actually need to be present as inputs to the INSERTPS.
8437     SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8438
8439     // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
8440     bool InsertNeedsShuffle = false;
8441     unsigned ZMask = 0;
8442     for (int i = 0; i < 4; ++i)
8443       if (i != V2Index) {
8444         if (Zeroable[i]) {
8445           ZMask |= 1 << i;
8446         } else if (Mask[i] != i) {
8447           InsertNeedsShuffle = true;
8448           break;
8449         }
8450       }
8451
8452     // We don't want to use INSERTPS or other insertion techniques if it will
8453     // require shuffling anyways.
8454     if (!InsertNeedsShuffle) {
8455       // If all of V1 is zeroable, replace it with undef.
8456       if ((ZMask | 1 << V2Index) == 0xF)
8457         V1 = DAG.getUNDEF(MVT::v4f32);
8458
8459       unsigned InsertPSMask = (Mask[V2Index] - 4) << 6 | V2Index << 4 | ZMask;
8460       assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8461
8462       // Insert the V2 element into the desired position.
8463       return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8464                          DAG.getConstant(InsertPSMask, MVT::i8));
8465     }
8466   }
8467
8468   // Otherwise fall back to a SHUFPS lowering strategy.
8469   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8470 }
8471
8472 /// \brief Lower 4-lane i32 vector shuffles.
8473 ///
8474 /// We try to handle these with integer-domain shuffles where we can, but for
8475 /// blends we use the floating point domain blend instructions.
8476 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8477                                        const X86Subtarget *Subtarget,
8478                                        SelectionDAG &DAG) {
8479   SDLoc DL(Op);
8480   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8481   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8482   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8483   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8484   ArrayRef<int> Mask = SVOp->getMask();
8485   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8486
8487   // Whenever we can lower this as a zext, that instruction is strictly faster
8488   // than any alternative. It also allows us to fold memory operands into the
8489   // shuffle in many cases.
8490   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8491                                                          Mask, Subtarget, DAG))
8492     return ZExt;
8493
8494   int NumV2Elements =
8495       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8496
8497   if (NumV2Elements == 0) {
8498     // Check for being able to broadcast a single element.
8499     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i32, DL, V1,
8500                                                           Mask, Subtarget, DAG))
8501       return Broadcast;
8502
8503     // Straight shuffle of a single input vector. For everything from SSE2
8504     // onward this has a single fast instruction with no scary immediates.
8505     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8506     // but we aren't actually going to use the UNPCK instruction because doing
8507     // so prevents folding a load into this instruction or making a copy.
8508     const int UnpackLoMask[] = {0, 0, 1, 1};
8509     const int UnpackHiMask[] = {2, 2, 3, 3};
8510     if (isShuffleEquivalent(Mask, 0, 0, 1, 1))
8511       Mask = UnpackLoMask;
8512     else if (isShuffleEquivalent(Mask, 2, 2, 3, 3))
8513       Mask = UnpackHiMask;
8514
8515     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8516                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8517   }
8518
8519   // Try to use byte shift instructions.
8520   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8521           DL, MVT::v4i32, V1, V2, Mask, DAG))
8522     return Shift;
8523
8524   // There are special ways we can lower some single-element blends.
8525   if (NumV2Elements == 1)
8526     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
8527                                                          Mask, Subtarget, DAG))
8528       return V;
8529
8530   // Use dedicated unpack instructions for masks that match their pattern.
8531   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8532     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8533   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8534     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8535
8536   if (Subtarget->hasSSE41())
8537     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8538                                                   Subtarget, DAG))
8539       return Blend;
8540
8541   // Try to use byte rotation instructions.
8542   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8543   if (Subtarget->hasSSSE3())
8544     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8545             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8546       return Rotate;
8547
8548   // We implement this with SHUFPS because it can blend from two vectors.
8549   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8550   // up the inputs, bypassing domain shift penalties that we would encur if we
8551   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8552   // relevant.
8553   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
8554                      DAG.getVectorShuffle(
8555                          MVT::v4f32, DL,
8556                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
8557                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
8558 }
8559
8560 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8561 /// shuffle lowering, and the most complex part.
8562 ///
8563 /// The lowering strategy is to try to form pairs of input lanes which are
8564 /// targeted at the same half of the final vector, and then use a dword shuffle
8565 /// to place them onto the right half, and finally unpack the paired lanes into
8566 /// their final position.
8567 ///
8568 /// The exact breakdown of how to form these dword pairs and align them on the
8569 /// correct sides is really tricky. See the comments within the function for
8570 /// more of the details.
8571 static SDValue lowerV8I16SingleInputVectorShuffle(
8572     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
8573     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8574   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8575   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8576   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8577
8578   SmallVector<int, 4> LoInputs;
8579   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8580                [](int M) { return M >= 0; });
8581   std::sort(LoInputs.begin(), LoInputs.end());
8582   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8583   SmallVector<int, 4> HiInputs;
8584   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8585                [](int M) { return M >= 0; });
8586   std::sort(HiInputs.begin(), HiInputs.end());
8587   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8588   int NumLToL =
8589       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8590   int NumHToL = LoInputs.size() - NumLToL;
8591   int NumLToH =
8592       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8593   int NumHToH = HiInputs.size() - NumLToH;
8594   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8595   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8596   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8597   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8598
8599   // Check for being able to broadcast a single element.
8600   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i16, DL, V,
8601                                                         Mask, Subtarget, DAG))
8602     return Broadcast;
8603
8604   // Try to use byte shift instructions.
8605   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8606           DL, MVT::v8i16, V, V, Mask, DAG))
8607     return Shift;
8608
8609   // Use dedicated unpack instructions for masks that match their pattern.
8610   if (isShuffleEquivalent(Mask, 0, 0, 1, 1, 2, 2, 3, 3))
8611     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
8612   if (isShuffleEquivalent(Mask, 4, 4, 5, 5, 6, 6, 7, 7))
8613     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
8614
8615   // Try to use byte rotation instructions.
8616   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8617           DL, MVT::v8i16, V, V, Mask, Subtarget, DAG))
8618     return Rotate;
8619
8620   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8621   // such inputs we can swap two of the dwords across the half mark and end up
8622   // with <=2 inputs to each half in each half. Once there, we can fall through
8623   // to the generic code below. For example:
8624   //
8625   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8626   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8627   //
8628   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8629   // and an existing 2-into-2 on the other half. In this case we may have to
8630   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8631   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8632   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8633   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8634   // half than the one we target for fixing) will be fixed when we re-enter this
8635   // path. We will also combine away any sequence of PSHUFD instructions that
8636   // result into a single instruction. Here is an example of the tricky case:
8637   //
8638   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8639   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8640   //
8641   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8642   //
8643   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8644   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8645   //
8646   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8647   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8648   //
8649   // The result is fine to be handled by the generic logic.
8650   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8651                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8652                           int AOffset, int BOffset) {
8653     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8654            "Must call this with A having 3 or 1 inputs from the A half.");
8655     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8656            "Must call this with B having 1 or 3 inputs from the B half.");
8657     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8658            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8659
8660     // Compute the index of dword with only one word among the three inputs in
8661     // a half by taking the sum of the half with three inputs and subtracting
8662     // the sum of the actual three inputs. The difference is the remaining
8663     // slot.
8664     int ADWord, BDWord;
8665     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8666     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8667     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8668     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8669     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8670     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8671     int TripleNonInputIdx =
8672         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8673     TripleDWord = TripleNonInputIdx / 2;
8674
8675     // We use xor with one to compute the adjacent DWord to whichever one the
8676     // OneInput is in.
8677     OneInputDWord = (OneInput / 2) ^ 1;
8678
8679     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8680     // and BToA inputs. If there is also such a problem with the BToB and AToB
8681     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8682     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8683     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8684     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8685       // Compute how many inputs will be flipped by swapping these DWords. We
8686       // need
8687       // to balance this to ensure we don't form a 3-1 shuffle in the other
8688       // half.
8689       int NumFlippedAToBInputs =
8690           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8691           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8692       int NumFlippedBToBInputs =
8693           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8694           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8695       if ((NumFlippedAToBInputs == 1 &&
8696            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8697           (NumFlippedBToBInputs == 1 &&
8698            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8699         // We choose whether to fix the A half or B half based on whether that
8700         // half has zero flipped inputs. At zero, we may not be able to fix it
8701         // with that half. We also bias towards fixing the B half because that
8702         // will more commonly be the high half, and we have to bias one way.
8703         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8704                                                        ArrayRef<int> Inputs) {
8705           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8706           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8707                                          PinnedIdx ^ 1) != Inputs.end();
8708           // Determine whether the free index is in the flipped dword or the
8709           // unflipped dword based on where the pinned index is. We use this bit
8710           // in an xor to conditionally select the adjacent dword.
8711           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8712           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8713                                              FixFreeIdx) != Inputs.end();
8714           if (IsFixIdxInput == IsFixFreeIdxInput)
8715             FixFreeIdx += 1;
8716           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8717                                         FixFreeIdx) != Inputs.end();
8718           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8719                  "We need to be changing the number of flipped inputs!");
8720           int PSHUFHalfMask[] = {0, 1, 2, 3};
8721           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8722           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8723                           MVT::v8i16, V,
8724                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
8725
8726           for (int &M : Mask)
8727             if (M != -1 && M == FixIdx)
8728               M = FixFreeIdx;
8729             else if (M != -1 && M == FixFreeIdx)
8730               M = FixIdx;
8731         };
8732         if (NumFlippedBToBInputs != 0) {
8733           int BPinnedIdx =
8734               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8735           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8736         } else {
8737           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8738           int APinnedIdx =
8739               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8740           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8741         }
8742       }
8743     }
8744
8745     int PSHUFDMask[] = {0, 1, 2, 3};
8746     PSHUFDMask[ADWord] = BDWord;
8747     PSHUFDMask[BDWord] = ADWord;
8748     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8749                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8750                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8751                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8752
8753     // Adjust the mask to match the new locations of A and B.
8754     for (int &M : Mask)
8755       if (M != -1 && M/2 == ADWord)
8756         M = 2 * BDWord + M % 2;
8757       else if (M != -1 && M/2 == BDWord)
8758         M = 2 * ADWord + M % 2;
8759
8760     // Recurse back into this routine to re-compute state now that this isn't
8761     // a 3 and 1 problem.
8762     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8763                                 Mask);
8764   };
8765   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8766     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8767   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8768     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8769
8770   // At this point there are at most two inputs to the low and high halves from
8771   // each half. That means the inputs can always be grouped into dwords and
8772   // those dwords can then be moved to the correct half with a dword shuffle.
8773   // We use at most one low and one high word shuffle to collect these paired
8774   // inputs into dwords, and finally a dword shuffle to place them.
8775   int PSHUFLMask[4] = {-1, -1, -1, -1};
8776   int PSHUFHMask[4] = {-1, -1, -1, -1};
8777   int PSHUFDMask[4] = {-1, -1, -1, -1};
8778
8779   // First fix the masks for all the inputs that are staying in their
8780   // original halves. This will then dictate the targets of the cross-half
8781   // shuffles.
8782   auto fixInPlaceInputs =
8783       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8784                     MutableArrayRef<int> SourceHalfMask,
8785                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8786     if (InPlaceInputs.empty())
8787       return;
8788     if (InPlaceInputs.size() == 1) {
8789       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8790           InPlaceInputs[0] - HalfOffset;
8791       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8792       return;
8793     }
8794     if (IncomingInputs.empty()) {
8795       // Just fix all of the in place inputs.
8796       for (int Input : InPlaceInputs) {
8797         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8798         PSHUFDMask[Input / 2] = Input / 2;
8799       }
8800       return;
8801     }
8802
8803     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8804     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8805         InPlaceInputs[0] - HalfOffset;
8806     // Put the second input next to the first so that they are packed into
8807     // a dword. We find the adjacent index by toggling the low bit.
8808     int AdjIndex = InPlaceInputs[0] ^ 1;
8809     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8810     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8811     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8812   };
8813   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8814   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8815
8816   // Now gather the cross-half inputs and place them into a free dword of
8817   // their target half.
8818   // FIXME: This operation could almost certainly be simplified dramatically to
8819   // look more like the 3-1 fixing operation.
8820   auto moveInputsToRightHalf = [&PSHUFDMask](
8821       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8822       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8823       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8824       int DestOffset) {
8825     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8826       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8827     };
8828     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8829                                                int Word) {
8830       int LowWord = Word & ~1;
8831       int HighWord = Word | 1;
8832       return isWordClobbered(SourceHalfMask, LowWord) ||
8833              isWordClobbered(SourceHalfMask, HighWord);
8834     };
8835
8836     if (IncomingInputs.empty())
8837       return;
8838
8839     if (ExistingInputs.empty()) {
8840       // Map any dwords with inputs from them into the right half.
8841       for (int Input : IncomingInputs) {
8842         // If the source half mask maps over the inputs, turn those into
8843         // swaps and use the swapped lane.
8844         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8845           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8846             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8847                 Input - SourceOffset;
8848             // We have to swap the uses in our half mask in one sweep.
8849             for (int &M : HalfMask)
8850               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8851                 M = Input;
8852               else if (M == Input)
8853                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8854           } else {
8855             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8856                        Input - SourceOffset &&
8857                    "Previous placement doesn't match!");
8858           }
8859           // Note that this correctly re-maps both when we do a swap and when
8860           // we observe the other side of the swap above. We rely on that to
8861           // avoid swapping the members of the input list directly.
8862           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8863         }
8864
8865         // Map the input's dword into the correct half.
8866         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8867           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8868         else
8869           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8870                      Input / 2 &&
8871                  "Previous placement doesn't match!");
8872       }
8873
8874       // And just directly shift any other-half mask elements to be same-half
8875       // as we will have mirrored the dword containing the element into the
8876       // same position within that half.
8877       for (int &M : HalfMask)
8878         if (M >= SourceOffset && M < SourceOffset + 4) {
8879           M = M - SourceOffset + DestOffset;
8880           assert(M >= 0 && "This should never wrap below zero!");
8881         }
8882       return;
8883     }
8884
8885     // Ensure we have the input in a viable dword of its current half. This
8886     // is particularly tricky because the original position may be clobbered
8887     // by inputs being moved and *staying* in that half.
8888     if (IncomingInputs.size() == 1) {
8889       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8890         int InputFixed = std::find(std::begin(SourceHalfMask),
8891                                    std::end(SourceHalfMask), -1) -
8892                          std::begin(SourceHalfMask) + SourceOffset;
8893         SourceHalfMask[InputFixed - SourceOffset] =
8894             IncomingInputs[0] - SourceOffset;
8895         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8896                      InputFixed);
8897         IncomingInputs[0] = InputFixed;
8898       }
8899     } else if (IncomingInputs.size() == 2) {
8900       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8901           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8902         // We have two non-adjacent or clobbered inputs we need to extract from
8903         // the source half. To do this, we need to map them into some adjacent
8904         // dword slot in the source mask.
8905         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8906                               IncomingInputs[1] - SourceOffset};
8907
8908         // If there is a free slot in the source half mask adjacent to one of
8909         // the inputs, place the other input in it. We use (Index XOR 1) to
8910         // compute an adjacent index.
8911         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8912             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8913           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8914           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8915           InputsFixed[1] = InputsFixed[0] ^ 1;
8916         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8917                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8918           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8919           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8920           InputsFixed[0] = InputsFixed[1] ^ 1;
8921         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8922                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8923           // The two inputs are in the same DWord but it is clobbered and the
8924           // adjacent DWord isn't used at all. Move both inputs to the free
8925           // slot.
8926           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8927           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8928           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8929           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8930         } else {
8931           // The only way we hit this point is if there is no clobbering
8932           // (because there are no off-half inputs to this half) and there is no
8933           // free slot adjacent to one of the inputs. In this case, we have to
8934           // swap an input with a non-input.
8935           for (int i = 0; i < 4; ++i)
8936             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8937                    "We can't handle any clobbers here!");
8938           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8939                  "Cannot have adjacent inputs here!");
8940
8941           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8942           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8943
8944           // We also have to update the final source mask in this case because
8945           // it may need to undo the above swap.
8946           for (int &M : FinalSourceHalfMask)
8947             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8948               M = InputsFixed[1] + SourceOffset;
8949             else if (M == InputsFixed[1] + SourceOffset)
8950               M = (InputsFixed[0] ^ 1) + SourceOffset;
8951
8952           InputsFixed[1] = InputsFixed[0] ^ 1;
8953         }
8954
8955         // Point everything at the fixed inputs.
8956         for (int &M : HalfMask)
8957           if (M == IncomingInputs[0])
8958             M = InputsFixed[0] + SourceOffset;
8959           else if (M == IncomingInputs[1])
8960             M = InputsFixed[1] + SourceOffset;
8961
8962         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8963         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8964       }
8965     } else {
8966       llvm_unreachable("Unhandled input size!");
8967     }
8968
8969     // Now hoist the DWord down to the right half.
8970     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8971     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8972     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8973     for (int &M : HalfMask)
8974       for (int Input : IncomingInputs)
8975         if (M == Input)
8976           M = FreeDWord * 2 + Input % 2;
8977   };
8978   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8979                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8980   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8981                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8982
8983   // Now enact all the shuffles we've computed to move the inputs into their
8984   // target half.
8985   if (!isNoopShuffleMask(PSHUFLMask))
8986     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8987                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8988   if (!isNoopShuffleMask(PSHUFHMask))
8989     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8990                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8991   if (!isNoopShuffleMask(PSHUFDMask))
8992     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8993                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8994                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8995                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8996
8997   // At this point, each half should contain all its inputs, and we can then
8998   // just shuffle them into their final position.
8999   assert(std::count_if(LoMask.begin(), LoMask.end(),
9000                        [](int M) { return M >= 4; }) == 0 &&
9001          "Failed to lift all the high half inputs to the low mask!");
9002   assert(std::count_if(HiMask.begin(), HiMask.end(),
9003                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9004          "Failed to lift all the low half inputs to the high mask!");
9005
9006   // Do a half shuffle for the low mask.
9007   if (!isNoopShuffleMask(LoMask))
9008     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
9009                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
9010
9011   // Do a half shuffle with the high mask after shifting its values down.
9012   for (int &M : HiMask)
9013     if (M >= 0)
9014       M -= 4;
9015   if (!isNoopShuffleMask(HiMask))
9016     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
9017                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
9018
9019   return V;
9020 }
9021
9022 /// \brief Detect whether the mask pattern should be lowered through
9023 /// interleaving.
9024 ///
9025 /// This essentially tests whether viewing the mask as an interleaving of two
9026 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
9027 /// lowering it through interleaving is a significantly better strategy.
9028 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
9029   int NumEvenInputs[2] = {0, 0};
9030   int NumOddInputs[2] = {0, 0};
9031   int NumLoInputs[2] = {0, 0};
9032   int NumHiInputs[2] = {0, 0};
9033   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9034     if (Mask[i] < 0)
9035       continue;
9036
9037     int InputIdx = Mask[i] >= Size;
9038
9039     if (i < Size / 2)
9040       ++NumLoInputs[InputIdx];
9041     else
9042       ++NumHiInputs[InputIdx];
9043
9044     if ((i % 2) == 0)
9045       ++NumEvenInputs[InputIdx];
9046     else
9047       ++NumOddInputs[InputIdx];
9048   }
9049
9050   // The minimum number of cross-input results for both the interleaved and
9051   // split cases. If interleaving results in fewer cross-input results, return
9052   // true.
9053   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
9054                                     NumEvenInputs[0] + NumOddInputs[1]);
9055   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
9056                               NumLoInputs[0] + NumHiInputs[1]);
9057   return InterleavedCrosses < SplitCrosses;
9058 }
9059
9060 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
9061 ///
9062 /// This strategy only works when the inputs from each vector fit into a single
9063 /// half of that vector, and generally there are not so many inputs as to leave
9064 /// the in-place shuffles required highly constrained (and thus expensive). It
9065 /// shifts all the inputs into a single side of both input vectors and then
9066 /// uses an unpack to interleave these inputs in a single vector. At that
9067 /// point, we will fall back on the generic single input shuffle lowering.
9068 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
9069                                                  SDValue V2,
9070                                                  MutableArrayRef<int> Mask,
9071                                                  const X86Subtarget *Subtarget,
9072                                                  SelectionDAG &DAG) {
9073   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9074   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9075   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
9076   for (int i = 0; i < 8; ++i)
9077     if (Mask[i] >= 0 && Mask[i] < 4)
9078       LoV1Inputs.push_back(i);
9079     else if (Mask[i] >= 4 && Mask[i] < 8)
9080       HiV1Inputs.push_back(i);
9081     else if (Mask[i] >= 8 && Mask[i] < 12)
9082       LoV2Inputs.push_back(i);
9083     else if (Mask[i] >= 12)
9084       HiV2Inputs.push_back(i);
9085
9086   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
9087   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
9088   (void)NumV1Inputs;
9089   (void)NumV2Inputs;
9090   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
9091   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
9092   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
9093
9094   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
9095                      HiV1Inputs.size() + HiV2Inputs.size();
9096
9097   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
9098                               ArrayRef<int> HiInputs, bool MoveToLo,
9099                               int MaskOffset) {
9100     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
9101     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
9102     if (BadInputs.empty())
9103       return V;
9104
9105     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9106     int MoveOffset = MoveToLo ? 0 : 4;
9107
9108     if (GoodInputs.empty()) {
9109       for (int BadInput : BadInputs) {
9110         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
9111         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
9112       }
9113     } else {
9114       if (GoodInputs.size() == 2) {
9115         // If the low inputs are spread across two dwords, pack them into
9116         // a single dword.
9117         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
9118         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
9119         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
9120         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
9121       } else {
9122         // Otherwise pin the good inputs.
9123         for (int GoodInput : GoodInputs)
9124           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
9125       }
9126
9127       if (BadInputs.size() == 2) {
9128         // If we have two bad inputs then there may be either one or two good
9129         // inputs fixed in place. Find a fixed input, and then find the *other*
9130         // two adjacent indices by using modular arithmetic.
9131         int GoodMaskIdx =
9132             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
9133                          [](int M) { return M >= 0; }) -
9134             std::begin(MoveMask);
9135         int MoveMaskIdx =
9136             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
9137         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
9138         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
9139         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9140         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
9141         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9142         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
9143       } else {
9144         assert(BadInputs.size() == 1 && "All sizes handled");
9145         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
9146                                     std::end(MoveMask), -1) -
9147                           std::begin(MoveMask);
9148         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9149         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9150       }
9151     }
9152
9153     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
9154                                 MoveMask);
9155   };
9156   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
9157                         /*MaskOffset*/ 0);
9158   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
9159                         /*MaskOffset*/ 8);
9160
9161   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
9162   // cross-half traffic in the final shuffle.
9163
9164   // Munge the mask to be a single-input mask after the unpack merges the
9165   // results.
9166   for (int &M : Mask)
9167     if (M != -1)
9168       M = 2 * (M % 4) + (M / 8);
9169
9170   return DAG.getVectorShuffle(
9171       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
9172                                   DL, MVT::v8i16, V1, V2),
9173       DAG.getUNDEF(MVT::v8i16), Mask);
9174 }
9175
9176 /// \brief Generic lowering of 8-lane i16 shuffles.
9177 ///
9178 /// This handles both single-input shuffles and combined shuffle/blends with
9179 /// two inputs. The single input shuffles are immediately delegated to
9180 /// a dedicated lowering routine.
9181 ///
9182 /// The blends are lowered in one of three fundamental ways. If there are few
9183 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9184 /// of the input is significantly cheaper when lowered as an interleaving of
9185 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9186 /// halves of the inputs separately (making them have relatively few inputs)
9187 /// and then concatenate them.
9188 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9189                                        const X86Subtarget *Subtarget,
9190                                        SelectionDAG &DAG) {
9191   SDLoc DL(Op);
9192   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9193   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9194   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9195   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9196   ArrayRef<int> OrigMask = SVOp->getMask();
9197   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9198                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9199   MutableArrayRef<int> Mask(MaskStorage);
9200
9201   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9202
9203   // Whenever we can lower this as a zext, that instruction is strictly faster
9204   // than any alternative.
9205   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9206           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9207     return ZExt;
9208
9209   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9210   auto isV2 = [](int M) { return M >= 8; };
9211
9212   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
9213   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9214
9215   if (NumV2Inputs == 0)
9216     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
9217
9218   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
9219                             "to be V1-input shuffles.");
9220
9221   // Try to use byte shift instructions.
9222   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9223           DL, MVT::v8i16, V1, V2, Mask, DAG))
9224     return Shift;
9225
9226   // There are special ways we can lower some single-element blends.
9227   if (NumV2Inputs == 1)
9228     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
9229                                                          Mask, Subtarget, DAG))
9230       return V;
9231
9232   // Use dedicated unpack instructions for masks that match their pattern.
9233   if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 2, 10, 3, 11))
9234     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9235   if (isShuffleEquivalent(Mask, 4, 12, 5, 13, 6, 14, 7, 15))
9236     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9237
9238   if (Subtarget->hasSSE41())
9239     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9240                                                   Subtarget, DAG))
9241       return Blend;
9242
9243   // Try to use byte rotation instructions.
9244   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9245           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9246     return Rotate;
9247
9248   if (NumV1Inputs + NumV2Inputs <= 4)
9249     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
9250
9251   // Check whether an interleaving lowering is likely to be more efficient.
9252   // This isn't perfect but it is a strong heuristic that tends to work well on
9253   // the kinds of shuffles that show up in practice.
9254   //
9255   // FIXME: Handle 1x, 2x, and 4x interleaving.
9256   if (shouldLowerAsInterleaving(Mask)) {
9257     // FIXME: Figure out whether we should pack these into the low or high
9258     // halves.
9259
9260     int EMask[8], OMask[8];
9261     for (int i = 0; i < 4; ++i) {
9262       EMask[i] = Mask[2*i];
9263       OMask[i] = Mask[2*i + 1];
9264       EMask[i + 4] = -1;
9265       OMask[i + 4] = -1;
9266     }
9267
9268     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
9269     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
9270
9271     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
9272   }
9273
9274   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9275   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9276
9277   for (int i = 0; i < 4; ++i) {
9278     LoBlendMask[i] = Mask[i];
9279     HiBlendMask[i] = Mask[i + 4];
9280   }
9281
9282   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9283   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9284   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
9285   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
9286
9287   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9288                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
9289 }
9290
9291 /// \brief Check whether a compaction lowering can be done by dropping even
9292 /// elements and compute how many times even elements must be dropped.
9293 ///
9294 /// This handles shuffles which take every Nth element where N is a power of
9295 /// two. Example shuffle masks:
9296 ///
9297 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9298 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9299 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9300 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9301 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9302 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9303 ///
9304 /// Any of these lanes can of course be undef.
9305 ///
9306 /// This routine only supports N <= 3.
9307 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9308 /// for larger N.
9309 ///
9310 /// \returns N above, or the number of times even elements must be dropped if
9311 /// there is such a number. Otherwise returns zero.
9312 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9313   // Figure out whether we're looping over two inputs or just one.
9314   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9315
9316   // The modulus for the shuffle vector entries is based on whether this is
9317   // a single input or not.
9318   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9319   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9320          "We should only be called with masks with a power-of-2 size!");
9321
9322   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9323
9324   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9325   // and 2^3 simultaneously. This is because we may have ambiguity with
9326   // partially undef inputs.
9327   bool ViableForN[3] = {true, true, true};
9328
9329   for (int i = 0, e = Mask.size(); i < e; ++i) {
9330     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9331     // want.
9332     if (Mask[i] == -1)
9333       continue;
9334
9335     bool IsAnyViable = false;
9336     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9337       if (ViableForN[j]) {
9338         uint64_t N = j + 1;
9339
9340         // The shuffle mask must be equal to (i * 2^N) % M.
9341         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9342           IsAnyViable = true;
9343         else
9344           ViableForN[j] = false;
9345       }
9346     // Early exit if we exhaust the possible powers of two.
9347     if (!IsAnyViable)
9348       break;
9349   }
9350
9351   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9352     if (ViableForN[j])
9353       return j + 1;
9354
9355   // Return 0 as there is no viable power of two.
9356   return 0;
9357 }
9358
9359 /// \brief Generic lowering of v16i8 shuffles.
9360 ///
9361 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9362 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9363 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9364 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9365 /// back together.
9366 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9367                                        const X86Subtarget *Subtarget,
9368                                        SelectionDAG &DAG) {
9369   SDLoc DL(Op);
9370   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9371   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9372   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9373   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9374   ArrayRef<int> OrigMask = SVOp->getMask();
9375   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9376
9377   // Try to use byte shift instructions.
9378   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9379           DL, MVT::v16i8, V1, V2, OrigMask, DAG))
9380     return Shift;
9381
9382   // Try to use byte rotation instructions.
9383   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9384           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9385     return Rotate;
9386
9387   // Try to use a zext lowering.
9388   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9389           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9390     return ZExt;
9391
9392   int MaskStorage[16] = {
9393       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
9394       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
9395       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
9396       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
9397   MutableArrayRef<int> Mask(MaskStorage);
9398   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
9399   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
9400
9401   int NumV2Elements =
9402       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9403
9404   // For single-input shuffles, there are some nicer lowering tricks we can use.
9405   if (NumV2Elements == 0) {
9406     // Check for being able to broadcast a single element.
9407     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i8, DL, V1,
9408                                                           Mask, Subtarget, DAG))
9409       return Broadcast;
9410
9411     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9412     // Notably, this handles splat and partial-splat shuffles more efficiently.
9413     // However, it only makes sense if the pre-duplication shuffle simplifies
9414     // things significantly. Currently, this means we need to be able to
9415     // express the pre-duplication shuffle as an i16 shuffle.
9416     //
9417     // FIXME: We should check for other patterns which can be widened into an
9418     // i16 shuffle as well.
9419     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9420       for (int i = 0; i < 16; i += 2)
9421         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9422           return false;
9423
9424       return true;
9425     };
9426     auto tryToWidenViaDuplication = [&]() -> SDValue {
9427       if (!canWidenViaDuplication(Mask))
9428         return SDValue();
9429       SmallVector<int, 4> LoInputs;
9430       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9431                    [](int M) { return M >= 0 && M < 8; });
9432       std::sort(LoInputs.begin(), LoInputs.end());
9433       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9434                      LoInputs.end());
9435       SmallVector<int, 4> HiInputs;
9436       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9437                    [](int M) { return M >= 8; });
9438       std::sort(HiInputs.begin(), HiInputs.end());
9439       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9440                      HiInputs.end());
9441
9442       bool TargetLo = LoInputs.size() >= HiInputs.size();
9443       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9444       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9445
9446       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9447       SmallDenseMap<int, int, 8> LaneMap;
9448       for (int I : InPlaceInputs) {
9449         PreDupI16Shuffle[I/2] = I/2;
9450         LaneMap[I] = I;
9451       }
9452       int j = TargetLo ? 0 : 4, je = j + 4;
9453       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9454         // Check if j is already a shuffle of this input. This happens when
9455         // there are two adjacent bytes after we move the low one.
9456         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9457           // If we haven't yet mapped the input, search for a slot into which
9458           // we can map it.
9459           while (j < je && PreDupI16Shuffle[j] != -1)
9460             ++j;
9461
9462           if (j == je)
9463             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9464             return SDValue();
9465
9466           // Map this input with the i16 shuffle.
9467           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9468         }
9469
9470         // Update the lane map based on the mapping we ended up with.
9471         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9472       }
9473       V1 = DAG.getNode(
9474           ISD::BITCAST, DL, MVT::v16i8,
9475           DAG.getVectorShuffle(MVT::v8i16, DL,
9476                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9477                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9478
9479       // Unpack the bytes to form the i16s that will be shuffled into place.
9480       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9481                        MVT::v16i8, V1, V1);
9482
9483       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9484       for (int i = 0; i < 16; ++i)
9485         if (Mask[i] != -1) {
9486           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9487           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9488           if (PostDupI16Shuffle[i / 2] == -1)
9489             PostDupI16Shuffle[i / 2] = MappedMask;
9490           else
9491             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9492                    "Conflicting entrties in the original shuffle!");
9493         }
9494       return DAG.getNode(
9495           ISD::BITCAST, DL, MVT::v16i8,
9496           DAG.getVectorShuffle(MVT::v8i16, DL,
9497                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9498                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9499     };
9500     if (SDValue V = tryToWidenViaDuplication())
9501       return V;
9502   }
9503
9504   // Check whether an interleaving lowering is likely to be more efficient.
9505   // This isn't perfect but it is a strong heuristic that tends to work well on
9506   // the kinds of shuffles that show up in practice.
9507   //
9508   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
9509   if (shouldLowerAsInterleaving(Mask)) {
9510     int NumLoHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9511       return (M >= 0 && M < 8) || (M >= 16 && M < 24);
9512     });
9513     int NumHiHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9514       return (M >= 8 && M < 16) || M >= 24;
9515     });
9516     int EMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9517                      -1, -1, -1, -1, -1, -1, -1, -1};
9518     int OMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9519                      -1, -1, -1, -1, -1, -1, -1, -1};
9520     bool UnpackLo = NumLoHalf >= NumHiHalf;
9521     MutableArrayRef<int> TargetEMask(UnpackLo ? EMask : EMask + 8, 8);
9522     MutableArrayRef<int> TargetOMask(UnpackLo ? OMask : OMask + 8, 8);
9523     for (int i = 0; i < 8; ++i) {
9524       TargetEMask[i] = Mask[2 * i];
9525       TargetOMask[i] = Mask[2 * i + 1];
9526     }
9527
9528     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
9529     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
9530
9531     return DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9532                        MVT::v16i8, Evens, Odds);
9533   }
9534
9535   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9536   // with PSHUFB. It is important to do this before we attempt to generate any
9537   // blends but after all of the single-input lowerings. If the single input
9538   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9539   // want to preserve that and we can DAG combine any longer sequences into
9540   // a PSHUFB in the end. But once we start blending from multiple inputs,
9541   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9542   // and there are *very* few patterns that would actually be faster than the
9543   // PSHUFB approach because of its ability to zero lanes.
9544   //
9545   // FIXME: The only exceptions to the above are blends which are exact
9546   // interleavings with direct instructions supporting them. We currently don't
9547   // handle those well here.
9548   if (Subtarget->hasSSSE3()) {
9549     SDValue V1Mask[16];
9550     SDValue V2Mask[16];
9551     for (int i = 0; i < 16; ++i)
9552       if (Mask[i] == -1) {
9553         V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9554       } else {
9555         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
9556         V2Mask[i] =
9557             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
9558       }
9559     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
9560                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9561     if (isSingleInputShuffleMask(Mask))
9562       return V1; // Single inputs are easy.
9563
9564     // Otherwise, blend the two.
9565     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
9566                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9567     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9568   }
9569
9570   // There are special ways we can lower some single-element blends.
9571   if (NumV2Elements == 1)
9572     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
9573                                                          Mask, Subtarget, DAG))
9574       return V;
9575
9576   // Check whether a compaction lowering can be done. This handles shuffles
9577   // which take every Nth element for some even N. See the helper function for
9578   // details.
9579   //
9580   // We special case these as they can be particularly efficiently handled with
9581   // the PACKUSB instruction on x86 and they show up in common patterns of
9582   // rearranging bytes to truncate wide elements.
9583   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9584     // NumEvenDrops is the power of two stride of the elements. Another way of
9585     // thinking about it is that we need to drop the even elements this many
9586     // times to get the original input.
9587     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9588
9589     // First we need to zero all the dropped bytes.
9590     assert(NumEvenDrops <= 3 &&
9591            "No support for dropping even elements more than 3 times.");
9592     // We use the mask type to pick which bytes are preserved based on how many
9593     // elements are dropped.
9594     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9595     SDValue ByteClearMask =
9596         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
9597                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
9598     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9599     if (!IsSingleInput)
9600       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9601
9602     // Now pack things back together.
9603     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
9604     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
9605     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9606     for (int i = 1; i < NumEvenDrops; ++i) {
9607       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
9608       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9609     }
9610
9611     return Result;
9612   }
9613
9614   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9615   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9616   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9617   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9618
9619   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
9620                             MutableArrayRef<int> V1HalfBlendMask,
9621                             MutableArrayRef<int> V2HalfBlendMask) {
9622     for (int i = 0; i < 8; ++i)
9623       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
9624         V1HalfBlendMask[i] = HalfMask[i];
9625         HalfMask[i] = i;
9626       } else if (HalfMask[i] >= 16) {
9627         V2HalfBlendMask[i] = HalfMask[i] - 16;
9628         HalfMask[i] = i + 8;
9629       }
9630   };
9631   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
9632   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
9633
9634   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9635
9636   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
9637                              MutableArrayRef<int> HiBlendMask) {
9638     SDValue V1, V2;
9639     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9640     // them out and avoid using UNPCK{L,H} to extract the elements of V as
9641     // i16s.
9642     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
9643                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
9644         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
9645                      [](int M) { return M >= 0 && M % 2 == 1; })) {
9646       // Use a mask to drop the high bytes.
9647       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
9648       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
9649                        DAG.getConstant(0x00FF, MVT::v8i16));
9650
9651       // This will be a single vector shuffle instead of a blend so nuke V2.
9652       V2 = DAG.getUNDEF(MVT::v8i16);
9653
9654       // Squash the masks to point directly into V1.
9655       for (int &M : LoBlendMask)
9656         if (M >= 0)
9657           M /= 2;
9658       for (int &M : HiBlendMask)
9659         if (M >= 0)
9660           M /= 2;
9661     } else {
9662       // Otherwise just unpack the low half of V into V1 and the high half into
9663       // V2 so that we can blend them as i16s.
9664       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9665                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9666       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9667                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9668     }
9669
9670     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9671     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9672     return std::make_pair(BlendedLo, BlendedHi);
9673   };
9674   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
9675   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
9676   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
9677
9678   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
9679   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
9680
9681   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9682 }
9683
9684 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9685 ///
9686 /// This routine breaks down the specific type of 128-bit shuffle and
9687 /// dispatches to the lowering routines accordingly.
9688 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9689                                         MVT VT, const X86Subtarget *Subtarget,
9690                                         SelectionDAG &DAG) {
9691   switch (VT.SimpleTy) {
9692   case MVT::v2i64:
9693     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9694   case MVT::v2f64:
9695     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9696   case MVT::v4i32:
9697     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9698   case MVT::v4f32:
9699     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9700   case MVT::v8i16:
9701     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9702   case MVT::v16i8:
9703     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9704
9705   default:
9706     llvm_unreachable("Unimplemented!");
9707   }
9708 }
9709
9710 /// \brief Helper function to test whether a shuffle mask could be
9711 /// simplified by widening the elements being shuffled.
9712 ///
9713 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9714 /// leaves it in an unspecified state.
9715 ///
9716 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9717 /// shuffle masks. The latter have the special property of a '-2' representing
9718 /// a zero-ed lane of a vector.
9719 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9720                                     SmallVectorImpl<int> &WidenedMask) {
9721   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9722     // If both elements are undef, its trivial.
9723     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9724       WidenedMask.push_back(SM_SentinelUndef);
9725       continue;
9726     }
9727
9728     // Check for an undef mask and a mask value properly aligned to fit with
9729     // a pair of values. If we find such a case, use the non-undef mask's value.
9730     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9731       WidenedMask.push_back(Mask[i + 1] / 2);
9732       continue;
9733     }
9734     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9735       WidenedMask.push_back(Mask[i] / 2);
9736       continue;
9737     }
9738
9739     // When zeroing, we need to spread the zeroing across both lanes to widen.
9740     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9741       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9742           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9743         WidenedMask.push_back(SM_SentinelZero);
9744         continue;
9745       }
9746       return false;
9747     }
9748
9749     // Finally check if the two mask values are adjacent and aligned with
9750     // a pair.
9751     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9752       WidenedMask.push_back(Mask[i] / 2);
9753       continue;
9754     }
9755
9756     // Otherwise we can't safely widen the elements used in this shuffle.
9757     return false;
9758   }
9759   assert(WidenedMask.size() == Mask.size() / 2 &&
9760          "Incorrect size of mask after widening the elements!");
9761
9762   return true;
9763 }
9764
9765 /// \brief Generic routine to split ector shuffle into half-sized shuffles.
9766 ///
9767 /// This routine just extracts two subvectors, shuffles them independently, and
9768 /// then concatenates them back together. This should work effectively with all
9769 /// AVX vector shuffle types.
9770 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9771                                           SDValue V2, ArrayRef<int> Mask,
9772                                           SelectionDAG &DAG) {
9773   assert(VT.getSizeInBits() >= 256 &&
9774          "Only for 256-bit or wider vector shuffles!");
9775   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9776   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9777
9778   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9779   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9780
9781   int NumElements = VT.getVectorNumElements();
9782   int SplitNumElements = NumElements / 2;
9783   MVT ScalarVT = VT.getScalarType();
9784   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9785
9786   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9787                              DAG.getIntPtrConstant(0));
9788   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9789                              DAG.getIntPtrConstant(SplitNumElements));
9790   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9791                              DAG.getIntPtrConstant(0));
9792   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9793                              DAG.getIntPtrConstant(SplitNumElements));
9794
9795   // Now create two 4-way blends of these half-width vectors.
9796   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9797     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9798     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9799     for (int i = 0; i < SplitNumElements; ++i) {
9800       int M = HalfMask[i];
9801       if (M >= NumElements) {
9802         if (M >= NumElements + SplitNumElements)
9803           UseHiV2 = true;
9804         else
9805           UseLoV2 = true;
9806         V2BlendMask.push_back(M - NumElements);
9807         V1BlendMask.push_back(-1);
9808         BlendMask.push_back(SplitNumElements + i);
9809       } else if (M >= 0) {
9810         if (M >= SplitNumElements)
9811           UseHiV1 = true;
9812         else
9813           UseLoV1 = true;
9814         V2BlendMask.push_back(-1);
9815         V1BlendMask.push_back(M);
9816         BlendMask.push_back(i);
9817       } else {
9818         V2BlendMask.push_back(-1);
9819         V1BlendMask.push_back(-1);
9820         BlendMask.push_back(-1);
9821       }
9822     }
9823
9824     // Because the lowering happens after all combining takes place, we need to
9825     // manually combine these blend masks as much as possible so that we create
9826     // a minimal number of high-level vector shuffle nodes.
9827
9828     // First try just blending the halves of V1 or V2.
9829     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9830       return DAG.getUNDEF(SplitVT);
9831     if (!UseLoV2 && !UseHiV2)
9832       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9833     if (!UseLoV1 && !UseHiV1)
9834       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9835
9836     SDValue V1Blend, V2Blend;
9837     if (UseLoV1 && UseHiV1) {
9838       V1Blend =
9839         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9840     } else {
9841       // We only use half of V1 so map the usage down into the final blend mask.
9842       V1Blend = UseLoV1 ? LoV1 : HiV1;
9843       for (int i = 0; i < SplitNumElements; ++i)
9844         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9845           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9846     }
9847     if (UseLoV2 && UseHiV2) {
9848       V2Blend =
9849         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9850     } else {
9851       // We only use half of V2 so map the usage down into the final blend mask.
9852       V2Blend = UseLoV2 ? LoV2 : HiV2;
9853       for (int i = 0; i < SplitNumElements; ++i)
9854         if (BlendMask[i] >= SplitNumElements)
9855           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9856     }
9857     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9858   };
9859   SDValue Lo = HalfBlend(LoMask);
9860   SDValue Hi = HalfBlend(HiMask);
9861   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9862 }
9863
9864 /// \brief Either split a vector in halves or decompose the shuffles and the
9865 /// blend.
9866 ///
9867 /// This is provided as a good fallback for many lowerings of non-single-input
9868 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9869 /// between splitting the shuffle into 128-bit components and stitching those
9870 /// back together vs. extracting the single-input shuffles and blending those
9871 /// results.
9872 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9873                                                 SDValue V2, ArrayRef<int> Mask,
9874                                                 SelectionDAG &DAG) {
9875   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9876                                             "lower single-input shuffles as it "
9877                                             "could then recurse on itself.");
9878   int Size = Mask.size();
9879
9880   // If this can be modeled as a broadcast of two elements followed by a blend,
9881   // prefer that lowering. This is especially important because broadcasts can
9882   // often fold with memory operands.
9883   auto DoBothBroadcast = [&] {
9884     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9885     for (int M : Mask)
9886       if (M >= Size) {
9887         if (V2BroadcastIdx == -1)
9888           V2BroadcastIdx = M - Size;
9889         else if (M - Size != V2BroadcastIdx)
9890           return false;
9891       } else if (M >= 0) {
9892         if (V1BroadcastIdx == -1)
9893           V1BroadcastIdx = M;
9894         else if (M != V1BroadcastIdx)
9895           return false;
9896       }
9897     return true;
9898   };
9899   if (DoBothBroadcast())
9900     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9901                                                       DAG);
9902
9903   // If the inputs all stem from a single 128-bit lane of each input, then we
9904   // split them rather than blending because the split will decompose to
9905   // unusually few instructions.
9906   int LaneCount = VT.getSizeInBits() / 128;
9907   int LaneSize = Size / LaneCount;
9908   SmallBitVector LaneInputs[2];
9909   LaneInputs[0].resize(LaneCount, false);
9910   LaneInputs[1].resize(LaneCount, false);
9911   for (int i = 0; i < Size; ++i)
9912     if (Mask[i] >= 0)
9913       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9914   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9915     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9916
9917   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9918   // that the decomposed single-input shuffles don't end up here.
9919   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9920 }
9921
9922 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9923 /// a permutation and blend of those lanes.
9924 ///
9925 /// This essentially blends the out-of-lane inputs to each lane into the lane
9926 /// from a permuted copy of the vector. This lowering strategy results in four
9927 /// instructions in the worst case for a single-input cross lane shuffle which
9928 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9929 /// of. Special cases for each particular shuffle pattern should be handled
9930 /// prior to trying this lowering.
9931 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9932                                                        SDValue V1, SDValue V2,
9933                                                        ArrayRef<int> Mask,
9934                                                        SelectionDAG &DAG) {
9935   // FIXME: This should probably be generalized for 512-bit vectors as well.
9936   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9937   int LaneSize = Mask.size() / 2;
9938
9939   // If there are only inputs from one 128-bit lane, splitting will in fact be
9940   // less expensive. The flags track wether the given lane contains an element
9941   // that crosses to another lane.
9942   bool LaneCrossing[2] = {false, false};
9943   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9944     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9945       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9946   if (!LaneCrossing[0] || !LaneCrossing[1])
9947     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9948
9949   if (isSingleInputShuffleMask(Mask)) {
9950     SmallVector<int, 32> FlippedBlendMask;
9951     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9952       FlippedBlendMask.push_back(
9953           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9954                                   ? Mask[i]
9955                                   : Mask[i] % LaneSize +
9956                                         (i / LaneSize) * LaneSize + Size));
9957
9958     // Flip the vector, and blend the results which should now be in-lane. The
9959     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9960     // 5 for the high source. The value 3 selects the high half of source 2 and
9961     // the value 2 selects the low half of source 2. We only use source 2 to
9962     // allow folding it into a memory operand.
9963     unsigned PERMMask = 3 | 2 << 4;
9964     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9965                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9966     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9967   }
9968
9969   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9970   // will be handled by the above logic and a blend of the results, much like
9971   // other patterns in AVX.
9972   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9973 }
9974
9975 /// \brief Handle lowering 2-lane 128-bit shuffles.
9976 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9977                                         SDValue V2, ArrayRef<int> Mask,
9978                                         const X86Subtarget *Subtarget,
9979                                         SelectionDAG &DAG) {
9980   // Blends are faster and handle all the non-lane-crossing cases.
9981   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9982                                                 Subtarget, DAG))
9983     return Blend;
9984
9985   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9986                                VT.getVectorNumElements() / 2);
9987   // Check for patterns which can be matched with a single insert of a 128-bit
9988   // subvector.
9989   if (isShuffleEquivalent(Mask, 0, 1, 0, 1) ||
9990       isShuffleEquivalent(Mask, 0, 1, 4, 5)) {
9991     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9992                               DAG.getIntPtrConstant(0));
9993     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9994                               Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
9995     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9996   }
9997   if (isShuffleEquivalent(Mask, 0, 1, 6, 7)) {
9998     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9999                               DAG.getIntPtrConstant(0));
10000     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
10001                               DAG.getIntPtrConstant(2));
10002     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10003   }
10004
10005   // Otherwise form a 128-bit permutation.
10006   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
10007   unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
10008   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10009                      DAG.getConstant(PermMask, MVT::i8));
10010 }
10011
10012 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10013 /// shuffling each lane.
10014 ///
10015 /// This will only succeed when the result of fixing the 128-bit lanes results
10016 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10017 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10018 /// the lane crosses early and then use simpler shuffles within each lane.
10019 ///
10020 /// FIXME: It might be worthwhile at some point to support this without
10021 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10022 /// in x86 only floating point has interesting non-repeating shuffles, and even
10023 /// those are still *marginally* more expensive.
10024 static SDValue lowerVectorShuffleByMerging128BitLanes(
10025     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10026     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10027   assert(!isSingleInputShuffleMask(Mask) &&
10028          "This is only useful with multiple inputs.");
10029
10030   int Size = Mask.size();
10031   int LaneSize = 128 / VT.getScalarSizeInBits();
10032   int NumLanes = Size / LaneSize;
10033   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10034
10035   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10036   // check whether the in-128-bit lane shuffles share a repeating pattern.
10037   SmallVector<int, 4> Lanes;
10038   Lanes.resize(NumLanes, -1);
10039   SmallVector<int, 4> InLaneMask;
10040   InLaneMask.resize(LaneSize, -1);
10041   for (int i = 0; i < Size; ++i) {
10042     if (Mask[i] < 0)
10043       continue;
10044
10045     int j = i / LaneSize;
10046
10047     if (Lanes[j] < 0) {
10048       // First entry we've seen for this lane.
10049       Lanes[j] = Mask[i] / LaneSize;
10050     } else if (Lanes[j] != Mask[i] / LaneSize) {
10051       // This doesn't match the lane selected previously!
10052       return SDValue();
10053     }
10054
10055     // Check that within each lane we have a consistent shuffle mask.
10056     int k = i % LaneSize;
10057     if (InLaneMask[k] < 0) {
10058       InLaneMask[k] = Mask[i] % LaneSize;
10059     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10060       // This doesn't fit a repeating in-lane mask.
10061       return SDValue();
10062     }
10063   }
10064
10065   // First shuffle the lanes into place.
10066   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10067                                 VT.getSizeInBits() / 64);
10068   SmallVector<int, 8> LaneMask;
10069   LaneMask.resize(NumLanes * 2, -1);
10070   for (int i = 0; i < NumLanes; ++i)
10071     if (Lanes[i] >= 0) {
10072       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10073       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10074     }
10075
10076   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
10077   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
10078   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10079
10080   // Cast it back to the type we actually want.
10081   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
10082
10083   // Now do a simple shuffle that isn't lane crossing.
10084   SmallVector<int, 8> NewMask;
10085   NewMask.resize(Size, -1);
10086   for (int i = 0; i < Size; ++i)
10087     if (Mask[i] >= 0)
10088       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10089   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10090          "Must not introduce lane crosses at this point!");
10091
10092   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10093 }
10094
10095 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10096 /// given mask.
10097 ///
10098 /// This returns true if the elements from a particular input are already in the
10099 /// slot required by the given mask and require no permutation.
10100 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10101   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10102   int Size = Mask.size();
10103   for (int i = 0; i < Size; ++i)
10104     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10105       return false;
10106
10107   return true;
10108 }
10109
10110 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10111 ///
10112 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10113 /// isn't available.
10114 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10115                                        const X86Subtarget *Subtarget,
10116                                        SelectionDAG &DAG) {
10117   SDLoc DL(Op);
10118   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10119   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10120   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10121   ArrayRef<int> Mask = SVOp->getMask();
10122   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10123
10124   SmallVector<int, 4> WidenedMask;
10125   if (canWidenShuffleElements(Mask, WidenedMask))
10126     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10127                                     DAG);
10128
10129   if (isSingleInputShuffleMask(Mask)) {
10130     // Check for being able to broadcast a single element.
10131     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f64, DL, V1,
10132                                                           Mask, Subtarget, DAG))
10133       return Broadcast;
10134
10135     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10136       // Non-half-crossing single input shuffles can be lowerid with an
10137       // interleaved permutation.
10138       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10139                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10140       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10141                          DAG.getConstant(VPERMILPMask, MVT::i8));
10142     }
10143
10144     // With AVX2 we have direct support for this permutation.
10145     if (Subtarget->hasAVX2())
10146       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10147                          getV4X86ShuffleImm8ForMask(Mask, DAG));
10148
10149     // Otherwise, fall back.
10150     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10151                                                    DAG);
10152   }
10153
10154   // X86 has dedicated unpack instructions that can handle specific blend
10155   // operations: UNPCKH and UNPCKL.
10156   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10157     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10158   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10159     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10160
10161   // If we have a single input to the zero element, insert that into V1 if we
10162   // can do so cheaply.
10163   int NumV2Elements =
10164       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
10165   if (NumV2Elements == 1 && Mask[0] >= 4)
10166     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10167             MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
10168       return Insertion;
10169
10170   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10171                                                 Subtarget, DAG))
10172     return Blend;
10173
10174   // Check if the blend happens to exactly fit that of SHUFPD.
10175   if ((Mask[0] == -1 || Mask[0] < 2) &&
10176       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
10177       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
10178       (Mask[3] == -1 || Mask[3] >= 6)) {
10179     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
10180                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
10181     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
10182                        DAG.getConstant(SHUFPDMask, MVT::i8));
10183   }
10184   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
10185       (Mask[1] == -1 || Mask[1] < 2) &&
10186       (Mask[2] == -1 || Mask[2] >= 6) &&
10187       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
10188     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
10189                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
10190     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
10191                        DAG.getConstant(SHUFPDMask, MVT::i8));
10192   }
10193
10194   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10195   // shuffle. However, if we have AVX2 and either inputs are already in place,
10196   // we will be able to shuffle even across lanes the other input in a single
10197   // instruction so skip this pattern.
10198   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10199                                  isShuffleMaskInputInPlace(1, Mask))))
10200     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10201             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10202       return Result;
10203
10204   // If we have AVX2 then we always want to lower with a blend because an v4 we
10205   // can fully permute the elements.
10206   if (Subtarget->hasAVX2())
10207     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10208                                                       Mask, DAG);
10209
10210   // Otherwise fall back on generic lowering.
10211   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10212 }
10213
10214 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10215 ///
10216 /// This routine is only called when we have AVX2 and thus a reasonable
10217 /// instruction set for v4i64 shuffling..
10218 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10219                                        const X86Subtarget *Subtarget,
10220                                        SelectionDAG &DAG) {
10221   SDLoc DL(Op);
10222   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10223   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10224   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10225   ArrayRef<int> Mask = SVOp->getMask();
10226   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10227   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10228
10229   SmallVector<int, 4> WidenedMask;
10230   if (canWidenShuffleElements(Mask, WidenedMask))
10231     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10232                                     DAG);
10233
10234   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10235                                                 Subtarget, DAG))
10236     return Blend;
10237
10238   // Check for being able to broadcast a single element.
10239   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i64, DL, V1,
10240                                                         Mask, Subtarget, DAG))
10241     return Broadcast;
10242
10243   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10244   // use lower latency instructions that will operate on both 128-bit lanes.
10245   SmallVector<int, 2> RepeatedMask;
10246   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10247     if (isSingleInputShuffleMask(Mask)) {
10248       int PSHUFDMask[] = {-1, -1, -1, -1};
10249       for (int i = 0; i < 2; ++i)
10250         if (RepeatedMask[i] >= 0) {
10251           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10252           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10253         }
10254       return DAG.getNode(
10255           ISD::BITCAST, DL, MVT::v4i64,
10256           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10257                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
10258                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
10259     }
10260
10261     // Use dedicated unpack instructions for masks that match their pattern.
10262     if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10263       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10264     if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10265       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10266   }
10267
10268   // AVX2 provides a direct instruction for permuting a single input across
10269   // lanes.
10270   if (isSingleInputShuffleMask(Mask))
10271     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10272                        getV4X86ShuffleImm8ForMask(Mask, DAG));
10273
10274   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10275   // shuffle. However, if we have AVX2 and either inputs are already in place,
10276   // we will be able to shuffle even across lanes the other input in a single
10277   // instruction so skip this pattern.
10278   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10279                                  isShuffleMaskInputInPlace(1, Mask))))
10280     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10281             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10282       return Result;
10283
10284   // Otherwise fall back on generic blend lowering.
10285   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10286                                                     Mask, DAG);
10287 }
10288
10289 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10290 ///
10291 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10292 /// isn't available.
10293 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10294                                        const X86Subtarget *Subtarget,
10295                                        SelectionDAG &DAG) {
10296   SDLoc DL(Op);
10297   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10298   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10299   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10300   ArrayRef<int> Mask = SVOp->getMask();
10301   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10302
10303   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10304                                                 Subtarget, DAG))
10305     return Blend;
10306
10307   // Check for being able to broadcast a single element.
10308   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8f32, DL, V1,
10309                                                         Mask, Subtarget, DAG))
10310     return Broadcast;
10311
10312   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10313   // options to efficiently lower the shuffle.
10314   SmallVector<int, 4> RepeatedMask;
10315   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10316     assert(RepeatedMask.size() == 4 &&
10317            "Repeated masks must be half the mask width!");
10318     if (isSingleInputShuffleMask(Mask))
10319       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10320                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10321
10322     // Use dedicated unpack instructions for masks that match their pattern.
10323     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10324       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10325     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10326       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10327
10328     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10329     // have already handled any direct blends. We also need to squash the
10330     // repeated mask into a simulated v4f32 mask.
10331     for (int i = 0; i < 4; ++i)
10332       if (RepeatedMask[i] >= 8)
10333         RepeatedMask[i] -= 4;
10334     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10335   }
10336
10337   // If we have a single input shuffle with different shuffle patterns in the
10338   // two 128-bit lanes use the variable mask to VPERMILPS.
10339   if (isSingleInputShuffleMask(Mask)) {
10340     SDValue VPermMask[8];
10341     for (int i = 0; i < 8; ++i)
10342       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10343                                  : DAG.getConstant(Mask[i], MVT::i32);
10344     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10345       return DAG.getNode(
10346           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10347           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10348
10349     if (Subtarget->hasAVX2())
10350       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
10351                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
10352                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
10353                                                  MVT::v8i32, VPermMask)),
10354                          V1);
10355
10356     // Otherwise, fall back.
10357     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10358                                                    DAG);
10359   }
10360
10361   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10362   // shuffle.
10363   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10364           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10365     return Result;
10366
10367   // If we have AVX2 then we always want to lower with a blend because at v8 we
10368   // can fully permute the elements.
10369   if (Subtarget->hasAVX2())
10370     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10371                                                       Mask, DAG);
10372
10373   // Otherwise fall back on generic lowering.
10374   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10375 }
10376
10377 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10378 ///
10379 /// This routine is only called when we have AVX2 and thus a reasonable
10380 /// instruction set for v8i32 shuffling..
10381 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10382                                        const X86Subtarget *Subtarget,
10383                                        SelectionDAG &DAG) {
10384   SDLoc DL(Op);
10385   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10386   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10387   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10388   ArrayRef<int> Mask = SVOp->getMask();
10389   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10390   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10391
10392   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10393                                                 Subtarget, DAG))
10394     return Blend;
10395
10396   // Check for being able to broadcast a single element.
10397   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i32, DL, V1,
10398                                                         Mask, Subtarget, DAG))
10399     return Broadcast;
10400
10401   // If the shuffle mask is repeated in each 128-bit lane we can use more
10402   // efficient instructions that mirror the shuffles across the two 128-bit
10403   // lanes.
10404   SmallVector<int, 4> RepeatedMask;
10405   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10406     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10407     if (isSingleInputShuffleMask(Mask))
10408       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10409                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10410
10411     // Use dedicated unpack instructions for masks that match their pattern.
10412     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10413       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10414     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10415       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10416   }
10417
10418   // If the shuffle patterns aren't repeated but it is a single input, directly
10419   // generate a cross-lane VPERMD instruction.
10420   if (isSingleInputShuffleMask(Mask)) {
10421     SDValue VPermMask[8];
10422     for (int i = 0; i < 8; ++i)
10423       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10424                                  : DAG.getConstant(Mask[i], MVT::i32);
10425     return DAG.getNode(
10426         X86ISD::VPERMV, DL, MVT::v8i32,
10427         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10428   }
10429
10430   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10431   // shuffle.
10432   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10433           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10434     return Result;
10435
10436   // Otherwise fall back on generic blend lowering.
10437   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10438                                                     Mask, DAG);
10439 }
10440
10441 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10442 ///
10443 /// This routine is only called when we have AVX2 and thus a reasonable
10444 /// instruction set for v16i16 shuffling..
10445 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10446                                         const X86Subtarget *Subtarget,
10447                                         SelectionDAG &DAG) {
10448   SDLoc DL(Op);
10449   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10450   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10451   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10452   ArrayRef<int> Mask = SVOp->getMask();
10453   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10454   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10455
10456   // Check for being able to broadcast a single element.
10457   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i16, DL, V1,
10458                                                         Mask, Subtarget, DAG))
10459     return Broadcast;
10460
10461   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10462                                                 Subtarget, DAG))
10463     return Blend;
10464
10465   // Use dedicated unpack instructions for masks that match their pattern.
10466   if (isShuffleEquivalent(Mask,
10467                           // First 128-bit lane:
10468                           0, 16, 1, 17, 2, 18, 3, 19,
10469                           // Second 128-bit lane:
10470                           8, 24, 9, 25, 10, 26, 11, 27))
10471     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10472   if (isShuffleEquivalent(Mask,
10473                           // First 128-bit lane:
10474                           4, 20, 5, 21, 6, 22, 7, 23,
10475                           // Second 128-bit lane:
10476                           12, 28, 13, 29, 14, 30, 15, 31))
10477     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10478
10479   if (isSingleInputShuffleMask(Mask)) {
10480     // There are no generalized cross-lane shuffle operations available on i16
10481     // element types.
10482     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10483       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10484                                                      Mask, DAG);
10485
10486     SDValue PSHUFBMask[32];
10487     for (int i = 0; i < 16; ++i) {
10488       if (Mask[i] == -1) {
10489         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10490         continue;
10491       }
10492
10493       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10494       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10495       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
10496       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
10497     }
10498     return DAG.getNode(
10499         ISD::BITCAST, DL, MVT::v16i16,
10500         DAG.getNode(
10501             X86ISD::PSHUFB, DL, MVT::v32i8,
10502             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
10503             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
10504   }
10505
10506   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10507   // shuffle.
10508   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10509           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10510     return Result;
10511
10512   // Otherwise fall back on generic lowering.
10513   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10514 }
10515
10516 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10517 ///
10518 /// This routine is only called when we have AVX2 and thus a reasonable
10519 /// instruction set for v32i8 shuffling..
10520 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10521                                        const X86Subtarget *Subtarget,
10522                                        SelectionDAG &DAG) {
10523   SDLoc DL(Op);
10524   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10525   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10526   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10527   ArrayRef<int> Mask = SVOp->getMask();
10528   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10529   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10530
10531   // Check for being able to broadcast a single element.
10532   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v32i8, DL, V1,
10533                                                         Mask, Subtarget, DAG))
10534     return Broadcast;
10535
10536   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10537                                                 Subtarget, DAG))
10538     return Blend;
10539
10540   // Use dedicated unpack instructions for masks that match their pattern.
10541   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10542   // 256-bit lanes.
10543   if (isShuffleEquivalent(
10544           Mask,
10545           // First 128-bit lane:
10546           0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10547           // Second 128-bit lane:
10548           16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55))
10549     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10550   if (isShuffleEquivalent(
10551           Mask,
10552           // First 128-bit lane:
10553           8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10554           // Second 128-bit lane:
10555           24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63))
10556     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10557
10558   if (isSingleInputShuffleMask(Mask)) {
10559     // There are no generalized cross-lane shuffle operations available on i8
10560     // element types.
10561     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10562       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10563                                                      Mask, DAG);
10564
10565     SDValue PSHUFBMask[32];
10566     for (int i = 0; i < 32; ++i)
10567       PSHUFBMask[i] =
10568           Mask[i] < 0
10569               ? DAG.getUNDEF(MVT::i8)
10570               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
10571
10572     return DAG.getNode(
10573         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10574         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10575   }
10576
10577   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10578   // shuffle.
10579   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10580           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10581     return Result;
10582
10583   // Otherwise fall back on generic lowering.
10584   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10585 }
10586
10587 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10588 ///
10589 /// This routine either breaks down the specific type of a 256-bit x86 vector
10590 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10591 /// together based on the available instructions.
10592 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10593                                         MVT VT, const X86Subtarget *Subtarget,
10594                                         SelectionDAG &DAG) {
10595   SDLoc DL(Op);
10596   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10597   ArrayRef<int> Mask = SVOp->getMask();
10598
10599   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10600   // check for those subtargets here and avoid much of the subtarget querying in
10601   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10602   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10603   // floating point types there eventually, just immediately cast everything to
10604   // a float and operate entirely in that domain.
10605   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10606     int ElementBits = VT.getScalarSizeInBits();
10607     if (ElementBits < 32)
10608       // No floating point type available, decompose into 128-bit vectors.
10609       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10610
10611     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10612                                 VT.getVectorNumElements());
10613     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10614     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10615     return DAG.getNode(ISD::BITCAST, DL, VT,
10616                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10617   }
10618
10619   switch (VT.SimpleTy) {
10620   case MVT::v4f64:
10621     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10622   case MVT::v4i64:
10623     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10624   case MVT::v8f32:
10625     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10626   case MVT::v8i32:
10627     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10628   case MVT::v16i16:
10629     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10630   case MVT::v32i8:
10631     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10632
10633   default:
10634     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10635   }
10636 }
10637
10638 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10639 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10640                                        const X86Subtarget *Subtarget,
10641                                        SelectionDAG &DAG) {
10642   SDLoc DL(Op);
10643   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10644   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10645   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10646   ArrayRef<int> Mask = SVOp->getMask();
10647   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10648
10649   // FIXME: Implement direct support for this type!
10650   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10651 }
10652
10653 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10654 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10655                                        const X86Subtarget *Subtarget,
10656                                        SelectionDAG &DAG) {
10657   SDLoc DL(Op);
10658   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10659   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10660   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10661   ArrayRef<int> Mask = SVOp->getMask();
10662   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10663
10664   // FIXME: Implement direct support for this type!
10665   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10666 }
10667
10668 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10669 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10670                                        const X86Subtarget *Subtarget,
10671                                        SelectionDAG &DAG) {
10672   SDLoc DL(Op);
10673   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10674   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10675   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10676   ArrayRef<int> Mask = SVOp->getMask();
10677   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10678
10679   // FIXME: Implement direct support for this type!
10680   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10681 }
10682
10683 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10684 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10685                                        const X86Subtarget *Subtarget,
10686                                        SelectionDAG &DAG) {
10687   SDLoc DL(Op);
10688   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10689   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10690   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10691   ArrayRef<int> Mask = SVOp->getMask();
10692   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10693
10694   // FIXME: Implement direct support for this type!
10695   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10696 }
10697
10698 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10699 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10700                                         const X86Subtarget *Subtarget,
10701                                         SelectionDAG &DAG) {
10702   SDLoc DL(Op);
10703   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10704   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10705   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10706   ArrayRef<int> Mask = SVOp->getMask();
10707   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10708   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10709
10710   // FIXME: Implement direct support for this type!
10711   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10712 }
10713
10714 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10715 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10716                                        const X86Subtarget *Subtarget,
10717                                        SelectionDAG &DAG) {
10718   SDLoc DL(Op);
10719   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10720   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10721   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10722   ArrayRef<int> Mask = SVOp->getMask();
10723   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10724   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10725
10726   // FIXME: Implement direct support for this type!
10727   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10728 }
10729
10730 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10731 ///
10732 /// This routine either breaks down the specific type of a 512-bit x86 vector
10733 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10734 /// together based on the available instructions.
10735 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10736                                         MVT VT, const X86Subtarget *Subtarget,
10737                                         SelectionDAG &DAG) {
10738   SDLoc DL(Op);
10739   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10740   ArrayRef<int> Mask = SVOp->getMask();
10741   assert(Subtarget->hasAVX512() &&
10742          "Cannot lower 512-bit vectors w/ basic ISA!");
10743
10744   // Check for being able to broadcast a single element.
10745   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(VT.SimpleTy, DL, V1,
10746                                                         Mask, Subtarget, DAG))
10747     return Broadcast;
10748
10749   // Dispatch to each element type for lowering. If we don't have supprot for
10750   // specific element type shuffles at 512 bits, immediately split them and
10751   // lower them. Each lowering routine of a given type is allowed to assume that
10752   // the requisite ISA extensions for that element type are available.
10753   switch (VT.SimpleTy) {
10754   case MVT::v8f64:
10755     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10756   case MVT::v16f32:
10757     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10758   case MVT::v8i64:
10759     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10760   case MVT::v16i32:
10761     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10762   case MVT::v32i16:
10763     if (Subtarget->hasBWI())
10764       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10765     break;
10766   case MVT::v64i8:
10767     if (Subtarget->hasBWI())
10768       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10769     break;
10770
10771   default:
10772     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10773   }
10774
10775   // Otherwise fall back on splitting.
10776   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10777 }
10778
10779 /// \brief Top-level lowering for x86 vector shuffles.
10780 ///
10781 /// This handles decomposition, canonicalization, and lowering of all x86
10782 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10783 /// above in helper routines. The canonicalization attempts to widen shuffles
10784 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10785 /// s.t. only one of the two inputs needs to be tested, etc.
10786 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10787                                   SelectionDAG &DAG) {
10788   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10789   ArrayRef<int> Mask = SVOp->getMask();
10790   SDValue V1 = Op.getOperand(0);
10791   SDValue V2 = Op.getOperand(1);
10792   MVT VT = Op.getSimpleValueType();
10793   int NumElements = VT.getVectorNumElements();
10794   SDLoc dl(Op);
10795
10796   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10797
10798   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10799   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10800   if (V1IsUndef && V2IsUndef)
10801     return DAG.getUNDEF(VT);
10802
10803   // When we create a shuffle node we put the UNDEF node to second operand,
10804   // but in some cases the first operand may be transformed to UNDEF.
10805   // In this case we should just commute the node.
10806   if (V1IsUndef)
10807     return DAG.getCommutedVectorShuffle(*SVOp);
10808
10809   // Check for non-undef masks pointing at an undef vector and make the masks
10810   // undef as well. This makes it easier to match the shuffle based solely on
10811   // the mask.
10812   if (V2IsUndef)
10813     for (int M : Mask)
10814       if (M >= NumElements) {
10815         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10816         for (int &M : NewMask)
10817           if (M >= NumElements)
10818             M = -1;
10819         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10820       }
10821
10822   // Try to collapse shuffles into using a vector type with fewer elements but
10823   // wider element types. We cap this to not form integers or floating point
10824   // elements wider than 64 bits, but it might be interesting to form i128
10825   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10826   SmallVector<int, 16> WidenedMask;
10827   if (VT.getScalarSizeInBits() < 64 &&
10828       canWidenShuffleElements(Mask, WidenedMask)) {
10829     MVT NewEltVT = VT.isFloatingPoint()
10830                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10831                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10832     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10833     // Make sure that the new vector type is legal. For example, v2f64 isn't
10834     // legal on SSE1.
10835     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10836       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10837       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10838       return DAG.getNode(ISD::BITCAST, dl, VT,
10839                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10840     }
10841   }
10842
10843   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10844   for (int M : SVOp->getMask())
10845     if (M < 0)
10846       ++NumUndefElements;
10847     else if (M < NumElements)
10848       ++NumV1Elements;
10849     else
10850       ++NumV2Elements;
10851
10852   // Commute the shuffle as needed such that more elements come from V1 than
10853   // V2. This allows us to match the shuffle pattern strictly on how many
10854   // elements come from V1 without handling the symmetric cases.
10855   if (NumV2Elements > NumV1Elements)
10856     return DAG.getCommutedVectorShuffle(*SVOp);
10857
10858   // When the number of V1 and V2 elements are the same, try to minimize the
10859   // number of uses of V2 in the low half of the vector. When that is tied,
10860   // ensure that the sum of indices for V1 is equal to or lower than the sum
10861   // indices for V2. When those are equal, try to ensure that the number of odd
10862   // indices for V1 is lower than the number of odd indices for V2.
10863   if (NumV1Elements == NumV2Elements) {
10864     int LowV1Elements = 0, LowV2Elements = 0;
10865     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10866       if (M >= NumElements)
10867         ++LowV2Elements;
10868       else if (M >= 0)
10869         ++LowV1Elements;
10870     if (LowV2Elements > LowV1Elements) {
10871       return DAG.getCommutedVectorShuffle(*SVOp);
10872     } else if (LowV2Elements == LowV1Elements) {
10873       int SumV1Indices = 0, SumV2Indices = 0;
10874       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10875         if (SVOp->getMask()[i] >= NumElements)
10876           SumV2Indices += i;
10877         else if (SVOp->getMask()[i] >= 0)
10878           SumV1Indices += i;
10879       if (SumV2Indices < SumV1Indices) {
10880         return DAG.getCommutedVectorShuffle(*SVOp);
10881       } else if (SumV2Indices == SumV1Indices) {
10882         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10883         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10884           if (SVOp->getMask()[i] >= NumElements)
10885             NumV2OddIndices += i % 2;
10886           else if (SVOp->getMask()[i] >= 0)
10887             NumV1OddIndices += i % 2;
10888         if (NumV2OddIndices < NumV1OddIndices)
10889           return DAG.getCommutedVectorShuffle(*SVOp);
10890       }
10891     }
10892   }
10893
10894   // For each vector width, delegate to a specialized lowering routine.
10895   if (VT.getSizeInBits() == 128)
10896     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10897
10898   if (VT.getSizeInBits() == 256)
10899     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10900
10901   // Force AVX-512 vectors to be scalarized for now.
10902   // FIXME: Implement AVX-512 support!
10903   if (VT.getSizeInBits() == 512)
10904     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10905
10906   llvm_unreachable("Unimplemented!");
10907 }
10908
10909
10910 //===----------------------------------------------------------------------===//
10911 // Legacy vector shuffle lowering
10912 //
10913 // This code is the legacy code handling vector shuffles until the above
10914 // replaces its functionality and performance.
10915 //===----------------------------------------------------------------------===//
10916
10917 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
10918                         bool hasInt256, unsigned *MaskOut = nullptr) {
10919   MVT EltVT = VT.getVectorElementType();
10920
10921   // There is no blend with immediate in AVX-512.
10922   if (VT.is512BitVector())
10923     return false;
10924
10925   if (!hasSSE41 || EltVT == MVT::i8)
10926     return false;
10927   if (!hasInt256 && VT == MVT::v16i16)
10928     return false;
10929
10930   unsigned MaskValue = 0;
10931   unsigned NumElems = VT.getVectorNumElements();
10932   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10933   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10934   unsigned NumElemsInLane = NumElems / NumLanes;
10935
10936   // Blend for v16i16 should be symetric for the both lanes.
10937   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10938
10939     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
10940     int EltIdx = MaskVals[i];
10941
10942     if ((EltIdx < 0 || EltIdx == (int)i) &&
10943         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
10944       continue;
10945
10946     if (((unsigned)EltIdx == (i + NumElems)) &&
10947         (SndLaneEltIdx < 0 ||
10948          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
10949       MaskValue |= (1 << i);
10950     else
10951       return false;
10952   }
10953
10954   if (MaskOut)
10955     *MaskOut = MaskValue;
10956   return true;
10957 }
10958
10959 // Try to lower a shuffle node into a simple blend instruction.
10960 // This function assumes isBlendMask returns true for this
10961 // SuffleVectorSDNode
10962 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
10963                                           unsigned MaskValue,
10964                                           const X86Subtarget *Subtarget,
10965                                           SelectionDAG &DAG) {
10966   MVT VT = SVOp->getSimpleValueType(0);
10967   MVT EltVT = VT.getVectorElementType();
10968   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
10969                      Subtarget->hasInt256() && "Trying to lower a "
10970                                                "VECTOR_SHUFFLE to a Blend but "
10971                                                "with the wrong mask"));
10972   SDValue V1 = SVOp->getOperand(0);
10973   SDValue V2 = SVOp->getOperand(1);
10974   SDLoc dl(SVOp);
10975   unsigned NumElems = VT.getVectorNumElements();
10976
10977   // Convert i32 vectors to floating point if it is not AVX2.
10978   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10979   MVT BlendVT = VT;
10980   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10981     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10982                                NumElems);
10983     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
10984     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
10985   }
10986
10987   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
10988                             DAG.getConstant(MaskValue, MVT::i32));
10989   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10990 }
10991
10992 /// In vector type \p VT, return true if the element at index \p InputIdx
10993 /// falls on a different 128-bit lane than \p OutputIdx.
10994 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
10995                                      unsigned OutputIdx) {
10996   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
10997   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
10998 }
10999
11000 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
11001 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
11002 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
11003 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
11004 /// zero.
11005 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
11006                          SelectionDAG &DAG) {
11007   MVT VT = V1.getSimpleValueType();
11008   assert(VT.is128BitVector() || VT.is256BitVector());
11009
11010   MVT EltVT = VT.getVectorElementType();
11011   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
11012   unsigned NumElts = VT.getVectorNumElements();
11013
11014   SmallVector<SDValue, 32> PshufbMask;
11015   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
11016     int InputIdx = MaskVals[OutputIdx];
11017     unsigned InputByteIdx;
11018
11019     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
11020       InputByteIdx = 0x80;
11021     else {
11022       // Cross lane is not allowed.
11023       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
11024         return SDValue();
11025       InputByteIdx = InputIdx * EltSizeInBytes;
11026       // Index is an byte offset within the 128-bit lane.
11027       InputByteIdx &= 0xf;
11028     }
11029
11030     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
11031       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
11032       if (InputByteIdx != 0x80)
11033         ++InputByteIdx;
11034     }
11035   }
11036
11037   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
11038   if (ShufVT != VT)
11039     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
11040   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
11041                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
11042 }
11043
11044 // v8i16 shuffles - Prefer shuffles in the following order:
11045 // 1. [all]   pshuflw, pshufhw, optional move
11046 // 2. [ssse3] 1 x pshufb
11047 // 3. [ssse3] 2 x pshufb + 1 x por
11048 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
11049 static SDValue
11050 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
11051                          SelectionDAG &DAG) {
11052   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11053   SDValue V1 = SVOp->getOperand(0);
11054   SDValue V2 = SVOp->getOperand(1);
11055   SDLoc dl(SVOp);
11056   SmallVector<int, 8> MaskVals;
11057
11058   // Determine if more than 1 of the words in each of the low and high quadwords
11059   // of the result come from the same quadword of one of the two inputs.  Undef
11060   // mask values count as coming from any quadword, for better codegen.
11061   //
11062   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
11063   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
11064   unsigned LoQuad[] = { 0, 0, 0, 0 };
11065   unsigned HiQuad[] = { 0, 0, 0, 0 };
11066   // Indices of quads used.
11067   std::bitset<4> InputQuads;
11068   for (unsigned i = 0; i < 8; ++i) {
11069     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
11070     int EltIdx = SVOp->getMaskElt(i);
11071     MaskVals.push_back(EltIdx);
11072     if (EltIdx < 0) {
11073       ++Quad[0];
11074       ++Quad[1];
11075       ++Quad[2];
11076       ++Quad[3];
11077       continue;
11078     }
11079     ++Quad[EltIdx / 4];
11080     InputQuads.set(EltIdx / 4);
11081   }
11082
11083   int BestLoQuad = -1;
11084   unsigned MaxQuad = 1;
11085   for (unsigned i = 0; i < 4; ++i) {
11086     if (LoQuad[i] > MaxQuad) {
11087       BestLoQuad = i;
11088       MaxQuad = LoQuad[i];
11089     }
11090   }
11091
11092   int BestHiQuad = -1;
11093   MaxQuad = 1;
11094   for (unsigned i = 0; i < 4; ++i) {
11095     if (HiQuad[i] > MaxQuad) {
11096       BestHiQuad = i;
11097       MaxQuad = HiQuad[i];
11098     }
11099   }
11100
11101   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
11102   // of the two input vectors, shuffle them into one input vector so only a
11103   // single pshufb instruction is necessary. If there are more than 2 input
11104   // quads, disable the next transformation since it does not help SSSE3.
11105   bool V1Used = InputQuads[0] || InputQuads[1];
11106   bool V2Used = InputQuads[2] || InputQuads[3];
11107   if (Subtarget->hasSSSE3()) {
11108     if (InputQuads.count() == 2 && V1Used && V2Used) {
11109       BestLoQuad = InputQuads[0] ? 0 : 1;
11110       BestHiQuad = InputQuads[2] ? 2 : 3;
11111     }
11112     if (InputQuads.count() > 2) {
11113       BestLoQuad = -1;
11114       BestHiQuad = -1;
11115     }
11116   }
11117
11118   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
11119   // the shuffle mask.  If a quad is scored as -1, that means that it contains
11120   // words from all 4 input quadwords.
11121   SDValue NewV;
11122   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
11123     int MaskV[] = {
11124       BestLoQuad < 0 ? 0 : BestLoQuad,
11125       BestHiQuad < 0 ? 1 : BestHiQuad
11126     };
11127     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
11128                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
11129                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
11130     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
11131
11132     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
11133     // source words for the shuffle, to aid later transformations.
11134     bool AllWordsInNewV = true;
11135     bool InOrder[2] = { true, true };
11136     for (unsigned i = 0; i != 8; ++i) {
11137       int idx = MaskVals[i];
11138       if (idx != (int)i)
11139         InOrder[i/4] = false;
11140       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
11141         continue;
11142       AllWordsInNewV = false;
11143       break;
11144     }
11145
11146     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
11147     if (AllWordsInNewV) {
11148       for (int i = 0; i != 8; ++i) {
11149         int idx = MaskVals[i];
11150         if (idx < 0)
11151           continue;
11152         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
11153         if ((idx != i) && idx < 4)
11154           pshufhw = false;
11155         if ((idx != i) && idx > 3)
11156           pshuflw = false;
11157       }
11158       V1 = NewV;
11159       V2Used = false;
11160       BestLoQuad = 0;
11161       BestHiQuad = 1;
11162     }
11163
11164     // If we've eliminated the use of V2, and the new mask is a pshuflw or
11165     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
11166     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
11167       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
11168       unsigned TargetMask = 0;
11169       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
11170                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
11171       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11172       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
11173                              getShufflePSHUFLWImmediate(SVOp);
11174       V1 = NewV.getOperand(0);
11175       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
11176     }
11177   }
11178
11179   // Promote splats to a larger type which usually leads to more efficient code.
11180   // FIXME: Is this true if pshufb is available?
11181   if (SVOp->isSplat())
11182     return PromoteSplat(SVOp, DAG);
11183
11184   // If we have SSSE3, and all words of the result are from 1 input vector,
11185   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
11186   // is present, fall back to case 4.
11187   if (Subtarget->hasSSSE3()) {
11188     SmallVector<SDValue,16> pshufbMask;
11189
11190     // If we have elements from both input vectors, set the high bit of the
11191     // shuffle mask element to zero out elements that come from V2 in the V1
11192     // mask, and elements that come from V1 in the V2 mask, so that the two
11193     // results can be OR'd together.
11194     bool TwoInputs = V1Used && V2Used;
11195     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
11196     if (!TwoInputs)
11197       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11198
11199     // Calculate the shuffle mask for the second input, shuffle it, and
11200     // OR it with the first shuffled input.
11201     CommuteVectorShuffleMask(MaskVals, 8);
11202     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
11203     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11204     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11205   }
11206
11207   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
11208   // and update MaskVals with new element order.
11209   std::bitset<8> InOrder;
11210   if (BestLoQuad >= 0) {
11211     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
11212     for (int i = 0; i != 4; ++i) {
11213       int idx = MaskVals[i];
11214       if (idx < 0) {
11215         InOrder.set(i);
11216       } else if ((idx / 4) == BestLoQuad) {
11217         MaskV[i] = idx & 3;
11218         InOrder.set(i);
11219       }
11220     }
11221     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11222                                 &MaskV[0]);
11223
11224     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11225       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11226       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
11227                                   NewV.getOperand(0),
11228                                   getShufflePSHUFLWImmediate(SVOp), DAG);
11229     }
11230   }
11231
11232   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
11233   // and update MaskVals with the new element order.
11234   if (BestHiQuad >= 0) {
11235     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
11236     for (unsigned i = 4; i != 8; ++i) {
11237       int idx = MaskVals[i];
11238       if (idx < 0) {
11239         InOrder.set(i);
11240       } else if ((idx / 4) == BestHiQuad) {
11241         MaskV[i] = (idx & 3) + 4;
11242         InOrder.set(i);
11243       }
11244     }
11245     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11246                                 &MaskV[0]);
11247
11248     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11249       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11250       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
11251                                   NewV.getOperand(0),
11252                                   getShufflePSHUFHWImmediate(SVOp), DAG);
11253     }
11254   }
11255
11256   // In case BestHi & BestLo were both -1, which means each quadword has a word
11257   // from each of the four input quadwords, calculate the InOrder bitvector now
11258   // before falling through to the insert/extract cleanup.
11259   if (BestLoQuad == -1 && BestHiQuad == -1) {
11260     NewV = V1;
11261     for (int i = 0; i != 8; ++i)
11262       if (MaskVals[i] < 0 || MaskVals[i] == i)
11263         InOrder.set(i);
11264   }
11265
11266   // The other elements are put in the right place using pextrw and pinsrw.
11267   for (unsigned i = 0; i != 8; ++i) {
11268     if (InOrder[i])
11269       continue;
11270     int EltIdx = MaskVals[i];
11271     if (EltIdx < 0)
11272       continue;
11273     SDValue ExtOp = (EltIdx < 8) ?
11274       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
11275                   DAG.getIntPtrConstant(EltIdx)) :
11276       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
11277                   DAG.getIntPtrConstant(EltIdx - 8));
11278     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
11279                        DAG.getIntPtrConstant(i));
11280   }
11281   return NewV;
11282 }
11283
11284 /// \brief v16i16 shuffles
11285 ///
11286 /// FIXME: We only support generation of a single pshufb currently.  We can
11287 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
11288 /// well (e.g 2 x pshufb + 1 x por).
11289 static SDValue
11290 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
11291   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11292   SDValue V1 = SVOp->getOperand(0);
11293   SDValue V2 = SVOp->getOperand(1);
11294   SDLoc dl(SVOp);
11295
11296   if (V2.getOpcode() != ISD::UNDEF)
11297     return SDValue();
11298
11299   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11300   return getPSHUFB(MaskVals, V1, dl, DAG);
11301 }
11302
11303 // v16i8 shuffles - Prefer shuffles in the following order:
11304 // 1. [ssse3] 1 x pshufb
11305 // 2. [ssse3] 2 x pshufb + 1 x por
11306 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
11307 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
11308                                         const X86Subtarget* Subtarget,
11309                                         SelectionDAG &DAG) {
11310   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11311   SDValue V1 = SVOp->getOperand(0);
11312   SDValue V2 = SVOp->getOperand(1);
11313   SDLoc dl(SVOp);
11314   ArrayRef<int> MaskVals = SVOp->getMask();
11315
11316   // Promote splats to a larger type which usually leads to more efficient code.
11317   // FIXME: Is this true if pshufb is available?
11318   if (SVOp->isSplat())
11319     return PromoteSplat(SVOp, DAG);
11320
11321   // If we have SSSE3, case 1 is generated when all result bytes come from
11322   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
11323   // present, fall back to case 3.
11324
11325   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
11326   if (Subtarget->hasSSSE3()) {
11327     SmallVector<SDValue,16> pshufbMask;
11328
11329     // If all result elements are from one input vector, then only translate
11330     // undef mask values to 0x80 (zero out result) in the pshufb mask.
11331     //
11332     // Otherwise, we have elements from both input vectors, and must zero out
11333     // elements that come from V2 in the first mask, and V1 in the second mask
11334     // so that we can OR them together.
11335     for (unsigned i = 0; i != 16; ++i) {
11336       int EltIdx = MaskVals[i];
11337       if (EltIdx < 0 || EltIdx >= 16)
11338         EltIdx = 0x80;
11339       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11340     }
11341     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
11342                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11343                                  MVT::v16i8, pshufbMask));
11344
11345     // As PSHUFB will zero elements with negative indices, it's safe to ignore
11346     // the 2nd operand if it's undefined or zero.
11347     if (V2.getOpcode() == ISD::UNDEF ||
11348         ISD::isBuildVectorAllZeros(V2.getNode()))
11349       return V1;
11350
11351     // Calculate the shuffle mask for the second input, shuffle it, and
11352     // OR it with the first shuffled input.
11353     pshufbMask.clear();
11354     for (unsigned i = 0; i != 16; ++i) {
11355       int EltIdx = MaskVals[i];
11356       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
11357       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11358     }
11359     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
11360                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11361                                  MVT::v16i8, pshufbMask));
11362     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11363   }
11364
11365   // No SSSE3 - Calculate in place words and then fix all out of place words
11366   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
11367   // the 16 different words that comprise the two doublequadword input vectors.
11368   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11369   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
11370   SDValue NewV = V1;
11371   for (int i = 0; i != 8; ++i) {
11372     int Elt0 = MaskVals[i*2];
11373     int Elt1 = MaskVals[i*2+1];
11374
11375     // This word of the result is all undef, skip it.
11376     if (Elt0 < 0 && Elt1 < 0)
11377       continue;
11378
11379     // This word of the result is already in the correct place, skip it.
11380     if ((Elt0 == i*2) && (Elt1 == i*2+1))
11381       continue;
11382
11383     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
11384     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
11385     SDValue InsElt;
11386
11387     // If Elt0 and Elt1 are defined, are consecutive, and can be load
11388     // using a single extract together, load it and store it.
11389     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
11390       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11391                            DAG.getIntPtrConstant(Elt1 / 2));
11392       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11393                         DAG.getIntPtrConstant(i));
11394       continue;
11395     }
11396
11397     // If Elt1 is defined, extract it from the appropriate source.  If the
11398     // source byte is not also odd, shift the extracted word left 8 bits
11399     // otherwise clear the bottom 8 bits if we need to do an or.
11400     if (Elt1 >= 0) {
11401       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11402                            DAG.getIntPtrConstant(Elt1 / 2));
11403       if ((Elt1 & 1) == 0)
11404         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
11405                              DAG.getConstant(8,
11406                                   TLI.getShiftAmountTy(InsElt.getValueType())));
11407       else if (Elt0 >= 0)
11408         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
11409                              DAG.getConstant(0xFF00, MVT::i16));
11410     }
11411     // If Elt0 is defined, extract it from the appropriate source.  If the
11412     // source byte is not also even, shift the extracted word right 8 bits. If
11413     // Elt1 was also defined, OR the extracted values together before
11414     // inserting them in the result.
11415     if (Elt0 >= 0) {
11416       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
11417                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
11418       if ((Elt0 & 1) != 0)
11419         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
11420                               DAG.getConstant(8,
11421                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
11422       else if (Elt1 >= 0)
11423         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
11424                              DAG.getConstant(0x00FF, MVT::i16));
11425       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
11426                          : InsElt0;
11427     }
11428     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11429                        DAG.getIntPtrConstant(i));
11430   }
11431   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
11432 }
11433
11434 // v32i8 shuffles - Translate to VPSHUFB if possible.
11435 static
11436 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
11437                                  const X86Subtarget *Subtarget,
11438                                  SelectionDAG &DAG) {
11439   MVT VT = SVOp->getSimpleValueType(0);
11440   SDValue V1 = SVOp->getOperand(0);
11441   SDValue V2 = SVOp->getOperand(1);
11442   SDLoc dl(SVOp);
11443   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11444
11445   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11446   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
11447   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
11448
11449   // VPSHUFB may be generated if
11450   // (1) one of input vector is undefined or zeroinitializer.
11451   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
11452   // And (2) the mask indexes don't cross the 128-bit lane.
11453   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
11454       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
11455     return SDValue();
11456
11457   if (V1IsAllZero && !V2IsAllZero) {
11458     CommuteVectorShuffleMask(MaskVals, 32);
11459     V1 = V2;
11460   }
11461   return getPSHUFB(MaskVals, V1, dl, DAG);
11462 }
11463
11464 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
11465 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
11466 /// done when every pair / quad of shuffle mask elements point to elements in
11467 /// the right sequence. e.g.
11468 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
11469 static
11470 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
11471                                  SelectionDAG &DAG) {
11472   MVT VT = SVOp->getSimpleValueType(0);
11473   SDLoc dl(SVOp);
11474   unsigned NumElems = VT.getVectorNumElements();
11475   MVT NewVT;
11476   unsigned Scale;
11477   switch (VT.SimpleTy) {
11478   default: llvm_unreachable("Unexpected!");
11479   case MVT::v2i64:
11480   case MVT::v2f64:
11481            return SDValue(SVOp, 0);
11482   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
11483   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
11484   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
11485   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
11486   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
11487   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
11488   }
11489
11490   SmallVector<int, 8> MaskVec;
11491   for (unsigned i = 0; i != NumElems; i += Scale) {
11492     int StartIdx = -1;
11493     for (unsigned j = 0; j != Scale; ++j) {
11494       int EltIdx = SVOp->getMaskElt(i+j);
11495       if (EltIdx < 0)
11496         continue;
11497       if (StartIdx < 0)
11498         StartIdx = (EltIdx / Scale);
11499       if (EltIdx != (int)(StartIdx*Scale + j))
11500         return SDValue();
11501     }
11502     MaskVec.push_back(StartIdx);
11503   }
11504
11505   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
11506   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
11507   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
11508 }
11509
11510 /// getVZextMovL - Return a zero-extending vector move low node.
11511 ///
11512 static SDValue getVZextMovL(MVT VT, MVT OpVT,
11513                             SDValue SrcOp, SelectionDAG &DAG,
11514                             const X86Subtarget *Subtarget, SDLoc dl) {
11515   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
11516     LoadSDNode *LD = nullptr;
11517     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
11518       LD = dyn_cast<LoadSDNode>(SrcOp);
11519     if (!LD) {
11520       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
11521       // instead.
11522       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
11523       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
11524           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11525           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
11526           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
11527         // PR2108
11528         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
11529         return DAG.getNode(ISD::BITCAST, dl, VT,
11530                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11531                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11532                                                    OpVT,
11533                                                    SrcOp.getOperand(0)
11534                                                           .getOperand(0))));
11535       }
11536     }
11537   }
11538
11539   return DAG.getNode(ISD::BITCAST, dl, VT,
11540                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11541                                  DAG.getNode(ISD::BITCAST, dl,
11542                                              OpVT, SrcOp)));
11543 }
11544
11545 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
11546 /// which could not be matched by any known target speficic shuffle
11547 static SDValue
11548 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11549
11550   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
11551   if (NewOp.getNode())
11552     return NewOp;
11553
11554   MVT VT = SVOp->getSimpleValueType(0);
11555
11556   unsigned NumElems = VT.getVectorNumElements();
11557   unsigned NumLaneElems = NumElems / 2;
11558
11559   SDLoc dl(SVOp);
11560   MVT EltVT = VT.getVectorElementType();
11561   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
11562   SDValue Output[2];
11563
11564   SmallVector<int, 16> Mask;
11565   for (unsigned l = 0; l < 2; ++l) {
11566     // Build a shuffle mask for the output, discovering on the fly which
11567     // input vectors to use as shuffle operands (recorded in InputUsed).
11568     // If building a suitable shuffle vector proves too hard, then bail
11569     // out with UseBuildVector set.
11570     bool UseBuildVector = false;
11571     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
11572     unsigned LaneStart = l * NumLaneElems;
11573     for (unsigned i = 0; i != NumLaneElems; ++i) {
11574       // The mask element.  This indexes into the input.
11575       int Idx = SVOp->getMaskElt(i+LaneStart);
11576       if (Idx < 0) {
11577         // the mask element does not index into any input vector.
11578         Mask.push_back(-1);
11579         continue;
11580       }
11581
11582       // The input vector this mask element indexes into.
11583       int Input = Idx / NumLaneElems;
11584
11585       // Turn the index into an offset from the start of the input vector.
11586       Idx -= Input * NumLaneElems;
11587
11588       // Find or create a shuffle vector operand to hold this input.
11589       unsigned OpNo;
11590       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
11591         if (InputUsed[OpNo] == Input)
11592           // This input vector is already an operand.
11593           break;
11594         if (InputUsed[OpNo] < 0) {
11595           // Create a new operand for this input vector.
11596           InputUsed[OpNo] = Input;
11597           break;
11598         }
11599       }
11600
11601       if (OpNo >= array_lengthof(InputUsed)) {
11602         // More than two input vectors used!  Give up on trying to create a
11603         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
11604         UseBuildVector = true;
11605         break;
11606       }
11607
11608       // Add the mask index for the new shuffle vector.
11609       Mask.push_back(Idx + OpNo * NumLaneElems);
11610     }
11611
11612     if (UseBuildVector) {
11613       SmallVector<SDValue, 16> SVOps;
11614       for (unsigned i = 0; i != NumLaneElems; ++i) {
11615         // The mask element.  This indexes into the input.
11616         int Idx = SVOp->getMaskElt(i+LaneStart);
11617         if (Idx < 0) {
11618           SVOps.push_back(DAG.getUNDEF(EltVT));
11619           continue;
11620         }
11621
11622         // The input vector this mask element indexes into.
11623         int Input = Idx / NumElems;
11624
11625         // Turn the index into an offset from the start of the input vector.
11626         Idx -= Input * NumElems;
11627
11628         // Extract the vector element by hand.
11629         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
11630                                     SVOp->getOperand(Input),
11631                                     DAG.getIntPtrConstant(Idx)));
11632       }
11633
11634       // Construct the output using a BUILD_VECTOR.
11635       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
11636     } else if (InputUsed[0] < 0) {
11637       // No input vectors were used! The result is undefined.
11638       Output[l] = DAG.getUNDEF(NVT);
11639     } else {
11640       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
11641                                         (InputUsed[0] % 2) * NumLaneElems,
11642                                         DAG, dl);
11643       // If only one input was used, use an undefined vector for the other.
11644       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
11645         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
11646                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
11647       // At least one input vector was used. Create a new shuffle vector.
11648       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
11649     }
11650
11651     Mask.clear();
11652   }
11653
11654   // Concatenate the result back
11655   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
11656 }
11657
11658 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
11659 /// 4 elements, and match them with several different shuffle types.
11660 static SDValue
11661 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11662   SDValue V1 = SVOp->getOperand(0);
11663   SDValue V2 = SVOp->getOperand(1);
11664   SDLoc dl(SVOp);
11665   MVT VT = SVOp->getSimpleValueType(0);
11666
11667   assert(VT.is128BitVector() && "Unsupported vector size");
11668
11669   std::pair<int, int> Locs[4];
11670   int Mask1[] = { -1, -1, -1, -1 };
11671   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
11672
11673   unsigned NumHi = 0;
11674   unsigned NumLo = 0;
11675   for (unsigned i = 0; i != 4; ++i) {
11676     int Idx = PermMask[i];
11677     if (Idx < 0) {
11678       Locs[i] = std::make_pair(-1, -1);
11679     } else {
11680       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
11681       if (Idx < 4) {
11682         Locs[i] = std::make_pair(0, NumLo);
11683         Mask1[NumLo] = Idx;
11684         NumLo++;
11685       } else {
11686         Locs[i] = std::make_pair(1, NumHi);
11687         if (2+NumHi < 4)
11688           Mask1[2+NumHi] = Idx;
11689         NumHi++;
11690       }
11691     }
11692   }
11693
11694   if (NumLo <= 2 && NumHi <= 2) {
11695     // If no more than two elements come from either vector. This can be
11696     // implemented with two shuffles. First shuffle gather the elements.
11697     // The second shuffle, which takes the first shuffle as both of its
11698     // vector operands, put the elements into the right order.
11699     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11700
11701     int Mask2[] = { -1, -1, -1, -1 };
11702
11703     for (unsigned i = 0; i != 4; ++i)
11704       if (Locs[i].first != -1) {
11705         unsigned Idx = (i < 2) ? 0 : 4;
11706         Idx += Locs[i].first * 2 + Locs[i].second;
11707         Mask2[i] = Idx;
11708       }
11709
11710     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
11711   }
11712
11713   if (NumLo == 3 || NumHi == 3) {
11714     // Otherwise, we must have three elements from one vector, call it X, and
11715     // one element from the other, call it Y.  First, use a shufps to build an
11716     // intermediate vector with the one element from Y and the element from X
11717     // that will be in the same half in the final destination (the indexes don't
11718     // matter). Then, use a shufps to build the final vector, taking the half
11719     // containing the element from Y from the intermediate, and the other half
11720     // from X.
11721     if (NumHi == 3) {
11722       // Normalize it so the 3 elements come from V1.
11723       CommuteVectorShuffleMask(PermMask, 4);
11724       std::swap(V1, V2);
11725     }
11726
11727     // Find the element from V2.
11728     unsigned HiIndex;
11729     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
11730       int Val = PermMask[HiIndex];
11731       if (Val < 0)
11732         continue;
11733       if (Val >= 4)
11734         break;
11735     }
11736
11737     Mask1[0] = PermMask[HiIndex];
11738     Mask1[1] = -1;
11739     Mask1[2] = PermMask[HiIndex^1];
11740     Mask1[3] = -1;
11741     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11742
11743     if (HiIndex >= 2) {
11744       Mask1[0] = PermMask[0];
11745       Mask1[1] = PermMask[1];
11746       Mask1[2] = HiIndex & 1 ? 6 : 4;
11747       Mask1[3] = HiIndex & 1 ? 4 : 6;
11748       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11749     }
11750
11751     Mask1[0] = HiIndex & 1 ? 2 : 0;
11752     Mask1[1] = HiIndex & 1 ? 0 : 2;
11753     Mask1[2] = PermMask[2];
11754     Mask1[3] = PermMask[3];
11755     if (Mask1[2] >= 0)
11756       Mask1[2] += 4;
11757     if (Mask1[3] >= 0)
11758       Mask1[3] += 4;
11759     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
11760   }
11761
11762   // Break it into (shuffle shuffle_hi, shuffle_lo).
11763   int LoMask[] = { -1, -1, -1, -1 };
11764   int HiMask[] = { -1, -1, -1, -1 };
11765
11766   int *MaskPtr = LoMask;
11767   unsigned MaskIdx = 0;
11768   unsigned LoIdx = 0;
11769   unsigned HiIdx = 2;
11770   for (unsigned i = 0; i != 4; ++i) {
11771     if (i == 2) {
11772       MaskPtr = HiMask;
11773       MaskIdx = 1;
11774       LoIdx = 0;
11775       HiIdx = 2;
11776     }
11777     int Idx = PermMask[i];
11778     if (Idx < 0) {
11779       Locs[i] = std::make_pair(-1, -1);
11780     } else if (Idx < 4) {
11781       Locs[i] = std::make_pair(MaskIdx, LoIdx);
11782       MaskPtr[LoIdx] = Idx;
11783       LoIdx++;
11784     } else {
11785       Locs[i] = std::make_pair(MaskIdx, HiIdx);
11786       MaskPtr[HiIdx] = Idx;
11787       HiIdx++;
11788     }
11789   }
11790
11791   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
11792   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
11793   int MaskOps[] = { -1, -1, -1, -1 };
11794   for (unsigned i = 0; i != 4; ++i)
11795     if (Locs[i].first != -1)
11796       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
11797   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
11798 }
11799
11800 static bool MayFoldVectorLoad(SDValue V) {
11801   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
11802     V = V.getOperand(0);
11803
11804   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
11805     V = V.getOperand(0);
11806   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
11807       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
11808     // BUILD_VECTOR (load), undef
11809     V = V.getOperand(0);
11810
11811   return MayFoldLoad(V);
11812 }
11813
11814 static
11815 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
11816   MVT VT = Op.getSimpleValueType();
11817
11818   // Canonizalize to v2f64.
11819   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
11820   return DAG.getNode(ISD::BITCAST, dl, VT,
11821                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
11822                                           V1, DAG));
11823 }
11824
11825 static
11826 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
11827                         bool HasSSE2) {
11828   SDValue V1 = Op.getOperand(0);
11829   SDValue V2 = Op.getOperand(1);
11830   MVT VT = Op.getSimpleValueType();
11831
11832   assert(VT != MVT::v2i64 && "unsupported shuffle type");
11833
11834   if (HasSSE2 && VT == MVT::v2f64)
11835     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
11836
11837   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
11838   return DAG.getNode(ISD::BITCAST, dl, VT,
11839                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
11840                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
11841                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
11842 }
11843
11844 static
11845 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
11846   SDValue V1 = Op.getOperand(0);
11847   SDValue V2 = Op.getOperand(1);
11848   MVT VT = Op.getSimpleValueType();
11849
11850   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
11851          "unsupported shuffle type");
11852
11853   if (V2.getOpcode() == ISD::UNDEF)
11854     V2 = V1;
11855
11856   // v4i32 or v4f32
11857   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
11858 }
11859
11860 static
11861 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
11862   SDValue V1 = Op.getOperand(0);
11863   SDValue V2 = Op.getOperand(1);
11864   MVT VT = Op.getSimpleValueType();
11865   unsigned NumElems = VT.getVectorNumElements();
11866
11867   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
11868   // operand of these instructions is only memory, so check if there's a
11869   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
11870   // same masks.
11871   bool CanFoldLoad = false;
11872
11873   // Trivial case, when V2 comes from a load.
11874   if (MayFoldVectorLoad(V2))
11875     CanFoldLoad = true;
11876
11877   // When V1 is a load, it can be folded later into a store in isel, example:
11878   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
11879   //    turns into:
11880   //  (MOVLPSmr addr:$src1, VR128:$src2)
11881   // So, recognize this potential and also use MOVLPS or MOVLPD
11882   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
11883     CanFoldLoad = true;
11884
11885   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11886   if (CanFoldLoad) {
11887     if (HasSSE2 && NumElems == 2)
11888       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
11889
11890     if (NumElems == 4)
11891       // If we don't care about the second element, proceed to use movss.
11892       if (SVOp->getMaskElt(1) != -1)
11893         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
11894   }
11895
11896   // movl and movlp will both match v2i64, but v2i64 is never matched by
11897   // movl earlier because we make it strict to avoid messing with the movlp load
11898   // folding logic (see the code above getMOVLP call). Match it here then,
11899   // this is horrible, but will stay like this until we move all shuffle
11900   // matching to x86 specific nodes. Note that for the 1st condition all
11901   // types are matched with movsd.
11902   if (HasSSE2) {
11903     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
11904     // as to remove this logic from here, as much as possible
11905     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
11906       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
11907     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
11908   }
11909
11910   assert(VT != MVT::v4i32 && "unsupported shuffle type");
11911
11912   // Invert the operand order and use SHUFPS to match it.
11913   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
11914                               getShuffleSHUFImmediate(SVOp), DAG);
11915 }
11916
11917 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
11918                                          SelectionDAG &DAG) {
11919   SDLoc dl(Load);
11920   MVT VT = Load->getSimpleValueType(0);
11921   MVT EVT = VT.getVectorElementType();
11922   SDValue Addr = Load->getOperand(1);
11923   SDValue NewAddr = DAG.getNode(
11924       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
11925       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
11926
11927   SDValue NewLoad =
11928       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
11929                   DAG.getMachineFunction().getMachineMemOperand(
11930                       Load->getMemOperand(), 0, EVT.getStoreSize()));
11931   return NewLoad;
11932 }
11933
11934 // It is only safe to call this function if isINSERTPSMask is true for
11935 // this shufflevector mask.
11936 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
11937                            SelectionDAG &DAG) {
11938   // Generate an insertps instruction when inserting an f32 from memory onto a
11939   // v4f32 or when copying a member from one v4f32 to another.
11940   // We also use it for transferring i32 from one register to another,
11941   // since it simply copies the same bits.
11942   // If we're transferring an i32 from memory to a specific element in a
11943   // register, we output a generic DAG that will match the PINSRD
11944   // instruction.
11945   MVT VT = SVOp->getSimpleValueType(0);
11946   MVT EVT = VT.getVectorElementType();
11947   SDValue V1 = SVOp->getOperand(0);
11948   SDValue V2 = SVOp->getOperand(1);
11949   auto Mask = SVOp->getMask();
11950   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
11951          "unsupported vector type for insertps/pinsrd");
11952
11953   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
11954   auto FromV2Predicate = [](const int &i) { return i >= 4; };
11955   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
11956
11957   SDValue From;
11958   SDValue To;
11959   unsigned DestIndex;
11960   if (FromV1 == 1) {
11961     From = V1;
11962     To = V2;
11963     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
11964                 Mask.begin();
11965
11966     // If we have 1 element from each vector, we have to check if we're
11967     // changing V1's element's place. If so, we're done. Otherwise, we
11968     // should assume we're changing V2's element's place and behave
11969     // accordingly.
11970     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
11971     assert(DestIndex <= INT32_MAX && "truncated destination index");
11972     if (FromV1 == FromV2 &&
11973         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
11974       From = V2;
11975       To = V1;
11976       DestIndex =
11977           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
11978     }
11979   } else {
11980     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
11981            "More than one element from V1 and from V2, or no elements from one "
11982            "of the vectors. This case should not have returned true from "
11983            "isINSERTPSMask");
11984     From = V2;
11985     To = V1;
11986     DestIndex =
11987         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
11988   }
11989
11990   // Get an index into the source vector in the range [0,4) (the mask is
11991   // in the range [0,8) because it can address V1 and V2)
11992   unsigned SrcIndex = Mask[DestIndex] % 4;
11993   if (MayFoldLoad(From)) {
11994     // Trivial case, when From comes from a load and is only used by the
11995     // shuffle. Make it use insertps from the vector that we need from that
11996     // load.
11997     SDValue NewLoad =
11998         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
11999     if (!NewLoad.getNode())
12000       return SDValue();
12001
12002     if (EVT == MVT::f32) {
12003       // Create this as a scalar to vector to match the instruction pattern.
12004       SDValue LoadScalarToVector =
12005           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
12006       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
12007       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
12008                          InsertpsMask);
12009     } else { // EVT == MVT::i32
12010       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
12011       // instruction, to match the PINSRD instruction, which loads an i32 to a
12012       // certain vector element.
12013       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
12014                          DAG.getConstant(DestIndex, MVT::i32));
12015     }
12016   }
12017
12018   // Vector-element-to-vector
12019   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
12020   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
12021 }
12022
12023 // Reduce a vector shuffle to zext.
12024 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
12025                                     SelectionDAG &DAG) {
12026   // PMOVZX is only available from SSE41.
12027   if (!Subtarget->hasSSE41())
12028     return SDValue();
12029
12030   MVT VT = Op.getSimpleValueType();
12031
12032   // Only AVX2 support 256-bit vector integer extending.
12033   if (!Subtarget->hasInt256() && VT.is256BitVector())
12034     return SDValue();
12035
12036   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12037   SDLoc DL(Op);
12038   SDValue V1 = Op.getOperand(0);
12039   SDValue V2 = Op.getOperand(1);
12040   unsigned NumElems = VT.getVectorNumElements();
12041
12042   // Extending is an unary operation and the element type of the source vector
12043   // won't be equal to or larger than i64.
12044   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
12045       VT.getVectorElementType() == MVT::i64)
12046     return SDValue();
12047
12048   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
12049   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
12050   while ((1U << Shift) < NumElems) {
12051     if (SVOp->getMaskElt(1U << Shift) == 1)
12052       break;
12053     Shift += 1;
12054     // The maximal ratio is 8, i.e. from i8 to i64.
12055     if (Shift > 3)
12056       return SDValue();
12057   }
12058
12059   // Check the shuffle mask.
12060   unsigned Mask = (1U << Shift) - 1;
12061   for (unsigned i = 0; i != NumElems; ++i) {
12062     int EltIdx = SVOp->getMaskElt(i);
12063     if ((i & Mask) != 0 && EltIdx != -1)
12064       return SDValue();
12065     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
12066       return SDValue();
12067   }
12068
12069   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
12070   MVT NeVT = MVT::getIntegerVT(NBits);
12071   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
12072
12073   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
12074     return SDValue();
12075
12076   return DAG.getNode(ISD::BITCAST, DL, VT,
12077                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
12078 }
12079
12080 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
12081                                       SelectionDAG &DAG) {
12082   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12083   MVT VT = Op.getSimpleValueType();
12084   SDLoc dl(Op);
12085   SDValue V1 = Op.getOperand(0);
12086   SDValue V2 = Op.getOperand(1);
12087
12088   if (isZeroShuffle(SVOp))
12089     return getZeroVector(VT, Subtarget, DAG, dl);
12090
12091   // Handle splat operations
12092   if (SVOp->isSplat()) {
12093     // Use vbroadcast whenever the splat comes from a foldable load
12094     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
12095     if (Broadcast.getNode())
12096       return Broadcast;
12097   }
12098
12099   // Check integer expanding shuffles.
12100   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
12101   if (NewOp.getNode())
12102     return NewOp;
12103
12104   // If the shuffle can be profitably rewritten as a narrower shuffle, then
12105   // do it!
12106   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
12107       VT == MVT::v32i8) {
12108     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12109     if (NewOp.getNode())
12110       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
12111   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
12112     // FIXME: Figure out a cleaner way to do this.
12113     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
12114       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12115       if (NewOp.getNode()) {
12116         MVT NewVT = NewOp.getSimpleValueType();
12117         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
12118                                NewVT, true, false))
12119           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
12120                               dl);
12121       }
12122     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
12123       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12124       if (NewOp.getNode()) {
12125         MVT NewVT = NewOp.getSimpleValueType();
12126         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
12127           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
12128                               dl);
12129       }
12130     }
12131   }
12132   return SDValue();
12133 }
12134
12135 SDValue
12136 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
12137   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12138   SDValue V1 = Op.getOperand(0);
12139   SDValue V2 = Op.getOperand(1);
12140   MVT VT = Op.getSimpleValueType();
12141   SDLoc dl(Op);
12142   unsigned NumElems = VT.getVectorNumElements();
12143   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
12144   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
12145   bool V1IsSplat = false;
12146   bool V2IsSplat = false;
12147   bool HasSSE2 = Subtarget->hasSSE2();
12148   bool HasFp256    = Subtarget->hasFp256();
12149   bool HasInt256   = Subtarget->hasInt256();
12150   MachineFunction &MF = DAG.getMachineFunction();
12151   bool OptForSize = MF.getFunction()->getAttributes().
12152     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
12153
12154   // Check if we should use the experimental vector shuffle lowering. If so,
12155   // delegate completely to that code path.
12156   if (ExperimentalVectorShuffleLowering)
12157     return lowerVectorShuffle(Op, Subtarget, DAG);
12158
12159   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
12160
12161   if (V1IsUndef && V2IsUndef)
12162     return DAG.getUNDEF(VT);
12163
12164   // When we create a shuffle node we put the UNDEF node to second operand,
12165   // but in some cases the first operand may be transformed to UNDEF.
12166   // In this case we should just commute the node.
12167   if (V1IsUndef)
12168     return DAG.getCommutedVectorShuffle(*SVOp);
12169
12170   // Vector shuffle lowering takes 3 steps:
12171   //
12172   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
12173   //    narrowing and commutation of operands should be handled.
12174   // 2) Matching of shuffles with known shuffle masks to x86 target specific
12175   //    shuffle nodes.
12176   // 3) Rewriting of unmatched masks into new generic shuffle operations,
12177   //    so the shuffle can be broken into other shuffles and the legalizer can
12178   //    try the lowering again.
12179   //
12180   // The general idea is that no vector_shuffle operation should be left to
12181   // be matched during isel, all of them must be converted to a target specific
12182   // node here.
12183
12184   // Normalize the input vectors. Here splats, zeroed vectors, profitable
12185   // narrowing and commutation of operands should be handled. The actual code
12186   // doesn't include all of those, work in progress...
12187   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
12188   if (NewOp.getNode())
12189     return NewOp;
12190
12191   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
12192
12193   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
12194   // unpckh_undef). Only use pshufd if speed is more important than size.
12195   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12196     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12197   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12198     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12199
12200   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
12201       V2IsUndef && MayFoldVectorLoad(V1))
12202     return getMOVDDup(Op, dl, V1, DAG);
12203
12204   if (isMOVHLPS_v_undef_Mask(M, VT))
12205     return getMOVHighToLow(Op, dl, DAG);
12206
12207   // Use to match splats
12208   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
12209       (VT == MVT::v2f64 || VT == MVT::v2i64))
12210     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12211
12212   if (isPSHUFDMask(M, VT)) {
12213     // The actual implementation will match the mask in the if above and then
12214     // during isel it can match several different instructions, not only pshufd
12215     // as its name says, sad but true, emulate the behavior for now...
12216     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
12217       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
12218
12219     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
12220
12221     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
12222       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
12223
12224     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
12225       return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1, TargetMask,
12226                                   DAG);
12227
12228     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
12229                                 TargetMask, DAG);
12230   }
12231
12232   if (isPALIGNRMask(M, VT, Subtarget))
12233     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
12234                                 getShufflePALIGNRImmediate(SVOp),
12235                                 DAG);
12236
12237   if (isVALIGNMask(M, VT, Subtarget))
12238     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
12239                                 getShuffleVALIGNImmediate(SVOp),
12240                                 DAG);
12241
12242   // Check if this can be converted into a logical shift.
12243   bool isLeft = false;
12244   unsigned ShAmt = 0;
12245   SDValue ShVal;
12246   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
12247   if (isShift && ShVal.hasOneUse()) {
12248     // If the shifted value has multiple uses, it may be cheaper to use
12249     // v_set0 + movlhps or movhlps, etc.
12250     MVT EltVT = VT.getVectorElementType();
12251     ShAmt *= EltVT.getSizeInBits();
12252     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12253   }
12254
12255   if (isMOVLMask(M, VT)) {
12256     if (ISD::isBuildVectorAllZeros(V1.getNode()))
12257       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
12258     if (!isMOVLPMask(M, VT)) {
12259       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
12260         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
12261
12262       if (VT == MVT::v4i32 || VT == MVT::v4f32)
12263         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
12264     }
12265   }
12266
12267   // FIXME: fold these into legal mask.
12268   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
12269     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
12270
12271   if (isMOVHLPSMask(M, VT))
12272     return getMOVHighToLow(Op, dl, DAG);
12273
12274   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
12275     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
12276
12277   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
12278     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
12279
12280   if (isMOVLPMask(M, VT))
12281     return getMOVLP(Op, dl, DAG, HasSSE2);
12282
12283   if (ShouldXformToMOVHLPS(M, VT) ||
12284       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
12285     return DAG.getCommutedVectorShuffle(*SVOp);
12286
12287   if (isShift) {
12288     // No better options. Use a vshldq / vsrldq.
12289     MVT EltVT = VT.getVectorElementType();
12290     ShAmt *= EltVT.getSizeInBits();
12291     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12292   }
12293
12294   bool Commuted = false;
12295   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
12296   // 1,1,1,1 -> v8i16 though.
12297   BitVector UndefElements;
12298   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
12299     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12300       V1IsSplat = true;
12301   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
12302     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12303       V2IsSplat = true;
12304
12305   // Canonicalize the splat or undef, if present, to be on the RHS.
12306   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
12307     CommuteVectorShuffleMask(M, NumElems);
12308     std::swap(V1, V2);
12309     std::swap(V1IsSplat, V2IsSplat);
12310     Commuted = true;
12311   }
12312
12313   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
12314     // Shuffling low element of v1 into undef, just return v1.
12315     if (V2IsUndef)
12316       return V1;
12317     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
12318     // the instruction selector will not match, so get a canonical MOVL with
12319     // swapped operands to undo the commute.
12320     return getMOVL(DAG, dl, VT, V2, V1);
12321   }
12322
12323   if (isUNPCKLMask(M, VT, HasInt256))
12324     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12325
12326   if (isUNPCKHMask(M, VT, HasInt256))
12327     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12328
12329   if (V2IsSplat) {
12330     // Normalize mask so all entries that point to V2 points to its first
12331     // element then try to match unpck{h|l} again. If match, return a
12332     // new vector_shuffle with the corrected mask.p
12333     SmallVector<int, 8> NewMask(M.begin(), M.end());
12334     NormalizeMask(NewMask, NumElems);
12335     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
12336       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12337     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
12338       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12339   }
12340
12341   if (Commuted) {
12342     // Commute is back and try unpck* again.
12343     // FIXME: this seems wrong.
12344     CommuteVectorShuffleMask(M, NumElems);
12345     std::swap(V1, V2);
12346     std::swap(V1IsSplat, V2IsSplat);
12347
12348     if (isUNPCKLMask(M, VT, HasInt256))
12349       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12350
12351     if (isUNPCKHMask(M, VT, HasInt256))
12352       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12353   }
12354
12355   // Normalize the node to match x86 shuffle ops if needed
12356   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
12357     return DAG.getCommutedVectorShuffle(*SVOp);
12358
12359   // The checks below are all present in isShuffleMaskLegal, but they are
12360   // inlined here right now to enable us to directly emit target specific
12361   // nodes, and remove one by one until they don't return Op anymore.
12362
12363   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
12364       SVOp->getSplatIndex() == 0 && V2IsUndef) {
12365     if (VT == MVT::v2f64 || VT == MVT::v2i64)
12366       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12367   }
12368
12369   if (isPSHUFHWMask(M, VT, HasInt256))
12370     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
12371                                 getShufflePSHUFHWImmediate(SVOp),
12372                                 DAG);
12373
12374   if (isPSHUFLWMask(M, VT, HasInt256))
12375     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
12376                                 getShufflePSHUFLWImmediate(SVOp),
12377                                 DAG);
12378
12379   unsigned MaskValue;
12380   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
12381                   &MaskValue))
12382     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
12383
12384   if (isSHUFPMask(M, VT))
12385     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
12386                                 getShuffleSHUFImmediate(SVOp), DAG);
12387
12388   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12389     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12390   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12391     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12392
12393   //===--------------------------------------------------------------------===//
12394   // Generate target specific nodes for 128 or 256-bit shuffles only
12395   // supported in the AVX instruction set.
12396   //
12397
12398   // Handle VMOVDDUPY permutations
12399   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
12400     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
12401
12402   // Handle VPERMILPS/D* permutations
12403   if (isVPERMILPMask(M, VT)) {
12404     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
12405       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
12406                                   getShuffleSHUFImmediate(SVOp), DAG);
12407     return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1,
12408                                 getShuffleSHUFImmediate(SVOp), DAG);
12409   }
12410
12411   unsigned Idx;
12412   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
12413     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
12414                               Idx*(NumElems/2), DAG, dl);
12415
12416   // Handle VPERM2F128/VPERM2I128 permutations
12417   if (isVPERM2X128Mask(M, VT, HasFp256))
12418     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
12419                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
12420
12421   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
12422     return getINSERTPS(SVOp, dl, DAG);
12423
12424   unsigned Imm8;
12425   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
12426     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
12427
12428   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
12429       VT.is512BitVector()) {
12430     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
12431     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
12432     SmallVector<SDValue, 16> permclMask;
12433     for (unsigned i = 0; i != NumElems; ++i) {
12434       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
12435     }
12436
12437     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
12438     if (V2IsUndef)
12439       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
12440       return DAG.getNode(X86ISD::VPERMV, dl, VT,
12441                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
12442     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
12443                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
12444   }
12445
12446   //===--------------------------------------------------------------------===//
12447   // Since no target specific shuffle was selected for this generic one,
12448   // lower it into other known shuffles. FIXME: this isn't true yet, but
12449   // this is the plan.
12450   //
12451
12452   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
12453   if (VT == MVT::v8i16) {
12454     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
12455     if (NewOp.getNode())
12456       return NewOp;
12457   }
12458
12459   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
12460     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
12461     if (NewOp.getNode())
12462       return NewOp;
12463   }
12464
12465   if (VT == MVT::v16i8) {
12466     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
12467     if (NewOp.getNode())
12468       return NewOp;
12469   }
12470
12471   if (VT == MVT::v32i8) {
12472     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
12473     if (NewOp.getNode())
12474       return NewOp;
12475   }
12476
12477   // Handle all 128-bit wide vectors with 4 elements, and match them with
12478   // several different shuffle types.
12479   if (NumElems == 4 && VT.is128BitVector())
12480     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
12481
12482   // Handle general 256-bit shuffles
12483   if (VT.is256BitVector())
12484     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
12485
12486   return SDValue();
12487 }
12488
12489 // This function assumes its argument is a BUILD_VECTOR of constants or
12490 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
12491 // true.
12492 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
12493                                     unsigned &MaskValue) {
12494   MaskValue = 0;
12495   unsigned NumElems = BuildVector->getNumOperands();
12496   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
12497   unsigned NumLanes = (NumElems - 1) / 8 + 1;
12498   unsigned NumElemsInLane = NumElems / NumLanes;
12499
12500   // Blend for v16i16 should be symetric for the both lanes.
12501   for (unsigned i = 0; i < NumElemsInLane; ++i) {
12502     SDValue EltCond = BuildVector->getOperand(i);
12503     SDValue SndLaneEltCond =
12504         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
12505
12506     int Lane1Cond = -1, Lane2Cond = -1;
12507     if (isa<ConstantSDNode>(EltCond))
12508       Lane1Cond = !isZero(EltCond);
12509     if (isa<ConstantSDNode>(SndLaneEltCond))
12510       Lane2Cond = !isZero(SndLaneEltCond);
12511
12512     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
12513       // Lane1Cond != 0, means we want the first argument.
12514       // Lane1Cond == 0, means we want the second argument.
12515       // The encoding of this argument is 0 for the first argument, 1
12516       // for the second. Therefore, invert the condition.
12517       MaskValue |= !Lane1Cond << i;
12518     else if (Lane1Cond < 0)
12519       MaskValue |= !Lane2Cond << i;
12520     else
12521       return false;
12522   }
12523   return true;
12524 }
12525
12526 /// \brief Try to lower a VSELECT instruction to an immediate-controlled blend
12527 /// instruction.
12528 static SDValue lowerVSELECTtoBLENDI(SDValue Op, const X86Subtarget *Subtarget,
12529                                     SelectionDAG &DAG) {
12530   SDValue Cond = Op.getOperand(0);
12531   SDValue LHS = Op.getOperand(1);
12532   SDValue RHS = Op.getOperand(2);
12533   SDLoc dl(Op);
12534   MVT VT = Op.getSimpleValueType();
12535   MVT EltVT = VT.getVectorElementType();
12536   unsigned NumElems = VT.getVectorNumElements();
12537
12538   // There is no blend with immediate in AVX-512.
12539   if (VT.is512BitVector())
12540     return SDValue();
12541
12542   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
12543     return SDValue();
12544   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
12545     return SDValue();
12546
12547   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
12548     return SDValue();
12549
12550   // Check the mask for BLEND and build the value.
12551   unsigned MaskValue = 0;
12552   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
12553     return SDValue();
12554
12555   // Convert i32 vectors to floating point if it is not AVX2.
12556   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
12557   MVT BlendVT = VT;
12558   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
12559     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
12560                                NumElems);
12561     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
12562     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
12563   }
12564
12565   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
12566                             DAG.getConstant(MaskValue, MVT::i32));
12567   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
12568 }
12569
12570 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
12571   // A vselect where all conditions and data are constants can be optimized into
12572   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
12573   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
12574       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
12575       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
12576     return SDValue();
12577
12578   SDValue BlendOp = lowerVSELECTtoBLENDI(Op, Subtarget, DAG);
12579   if (BlendOp.getNode())
12580     return BlendOp;
12581
12582   // Some types for vselect were previously set to Expand, not Legal or
12583   // Custom. Return an empty SDValue so we fall-through to Expand, after
12584   // the Custom lowering phase.
12585   MVT VT = Op.getSimpleValueType();
12586   switch (VT.SimpleTy) {
12587   default:
12588     break;
12589   case MVT::v8i16:
12590   case MVT::v16i16:
12591     if (Subtarget->hasBWI() && Subtarget->hasVLX())
12592       break;
12593     return SDValue();
12594   }
12595
12596   // We couldn't create a "Blend with immediate" node.
12597   // This node should still be legal, but we'll have to emit a blendv*
12598   // instruction.
12599   return Op;
12600 }
12601
12602 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
12603   MVT VT = Op.getSimpleValueType();
12604   SDLoc dl(Op);
12605
12606   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
12607     return SDValue();
12608
12609   if (VT.getSizeInBits() == 8) {
12610     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
12611                                   Op.getOperand(0), Op.getOperand(1));
12612     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12613                                   DAG.getValueType(VT));
12614     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12615   }
12616
12617   if (VT.getSizeInBits() == 16) {
12618     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12619     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
12620     if (Idx == 0)
12621       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12622                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12623                                      DAG.getNode(ISD::BITCAST, dl,
12624                                                  MVT::v4i32,
12625                                                  Op.getOperand(0)),
12626                                      Op.getOperand(1)));
12627     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
12628                                   Op.getOperand(0), Op.getOperand(1));
12629     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12630                                   DAG.getValueType(VT));
12631     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12632   }
12633
12634   if (VT == MVT::f32) {
12635     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
12636     // the result back to FR32 register. It's only worth matching if the
12637     // result has a single use which is a store or a bitcast to i32.  And in
12638     // the case of a store, it's not worth it if the index is a constant 0,
12639     // because a MOVSSmr can be used instead, which is smaller and faster.
12640     if (!Op.hasOneUse())
12641       return SDValue();
12642     SDNode *User = *Op.getNode()->use_begin();
12643     if ((User->getOpcode() != ISD::STORE ||
12644          (isa<ConstantSDNode>(Op.getOperand(1)) &&
12645           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
12646         (User->getOpcode() != ISD::BITCAST ||
12647          User->getValueType(0) != MVT::i32))
12648       return SDValue();
12649     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12650                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
12651                                               Op.getOperand(0)),
12652                                               Op.getOperand(1));
12653     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
12654   }
12655
12656   if (VT == MVT::i32 || VT == MVT::i64) {
12657     // ExtractPS/pextrq works with constant index.
12658     if (isa<ConstantSDNode>(Op.getOperand(1)))
12659       return Op;
12660   }
12661   return SDValue();
12662 }
12663
12664 /// Extract one bit from mask vector, like v16i1 or v8i1.
12665 /// AVX-512 feature.
12666 SDValue
12667 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
12668   SDValue Vec = Op.getOperand(0);
12669   SDLoc dl(Vec);
12670   MVT VecVT = Vec.getSimpleValueType();
12671   SDValue Idx = Op.getOperand(1);
12672   MVT EltVT = Op.getSimpleValueType();
12673
12674   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
12675
12676   // variable index can't be handled in mask registers,
12677   // extend vector to VR512
12678   if (!isa<ConstantSDNode>(Idx)) {
12679     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12680     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
12681     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
12682                               ExtVT.getVectorElementType(), Ext, Idx);
12683     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
12684   }
12685
12686   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12687   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12688   unsigned MaxSift = rc->getSize()*8 - 1;
12689   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
12690                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12691   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
12692                     DAG.getConstant(MaxSift, MVT::i8));
12693   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
12694                        DAG.getIntPtrConstant(0));
12695 }
12696
12697 SDValue
12698 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
12699                                            SelectionDAG &DAG) const {
12700   SDLoc dl(Op);
12701   SDValue Vec = Op.getOperand(0);
12702   MVT VecVT = Vec.getSimpleValueType();
12703   SDValue Idx = Op.getOperand(1);
12704
12705   if (Op.getSimpleValueType() == MVT::i1)
12706     return ExtractBitFromMaskVector(Op, DAG);
12707
12708   if (!isa<ConstantSDNode>(Idx)) {
12709     if (VecVT.is512BitVector() ||
12710         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
12711          VecVT.getVectorElementType().getSizeInBits() == 32)) {
12712
12713       MVT MaskEltVT =
12714         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
12715       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
12716                                     MaskEltVT.getSizeInBits());
12717
12718       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
12719       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
12720                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
12721                                 Idx, DAG.getConstant(0, getPointerTy()));
12722       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
12723       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
12724                         Perm, DAG.getConstant(0, getPointerTy()));
12725     }
12726     return SDValue();
12727   }
12728
12729   // If this is a 256-bit vector result, first extract the 128-bit vector and
12730   // then extract the element from the 128-bit vector.
12731   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
12732
12733     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12734     // Get the 128-bit vector.
12735     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
12736     MVT EltVT = VecVT.getVectorElementType();
12737
12738     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
12739
12740     //if (IdxVal >= NumElems/2)
12741     //  IdxVal -= NumElems/2;
12742     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
12743     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
12744                        DAG.getConstant(IdxVal, MVT::i32));
12745   }
12746
12747   assert(VecVT.is128BitVector() && "Unexpected vector length");
12748
12749   if (Subtarget->hasSSE41()) {
12750     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
12751     if (Res.getNode())
12752       return Res;
12753   }
12754
12755   MVT VT = Op.getSimpleValueType();
12756   // TODO: handle v16i8.
12757   if (VT.getSizeInBits() == 16) {
12758     SDValue Vec = Op.getOperand(0);
12759     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12760     if (Idx == 0)
12761       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12762                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12763                                      DAG.getNode(ISD::BITCAST, dl,
12764                                                  MVT::v4i32, Vec),
12765                                      Op.getOperand(1)));
12766     // Transform it so it match pextrw which produces a 32-bit result.
12767     MVT EltVT = MVT::i32;
12768     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
12769                                   Op.getOperand(0), Op.getOperand(1));
12770     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
12771                                   DAG.getValueType(VT));
12772     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12773   }
12774
12775   if (VT.getSizeInBits() == 32) {
12776     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12777     if (Idx == 0)
12778       return Op;
12779
12780     // SHUFPS the element to the lowest double word, then movss.
12781     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
12782     MVT VVT = Op.getOperand(0).getSimpleValueType();
12783     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12784                                        DAG.getUNDEF(VVT), Mask);
12785     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12786                        DAG.getIntPtrConstant(0));
12787   }
12788
12789   if (VT.getSizeInBits() == 64) {
12790     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
12791     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
12792     //        to match extract_elt for f64.
12793     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12794     if (Idx == 0)
12795       return Op;
12796
12797     // UNPCKHPD the element to the lowest double word, then movsd.
12798     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
12799     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
12800     int Mask[2] = { 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   return SDValue();
12809 }
12810
12811 /// Insert one bit to mask vector, like v16i1 or v8i1.
12812 /// AVX-512 feature.
12813 SDValue
12814 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
12815   SDLoc dl(Op);
12816   SDValue Vec = Op.getOperand(0);
12817   SDValue Elt = Op.getOperand(1);
12818   SDValue Idx = Op.getOperand(2);
12819   MVT VecVT = Vec.getSimpleValueType();
12820
12821   if (!isa<ConstantSDNode>(Idx)) {
12822     // Non constant index. Extend source and destination,
12823     // insert element and then truncate the result.
12824     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12825     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
12826     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
12827       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
12828       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
12829     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
12830   }
12831
12832   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12833   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
12834   if (Vec.getOpcode() == ISD::UNDEF)
12835     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12836                        DAG.getConstant(IdxVal, MVT::i8));
12837   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12838   unsigned MaxSift = rc->getSize()*8 - 1;
12839   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12840                     DAG.getConstant(MaxSift, MVT::i8));
12841   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
12842                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12843   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
12844 }
12845
12846 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12847                                                   SelectionDAG &DAG) const {
12848   MVT VT = Op.getSimpleValueType();
12849   MVT EltVT = VT.getVectorElementType();
12850
12851   if (EltVT == MVT::i1)
12852     return InsertBitToMaskVector(Op, DAG);
12853
12854   SDLoc dl(Op);
12855   SDValue N0 = Op.getOperand(0);
12856   SDValue N1 = Op.getOperand(1);
12857   SDValue N2 = Op.getOperand(2);
12858   if (!isa<ConstantSDNode>(N2))
12859     return SDValue();
12860   auto *N2C = cast<ConstantSDNode>(N2);
12861   unsigned IdxVal = N2C->getZExtValue();
12862
12863   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
12864   // into that, and then insert the subvector back into the result.
12865   if (VT.is256BitVector() || VT.is512BitVector()) {
12866     // Get the desired 128-bit vector half.
12867     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
12868
12869     // Insert the element into the desired half.
12870     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
12871     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
12872
12873     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
12874                     DAG.getConstant(IdxIn128, MVT::i32));
12875
12876     // Insert the changed part back to the 256-bit vector
12877     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
12878   }
12879   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
12880
12881   if (Subtarget->hasSSE41()) {
12882     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
12883       unsigned Opc;
12884       if (VT == MVT::v8i16) {
12885         Opc = X86ISD::PINSRW;
12886       } else {
12887         assert(VT == MVT::v16i8);
12888         Opc = X86ISD::PINSRB;
12889       }
12890
12891       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
12892       // argument.
12893       if (N1.getValueType() != MVT::i32)
12894         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12895       if (N2.getValueType() != MVT::i32)
12896         N2 = DAG.getIntPtrConstant(IdxVal);
12897       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
12898     }
12899
12900     if (EltVT == MVT::f32) {
12901       // Bits [7:6] of the constant are the source select.  This will always be
12902       //  zero here.  The DAG Combiner may combine an extract_elt index into
12903       //  these
12904       //  bits.  For example (insert (extract, 3), 2) could be matched by
12905       //  putting
12906       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
12907       // Bits [5:4] of the constant are the destination select.  This is the
12908       //  value of the incoming immediate.
12909       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
12910       //   combine either bitwise AND or insert of float 0.0 to set these bits.
12911       N2 = DAG.getIntPtrConstant(IdxVal << 4);
12912       // Create this as a scalar to vector..
12913       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
12914       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
12915     }
12916
12917     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
12918       // PINSR* works with constant index.
12919       return Op;
12920     }
12921   }
12922
12923   if (EltVT == MVT::i8)
12924     return SDValue();
12925
12926   if (EltVT.getSizeInBits() == 16) {
12927     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12928     // as its second argument.
12929     if (N1.getValueType() != MVT::i32)
12930       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12931     if (N2.getValueType() != MVT::i32)
12932       N2 = DAG.getIntPtrConstant(IdxVal);
12933     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12934   }
12935   return SDValue();
12936 }
12937
12938 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12939   SDLoc dl(Op);
12940   MVT OpVT = Op.getSimpleValueType();
12941
12942   // If this is a 256-bit vector result, first insert into a 128-bit
12943   // vector and then insert into the 256-bit vector.
12944   if (!OpVT.is128BitVector()) {
12945     // Insert into a 128-bit vector.
12946     unsigned SizeFactor = OpVT.getSizeInBits()/128;
12947     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12948                                  OpVT.getVectorNumElements() / SizeFactor);
12949
12950     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12951
12952     // Insert the 128-bit vector.
12953     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12954   }
12955
12956   if (OpVT == MVT::v1i64 &&
12957       Op.getOperand(0).getValueType() == MVT::i64)
12958     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12959
12960   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12961   assert(OpVT.is128BitVector() && "Expected an SSE type!");
12962   return DAG.getNode(ISD::BITCAST, dl, OpVT,
12963                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
12964 }
12965
12966 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
12967 // a simple subregister reference or explicit instructions to grab
12968 // upper bits of a vector.
12969 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12970                                       SelectionDAG &DAG) {
12971   SDLoc dl(Op);
12972   SDValue In =  Op.getOperand(0);
12973   SDValue Idx = Op.getOperand(1);
12974   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12975   MVT ResVT   = Op.getSimpleValueType();
12976   MVT InVT    = In.getSimpleValueType();
12977
12978   if (Subtarget->hasFp256()) {
12979     if (ResVT.is128BitVector() &&
12980         (InVT.is256BitVector() || InVT.is512BitVector()) &&
12981         isa<ConstantSDNode>(Idx)) {
12982       return Extract128BitVector(In, IdxVal, DAG, dl);
12983     }
12984     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12985         isa<ConstantSDNode>(Idx)) {
12986       return Extract256BitVector(In, IdxVal, DAG, dl);
12987     }
12988   }
12989   return SDValue();
12990 }
12991
12992 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12993 // simple superregister reference or explicit instructions to insert
12994 // the upper bits of a vector.
12995 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12996                                      SelectionDAG &DAG) {
12997   if (Subtarget->hasFp256()) {
12998     SDLoc dl(Op.getNode());
12999     SDValue Vec = Op.getNode()->getOperand(0);
13000     SDValue SubVec = Op.getNode()->getOperand(1);
13001     SDValue Idx = Op.getNode()->getOperand(2);
13002
13003     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
13004          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
13005         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
13006         isa<ConstantSDNode>(Idx)) {
13007       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13008       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
13009     }
13010
13011     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
13012         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
13013         isa<ConstantSDNode>(Idx)) {
13014       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
13015       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
13016     }
13017   }
13018   return SDValue();
13019 }
13020
13021 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
13022 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
13023 // one of the above mentioned nodes. It has to be wrapped because otherwise
13024 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
13025 // be used to form addressing mode. These wrapped nodes will be selected
13026 // into MOV32ri.
13027 SDValue
13028 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
13029   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
13030
13031   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13032   // global base reg.
13033   unsigned char OpFlag = 0;
13034   unsigned WrapperKind = X86ISD::Wrapper;
13035   CodeModel::Model M = DAG.getTarget().getCodeModel();
13036
13037   if (Subtarget->isPICStyleRIPRel() &&
13038       (M == CodeModel::Small || M == CodeModel::Kernel))
13039     WrapperKind = X86ISD::WrapperRIP;
13040   else if (Subtarget->isPICStyleGOT())
13041     OpFlag = X86II::MO_GOTOFF;
13042   else if (Subtarget->isPICStyleStubPIC())
13043     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13044
13045   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
13046                                              CP->getAlignment(),
13047                                              CP->getOffset(), OpFlag);
13048   SDLoc DL(CP);
13049   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13050   // With PIC, the address is actually $g + Offset.
13051   if (OpFlag) {
13052     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13053                          DAG.getNode(X86ISD::GlobalBaseReg,
13054                                      SDLoc(), getPointerTy()),
13055                          Result);
13056   }
13057
13058   return Result;
13059 }
13060
13061 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
13062   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
13063
13064   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13065   // global base reg.
13066   unsigned char OpFlag = 0;
13067   unsigned WrapperKind = X86ISD::Wrapper;
13068   CodeModel::Model M = DAG.getTarget().getCodeModel();
13069
13070   if (Subtarget->isPICStyleRIPRel() &&
13071       (M == CodeModel::Small || M == CodeModel::Kernel))
13072     WrapperKind = X86ISD::WrapperRIP;
13073   else if (Subtarget->isPICStyleGOT())
13074     OpFlag = X86II::MO_GOTOFF;
13075   else if (Subtarget->isPICStyleStubPIC())
13076     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13077
13078   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
13079                                           OpFlag);
13080   SDLoc DL(JT);
13081   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13082
13083   // With PIC, the address is actually $g + Offset.
13084   if (OpFlag)
13085     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13086                          DAG.getNode(X86ISD::GlobalBaseReg,
13087                                      SDLoc(), getPointerTy()),
13088                          Result);
13089
13090   return Result;
13091 }
13092
13093 SDValue
13094 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
13095   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13096
13097   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13098   // global base reg.
13099   unsigned char OpFlag = 0;
13100   unsigned WrapperKind = X86ISD::Wrapper;
13101   CodeModel::Model M = DAG.getTarget().getCodeModel();
13102
13103   if (Subtarget->isPICStyleRIPRel() &&
13104       (M == CodeModel::Small || M == CodeModel::Kernel)) {
13105     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
13106       OpFlag = X86II::MO_GOTPCREL;
13107     WrapperKind = X86ISD::WrapperRIP;
13108   } else if (Subtarget->isPICStyleGOT()) {
13109     OpFlag = X86II::MO_GOT;
13110   } else if (Subtarget->isPICStyleStubPIC()) {
13111     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
13112   } else if (Subtarget->isPICStyleStubNoDynamic()) {
13113     OpFlag = X86II::MO_DARWIN_NONLAZY;
13114   }
13115
13116   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
13117
13118   SDLoc DL(Op);
13119   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13120
13121   // With PIC, the address is actually $g + Offset.
13122   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
13123       !Subtarget->is64Bit()) {
13124     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13125                          DAG.getNode(X86ISD::GlobalBaseReg,
13126                                      SDLoc(), getPointerTy()),
13127                          Result);
13128   }
13129
13130   // For symbols that require a load from a stub to get the address, emit the
13131   // load.
13132   if (isGlobalStubReference(OpFlag))
13133     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
13134                          MachinePointerInfo::getGOT(), false, false, false, 0);
13135
13136   return Result;
13137 }
13138
13139 SDValue
13140 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
13141   // Create the TargetBlockAddressAddress node.
13142   unsigned char OpFlags =
13143     Subtarget->ClassifyBlockAddressReference();
13144   CodeModel::Model M = DAG.getTarget().getCodeModel();
13145   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
13146   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
13147   SDLoc dl(Op);
13148   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
13149                                              OpFlags);
13150
13151   if (Subtarget->isPICStyleRIPRel() &&
13152       (M == CodeModel::Small || M == CodeModel::Kernel))
13153     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13154   else
13155     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13156
13157   // With PIC, the address is actually $g + Offset.
13158   if (isGlobalRelativeToPICBase(OpFlags)) {
13159     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13160                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13161                          Result);
13162   }
13163
13164   return Result;
13165 }
13166
13167 SDValue
13168 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
13169                                       int64_t Offset, SelectionDAG &DAG) const {
13170   // Create the TargetGlobalAddress node, folding in the constant
13171   // offset if it is legal.
13172   unsigned char OpFlags =
13173       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
13174   CodeModel::Model M = DAG.getTarget().getCodeModel();
13175   SDValue Result;
13176   if (OpFlags == X86II::MO_NO_FLAG &&
13177       X86::isOffsetSuitableForCodeModel(Offset, M)) {
13178     // A direct static reference to a global.
13179     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
13180     Offset = 0;
13181   } else {
13182     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
13183   }
13184
13185   if (Subtarget->isPICStyleRIPRel() &&
13186       (M == CodeModel::Small || M == CodeModel::Kernel))
13187     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13188   else
13189     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13190
13191   // With PIC, the address is actually $g + Offset.
13192   if (isGlobalRelativeToPICBase(OpFlags)) {
13193     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13194                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13195                          Result);
13196   }
13197
13198   // For globals that require a load from a stub to get the address, emit the
13199   // load.
13200   if (isGlobalStubReference(OpFlags))
13201     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
13202                          MachinePointerInfo::getGOT(), false, false, false, 0);
13203
13204   // If there was a non-zero offset that we didn't fold, create an explicit
13205   // addition for it.
13206   if (Offset != 0)
13207     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
13208                          DAG.getConstant(Offset, getPointerTy()));
13209
13210   return Result;
13211 }
13212
13213 SDValue
13214 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
13215   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
13216   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
13217   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
13218 }
13219
13220 static SDValue
13221 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
13222            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
13223            unsigned char OperandFlags, bool LocalDynamic = false) {
13224   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13225   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13226   SDLoc dl(GA);
13227   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13228                                            GA->getValueType(0),
13229                                            GA->getOffset(),
13230                                            OperandFlags);
13231
13232   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
13233                                            : X86ISD::TLSADDR;
13234
13235   if (InFlag) {
13236     SDValue Ops[] = { Chain,  TGA, *InFlag };
13237     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13238   } else {
13239     SDValue Ops[]  = { Chain, TGA };
13240     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13241   }
13242
13243   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
13244   MFI->setAdjustsStack(true);
13245   MFI->setHasCalls(true);
13246
13247   SDValue Flag = Chain.getValue(1);
13248   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
13249 }
13250
13251 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
13252 static SDValue
13253 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13254                                 const EVT PtrVT) {
13255   SDValue InFlag;
13256   SDLoc dl(GA);  // ? function entry point might be better
13257   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13258                                    DAG.getNode(X86ISD::GlobalBaseReg,
13259                                                SDLoc(), PtrVT), InFlag);
13260   InFlag = Chain.getValue(1);
13261
13262   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
13263 }
13264
13265 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
13266 static SDValue
13267 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13268                                 const EVT PtrVT) {
13269   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
13270                     X86::RAX, X86II::MO_TLSGD);
13271 }
13272
13273 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
13274                                            SelectionDAG &DAG,
13275                                            const EVT PtrVT,
13276                                            bool is64Bit) {
13277   SDLoc dl(GA);
13278
13279   // Get the start address of the TLS block for this module.
13280   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
13281       .getInfo<X86MachineFunctionInfo>();
13282   MFI->incNumLocalDynamicTLSAccesses();
13283
13284   SDValue Base;
13285   if (is64Bit) {
13286     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
13287                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
13288   } else {
13289     SDValue InFlag;
13290     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13291         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
13292     InFlag = Chain.getValue(1);
13293     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
13294                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
13295   }
13296
13297   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
13298   // of Base.
13299
13300   // Build x@dtpoff.
13301   unsigned char OperandFlags = X86II::MO_DTPOFF;
13302   unsigned WrapperKind = X86ISD::Wrapper;
13303   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13304                                            GA->getValueType(0),
13305                                            GA->getOffset(), OperandFlags);
13306   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13307
13308   // Add x@dtpoff with the base.
13309   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
13310 }
13311
13312 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
13313 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13314                                    const EVT PtrVT, TLSModel::Model model,
13315                                    bool is64Bit, bool isPIC) {
13316   SDLoc dl(GA);
13317
13318   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
13319   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
13320                                                          is64Bit ? 257 : 256));
13321
13322   SDValue ThreadPointer =
13323       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
13324                   MachinePointerInfo(Ptr), false, false, false, 0);
13325
13326   unsigned char OperandFlags = 0;
13327   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
13328   // initialexec.
13329   unsigned WrapperKind = X86ISD::Wrapper;
13330   if (model == TLSModel::LocalExec) {
13331     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
13332   } else if (model == TLSModel::InitialExec) {
13333     if (is64Bit) {
13334       OperandFlags = X86II::MO_GOTTPOFF;
13335       WrapperKind = X86ISD::WrapperRIP;
13336     } else {
13337       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
13338     }
13339   } else {
13340     llvm_unreachable("Unexpected model");
13341   }
13342
13343   // emit "addl x@ntpoff,%eax" (local exec)
13344   // or "addl x@indntpoff,%eax" (initial exec)
13345   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
13346   SDValue TGA =
13347       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
13348                                  GA->getOffset(), OperandFlags);
13349   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13350
13351   if (model == TLSModel::InitialExec) {
13352     if (isPIC && !is64Bit) {
13353       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
13354                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
13355                            Offset);
13356     }
13357
13358     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
13359                          MachinePointerInfo::getGOT(), false, false, false, 0);
13360   }
13361
13362   // The address of the thread local variable is the add of the thread
13363   // pointer with the offset of the variable.
13364   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
13365 }
13366
13367 SDValue
13368 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
13369
13370   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
13371   const GlobalValue *GV = GA->getGlobal();
13372
13373   if (Subtarget->isTargetELF()) {
13374     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
13375
13376     switch (model) {
13377       case TLSModel::GeneralDynamic:
13378         if (Subtarget->is64Bit())
13379           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
13380         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
13381       case TLSModel::LocalDynamic:
13382         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
13383                                            Subtarget->is64Bit());
13384       case TLSModel::InitialExec:
13385       case TLSModel::LocalExec:
13386         return LowerToTLSExecModel(
13387             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
13388             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
13389     }
13390     llvm_unreachable("Unknown TLS model.");
13391   }
13392
13393   if (Subtarget->isTargetDarwin()) {
13394     // Darwin only has one model of TLS.  Lower to that.
13395     unsigned char OpFlag = 0;
13396     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
13397                            X86ISD::WrapperRIP : X86ISD::Wrapper;
13398
13399     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13400     // global base reg.
13401     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
13402                  !Subtarget->is64Bit();
13403     if (PIC32)
13404       OpFlag = X86II::MO_TLVP_PIC_BASE;
13405     else
13406       OpFlag = X86II::MO_TLVP;
13407     SDLoc DL(Op);
13408     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
13409                                                 GA->getValueType(0),
13410                                                 GA->getOffset(), OpFlag);
13411     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13412
13413     // With PIC32, the address is actually $g + Offset.
13414     if (PIC32)
13415       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13416                            DAG.getNode(X86ISD::GlobalBaseReg,
13417                                        SDLoc(), getPointerTy()),
13418                            Offset);
13419
13420     // Lowering the machine isd will make sure everything is in the right
13421     // location.
13422     SDValue Chain = DAG.getEntryNode();
13423     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13424     SDValue Args[] = { Chain, Offset };
13425     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
13426
13427     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
13428     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13429     MFI->setAdjustsStack(true);
13430
13431     // And our return value (tls address) is in the standard call return value
13432     // location.
13433     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13434     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
13435                               Chain.getValue(1));
13436   }
13437
13438   if (Subtarget->isTargetKnownWindowsMSVC() ||
13439       Subtarget->isTargetWindowsGNU()) {
13440     // Just use the implicit TLS architecture
13441     // Need to generate someting similar to:
13442     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
13443     //                                  ; from TEB
13444     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
13445     //   mov     rcx, qword [rdx+rcx*8]
13446     //   mov     eax, .tls$:tlsvar
13447     //   [rax+rcx] contains the address
13448     // Windows 64bit: gs:0x58
13449     // Windows 32bit: fs:__tls_array
13450
13451     SDLoc dl(GA);
13452     SDValue Chain = DAG.getEntryNode();
13453
13454     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
13455     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
13456     // use its literal value of 0x2C.
13457     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
13458                                         ? Type::getInt8PtrTy(*DAG.getContext(),
13459                                                              256)
13460                                         : Type::getInt32PtrTy(*DAG.getContext(),
13461                                                               257));
13462
13463     SDValue TlsArray =
13464         Subtarget->is64Bit()
13465             ? DAG.getIntPtrConstant(0x58)
13466             : (Subtarget->isTargetWindowsGNU()
13467                    ? DAG.getIntPtrConstant(0x2C)
13468                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
13469
13470     SDValue ThreadPointer =
13471         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
13472                     MachinePointerInfo(Ptr), false, false, false, 0);
13473
13474     // Load the _tls_index variable
13475     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
13476     if (Subtarget->is64Bit())
13477       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
13478                            IDX, MachinePointerInfo(), MVT::i32,
13479                            false, false, false, 0);
13480     else
13481       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
13482                         false, false, false, 0);
13483
13484     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
13485                                     getPointerTy());
13486     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
13487
13488     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
13489     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
13490                       false, false, false, 0);
13491
13492     // Get the offset of start of .tls section
13493     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13494                                              GA->getValueType(0),
13495                                              GA->getOffset(), X86II::MO_SECREL);
13496     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
13497
13498     // The address of the thread local variable is the add of the thread
13499     // pointer with the offset of the variable.
13500     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
13501   }
13502
13503   llvm_unreachable("TLS not implemented for this target.");
13504 }
13505
13506 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
13507 /// and take a 2 x i32 value to shift plus a shift amount.
13508 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
13509   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
13510   MVT VT = Op.getSimpleValueType();
13511   unsigned VTBits = VT.getSizeInBits();
13512   SDLoc dl(Op);
13513   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
13514   SDValue ShOpLo = Op.getOperand(0);
13515   SDValue ShOpHi = Op.getOperand(1);
13516   SDValue ShAmt  = Op.getOperand(2);
13517   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
13518   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
13519   // during isel.
13520   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13521                                   DAG.getConstant(VTBits - 1, MVT::i8));
13522   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
13523                                      DAG.getConstant(VTBits - 1, MVT::i8))
13524                        : DAG.getConstant(0, VT);
13525
13526   SDValue Tmp2, Tmp3;
13527   if (Op.getOpcode() == ISD::SHL_PARTS) {
13528     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
13529     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
13530   } else {
13531     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
13532     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
13533   }
13534
13535   // If the shift amount is larger or equal than the width of a part we can't
13536   // rely on the results of shld/shrd. Insert a test and select the appropriate
13537   // values for large shift amounts.
13538   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13539                                 DAG.getConstant(VTBits, MVT::i8));
13540   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13541                              AndNode, DAG.getConstant(0, MVT::i8));
13542
13543   SDValue Hi, Lo;
13544   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13545   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
13546   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
13547
13548   if (Op.getOpcode() == ISD::SHL_PARTS) {
13549     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13550     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13551   } else {
13552     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13553     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13554   }
13555
13556   SDValue Ops[2] = { Lo, Hi };
13557   return DAG.getMergeValues(Ops, dl);
13558 }
13559
13560 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
13561                                            SelectionDAG &DAG) const {
13562   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13563   SDLoc dl(Op);
13564
13565   if (SrcVT.isVector()) {
13566     if (SrcVT.getVectorElementType() == MVT::i1) {
13567       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
13568       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13569                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
13570                                      Op.getOperand(0)));
13571     }
13572     return SDValue();
13573   }
13574
13575   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
13576          "Unknown SINT_TO_FP to lower!");
13577
13578   // These are really Legal; return the operand so the caller accepts it as
13579   // Legal.
13580   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
13581     return Op;
13582   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
13583       Subtarget->is64Bit()) {
13584     return Op;
13585   }
13586
13587   unsigned Size = SrcVT.getSizeInBits()/8;
13588   MachineFunction &MF = DAG.getMachineFunction();
13589   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
13590   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13591   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13592                                StackSlot,
13593                                MachinePointerInfo::getFixedStack(SSFI),
13594                                false, false, 0);
13595   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
13596 }
13597
13598 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
13599                                      SDValue StackSlot,
13600                                      SelectionDAG &DAG) const {
13601   // Build the FILD
13602   SDLoc DL(Op);
13603   SDVTList Tys;
13604   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
13605   if (useSSE)
13606     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
13607   else
13608     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
13609
13610   unsigned ByteSize = SrcVT.getSizeInBits()/8;
13611
13612   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
13613   MachineMemOperand *MMO;
13614   if (FI) {
13615     int SSFI = FI->getIndex();
13616     MMO =
13617       DAG.getMachineFunction()
13618       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13619                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
13620   } else {
13621     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
13622     StackSlot = StackSlot.getOperand(1);
13623   }
13624   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
13625   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
13626                                            X86ISD::FILD, DL,
13627                                            Tys, Ops, SrcVT, MMO);
13628
13629   if (useSSE) {
13630     Chain = Result.getValue(1);
13631     SDValue InFlag = Result.getValue(2);
13632
13633     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
13634     // shouldn't be necessary except that RFP cannot be live across
13635     // multiple blocks. When stackifier is fixed, they can be uncoupled.
13636     MachineFunction &MF = DAG.getMachineFunction();
13637     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
13638     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
13639     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13640     Tys = DAG.getVTList(MVT::Other);
13641     SDValue Ops[] = {
13642       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
13643     };
13644     MachineMemOperand *MMO =
13645       DAG.getMachineFunction()
13646       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13647                             MachineMemOperand::MOStore, SSFISize, SSFISize);
13648
13649     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
13650                                     Ops, Op.getValueType(), MMO);
13651     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
13652                          MachinePointerInfo::getFixedStack(SSFI),
13653                          false, false, false, 0);
13654   }
13655
13656   return Result;
13657 }
13658
13659 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
13660 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
13661                                                SelectionDAG &DAG) const {
13662   // This algorithm is not obvious. Here it is what we're trying to output:
13663   /*
13664      movq       %rax,  %xmm0
13665      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
13666      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
13667      #ifdef __SSE3__
13668        haddpd   %xmm0, %xmm0
13669      #else
13670        pshufd   $0x4e, %xmm0, %xmm1
13671        addpd    %xmm1, %xmm0
13672      #endif
13673   */
13674
13675   SDLoc dl(Op);
13676   LLVMContext *Context = DAG.getContext();
13677
13678   // Build some magic constants.
13679   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
13680   Constant *C0 = ConstantDataVector::get(*Context, CV0);
13681   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
13682
13683   SmallVector<Constant*,2> CV1;
13684   CV1.push_back(
13685     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13686                                       APInt(64, 0x4330000000000000ULL))));
13687   CV1.push_back(
13688     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13689                                       APInt(64, 0x4530000000000000ULL))));
13690   Constant *C1 = ConstantVector::get(CV1);
13691   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
13692
13693   // Load the 64-bit value into an XMM register.
13694   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
13695                             Op.getOperand(0));
13696   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
13697                               MachinePointerInfo::getConstantPool(),
13698                               false, false, false, 16);
13699   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
13700                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
13701                               CLod0);
13702
13703   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
13704                               MachinePointerInfo::getConstantPool(),
13705                               false, false, false, 16);
13706   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
13707   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
13708   SDValue Result;
13709
13710   if (Subtarget->hasSSE3()) {
13711     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
13712     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
13713   } else {
13714     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
13715     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
13716                                            S2F, 0x4E, DAG);
13717     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
13718                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
13719                          Sub);
13720   }
13721
13722   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
13723                      DAG.getIntPtrConstant(0));
13724 }
13725
13726 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
13727 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
13728                                                SelectionDAG &DAG) const {
13729   SDLoc dl(Op);
13730   // FP constant to bias correct the final result.
13731   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13732                                    MVT::f64);
13733
13734   // Load the 32-bit value into an XMM register.
13735   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
13736                              Op.getOperand(0));
13737
13738   // Zero out the upper parts of the register.
13739   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
13740
13741   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13742                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
13743                      DAG.getIntPtrConstant(0));
13744
13745   // Or the load with the bias.
13746   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
13747                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13748                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13749                                                    MVT::v2f64, Load)),
13750                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13751                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13752                                                    MVT::v2f64, Bias)));
13753   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13754                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
13755                    DAG.getIntPtrConstant(0));
13756
13757   // Subtract the bias.
13758   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
13759
13760   // Handle final rounding.
13761   EVT DestVT = Op.getValueType();
13762
13763   if (DestVT.bitsLT(MVT::f64))
13764     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
13765                        DAG.getIntPtrConstant(0));
13766   if (DestVT.bitsGT(MVT::f64))
13767     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
13768
13769   // Handle final rounding.
13770   return Sub;
13771 }
13772
13773 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
13774                                      const X86Subtarget &Subtarget) {
13775   // The algorithm is the following:
13776   // #ifdef __SSE4_1__
13777   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13778   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13779   //                                 (uint4) 0x53000000, 0xaa);
13780   // #else
13781   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13782   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13783   // #endif
13784   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13785   //     return (float4) lo + fhi;
13786
13787   SDLoc DL(Op);
13788   SDValue V = Op->getOperand(0);
13789   EVT VecIntVT = V.getValueType();
13790   bool Is128 = VecIntVT == MVT::v4i32;
13791   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
13792   // If we convert to something else than the supported type, e.g., to v4f64,
13793   // abort early.
13794   if (VecFloatVT != Op->getValueType(0))
13795     return SDValue();
13796
13797   unsigned NumElts = VecIntVT.getVectorNumElements();
13798   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
13799          "Unsupported custom type");
13800   assert(NumElts <= 8 && "The size of the constant array must be fixed");
13801
13802   // In the #idef/#else code, we have in common:
13803   // - The vector of constants:
13804   // -- 0x4b000000
13805   // -- 0x53000000
13806   // - A shift:
13807   // -- v >> 16
13808
13809   // Create the splat vector for 0x4b000000.
13810   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
13811   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
13812                            CstLow, CstLow, CstLow, CstLow};
13813   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13814                                   makeArrayRef(&CstLowArray[0], NumElts));
13815   // Create the splat vector for 0x53000000.
13816   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
13817   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
13818                             CstHigh, CstHigh, CstHigh, CstHigh};
13819   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13820                                    makeArrayRef(&CstHighArray[0], NumElts));
13821
13822   // Create the right shift.
13823   SDValue CstShift = DAG.getConstant(16, MVT::i32);
13824   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
13825                              CstShift, CstShift, CstShift, CstShift};
13826   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13827                                     makeArrayRef(&CstShiftArray[0], NumElts));
13828   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
13829
13830   SDValue Low, High;
13831   if (Subtarget.hasSSE41()) {
13832     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
13833     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13834     SDValue VecCstLowBitcast =
13835         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
13836     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
13837     // Low will be bitcasted right away, so do not bother bitcasting back to its
13838     // original type.
13839     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
13840                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
13841     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13842     //                                 (uint4) 0x53000000, 0xaa);
13843     SDValue VecCstHighBitcast =
13844         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
13845     SDValue VecShiftBitcast =
13846         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
13847     // High will be bitcasted right away, so do not bother bitcasting back to
13848     // its original type.
13849     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
13850                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
13851   } else {
13852     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
13853     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13854                                      CstMask, CstMask, CstMask);
13855     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13856     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13857     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13858
13859     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13860     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13861   }
13862
13863   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13864   SDValue CstFAdd = DAG.getConstantFP(
13865       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
13866   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13867                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13868   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13869                                    makeArrayRef(&CstFAddArray[0], NumElts));
13870
13871   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13872   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
13873   SDValue FHigh =
13874       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13875   //     return (float4) lo + fhi;
13876   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
13877   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13878 }
13879
13880 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13881                                                SelectionDAG &DAG) const {
13882   SDValue N0 = Op.getOperand(0);
13883   MVT SVT = N0.getSimpleValueType();
13884   SDLoc dl(Op);
13885
13886   switch (SVT.SimpleTy) {
13887   default:
13888     llvm_unreachable("Custom UINT_TO_FP is not supported!");
13889   case MVT::v4i8:
13890   case MVT::v4i16:
13891   case MVT::v8i8:
13892   case MVT::v8i16: {
13893     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13894     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13895                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13896   }
13897   case MVT::v4i32:
13898   case MVT::v8i32:
13899     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13900   }
13901   llvm_unreachable(nullptr);
13902 }
13903
13904 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13905                                            SelectionDAG &DAG) const {
13906   SDValue N0 = Op.getOperand(0);
13907   SDLoc dl(Op);
13908
13909   if (Op.getValueType().isVector())
13910     return lowerUINT_TO_FP_vec(Op, DAG);
13911
13912   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13913   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13914   // the optimization here.
13915   if (DAG.SignBitIsZero(N0))
13916     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13917
13918   MVT SrcVT = N0.getSimpleValueType();
13919   MVT DstVT = Op.getSimpleValueType();
13920   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13921     return LowerUINT_TO_FP_i64(Op, DAG);
13922   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13923     return LowerUINT_TO_FP_i32(Op, DAG);
13924   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13925     return SDValue();
13926
13927   // Make a 64-bit buffer, and use it to build an FILD.
13928   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13929   if (SrcVT == MVT::i32) {
13930     SDValue WordOff = DAG.getConstant(4, getPointerTy());
13931     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
13932                                      getPointerTy(), StackSlot, WordOff);
13933     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13934                                   StackSlot, MachinePointerInfo(),
13935                                   false, false, 0);
13936     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
13937                                   OffsetSlot, MachinePointerInfo(),
13938                                   false, false, 0);
13939     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13940     return Fild;
13941   }
13942
13943   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13944   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13945                                StackSlot, MachinePointerInfo(),
13946                                false, false, 0);
13947   // For i64 source, we need to add the appropriate power of 2 if the input
13948   // was negative.  This is the same as the optimization in
13949   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13950   // we must be careful to do the computation in x87 extended precision, not
13951   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13952   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13953   MachineMemOperand *MMO =
13954     DAG.getMachineFunction()
13955     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13956                           MachineMemOperand::MOLoad, 8, 8);
13957
13958   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13959   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13960   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13961                                          MVT::i64, MMO);
13962
13963   APInt FF(32, 0x5F800000ULL);
13964
13965   // Check whether the sign bit is set.
13966   SDValue SignSet = DAG.getSetCC(dl,
13967                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
13968                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
13969                                  ISD::SETLT);
13970
13971   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13972   SDValue FudgePtr = DAG.getConstantPool(
13973                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
13974                                          getPointerTy());
13975
13976   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13977   SDValue Zero = DAG.getIntPtrConstant(0);
13978   SDValue Four = DAG.getIntPtrConstant(4);
13979   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13980                                Zero, Four);
13981   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
13982
13983   // Load the value out, extending it from f32 to f80.
13984   // FIXME: Avoid the extend by constructing the right constant pool?
13985   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
13986                                  FudgePtr, MachinePointerInfo::getConstantPool(),
13987                                  MVT::f32, false, false, false, 4);
13988   // Extend everything to 80 bits to force it to be done on x87.
13989   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13990   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
13991 }
13992
13993 std::pair<SDValue,SDValue>
13994 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13995                                     bool IsSigned, bool IsReplace) const {
13996   SDLoc DL(Op);
13997
13998   EVT DstTy = Op.getValueType();
13999
14000   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
14001     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
14002     DstTy = MVT::i64;
14003   }
14004
14005   assert(DstTy.getSimpleVT() <= MVT::i64 &&
14006          DstTy.getSimpleVT() >= MVT::i16 &&
14007          "Unknown FP_TO_INT to lower!");
14008
14009   // These are really Legal.
14010   if (DstTy == MVT::i32 &&
14011       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14012     return std::make_pair(SDValue(), SDValue());
14013   if (Subtarget->is64Bit() &&
14014       DstTy == MVT::i64 &&
14015       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
14016     return std::make_pair(SDValue(), SDValue());
14017
14018   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
14019   // stack slot, or into the FTOL runtime function.
14020   MachineFunction &MF = DAG.getMachineFunction();
14021   unsigned MemSize = DstTy.getSizeInBits()/8;
14022   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14023   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14024
14025   unsigned Opc;
14026   if (!IsSigned && isIntegerTypeFTOL(DstTy))
14027     Opc = X86ISD::WIN_FTOL;
14028   else
14029     switch (DstTy.getSimpleVT().SimpleTy) {
14030     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
14031     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
14032     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
14033     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
14034     }
14035
14036   SDValue Chain = DAG.getEntryNode();
14037   SDValue Value = Op.getOperand(0);
14038   EVT TheVT = Op.getOperand(0).getValueType();
14039   // FIXME This causes a redundant load/store if the SSE-class value is already
14040   // in memory, such as if it is on the callstack.
14041   if (isScalarFPTypeInSSEReg(TheVT)) {
14042     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
14043     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
14044                          MachinePointerInfo::getFixedStack(SSFI),
14045                          false, false, 0);
14046     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
14047     SDValue Ops[] = {
14048       Chain, StackSlot, DAG.getValueType(TheVT)
14049     };
14050
14051     MachineMemOperand *MMO =
14052       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14053                               MachineMemOperand::MOLoad, MemSize, MemSize);
14054     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
14055     Chain = Value.getValue(1);
14056     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14057     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14058   }
14059
14060   MachineMemOperand *MMO =
14061     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14062                             MachineMemOperand::MOStore, MemSize, MemSize);
14063
14064   if (Opc != X86ISD::WIN_FTOL) {
14065     // Build the FP_TO_INT*_IN_MEM
14066     SDValue Ops[] = { Chain, Value, StackSlot };
14067     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
14068                                            Ops, DstTy, MMO);
14069     return std::make_pair(FIST, StackSlot);
14070   } else {
14071     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
14072       DAG.getVTList(MVT::Other, MVT::Glue),
14073       Chain, Value);
14074     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
14075       MVT::i32, ftol.getValue(1));
14076     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
14077       MVT::i32, eax.getValue(2));
14078     SDValue Ops[] = { eax, edx };
14079     SDValue pair = IsReplace
14080       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
14081       : DAG.getMergeValues(Ops, DL);
14082     return std::make_pair(pair, SDValue());
14083   }
14084 }
14085
14086 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
14087                               const X86Subtarget *Subtarget) {
14088   MVT VT = Op->getSimpleValueType(0);
14089   SDValue In = Op->getOperand(0);
14090   MVT InVT = In.getSimpleValueType();
14091   SDLoc dl(Op);
14092
14093   // Optimize vectors in AVX mode:
14094   //
14095   //   v8i16 -> v8i32
14096   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
14097   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
14098   //   Concat upper and lower parts.
14099   //
14100   //   v4i32 -> v4i64
14101   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
14102   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
14103   //   Concat upper and lower parts.
14104   //
14105
14106   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
14107       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
14108       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
14109     return SDValue();
14110
14111   if (Subtarget->hasInt256())
14112     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
14113
14114   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
14115   SDValue Undef = DAG.getUNDEF(InVT);
14116   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
14117   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14118   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14119
14120   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
14121                              VT.getVectorNumElements()/2);
14122
14123   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
14124   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
14125
14126   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14127 }
14128
14129 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
14130                                         SelectionDAG &DAG) {
14131   MVT VT = Op->getSimpleValueType(0);
14132   SDValue In = Op->getOperand(0);
14133   MVT InVT = In.getSimpleValueType();
14134   SDLoc DL(Op);
14135   unsigned int NumElts = VT.getVectorNumElements();
14136   if (NumElts != 8 && NumElts != 16)
14137     return SDValue();
14138
14139   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
14140     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
14141
14142   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
14143   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14144   // Now we have only mask extension
14145   assert(InVT.getVectorElementType() == MVT::i1);
14146   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
14147   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14148   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
14149   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14150   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14151                            MachinePointerInfo::getConstantPool(),
14152                            false, false, false, Alignment);
14153
14154   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
14155   if (VT.is512BitVector())
14156     return Brcst;
14157   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
14158 }
14159
14160 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14161                                SelectionDAG &DAG) {
14162   if (Subtarget->hasFp256()) {
14163     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14164     if (Res.getNode())
14165       return Res;
14166   }
14167
14168   return SDValue();
14169 }
14170
14171 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14172                                 SelectionDAG &DAG) {
14173   SDLoc DL(Op);
14174   MVT VT = Op.getSimpleValueType();
14175   SDValue In = Op.getOperand(0);
14176   MVT SVT = In.getSimpleValueType();
14177
14178   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
14179     return LowerZERO_EXTEND_AVX512(Op, DAG);
14180
14181   if (Subtarget->hasFp256()) {
14182     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14183     if (Res.getNode())
14184       return Res;
14185   }
14186
14187   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
14188          VT.getVectorNumElements() != SVT.getVectorNumElements());
14189   return SDValue();
14190 }
14191
14192 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
14193   SDLoc DL(Op);
14194   MVT VT = Op.getSimpleValueType();
14195   SDValue In = Op.getOperand(0);
14196   MVT InVT = In.getSimpleValueType();
14197
14198   if (VT == MVT::i1) {
14199     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
14200            "Invalid scalar TRUNCATE operation");
14201     if (InVT.getSizeInBits() >= 32)
14202       return SDValue();
14203     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
14204     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
14205   }
14206   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
14207          "Invalid TRUNCATE operation");
14208
14209   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
14210     if (VT.getVectorElementType().getSizeInBits() >=8)
14211       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
14212
14213     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14214     unsigned NumElts = InVT.getVectorNumElements();
14215     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
14216     if (InVT.getSizeInBits() < 512) {
14217       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
14218       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
14219       InVT = ExtVT;
14220     }
14221
14222     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
14223     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14224     SDValue CP = DAG.getConstantPool(C, getPointerTy());
14225     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14226     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14227                            MachinePointerInfo::getConstantPool(),
14228                            false, false, false, Alignment);
14229     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
14230     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
14231     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
14232   }
14233
14234   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
14235     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
14236     if (Subtarget->hasInt256()) {
14237       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14238       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
14239       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
14240                                 ShufMask);
14241       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
14242                          DAG.getIntPtrConstant(0));
14243     }
14244
14245     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14246                                DAG.getIntPtrConstant(0));
14247     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14248                                DAG.getIntPtrConstant(2));
14249     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14250     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14251     static const int ShufMask[] = {0, 2, 4, 6};
14252     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
14253   }
14254
14255   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
14256     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
14257     if (Subtarget->hasInt256()) {
14258       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
14259
14260       SmallVector<SDValue,32> pshufbMask;
14261       for (unsigned i = 0; i < 2; ++i) {
14262         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14263         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14264         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14265         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14266         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14267         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14268         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14269         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14270         for (unsigned j = 0; j < 8; ++j)
14271           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14272       }
14273       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
14274       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
14275       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
14276
14277       static const int ShufMask[] = {0,  2,  -1,  -1};
14278       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
14279                                 &ShufMask[0]);
14280       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14281                        DAG.getIntPtrConstant(0));
14282       return DAG.getNode(ISD::BITCAST, DL, VT, In);
14283     }
14284
14285     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14286                                DAG.getIntPtrConstant(0));
14287
14288     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14289                                DAG.getIntPtrConstant(4));
14290
14291     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
14292     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
14293
14294     // The PSHUFB mask:
14295     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14296                                    -1, -1, -1, -1, -1, -1, -1, -1};
14297
14298     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14299     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
14300     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
14301
14302     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14303     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14304
14305     // The MOVLHPS Mask:
14306     static const int ShufMask2[] = {0, 1, 4, 5};
14307     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
14308     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
14309   }
14310
14311   // Handle truncation of V256 to V128 using shuffles.
14312   if (!VT.is128BitVector() || !InVT.is256BitVector())
14313     return SDValue();
14314
14315   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
14316
14317   unsigned NumElems = VT.getVectorNumElements();
14318   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
14319
14320   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
14321   // Prepare truncation shuffle mask
14322   for (unsigned i = 0; i != NumElems; ++i)
14323     MaskVec[i] = i * 2;
14324   SDValue V = DAG.getVectorShuffle(NVT, DL,
14325                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
14326                                    DAG.getUNDEF(NVT), &MaskVec[0]);
14327   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
14328                      DAG.getIntPtrConstant(0));
14329 }
14330
14331 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
14332                                            SelectionDAG &DAG) const {
14333   assert(!Op.getSimpleValueType().isVector());
14334
14335   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14336     /*IsSigned=*/ true, /*IsReplace=*/ false);
14337   SDValue FIST = Vals.first, StackSlot = Vals.second;
14338   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
14339   if (!FIST.getNode()) return Op;
14340
14341   if (StackSlot.getNode())
14342     // Load the result.
14343     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14344                        FIST, StackSlot, MachinePointerInfo(),
14345                        false, false, false, 0);
14346
14347   // The node is the result.
14348   return FIST;
14349 }
14350
14351 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
14352                                            SelectionDAG &DAG) const {
14353   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14354     /*IsSigned=*/ false, /*IsReplace=*/ false);
14355   SDValue FIST = Vals.first, StackSlot = Vals.second;
14356   assert(FIST.getNode() && "Unexpected failure");
14357
14358   if (StackSlot.getNode())
14359     // Load the result.
14360     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14361                        FIST, StackSlot, MachinePointerInfo(),
14362                        false, false, false, 0);
14363
14364   // The node is the result.
14365   return FIST;
14366 }
14367
14368 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
14369   SDLoc DL(Op);
14370   MVT VT = Op.getSimpleValueType();
14371   SDValue In = Op.getOperand(0);
14372   MVT SVT = In.getSimpleValueType();
14373
14374   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
14375
14376   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
14377                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
14378                                  In, DAG.getUNDEF(SVT)));
14379 }
14380
14381 /// The only differences between FABS and FNEG are the mask and the logic op.
14382 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
14383 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
14384   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
14385          "Wrong opcode for lowering FABS or FNEG.");
14386
14387   bool IsFABS = (Op.getOpcode() == ISD::FABS);
14388
14389   // If this is a FABS and it has an FNEG user, bail out to fold the combination
14390   // into an FNABS. We'll lower the FABS after that if it is still in use.
14391   if (IsFABS)
14392     for (SDNode *User : Op->uses())
14393       if (User->getOpcode() == ISD::FNEG)
14394         return Op;
14395
14396   SDValue Op0 = Op.getOperand(0);
14397   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
14398
14399   SDLoc dl(Op);
14400   MVT VT = Op.getSimpleValueType();
14401   // Assume scalar op for initialization; update for vector if needed.
14402   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
14403   // generate a 16-byte vector constant and logic op even for the scalar case.
14404   // Using a 16-byte mask allows folding the load of the mask with
14405   // the logic op, so it can save (~4 bytes) on code size.
14406   MVT EltVT = VT;
14407   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
14408   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
14409   // decide if we should generate a 16-byte constant mask when we only need 4 or
14410   // 8 bytes for the scalar case.
14411   if (VT.isVector()) {
14412     EltVT = VT.getVectorElementType();
14413     NumElts = VT.getVectorNumElements();
14414   }
14415
14416   unsigned EltBits = EltVT.getSizeInBits();
14417   LLVMContext *Context = DAG.getContext();
14418   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
14419   APInt MaskElt =
14420     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
14421   Constant *C = ConstantInt::get(*Context, MaskElt);
14422   C = ConstantVector::getSplat(NumElts, C);
14423   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14424   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
14425   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14426   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14427                              MachinePointerInfo::getConstantPool(),
14428                              false, false, false, Alignment);
14429
14430   if (VT.isVector()) {
14431     // For a vector, cast operands to a vector type, perform the logic op,
14432     // and cast the result back to the original value type.
14433     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
14434     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
14435     SDValue Operand = IsFNABS ?
14436       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
14437       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
14438     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
14439     return DAG.getNode(ISD::BITCAST, dl, VT,
14440                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
14441   }
14442
14443   // If not vector, then scalar.
14444   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
14445   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
14446   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
14447 }
14448
14449 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
14450   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14451   LLVMContext *Context = DAG.getContext();
14452   SDValue Op0 = Op.getOperand(0);
14453   SDValue Op1 = Op.getOperand(1);
14454   SDLoc dl(Op);
14455   MVT VT = Op.getSimpleValueType();
14456   MVT SrcVT = Op1.getSimpleValueType();
14457
14458   // If second operand is smaller, extend it first.
14459   if (SrcVT.bitsLT(VT)) {
14460     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
14461     SrcVT = VT;
14462   }
14463   // And if it is bigger, shrink it first.
14464   if (SrcVT.bitsGT(VT)) {
14465     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
14466     SrcVT = VT;
14467   }
14468
14469   // At this point the operands and the result should have the same
14470   // type, and that won't be f80 since that is not custom lowered.
14471
14472   const fltSemantics &Sem =
14473       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
14474   const unsigned SizeInBits = VT.getSizeInBits();
14475
14476   SmallVector<Constant *, 4> CV(
14477       VT == MVT::f64 ? 2 : 4,
14478       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
14479
14480   // First, clear all bits but the sign bit from the second operand (sign).
14481   CV[0] = ConstantFP::get(*Context,
14482                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
14483   Constant *C = ConstantVector::get(CV);
14484   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14485   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
14486                               MachinePointerInfo::getConstantPool(),
14487                               false, false, false, 16);
14488   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
14489
14490   // Next, clear the sign bit from the first operand (magnitude).
14491   CV[0] = ConstantFP::get(
14492       *Context, APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
14493   C = ConstantVector::get(CV);
14494   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14495   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14496                               MachinePointerInfo::getConstantPool(),
14497                               false, false, false, 16);
14498   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
14499
14500   // OR the magnitude value with the sign bit.
14501   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
14502 }
14503
14504 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
14505   SDValue N0 = Op.getOperand(0);
14506   SDLoc dl(Op);
14507   MVT VT = Op.getSimpleValueType();
14508
14509   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
14510   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
14511                                   DAG.getConstant(1, VT));
14512   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
14513 }
14514
14515 // Check whether an OR'd tree is PTEST-able.
14516 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
14517                                       SelectionDAG &DAG) {
14518   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
14519
14520   if (!Subtarget->hasSSE41())
14521     return SDValue();
14522
14523   if (!Op->hasOneUse())
14524     return SDValue();
14525
14526   SDNode *N = Op.getNode();
14527   SDLoc DL(N);
14528
14529   SmallVector<SDValue, 8> Opnds;
14530   DenseMap<SDValue, unsigned> VecInMap;
14531   SmallVector<SDValue, 8> VecIns;
14532   EVT VT = MVT::Other;
14533
14534   // Recognize a special case where a vector is casted into wide integer to
14535   // test all 0s.
14536   Opnds.push_back(N->getOperand(0));
14537   Opnds.push_back(N->getOperand(1));
14538
14539   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14540     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
14541     // BFS traverse all OR'd operands.
14542     if (I->getOpcode() == ISD::OR) {
14543       Opnds.push_back(I->getOperand(0));
14544       Opnds.push_back(I->getOperand(1));
14545       // Re-evaluate the number of nodes to be traversed.
14546       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14547       continue;
14548     }
14549
14550     // Quit if a non-EXTRACT_VECTOR_ELT
14551     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14552       return SDValue();
14553
14554     // Quit if without a constant index.
14555     SDValue Idx = I->getOperand(1);
14556     if (!isa<ConstantSDNode>(Idx))
14557       return SDValue();
14558
14559     SDValue ExtractedFromVec = I->getOperand(0);
14560     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
14561     if (M == VecInMap.end()) {
14562       VT = ExtractedFromVec.getValueType();
14563       // Quit if not 128/256-bit vector.
14564       if (!VT.is128BitVector() && !VT.is256BitVector())
14565         return SDValue();
14566       // Quit if not the same type.
14567       if (VecInMap.begin() != VecInMap.end() &&
14568           VT != VecInMap.begin()->first.getValueType())
14569         return SDValue();
14570       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
14571       VecIns.push_back(ExtractedFromVec);
14572     }
14573     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14574   }
14575
14576   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14577          "Not extracted from 128-/256-bit vector.");
14578
14579   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
14580
14581   for (DenseMap<SDValue, unsigned>::const_iterator
14582         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
14583     // Quit if not all elements are used.
14584     if (I->second != FullMask)
14585       return SDValue();
14586   }
14587
14588   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
14589
14590   // Cast all vectors into TestVT for PTEST.
14591   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
14592     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
14593
14594   // If more than one full vectors are evaluated, OR them first before PTEST.
14595   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
14596     // Each iteration will OR 2 nodes and append the result until there is only
14597     // 1 node left, i.e. the final OR'd value of all vectors.
14598     SDValue LHS = VecIns[Slot];
14599     SDValue RHS = VecIns[Slot + 1];
14600     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
14601   }
14602
14603   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
14604                      VecIns.back(), VecIns.back());
14605 }
14606
14607 /// \brief return true if \c Op has a use that doesn't just read flags.
14608 static bool hasNonFlagsUse(SDValue Op) {
14609   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
14610        ++UI) {
14611     SDNode *User = *UI;
14612     unsigned UOpNo = UI.getOperandNo();
14613     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
14614       // Look pass truncate.
14615       UOpNo = User->use_begin().getOperandNo();
14616       User = *User->use_begin();
14617     }
14618
14619     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
14620         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
14621       return true;
14622   }
14623   return false;
14624 }
14625
14626 /// Emit nodes that will be selected as "test Op0,Op0", or something
14627 /// equivalent.
14628 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
14629                                     SelectionDAG &DAG) const {
14630   if (Op.getValueType() == MVT::i1)
14631     // KORTEST instruction should be selected
14632     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14633                        DAG.getConstant(0, Op.getValueType()));
14634
14635   // CF and OF aren't always set the way we want. Determine which
14636   // of these we need.
14637   bool NeedCF = false;
14638   bool NeedOF = false;
14639   switch (X86CC) {
14640   default: break;
14641   case X86::COND_A: case X86::COND_AE:
14642   case X86::COND_B: case X86::COND_BE:
14643     NeedCF = true;
14644     break;
14645   case X86::COND_G: case X86::COND_GE:
14646   case X86::COND_L: case X86::COND_LE:
14647   case X86::COND_O: case X86::COND_NO: {
14648     // Check if we really need to set the
14649     // Overflow flag. If NoSignedWrap is present
14650     // that is not actually needed.
14651     switch (Op->getOpcode()) {
14652     case ISD::ADD:
14653     case ISD::SUB:
14654     case ISD::MUL:
14655     case ISD::SHL: {
14656       const BinaryWithFlagsSDNode *BinNode =
14657           cast<BinaryWithFlagsSDNode>(Op.getNode());
14658       if (BinNode->hasNoSignedWrap())
14659         break;
14660     }
14661     default:
14662       NeedOF = true;
14663       break;
14664     }
14665     break;
14666   }
14667   }
14668   // See if we can use the EFLAGS value from the operand instead of
14669   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14670   // we prove that the arithmetic won't overflow, we can't use OF or CF.
14671   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14672     // Emit a CMP with 0, which is the TEST pattern.
14673     //if (Op.getValueType() == MVT::i1)
14674     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14675     //                     DAG.getConstant(0, MVT::i1));
14676     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14677                        DAG.getConstant(0, Op.getValueType()));
14678   }
14679   unsigned Opcode = 0;
14680   unsigned NumOperands = 0;
14681
14682   // Truncate operations may prevent the merge of the SETCC instruction
14683   // and the arithmetic instruction before it. Attempt to truncate the operands
14684   // of the arithmetic instruction and use a reduced bit-width instruction.
14685   bool NeedTruncation = false;
14686   SDValue ArithOp = Op;
14687   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14688     SDValue Arith = Op->getOperand(0);
14689     // Both the trunc and the arithmetic op need to have one user each.
14690     if (Arith->hasOneUse())
14691       switch (Arith.getOpcode()) {
14692         default: break;
14693         case ISD::ADD:
14694         case ISD::SUB:
14695         case ISD::AND:
14696         case ISD::OR:
14697         case ISD::XOR: {
14698           NeedTruncation = true;
14699           ArithOp = Arith;
14700         }
14701       }
14702   }
14703
14704   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14705   // which may be the result of a CAST.  We use the variable 'Op', which is the
14706   // non-casted variable when we check for possible users.
14707   switch (ArithOp.getOpcode()) {
14708   case ISD::ADD:
14709     // Due to an isel shortcoming, be conservative if this add is likely to be
14710     // selected as part of a load-modify-store instruction. When the root node
14711     // in a match is a store, isel doesn't know how to remap non-chain non-flag
14712     // uses of other nodes in the match, such as the ADD in this case. This
14713     // leads to the ADD being left around and reselected, with the result being
14714     // two adds in the output.  Alas, even if none our users are stores, that
14715     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
14716     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
14717     // climbing the DAG back to the root, and it doesn't seem to be worth the
14718     // effort.
14719     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14720          UE = Op.getNode()->use_end(); UI != UE; ++UI)
14721       if (UI->getOpcode() != ISD::CopyToReg &&
14722           UI->getOpcode() != ISD::SETCC &&
14723           UI->getOpcode() != ISD::STORE)
14724         goto default_case;
14725
14726     if (ConstantSDNode *C =
14727         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14728       // An add of one will be selected as an INC.
14729       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
14730         Opcode = X86ISD::INC;
14731         NumOperands = 1;
14732         break;
14733       }
14734
14735       // An add of negative one (subtract of one) will be selected as a DEC.
14736       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
14737         Opcode = X86ISD::DEC;
14738         NumOperands = 1;
14739         break;
14740       }
14741     }
14742
14743     // Otherwise use a regular EFLAGS-setting add.
14744     Opcode = X86ISD::ADD;
14745     NumOperands = 2;
14746     break;
14747   case ISD::SHL:
14748   case ISD::SRL:
14749     // If we have a constant logical shift that's only used in a comparison
14750     // against zero turn it into an equivalent AND. This allows turning it into
14751     // a TEST instruction later.
14752     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14753         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14754       EVT VT = Op.getValueType();
14755       unsigned BitWidth = VT.getSizeInBits();
14756       unsigned ShAmt = Op->getConstantOperandVal(1);
14757       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14758         break;
14759       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14760                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14761                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14762       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14763         break;
14764       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14765                                 DAG.getConstant(Mask, VT));
14766       DAG.ReplaceAllUsesWith(Op, New);
14767       Op = New;
14768     }
14769     break;
14770
14771   case ISD::AND:
14772     // If the primary and result isn't used, don't bother using X86ISD::AND,
14773     // because a TEST instruction will be better.
14774     if (!hasNonFlagsUse(Op))
14775       break;
14776     // FALL THROUGH
14777   case ISD::SUB:
14778   case ISD::OR:
14779   case ISD::XOR:
14780     // Due to the ISEL shortcoming noted above, be conservative if this op is
14781     // likely to be selected as part of a load-modify-store instruction.
14782     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14783            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14784       if (UI->getOpcode() == ISD::STORE)
14785         goto default_case;
14786
14787     // Otherwise use a regular EFLAGS-setting instruction.
14788     switch (ArithOp.getOpcode()) {
14789     default: llvm_unreachable("unexpected operator!");
14790     case ISD::SUB: Opcode = X86ISD::SUB; break;
14791     case ISD::XOR: Opcode = X86ISD::XOR; break;
14792     case ISD::AND: Opcode = X86ISD::AND; break;
14793     case ISD::OR: {
14794       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14795         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14796         if (EFLAGS.getNode())
14797           return EFLAGS;
14798       }
14799       Opcode = X86ISD::OR;
14800       break;
14801     }
14802     }
14803
14804     NumOperands = 2;
14805     break;
14806   case X86ISD::ADD:
14807   case X86ISD::SUB:
14808   case X86ISD::INC:
14809   case X86ISD::DEC:
14810   case X86ISD::OR:
14811   case X86ISD::XOR:
14812   case X86ISD::AND:
14813     return SDValue(Op.getNode(), 1);
14814   default:
14815   default_case:
14816     break;
14817   }
14818
14819   // If we found that truncation is beneficial, perform the truncation and
14820   // update 'Op'.
14821   if (NeedTruncation) {
14822     EVT VT = Op.getValueType();
14823     SDValue WideVal = Op->getOperand(0);
14824     EVT WideVT = WideVal.getValueType();
14825     unsigned ConvertedOp = 0;
14826     // Use a target machine opcode to prevent further DAGCombine
14827     // optimizations that may separate the arithmetic operations
14828     // from the setcc node.
14829     switch (WideVal.getOpcode()) {
14830       default: break;
14831       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14832       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14833       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14834       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14835       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14836     }
14837
14838     if (ConvertedOp) {
14839       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14840       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14841         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14842         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14843         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14844       }
14845     }
14846   }
14847
14848   if (Opcode == 0)
14849     // Emit a CMP with 0, which is the TEST pattern.
14850     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14851                        DAG.getConstant(0, Op.getValueType()));
14852
14853   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14854   SmallVector<SDValue, 4> Ops;
14855   for (unsigned i = 0; i != NumOperands; ++i)
14856     Ops.push_back(Op.getOperand(i));
14857
14858   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14859   DAG.ReplaceAllUsesWith(Op, New);
14860   return SDValue(New.getNode(), 1);
14861 }
14862
14863 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14864 /// equivalent.
14865 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14866                                    SDLoc dl, SelectionDAG &DAG) const {
14867   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
14868     if (C->getAPIntValue() == 0)
14869       return EmitTest(Op0, X86CC, dl, DAG);
14870
14871      if (Op0.getValueType() == MVT::i1)
14872        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
14873   }
14874
14875   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14876        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14877     // Do the comparison at i32 if it's smaller, besides the Atom case.
14878     // This avoids subregister aliasing issues. Keep the smaller reference
14879     // if we're optimizing for size, however, as that'll allow better folding
14880     // of memory operations.
14881     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14882         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
14883              AttributeSet::FunctionIndex, Attribute::MinSize) &&
14884         !Subtarget->isAtom()) {
14885       unsigned ExtendOp =
14886           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14887       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14888       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14889     }
14890     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14891     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14892     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14893                               Op0, Op1);
14894     return SDValue(Sub.getNode(), 1);
14895   }
14896   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14897 }
14898
14899 /// Convert a comparison if required by the subtarget.
14900 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14901                                                  SelectionDAG &DAG) const {
14902   // If the subtarget does not support the FUCOMI instruction, floating-point
14903   // comparisons have to be converted.
14904   if (Subtarget->hasCMov() ||
14905       Cmp.getOpcode() != X86ISD::CMP ||
14906       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14907       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14908     return Cmp;
14909
14910   // The instruction selector will select an FUCOM instruction instead of
14911   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14912   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14913   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14914   SDLoc dl(Cmp);
14915   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14916   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14917   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14918                             DAG.getConstant(8, MVT::i8));
14919   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14920   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14921 }
14922
14923 /// The minimum architected relative accuracy is 2^-12. We need one
14924 /// Newton-Raphson step to have a good float result (24 bits of precision).
14925 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14926                                             DAGCombinerInfo &DCI,
14927                                             unsigned &RefinementSteps,
14928                                             bool &UseOneConstNR) const {
14929   // FIXME: We should use instruction latency models to calculate the cost of
14930   // each potential sequence, but this is very hard to do reliably because
14931   // at least Intel's Core* chips have variable timing based on the number of
14932   // significant digits in the divisor and/or sqrt operand.
14933   if (!Subtarget->useSqrtEst())
14934     return SDValue();
14935
14936   EVT VT = Op.getValueType();
14937
14938   // SSE1 has rsqrtss and rsqrtps.
14939   // TODO: Add support for AVX512 (v16f32).
14940   // It is likely not profitable to do this for f64 because a double-precision
14941   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14942   // instructions: convert to single, rsqrtss, convert back to double, refine
14943   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14944   // along with FMA, this could be a throughput win.
14945   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14946       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14947     RefinementSteps = 1;
14948     UseOneConstNR = false;
14949     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14950   }
14951   return SDValue();
14952 }
14953
14954 /// The minimum architected relative accuracy is 2^-12. We need one
14955 /// Newton-Raphson step to have a good float result (24 bits of precision).
14956 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14957                                             DAGCombinerInfo &DCI,
14958                                             unsigned &RefinementSteps) const {
14959   // FIXME: We should use instruction latency models to calculate the cost of
14960   // each potential sequence, but this is very hard to do reliably because
14961   // at least Intel's Core* chips have variable timing based on the number of
14962   // significant digits in the divisor.
14963   if (!Subtarget->useReciprocalEst())
14964     return SDValue();
14965
14966   EVT VT = Op.getValueType();
14967
14968   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14969   // TODO: Add support for AVX512 (v16f32).
14970   // It is likely not profitable to do this for f64 because a double-precision
14971   // reciprocal estimate with refinement on x86 prior to FMA requires
14972   // 15 instructions: convert to single, rcpss, convert back to double, refine
14973   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14974   // along with FMA, this could be a throughput win.
14975   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14976       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14977     RefinementSteps = ReciprocalEstimateRefinementSteps;
14978     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14979   }
14980   return SDValue();
14981 }
14982
14983 static bool isAllOnes(SDValue V) {
14984   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
14985   return C && C->isAllOnesValue();
14986 }
14987
14988 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14989 /// if it's possible.
14990 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14991                                      SDLoc dl, SelectionDAG &DAG) const {
14992   SDValue Op0 = And.getOperand(0);
14993   SDValue Op1 = And.getOperand(1);
14994   if (Op0.getOpcode() == ISD::TRUNCATE)
14995     Op0 = Op0.getOperand(0);
14996   if (Op1.getOpcode() == ISD::TRUNCATE)
14997     Op1 = Op1.getOperand(0);
14998
14999   SDValue LHS, RHS;
15000   if (Op1.getOpcode() == ISD::SHL)
15001     std::swap(Op0, Op1);
15002   if (Op0.getOpcode() == ISD::SHL) {
15003     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
15004       if (And00C->getZExtValue() == 1) {
15005         // If we looked past a truncate, check that it's only truncating away
15006         // known zeros.
15007         unsigned BitWidth = Op0.getValueSizeInBits();
15008         unsigned AndBitWidth = And.getValueSizeInBits();
15009         if (BitWidth > AndBitWidth) {
15010           APInt Zeros, Ones;
15011           DAG.computeKnownBits(Op0, Zeros, Ones);
15012           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
15013             return SDValue();
15014         }
15015         LHS = Op1;
15016         RHS = Op0.getOperand(1);
15017       }
15018   } else if (Op1.getOpcode() == ISD::Constant) {
15019     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
15020     uint64_t AndRHSVal = AndRHS->getZExtValue();
15021     SDValue AndLHS = Op0;
15022
15023     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
15024       LHS = AndLHS.getOperand(0);
15025       RHS = AndLHS.getOperand(1);
15026     }
15027
15028     // Use BT if the immediate can't be encoded in a TEST instruction.
15029     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
15030       LHS = AndLHS;
15031       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
15032     }
15033   }
15034
15035   if (LHS.getNode()) {
15036     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
15037     // instruction.  Since the shift amount is in-range-or-undefined, we know
15038     // that doing a bittest on the i32 value is ok.  We extend to i32 because
15039     // the encoding for the i16 version is larger than the i32 version.
15040     // Also promote i16 to i32 for performance / code size reason.
15041     if (LHS.getValueType() == MVT::i8 ||
15042         LHS.getValueType() == MVT::i16)
15043       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
15044
15045     // If the operand types disagree, extend the shift amount to match.  Since
15046     // BT ignores high bits (like shifts) we can use anyextend.
15047     if (LHS.getValueType() != RHS.getValueType())
15048       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
15049
15050     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
15051     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
15052     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15053                        DAG.getConstant(Cond, MVT::i8), BT);
15054   }
15055
15056   return SDValue();
15057 }
15058
15059 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
15060 /// mask CMPs.
15061 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
15062                               SDValue &Op1) {
15063   unsigned SSECC;
15064   bool Swap = false;
15065
15066   // SSE Condition code mapping:
15067   //  0 - EQ
15068   //  1 - LT
15069   //  2 - LE
15070   //  3 - UNORD
15071   //  4 - NEQ
15072   //  5 - NLT
15073   //  6 - NLE
15074   //  7 - ORD
15075   switch (SetCCOpcode) {
15076   default: llvm_unreachable("Unexpected SETCC condition");
15077   case ISD::SETOEQ:
15078   case ISD::SETEQ:  SSECC = 0; break;
15079   case ISD::SETOGT:
15080   case ISD::SETGT:  Swap = true; // Fallthrough
15081   case ISD::SETLT:
15082   case ISD::SETOLT: SSECC = 1; break;
15083   case ISD::SETOGE:
15084   case ISD::SETGE:  Swap = true; // Fallthrough
15085   case ISD::SETLE:
15086   case ISD::SETOLE: SSECC = 2; break;
15087   case ISD::SETUO:  SSECC = 3; break;
15088   case ISD::SETUNE:
15089   case ISD::SETNE:  SSECC = 4; break;
15090   case ISD::SETULE: Swap = true; // Fallthrough
15091   case ISD::SETUGE: SSECC = 5; break;
15092   case ISD::SETULT: Swap = true; // Fallthrough
15093   case ISD::SETUGT: SSECC = 6; break;
15094   case ISD::SETO:   SSECC = 7; break;
15095   case ISD::SETUEQ:
15096   case ISD::SETONE: SSECC = 8; break;
15097   }
15098   if (Swap)
15099     std::swap(Op0, Op1);
15100
15101   return SSECC;
15102 }
15103
15104 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
15105 // ones, and then concatenate the result back.
15106 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
15107   MVT VT = Op.getSimpleValueType();
15108
15109   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
15110          "Unsupported value type for operation");
15111
15112   unsigned NumElems = VT.getVectorNumElements();
15113   SDLoc dl(Op);
15114   SDValue CC = Op.getOperand(2);
15115
15116   // Extract the LHS vectors
15117   SDValue LHS = Op.getOperand(0);
15118   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15119   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15120
15121   // Extract the RHS vectors
15122   SDValue RHS = Op.getOperand(1);
15123   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15124   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15125
15126   // Issue the operation on the smaller types and concatenate the result back
15127   MVT EltVT = VT.getVectorElementType();
15128   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15129   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15130                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
15131                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
15132 }
15133
15134 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
15135                                      const X86Subtarget *Subtarget) {
15136   SDValue Op0 = Op.getOperand(0);
15137   SDValue Op1 = Op.getOperand(1);
15138   SDValue CC = Op.getOperand(2);
15139   MVT VT = Op.getSimpleValueType();
15140   SDLoc dl(Op);
15141
15142   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
15143          Op.getValueType().getScalarType() == MVT::i1 &&
15144          "Cannot set masked compare for this operation");
15145
15146   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15147   unsigned  Opc = 0;
15148   bool Unsigned = false;
15149   bool Swap = false;
15150   unsigned SSECC;
15151   switch (SetCCOpcode) {
15152   default: llvm_unreachable("Unexpected SETCC condition");
15153   case ISD::SETNE:  SSECC = 4; break;
15154   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
15155   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
15156   case ISD::SETLT:  Swap = true; //fall-through
15157   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
15158   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
15159   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
15160   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
15161   case ISD::SETULE: Unsigned = true; //fall-through
15162   case ISD::SETLE:  SSECC = 2; break;
15163   }
15164
15165   if (Swap)
15166     std::swap(Op0, Op1);
15167   if (Opc)
15168     return DAG.getNode(Opc, dl, VT, Op0, Op1);
15169   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
15170   return DAG.getNode(Opc, dl, VT, Op0, Op1,
15171                      DAG.getConstant(SSECC, MVT::i8));
15172 }
15173
15174 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
15175 /// operand \p Op1.  If non-trivial (for example because it's not constant)
15176 /// return an empty value.
15177 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
15178 {
15179   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
15180   if (!BV)
15181     return SDValue();
15182
15183   MVT VT = Op1.getSimpleValueType();
15184   MVT EVT = VT.getVectorElementType();
15185   unsigned n = VT.getVectorNumElements();
15186   SmallVector<SDValue, 8> ULTOp1;
15187
15188   for (unsigned i = 0; i < n; ++i) {
15189     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
15190     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
15191       return SDValue();
15192
15193     // Avoid underflow.
15194     APInt Val = Elt->getAPIntValue();
15195     if (Val == 0)
15196       return SDValue();
15197
15198     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
15199   }
15200
15201   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
15202 }
15203
15204 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
15205                            SelectionDAG &DAG) {
15206   SDValue Op0 = Op.getOperand(0);
15207   SDValue Op1 = Op.getOperand(1);
15208   SDValue CC = Op.getOperand(2);
15209   MVT VT = Op.getSimpleValueType();
15210   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15211   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
15212   SDLoc dl(Op);
15213
15214   if (isFP) {
15215 #ifndef NDEBUG
15216     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
15217     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
15218 #endif
15219
15220     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
15221     unsigned Opc = X86ISD::CMPP;
15222     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
15223       assert(VT.getVectorNumElements() <= 16);
15224       Opc = X86ISD::CMPM;
15225     }
15226     // In the two special cases we can't handle, emit two comparisons.
15227     if (SSECC == 8) {
15228       unsigned CC0, CC1;
15229       unsigned CombineOpc;
15230       if (SetCCOpcode == ISD::SETUEQ) {
15231         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
15232       } else {
15233         assert(SetCCOpcode == ISD::SETONE);
15234         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
15235       }
15236
15237       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15238                                  DAG.getConstant(CC0, MVT::i8));
15239       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15240                                  DAG.getConstant(CC1, MVT::i8));
15241       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
15242     }
15243     // Handle all other FP comparisons here.
15244     return DAG.getNode(Opc, dl, VT, Op0, Op1,
15245                        DAG.getConstant(SSECC, MVT::i8));
15246   }
15247
15248   // Break 256-bit integer vector compare into smaller ones.
15249   if (VT.is256BitVector() && !Subtarget->hasInt256())
15250     return Lower256IntVSETCC(Op, DAG);
15251
15252   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
15253   EVT OpVT = Op1.getValueType();
15254   if (Subtarget->hasAVX512()) {
15255     if (Op1.getValueType().is512BitVector() ||
15256         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
15257         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
15258       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
15259
15260     // In AVX-512 architecture setcc returns mask with i1 elements,
15261     // But there is no compare instruction for i8 and i16 elements in KNL.
15262     // We are not talking about 512-bit operands in this case, these
15263     // types are illegal.
15264     if (MaskResult &&
15265         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
15266          OpVT.getVectorElementType().getSizeInBits() >= 8))
15267       return DAG.getNode(ISD::TRUNCATE, dl, VT,
15268                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
15269   }
15270
15271   // We are handling one of the integer comparisons here.  Since SSE only has
15272   // GT and EQ comparisons for integer, swapping operands and multiple
15273   // operations may be required for some comparisons.
15274   unsigned Opc;
15275   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
15276   bool Subus = false;
15277
15278   switch (SetCCOpcode) {
15279   default: llvm_unreachable("Unexpected SETCC condition");
15280   case ISD::SETNE:  Invert = true;
15281   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
15282   case ISD::SETLT:  Swap = true;
15283   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
15284   case ISD::SETGE:  Swap = true;
15285   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
15286                     Invert = true; break;
15287   case ISD::SETULT: Swap = true;
15288   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
15289                     FlipSigns = true; break;
15290   case ISD::SETUGE: Swap = true;
15291   case ISD::SETULE: Opc = X86ISD::PCMPGT;
15292                     FlipSigns = true; Invert = true; break;
15293   }
15294
15295   // Special case: Use min/max operations for SETULE/SETUGE
15296   MVT VET = VT.getVectorElementType();
15297   bool hasMinMax =
15298        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
15299     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
15300
15301   if (hasMinMax) {
15302     switch (SetCCOpcode) {
15303     default: break;
15304     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
15305     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
15306     }
15307
15308     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
15309   }
15310
15311   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
15312   if (!MinMax && hasSubus) {
15313     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
15314     // Op0 u<= Op1:
15315     //   t = psubus Op0, Op1
15316     //   pcmpeq t, <0..0>
15317     switch (SetCCOpcode) {
15318     default: break;
15319     case ISD::SETULT: {
15320       // If the comparison is against a constant we can turn this into a
15321       // setule.  With psubus, setule does not require a swap.  This is
15322       // beneficial because the constant in the register is no longer
15323       // destructed as the destination so it can be hoisted out of a loop.
15324       // Only do this pre-AVX since vpcmp* is no longer destructive.
15325       if (Subtarget->hasAVX())
15326         break;
15327       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
15328       if (ULEOp1.getNode()) {
15329         Op1 = ULEOp1;
15330         Subus = true; Invert = false; Swap = false;
15331       }
15332       break;
15333     }
15334     // Psubus is better than flip-sign because it requires no inversion.
15335     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
15336     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
15337     }
15338
15339     if (Subus) {
15340       Opc = X86ISD::SUBUS;
15341       FlipSigns = false;
15342     }
15343   }
15344
15345   if (Swap)
15346     std::swap(Op0, Op1);
15347
15348   // Check that the operation in question is available (most are plain SSE2,
15349   // but PCMPGTQ and PCMPEQQ have different requirements).
15350   if (VT == MVT::v2i64) {
15351     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
15352       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
15353
15354       // First cast everything to the right type.
15355       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15356       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15357
15358       // Since SSE has no unsigned integer comparisons, we need to flip the sign
15359       // bits of the inputs before performing those operations. The lower
15360       // compare is always unsigned.
15361       SDValue SB;
15362       if (FlipSigns) {
15363         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
15364       } else {
15365         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
15366         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
15367         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
15368                          Sign, Zero, Sign, Zero);
15369       }
15370       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
15371       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
15372
15373       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
15374       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
15375       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
15376
15377       // Create masks for only the low parts/high parts of the 64 bit integers.
15378       static const int MaskHi[] = { 1, 1, 3, 3 };
15379       static const int MaskLo[] = { 0, 0, 2, 2 };
15380       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
15381       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
15382       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
15383
15384       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
15385       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
15386
15387       if (Invert)
15388         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15389
15390       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15391     }
15392
15393     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
15394       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
15395       // pcmpeqd + pshufd + pand.
15396       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
15397
15398       // First cast everything to the right type.
15399       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15400       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15401
15402       // Do the compare.
15403       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
15404
15405       // Make sure the lower and upper halves are both all-ones.
15406       static const int Mask[] = { 1, 0, 3, 2 };
15407       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
15408       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
15409
15410       if (Invert)
15411         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15412
15413       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15414     }
15415   }
15416
15417   // Since SSE has no unsigned integer comparisons, we need to flip the sign
15418   // bits of the inputs before performing those operations.
15419   if (FlipSigns) {
15420     EVT EltVT = VT.getVectorElementType();
15421     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
15422     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
15423     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
15424   }
15425
15426   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
15427
15428   // If the logical-not of the result is required, perform that now.
15429   if (Invert)
15430     Result = DAG.getNOT(dl, Result, VT);
15431
15432   if (MinMax)
15433     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
15434
15435   if (Subus)
15436     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
15437                          getZeroVector(VT, Subtarget, DAG, dl));
15438
15439   return Result;
15440 }
15441
15442 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
15443
15444   MVT VT = Op.getSimpleValueType();
15445
15446   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
15447
15448   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
15449          && "SetCC type must be 8-bit or 1-bit integer");
15450   SDValue Op0 = Op.getOperand(0);
15451   SDValue Op1 = Op.getOperand(1);
15452   SDLoc dl(Op);
15453   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
15454
15455   // Optimize to BT if possible.
15456   // Lower (X & (1 << N)) == 0 to BT(X, N).
15457   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
15458   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
15459   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
15460       Op1.getOpcode() == ISD::Constant &&
15461       cast<ConstantSDNode>(Op1)->isNullValue() &&
15462       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15463     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
15464     if (NewSetCC.getNode()) {
15465       if (VT == MVT::i1)
15466         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
15467       return NewSetCC;
15468     }
15469   }
15470
15471   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
15472   // these.
15473   if (Op1.getOpcode() == ISD::Constant &&
15474       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
15475        cast<ConstantSDNode>(Op1)->isNullValue()) &&
15476       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15477
15478     // If the input is a setcc, then reuse the input setcc or use a new one with
15479     // the inverted condition.
15480     if (Op0.getOpcode() == X86ISD::SETCC) {
15481       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
15482       bool Invert = (CC == ISD::SETNE) ^
15483         cast<ConstantSDNode>(Op1)->isNullValue();
15484       if (!Invert)
15485         return Op0;
15486
15487       CCode = X86::GetOppositeBranchCondition(CCode);
15488       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15489                                   DAG.getConstant(CCode, MVT::i8),
15490                                   Op0.getOperand(1));
15491       if (VT == MVT::i1)
15492         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15493       return SetCC;
15494     }
15495   }
15496   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
15497       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
15498       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15499
15500     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
15501     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
15502   }
15503
15504   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
15505   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
15506   if (X86CC == X86::COND_INVALID)
15507     return SDValue();
15508
15509   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
15510   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
15511   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15512                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
15513   if (VT == MVT::i1)
15514     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15515   return SetCC;
15516 }
15517
15518 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
15519 static bool isX86LogicalCmp(SDValue Op) {
15520   unsigned Opc = Op.getNode()->getOpcode();
15521   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
15522       Opc == X86ISD::SAHF)
15523     return true;
15524   if (Op.getResNo() == 1 &&
15525       (Opc == X86ISD::ADD ||
15526        Opc == X86ISD::SUB ||
15527        Opc == X86ISD::ADC ||
15528        Opc == X86ISD::SBB ||
15529        Opc == X86ISD::SMUL ||
15530        Opc == X86ISD::UMUL ||
15531        Opc == X86ISD::INC ||
15532        Opc == X86ISD::DEC ||
15533        Opc == X86ISD::OR ||
15534        Opc == X86ISD::XOR ||
15535        Opc == X86ISD::AND))
15536     return true;
15537
15538   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15539     return true;
15540
15541   return false;
15542 }
15543
15544 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15545   if (V.getOpcode() != ISD::TRUNCATE)
15546     return false;
15547
15548   SDValue VOp0 = V.getOperand(0);
15549   unsigned InBits = VOp0.getValueSizeInBits();
15550   unsigned Bits = V.getValueSizeInBits();
15551   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15552 }
15553
15554 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15555   bool addTest = true;
15556   SDValue Cond  = Op.getOperand(0);
15557   SDValue Op1 = Op.getOperand(1);
15558   SDValue Op2 = Op.getOperand(2);
15559   SDLoc DL(Op);
15560   EVT VT = Op1.getValueType();
15561   SDValue CC;
15562
15563   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15564   // are available. Otherwise fp cmovs get lowered into a less efficient branch
15565   // sequence later on.
15566   if (Cond.getOpcode() == ISD::SETCC &&
15567       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15568        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15569       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
15570     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15571     int SSECC = translateX86FSETCC(
15572         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15573
15574     if (SSECC != 8) {
15575       if (Subtarget->hasAVX512()) {
15576         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15577                                   DAG.getConstant(SSECC, MVT::i8));
15578         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15579       }
15580       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15581                                 DAG.getConstant(SSECC, MVT::i8));
15582       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15583       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15584       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15585     }
15586   }
15587
15588   if (Cond.getOpcode() == ISD::SETCC) {
15589     SDValue NewCond = LowerSETCC(Cond, DAG);
15590     if (NewCond.getNode())
15591       Cond = NewCond;
15592   }
15593
15594   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15595   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15596   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15597   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15598   if (Cond.getOpcode() == X86ISD::SETCC &&
15599       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15600       isZero(Cond.getOperand(1).getOperand(1))) {
15601     SDValue Cmp = Cond.getOperand(1);
15602
15603     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15604
15605     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
15606         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15607       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
15608
15609       SDValue CmpOp0 = Cmp.getOperand(0);
15610       // Apply further optimizations for special cases
15611       // (select (x != 0), -1, 0) -> neg & sbb
15612       // (select (x == 0), 0, -1) -> neg & sbb
15613       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
15614         if (YC->isNullValue() &&
15615             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
15616           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15617           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15618                                     DAG.getConstant(0, CmpOp0.getValueType()),
15619                                     CmpOp0);
15620           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15621                                     DAG.getConstant(X86::COND_B, MVT::i8),
15622                                     SDValue(Neg.getNode(), 1));
15623           return Res;
15624         }
15625
15626       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15627                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
15628       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15629
15630       SDValue Res =   // Res = 0 or -1.
15631         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15632                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
15633
15634       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
15635         Res = DAG.getNOT(DL, Res, Res.getValueType());
15636
15637       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
15638       if (!N2C || !N2C->isNullValue())
15639         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15640       return Res;
15641     }
15642   }
15643
15644   // Look past (and (setcc_carry (cmp ...)), 1).
15645   if (Cond.getOpcode() == ISD::AND &&
15646       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15647     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15648     if (C && C->getAPIntValue() == 1)
15649       Cond = Cond.getOperand(0);
15650   }
15651
15652   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15653   // setting operand in place of the X86ISD::SETCC.
15654   unsigned CondOpcode = Cond.getOpcode();
15655   if (CondOpcode == X86ISD::SETCC ||
15656       CondOpcode == X86ISD::SETCC_CARRY) {
15657     CC = Cond.getOperand(0);
15658
15659     SDValue Cmp = Cond.getOperand(1);
15660     unsigned Opc = Cmp.getOpcode();
15661     MVT VT = Op.getSimpleValueType();
15662
15663     bool IllegalFPCMov = false;
15664     if (VT.isFloatingPoint() && !VT.isVector() &&
15665         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15666       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15667
15668     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15669         Opc == X86ISD::BT) { // FIXME
15670       Cond = Cmp;
15671       addTest = false;
15672     }
15673   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15674              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15675              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15676               Cond.getOperand(0).getValueType() != MVT::i8)) {
15677     SDValue LHS = Cond.getOperand(0);
15678     SDValue RHS = Cond.getOperand(1);
15679     unsigned X86Opcode;
15680     unsigned X86Cond;
15681     SDVTList VTs;
15682     switch (CondOpcode) {
15683     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15684     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15685     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15686     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15687     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15688     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15689     default: llvm_unreachable("unexpected overflowing operator");
15690     }
15691     if (CondOpcode == ISD::UMULO)
15692       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15693                           MVT::i32);
15694     else
15695       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15696
15697     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15698
15699     if (CondOpcode == ISD::UMULO)
15700       Cond = X86Op.getValue(2);
15701     else
15702       Cond = X86Op.getValue(1);
15703
15704     CC = DAG.getConstant(X86Cond, MVT::i8);
15705     addTest = false;
15706   }
15707
15708   if (addTest) {
15709     // Look pass the truncate if the high bits are known zero.
15710     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15711         Cond = Cond.getOperand(0);
15712
15713     // We know the result of AND is compared against zero. Try to match
15714     // it to BT.
15715     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15716       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
15717       if (NewSetCC.getNode()) {
15718         CC = NewSetCC.getOperand(0);
15719         Cond = NewSetCC.getOperand(1);
15720         addTest = false;
15721       }
15722     }
15723   }
15724
15725   if (addTest) {
15726     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15727     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15728   }
15729
15730   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15731   // a <  b ?  0 : -1 -> RES = setcc_carry
15732   // a >= b ? -1 :  0 -> RES = setcc_carry
15733   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15734   if (Cond.getOpcode() == X86ISD::SUB) {
15735     Cond = ConvertCmpIfNecessary(Cond, DAG);
15736     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15737
15738     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15739         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
15740       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15741                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
15742       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
15743         return DAG.getNOT(DL, Res, Res.getValueType());
15744       return Res;
15745     }
15746   }
15747
15748   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15749   // widen the cmov and push the truncate through. This avoids introducing a new
15750   // branch during isel and doesn't add any extensions.
15751   if (Op.getValueType() == MVT::i8 &&
15752       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15753     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15754     if (T1.getValueType() == T2.getValueType() &&
15755         // Blacklist CopyFromReg to avoid partial register stalls.
15756         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15757       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15758       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15759       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15760     }
15761   }
15762
15763   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15764   // condition is true.
15765   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15766   SDValue Ops[] = { Op2, Op1, CC, Cond };
15767   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15768 }
15769
15770 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
15771                                        SelectionDAG &DAG) {
15772   MVT VT = Op->getSimpleValueType(0);
15773   SDValue In = Op->getOperand(0);
15774   MVT InVT = In.getSimpleValueType();
15775   MVT VTElt = VT.getVectorElementType();
15776   MVT InVTElt = InVT.getVectorElementType();
15777   SDLoc dl(Op);
15778
15779   // SKX processor
15780   if ((InVTElt == MVT::i1) &&
15781       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15782         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15783
15784        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15785         VTElt.getSizeInBits() <= 16)) ||
15786
15787        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15788         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15789
15790        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15791         VTElt.getSizeInBits() >= 32))))
15792     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15793
15794   unsigned int NumElts = VT.getVectorNumElements();
15795
15796   if (NumElts != 8 && NumElts != 16)
15797     return SDValue();
15798
15799   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15800     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15801       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15802     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15803   }
15804
15805   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15806   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15807
15808   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
15809   Constant *C = ConstantInt::get(*DAG.getContext(),
15810     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
15811
15812   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
15813   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
15814   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
15815                           MachinePointerInfo::getConstantPool(),
15816                           false, false, false, Alignment);
15817   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
15818   if (VT.is512BitVector())
15819     return Brcst;
15820   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
15821 }
15822
15823 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15824                                 SelectionDAG &DAG) {
15825   MVT VT = Op->getSimpleValueType(0);
15826   SDValue In = Op->getOperand(0);
15827   MVT InVT = In.getSimpleValueType();
15828   SDLoc dl(Op);
15829
15830   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15831     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15832
15833   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15834       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15835       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15836     return SDValue();
15837
15838   if (Subtarget->hasInt256())
15839     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15840
15841   // Optimize vectors in AVX mode
15842   // Sign extend  v8i16 to v8i32 and
15843   //              v4i32 to v4i64
15844   //
15845   // Divide input vector into two parts
15846   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15847   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15848   // concat the vectors to original VT
15849
15850   unsigned NumElems = InVT.getVectorNumElements();
15851   SDValue Undef = DAG.getUNDEF(InVT);
15852
15853   SmallVector<int,8> ShufMask1(NumElems, -1);
15854   for (unsigned i = 0; i != NumElems/2; ++i)
15855     ShufMask1[i] = i;
15856
15857   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15858
15859   SmallVector<int,8> ShufMask2(NumElems, -1);
15860   for (unsigned i = 0; i != NumElems/2; ++i)
15861     ShufMask2[i] = i + NumElems/2;
15862
15863   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15864
15865   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15866                                 VT.getVectorNumElements()/2);
15867
15868   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15869   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15870
15871   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15872 }
15873
15874 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15875 // may emit an illegal shuffle but the expansion is still better than scalar
15876 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15877 // we'll emit a shuffle and a arithmetic shift.
15878 // TODO: It is possible to support ZExt by zeroing the undef values during
15879 // the shuffle phase or after the shuffle.
15880 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15881                                  SelectionDAG &DAG) {
15882   MVT RegVT = Op.getSimpleValueType();
15883   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15884   assert(RegVT.isInteger() &&
15885          "We only custom lower integer vector sext loads.");
15886
15887   // Nothing useful we can do without SSE2 shuffles.
15888   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15889
15890   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15891   SDLoc dl(Ld);
15892   EVT MemVT = Ld->getMemoryVT();
15893   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15894   unsigned RegSz = RegVT.getSizeInBits();
15895
15896   ISD::LoadExtType Ext = Ld->getExtensionType();
15897
15898   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15899          && "Only anyext and sext are currently implemented.");
15900   assert(MemVT != RegVT && "Cannot extend to the same type");
15901   assert(MemVT.isVector() && "Must load a vector from memory");
15902
15903   unsigned NumElems = RegVT.getVectorNumElements();
15904   unsigned MemSz = MemVT.getSizeInBits();
15905   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15906
15907   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15908     // The only way in which we have a legal 256-bit vector result but not the
15909     // integer 256-bit operations needed to directly lower a sextload is if we
15910     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15911     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15912     // correctly legalized. We do this late to allow the canonical form of
15913     // sextload to persist throughout the rest of the DAG combiner -- it wants
15914     // to fold together any extensions it can, and so will fuse a sign_extend
15915     // of an sextload into a sextload targeting a wider value.
15916     SDValue Load;
15917     if (MemSz == 128) {
15918       // Just switch this to a normal load.
15919       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15920                                        "it must be a legal 128-bit vector "
15921                                        "type!");
15922       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15923                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15924                   Ld->isInvariant(), Ld->getAlignment());
15925     } else {
15926       assert(MemSz < 128 &&
15927              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15928       // Do an sext load to a 128-bit vector type. We want to use the same
15929       // number of elements, but elements half as wide. This will end up being
15930       // recursively lowered by this routine, but will succeed as we definitely
15931       // have all the necessary features if we're using AVX1.
15932       EVT HalfEltVT =
15933           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15934       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15935       Load =
15936           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15937                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15938                          Ld->isNonTemporal(), Ld->isInvariant(),
15939                          Ld->getAlignment());
15940     }
15941
15942     // Replace chain users with the new chain.
15943     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15944     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15945
15946     // Finally, do a normal sign-extend to the desired register.
15947     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15948   }
15949
15950   // All sizes must be a power of two.
15951   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15952          "Non-power-of-two elements are not custom lowered!");
15953
15954   // Attempt to load the original value using scalar loads.
15955   // Find the largest scalar type that divides the total loaded size.
15956   MVT SclrLoadTy = MVT::i8;
15957   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15958        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15959     MVT Tp = (MVT::SimpleValueType)tp;
15960     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15961       SclrLoadTy = Tp;
15962     }
15963   }
15964
15965   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15966   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15967       (64 <= MemSz))
15968     SclrLoadTy = MVT::f64;
15969
15970   // Calculate the number of scalar loads that we need to perform
15971   // in order to load our vector from memory.
15972   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15973
15974   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15975          "Can only lower sext loads with a single scalar load!");
15976
15977   unsigned loadRegZize = RegSz;
15978   if (Ext == ISD::SEXTLOAD && RegSz == 256)
15979     loadRegZize /= 2;
15980
15981   // Represent our vector as a sequence of elements which are the
15982   // largest scalar that we can load.
15983   EVT LoadUnitVecVT = EVT::getVectorVT(
15984       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15985
15986   // Represent the data using the same element type that is stored in
15987   // memory. In practice, we ''widen'' MemVT.
15988   EVT WideVecVT =
15989       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15990                        loadRegZize / MemVT.getScalarType().getSizeInBits());
15991
15992   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15993          "Invalid vector type");
15994
15995   // We can't shuffle using an illegal type.
15996   assert(TLI.isTypeLegal(WideVecVT) &&
15997          "We only lower types that form legal widened vector types");
15998
15999   SmallVector<SDValue, 8> Chains;
16000   SDValue Ptr = Ld->getBasePtr();
16001   SDValue Increment =
16002       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
16003   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16004
16005   for (unsigned i = 0; i < NumLoads; ++i) {
16006     // Perform a single load.
16007     SDValue ScalarLoad =
16008         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
16009                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
16010                     Ld->getAlignment());
16011     Chains.push_back(ScalarLoad.getValue(1));
16012     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16013     // another round of DAGCombining.
16014     if (i == 0)
16015       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16016     else
16017       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16018                         ScalarLoad, DAG.getIntPtrConstant(i));
16019
16020     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16021   }
16022
16023   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
16024
16025   // Bitcast the loaded value to a vector of the original element type, in
16026   // the size of the target vector type.
16027   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16028   unsigned SizeRatio = RegSz / MemSz;
16029
16030   if (Ext == ISD::SEXTLOAD) {
16031     // If we have SSE4.1, we can directly emit a VSEXT node.
16032     if (Subtarget->hasSSE41()) {
16033       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16034       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16035       return Sext;
16036     }
16037
16038     // Otherwise we'll shuffle the small elements in the high bits of the
16039     // larger type and perform an arithmetic shift. If the shift is not legal
16040     // it's better to scalarize.
16041     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
16042            "We can't implement a sext load without an arithmetic right shift!");
16043
16044     // Redistribute the loaded elements into the different locations.
16045     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16046     for (unsigned i = 0; i != NumElems; ++i)
16047       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
16048
16049     SDValue Shuff = DAG.getVectorShuffle(
16050         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16051
16052     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16053
16054     // Build the arithmetic shift.
16055     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16056                    MemVT.getVectorElementType().getSizeInBits();
16057     Shuff =
16058         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
16059
16060     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16061     return Shuff;
16062   }
16063
16064   // Redistribute the loaded elements into the different locations.
16065   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16066   for (unsigned i = 0; i != NumElems; ++i)
16067     ShuffleVec[i * SizeRatio] = i;
16068
16069   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16070                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16071
16072   // Bitcast to the requested type.
16073   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16074   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16075   return Shuff;
16076 }
16077
16078 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
16079 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
16080 // from the AND / OR.
16081 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
16082   Opc = Op.getOpcode();
16083   if (Opc != ISD::OR && Opc != ISD::AND)
16084     return false;
16085   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16086           Op.getOperand(0).hasOneUse() &&
16087           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
16088           Op.getOperand(1).hasOneUse());
16089 }
16090
16091 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
16092 // 1 and that the SETCC node has a single use.
16093 static bool isXor1OfSetCC(SDValue Op) {
16094   if (Op.getOpcode() != ISD::XOR)
16095     return false;
16096   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
16097   if (N1C && N1C->getAPIntValue() == 1) {
16098     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16099       Op.getOperand(0).hasOneUse();
16100   }
16101   return false;
16102 }
16103
16104 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
16105   bool addTest = true;
16106   SDValue Chain = Op.getOperand(0);
16107   SDValue Cond  = Op.getOperand(1);
16108   SDValue Dest  = Op.getOperand(2);
16109   SDLoc dl(Op);
16110   SDValue CC;
16111   bool Inverted = false;
16112
16113   if (Cond.getOpcode() == ISD::SETCC) {
16114     // Check for setcc([su]{add,sub,mul}o == 0).
16115     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
16116         isa<ConstantSDNode>(Cond.getOperand(1)) &&
16117         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
16118         Cond.getOperand(0).getResNo() == 1 &&
16119         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
16120          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
16121          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
16122          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
16123          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
16124          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
16125       Inverted = true;
16126       Cond = Cond.getOperand(0);
16127     } else {
16128       SDValue NewCond = LowerSETCC(Cond, DAG);
16129       if (NewCond.getNode())
16130         Cond = NewCond;
16131     }
16132   }
16133 #if 0
16134   // FIXME: LowerXALUO doesn't handle these!!
16135   else if (Cond.getOpcode() == X86ISD::ADD  ||
16136            Cond.getOpcode() == X86ISD::SUB  ||
16137            Cond.getOpcode() == X86ISD::SMUL ||
16138            Cond.getOpcode() == X86ISD::UMUL)
16139     Cond = LowerXALUO(Cond, DAG);
16140 #endif
16141
16142   // Look pass (and (setcc_carry (cmp ...)), 1).
16143   if (Cond.getOpcode() == ISD::AND &&
16144       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
16145     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
16146     if (C && C->getAPIntValue() == 1)
16147       Cond = Cond.getOperand(0);
16148   }
16149
16150   // If condition flag is set by a X86ISD::CMP, then use it as the condition
16151   // setting operand in place of the X86ISD::SETCC.
16152   unsigned CondOpcode = Cond.getOpcode();
16153   if (CondOpcode == X86ISD::SETCC ||
16154       CondOpcode == X86ISD::SETCC_CARRY) {
16155     CC = Cond.getOperand(0);
16156
16157     SDValue Cmp = Cond.getOperand(1);
16158     unsigned Opc = Cmp.getOpcode();
16159     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
16160     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
16161       Cond = Cmp;
16162       addTest = false;
16163     } else {
16164       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
16165       default: break;
16166       case X86::COND_O:
16167       case X86::COND_B:
16168         // These can only come from an arithmetic instruction with overflow,
16169         // e.g. SADDO, UADDO.
16170         Cond = Cond.getNode()->getOperand(1);
16171         addTest = false;
16172         break;
16173       }
16174     }
16175   }
16176   CondOpcode = Cond.getOpcode();
16177   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
16178       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
16179       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
16180        Cond.getOperand(0).getValueType() != MVT::i8)) {
16181     SDValue LHS = Cond.getOperand(0);
16182     SDValue RHS = Cond.getOperand(1);
16183     unsigned X86Opcode;
16184     unsigned X86Cond;
16185     SDVTList VTs;
16186     // Keep this in sync with LowerXALUO, otherwise we might create redundant
16187     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
16188     // X86ISD::INC).
16189     switch (CondOpcode) {
16190     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
16191     case ISD::SADDO:
16192       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16193         if (C->isOne()) {
16194           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
16195           break;
16196         }
16197       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
16198     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
16199     case ISD::SSUBO:
16200       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16201         if (C->isOne()) {
16202           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
16203           break;
16204         }
16205       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
16206     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
16207     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
16208     default: llvm_unreachable("unexpected overflowing operator");
16209     }
16210     if (Inverted)
16211       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
16212     if (CondOpcode == ISD::UMULO)
16213       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
16214                           MVT::i32);
16215     else
16216       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
16217
16218     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
16219
16220     if (CondOpcode == ISD::UMULO)
16221       Cond = X86Op.getValue(2);
16222     else
16223       Cond = X86Op.getValue(1);
16224
16225     CC = DAG.getConstant(X86Cond, MVT::i8);
16226     addTest = false;
16227   } else {
16228     unsigned CondOpc;
16229     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
16230       SDValue Cmp = Cond.getOperand(0).getOperand(1);
16231       if (CondOpc == ISD::OR) {
16232         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
16233         // two branches instead of an explicit OR instruction with a
16234         // separate test.
16235         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16236             isX86LogicalCmp(Cmp)) {
16237           CC = Cond.getOperand(0).getOperand(0);
16238           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16239                               Chain, Dest, CC, Cmp);
16240           CC = Cond.getOperand(1).getOperand(0);
16241           Cond = Cmp;
16242           addTest = false;
16243         }
16244       } else { // ISD::AND
16245         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
16246         // two branches instead of an explicit AND instruction with a
16247         // separate test. However, we only do this if this block doesn't
16248         // have a fall-through edge, because this requires an explicit
16249         // jmp when the condition is false.
16250         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16251             isX86LogicalCmp(Cmp) &&
16252             Op.getNode()->hasOneUse()) {
16253           X86::CondCode CCode =
16254             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16255           CCode = X86::GetOppositeBranchCondition(CCode);
16256           CC = DAG.getConstant(CCode, MVT::i8);
16257           SDNode *User = *Op.getNode()->use_begin();
16258           // Look for an unconditional branch following this conditional branch.
16259           // We need this because we need to reverse the successors in order
16260           // to implement FCMP_OEQ.
16261           if (User->getOpcode() == ISD::BR) {
16262             SDValue FalseBB = User->getOperand(1);
16263             SDNode *NewBR =
16264               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16265             assert(NewBR == User);
16266             (void)NewBR;
16267             Dest = FalseBB;
16268
16269             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16270                                 Chain, Dest, CC, Cmp);
16271             X86::CondCode CCode =
16272               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
16273             CCode = X86::GetOppositeBranchCondition(CCode);
16274             CC = DAG.getConstant(CCode, MVT::i8);
16275             Cond = Cmp;
16276             addTest = false;
16277           }
16278         }
16279       }
16280     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
16281       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
16282       // It should be transformed during dag combiner except when the condition
16283       // is set by a arithmetics with overflow node.
16284       X86::CondCode CCode =
16285         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16286       CCode = X86::GetOppositeBranchCondition(CCode);
16287       CC = DAG.getConstant(CCode, MVT::i8);
16288       Cond = Cond.getOperand(0).getOperand(1);
16289       addTest = false;
16290     } else if (Cond.getOpcode() == ISD::SETCC &&
16291                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
16292       // For FCMP_OEQ, we can emit
16293       // two branches instead of an explicit AND instruction with a
16294       // separate test. However, we only do this if this block doesn't
16295       // have a fall-through edge, because this requires an explicit
16296       // jmp when the condition is false.
16297       if (Op.getNode()->hasOneUse()) {
16298         SDNode *User = *Op.getNode()->use_begin();
16299         // Look for an unconditional branch following this conditional branch.
16300         // We need this because we need to reverse the successors in order
16301         // to implement FCMP_OEQ.
16302         if (User->getOpcode() == ISD::BR) {
16303           SDValue FalseBB = User->getOperand(1);
16304           SDNode *NewBR =
16305             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16306           assert(NewBR == User);
16307           (void)NewBR;
16308           Dest = FalseBB;
16309
16310           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16311                                     Cond.getOperand(0), Cond.getOperand(1));
16312           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16313           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16314           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16315                               Chain, Dest, CC, Cmp);
16316           CC = DAG.getConstant(X86::COND_P, MVT::i8);
16317           Cond = Cmp;
16318           addTest = false;
16319         }
16320       }
16321     } else if (Cond.getOpcode() == ISD::SETCC &&
16322                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
16323       // For FCMP_UNE, we can emit
16324       // two branches instead of an explicit AND instruction with a
16325       // separate test. However, we only do this if this block doesn't
16326       // have a fall-through edge, because this requires an explicit
16327       // jmp when the condition is false.
16328       if (Op.getNode()->hasOneUse()) {
16329         SDNode *User = *Op.getNode()->use_begin();
16330         // Look for an unconditional branch following this conditional branch.
16331         // We need this because we need to reverse the successors in order
16332         // to implement FCMP_UNE.
16333         if (User->getOpcode() == ISD::BR) {
16334           SDValue FalseBB = User->getOperand(1);
16335           SDNode *NewBR =
16336             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16337           assert(NewBR == User);
16338           (void)NewBR;
16339
16340           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16341                                     Cond.getOperand(0), Cond.getOperand(1));
16342           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16343           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16344           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16345                               Chain, Dest, CC, Cmp);
16346           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
16347           Cond = Cmp;
16348           addTest = false;
16349           Dest = FalseBB;
16350         }
16351       }
16352     }
16353   }
16354
16355   if (addTest) {
16356     // Look pass the truncate if the high bits are known zero.
16357     if (isTruncWithZeroHighBitsInput(Cond, DAG))
16358         Cond = Cond.getOperand(0);
16359
16360     // We know the result of AND is compared against zero. Try to match
16361     // it to BT.
16362     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
16363       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
16364       if (NewSetCC.getNode()) {
16365         CC = NewSetCC.getOperand(0);
16366         Cond = NewSetCC.getOperand(1);
16367         addTest = false;
16368       }
16369     }
16370   }
16371
16372   if (addTest) {
16373     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
16374     CC = DAG.getConstant(X86Cond, MVT::i8);
16375     Cond = EmitTest(Cond, X86Cond, dl, DAG);
16376   }
16377   Cond = ConvertCmpIfNecessary(Cond, DAG);
16378   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16379                      Chain, Dest, CC, Cond);
16380 }
16381
16382 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
16383 // Calls to _alloca are needed to probe the stack when allocating more than 4k
16384 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
16385 // that the guard pages used by the OS virtual memory manager are allocated in
16386 // correct sequence.
16387 SDValue
16388 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
16389                                            SelectionDAG &DAG) const {
16390   MachineFunction &MF = DAG.getMachineFunction();
16391   bool SplitStack = MF.shouldSplitStack();
16392   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
16393                SplitStack;
16394   SDLoc dl(Op);
16395
16396   if (!Lower) {
16397     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16398     SDNode* Node = Op.getNode();
16399
16400     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
16401     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
16402         " not tell us which reg is the stack pointer!");
16403     EVT VT = Node->getValueType(0);
16404     SDValue Tmp1 = SDValue(Node, 0);
16405     SDValue Tmp2 = SDValue(Node, 1);
16406     SDValue Tmp3 = Node->getOperand(2);
16407     SDValue Chain = Tmp1.getOperand(0);
16408
16409     // Chain the dynamic stack allocation so that it doesn't modify the stack
16410     // pointer when other instructions are using the stack.
16411     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
16412         SDLoc(Node));
16413
16414     SDValue Size = Tmp2.getOperand(1);
16415     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
16416     Chain = SP.getValue(1);
16417     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
16418     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
16419     unsigned StackAlign = TFI.getStackAlignment();
16420     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
16421     if (Align > StackAlign)
16422       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
16423           DAG.getConstant(-(uint64_t)Align, VT));
16424     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
16425
16426     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
16427         DAG.getIntPtrConstant(0, true), SDValue(),
16428         SDLoc(Node));
16429
16430     SDValue Ops[2] = { Tmp1, Tmp2 };
16431     return DAG.getMergeValues(Ops, dl);
16432   }
16433
16434   // Get the inputs.
16435   SDValue Chain = Op.getOperand(0);
16436   SDValue Size  = Op.getOperand(1);
16437   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16438   EVT VT = Op.getNode()->getValueType(0);
16439
16440   bool Is64Bit = Subtarget->is64Bit();
16441   EVT SPTy = getPointerTy();
16442
16443   if (SplitStack) {
16444     MachineRegisterInfo &MRI = MF.getRegInfo();
16445
16446     if (Is64Bit) {
16447       // The 64 bit implementation of segmented stacks needs to clobber both r10
16448       // r11. This makes it impossible to use it along with nested parameters.
16449       const Function *F = MF.getFunction();
16450
16451       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16452            I != E; ++I)
16453         if (I->hasNestAttr())
16454           report_fatal_error("Cannot use segmented stacks with functions that "
16455                              "have nested arguments.");
16456     }
16457
16458     const TargetRegisterClass *AddrRegClass =
16459       getRegClassFor(getPointerTy());
16460     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16461     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16462     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16463                                 DAG.getRegister(Vreg, SPTy));
16464     SDValue Ops1[2] = { Value, Chain };
16465     return DAG.getMergeValues(Ops1, dl);
16466   } else {
16467     SDValue Flag;
16468     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16469
16470     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16471     Flag = Chain.getValue(1);
16472     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16473
16474     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16475
16476     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16477         DAG.getSubtarget().getRegisterInfo());
16478     unsigned SPReg = RegInfo->getStackRegister();
16479     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16480     Chain = SP.getValue(1);
16481
16482     if (Align) {
16483       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16484                        DAG.getConstant(-(uint64_t)Align, VT));
16485       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16486     }
16487
16488     SDValue Ops1[2] = { SP, Chain };
16489     return DAG.getMergeValues(Ops1, dl);
16490   }
16491 }
16492
16493 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16494   MachineFunction &MF = DAG.getMachineFunction();
16495   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16496
16497   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16498   SDLoc DL(Op);
16499
16500   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
16501     // vastart just stores the address of the VarArgsFrameIndex slot into the
16502     // memory location argument.
16503     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16504                                    getPointerTy());
16505     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16506                         MachinePointerInfo(SV), false, false, 0);
16507   }
16508
16509   // __va_list_tag:
16510   //   gp_offset         (0 - 6 * 8)
16511   //   fp_offset         (48 - 48 + 8 * 16)
16512   //   overflow_arg_area (point to parameters coming in memory).
16513   //   reg_save_area
16514   SmallVector<SDValue, 8> MemOps;
16515   SDValue FIN = Op.getOperand(1);
16516   // Store gp_offset
16517   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16518                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16519                                                MVT::i32),
16520                                FIN, MachinePointerInfo(SV), false, false, 0);
16521   MemOps.push_back(Store);
16522
16523   // Store fp_offset
16524   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16525                     FIN, DAG.getIntPtrConstant(4));
16526   Store = DAG.getStore(Op.getOperand(0), DL,
16527                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
16528                                        MVT::i32),
16529                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16530   MemOps.push_back(Store);
16531
16532   // Store ptr to overflow_arg_area
16533   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16534                     FIN, DAG.getIntPtrConstant(4));
16535   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16536                                     getPointerTy());
16537   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16538                        MachinePointerInfo(SV, 8),
16539                        false, false, 0);
16540   MemOps.push_back(Store);
16541
16542   // Store ptr to reg_save_area.
16543   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16544                     FIN, DAG.getIntPtrConstant(8));
16545   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
16546                                     getPointerTy());
16547   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
16548                        MachinePointerInfo(SV, 16), false, false, 0);
16549   MemOps.push_back(Store);
16550   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16551 }
16552
16553 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16554   assert(Subtarget->is64Bit() &&
16555          "LowerVAARG only handles 64-bit va_arg!");
16556   assert((Subtarget->isTargetLinux() ||
16557           Subtarget->isTargetDarwin()) &&
16558           "Unhandled target in LowerVAARG");
16559   assert(Op.getNode()->getNumOperands() == 4);
16560   SDValue Chain = Op.getOperand(0);
16561   SDValue SrcPtr = Op.getOperand(1);
16562   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16563   unsigned Align = Op.getConstantOperandVal(3);
16564   SDLoc dl(Op);
16565
16566   EVT ArgVT = Op.getNode()->getValueType(0);
16567   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16568   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
16569   uint8_t ArgMode;
16570
16571   // Decide which area this value should be read from.
16572   // TODO: Implement the AMD64 ABI in its entirety. This simple
16573   // selection mechanism works only for the basic types.
16574   if (ArgVT == MVT::f80) {
16575     llvm_unreachable("va_arg for f80 not yet implemented");
16576   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16577     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16578   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16579     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16580   } else {
16581     llvm_unreachable("Unhandled argument type in LowerVAARG");
16582   }
16583
16584   if (ArgMode == 2) {
16585     // Sanity Check: Make sure using fp_offset makes sense.
16586     assert(!DAG.getTarget().Options.UseSoftFloat &&
16587            !(DAG.getMachineFunction()
16588                 .getFunction()->getAttributes()
16589                 .hasAttribute(AttributeSet::FunctionIndex,
16590                               Attribute::NoImplicitFloat)) &&
16591            Subtarget->hasSSE1());
16592   }
16593
16594   // Insert VAARG_64 node into the DAG
16595   // VAARG_64 returns two values: Variable Argument Address, Chain
16596   SmallVector<SDValue, 11> InstOps;
16597   InstOps.push_back(Chain);
16598   InstOps.push_back(SrcPtr);
16599   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
16600   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
16601   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
16602   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
16603   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16604                                           VTs, InstOps, MVT::i64,
16605                                           MachinePointerInfo(SV),
16606                                           /*Align=*/0,
16607                                           /*Volatile=*/false,
16608                                           /*ReadMem=*/true,
16609                                           /*WriteMem=*/true);
16610   Chain = VAARG.getValue(1);
16611
16612   // Load the next argument and return it
16613   return DAG.getLoad(ArgVT, dl,
16614                      Chain,
16615                      VAARG,
16616                      MachinePointerInfo(),
16617                      false, false, false, 0);
16618 }
16619
16620 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16621                            SelectionDAG &DAG) {
16622   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
16623   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16624   SDValue Chain = Op.getOperand(0);
16625   SDValue DstPtr = Op.getOperand(1);
16626   SDValue SrcPtr = Op.getOperand(2);
16627   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16628   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16629   SDLoc DL(Op);
16630
16631   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16632                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
16633                        false,
16634                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16635 }
16636
16637 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16638 // amount is a constant. Takes immediate version of shift as input.
16639 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16640                                           SDValue SrcOp, uint64_t ShiftAmt,
16641                                           SelectionDAG &DAG) {
16642   MVT ElementType = VT.getVectorElementType();
16643
16644   // Fold this packed shift into its first operand if ShiftAmt is 0.
16645   if (ShiftAmt == 0)
16646     return SrcOp;
16647
16648   // Check for ShiftAmt >= element width
16649   if (ShiftAmt >= ElementType.getSizeInBits()) {
16650     if (Opc == X86ISD::VSRAI)
16651       ShiftAmt = ElementType.getSizeInBits() - 1;
16652     else
16653       return DAG.getConstant(0, VT);
16654   }
16655
16656   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16657          && "Unknown target vector shift-by-constant node");
16658
16659   // Fold this packed vector shift into a build vector if SrcOp is a
16660   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16661   if (VT == SrcOp.getSimpleValueType() &&
16662       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16663     SmallVector<SDValue, 8> Elts;
16664     unsigned NumElts = SrcOp->getNumOperands();
16665     ConstantSDNode *ND;
16666
16667     switch(Opc) {
16668     default: llvm_unreachable(nullptr);
16669     case X86ISD::VSHLI:
16670       for (unsigned i=0; i!=NumElts; ++i) {
16671         SDValue CurrentOp = SrcOp->getOperand(i);
16672         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16673           Elts.push_back(CurrentOp);
16674           continue;
16675         }
16676         ND = cast<ConstantSDNode>(CurrentOp);
16677         const APInt &C = ND->getAPIntValue();
16678         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
16679       }
16680       break;
16681     case X86ISD::VSRLI:
16682       for (unsigned i=0; i!=NumElts; ++i) {
16683         SDValue CurrentOp = SrcOp->getOperand(i);
16684         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16685           Elts.push_back(CurrentOp);
16686           continue;
16687         }
16688         ND = cast<ConstantSDNode>(CurrentOp);
16689         const APInt &C = ND->getAPIntValue();
16690         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
16691       }
16692       break;
16693     case X86ISD::VSRAI:
16694       for (unsigned i=0; i!=NumElts; ++i) {
16695         SDValue CurrentOp = SrcOp->getOperand(i);
16696         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16697           Elts.push_back(CurrentOp);
16698           continue;
16699         }
16700         ND = cast<ConstantSDNode>(CurrentOp);
16701         const APInt &C = ND->getAPIntValue();
16702         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
16703       }
16704       break;
16705     }
16706
16707     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16708   }
16709
16710   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
16711 }
16712
16713 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16714 // may or may not be a constant. Takes immediate version of shift as input.
16715 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16716                                    SDValue SrcOp, SDValue ShAmt,
16717                                    SelectionDAG &DAG) {
16718   MVT SVT = ShAmt.getSimpleValueType();
16719   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16720
16721   // Catch shift-by-constant.
16722   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16723     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16724                                       CShAmt->getZExtValue(), DAG);
16725
16726   // Change opcode to non-immediate version
16727   switch (Opc) {
16728     default: llvm_unreachable("Unknown target vector shift node");
16729     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16730     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16731     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16732   }
16733
16734   const X86Subtarget &Subtarget =
16735       DAG.getTarget().getSubtarget<X86Subtarget>();
16736   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16737       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16738     // Let the shuffle legalizer expand this shift amount node.
16739     SDValue Op0 = ShAmt.getOperand(0);
16740     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16741     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16742   } else {
16743     // Need to build a vector containing shift amount.
16744     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16745     SmallVector<SDValue, 4> ShOps;
16746     ShOps.push_back(ShAmt);
16747     if (SVT == MVT::i32) {
16748       ShOps.push_back(DAG.getConstant(0, SVT));
16749       ShOps.push_back(DAG.getUNDEF(SVT));
16750     }
16751     ShOps.push_back(DAG.getUNDEF(SVT));
16752
16753     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16754     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16755   }
16756
16757   // The return type has to be a 128-bit type with the same element
16758   // type as the input type.
16759   MVT EltVT = VT.getVectorElementType();
16760   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16761
16762   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
16763   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16764 }
16765
16766 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16767 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16768 /// necessary casting for \p Mask when lowering masking intrinsics.
16769 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16770                                     SDValue PreservedSrc,
16771                                     const X86Subtarget *Subtarget,
16772                                     SelectionDAG &DAG) {
16773     EVT VT = Op.getValueType();
16774     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16775                                   MVT::i1, VT.getVectorNumElements());
16776     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16777                                      Mask.getValueType().getSizeInBits());
16778     SDLoc dl(Op);
16779
16780     assert(MaskVT.isSimple() && "invalid mask type");
16781
16782     if (isAllOnes(Mask))
16783       return Op;
16784
16785     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16786     // are extracted by EXTRACT_SUBVECTOR.
16787     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16788                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
16789                               DAG.getIntPtrConstant(0));
16790
16791     switch (Op.getOpcode()) {
16792       default: break;
16793       case X86ISD::PCMPEQM:
16794       case X86ISD::PCMPGTM:
16795       case X86ISD::CMPM:
16796       case X86ISD::CMPMU:
16797         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16798     }
16799     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16800       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16801     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
16802 }
16803
16804 /// \brief Creates an SDNode for a predicated scalar operation.
16805 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16806 /// The mask is comming as MVT::i8 and it should be truncated
16807 /// to MVT::i1 while lowering masking intrinsics.
16808 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16809 /// "X86select" instead of "vselect". We just can't create the "vselect" node for 
16810 /// a scalar instruction.
16811 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16812                                     SDValue PreservedSrc,
16813                                     const X86Subtarget *Subtarget,
16814                                     SelectionDAG &DAG) {
16815     if (isAllOnes(Mask))
16816       return Op;
16817
16818     EVT VT = Op.getValueType();
16819     SDLoc dl(Op);
16820     // The mask should be of type MVT::i1
16821     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16822
16823     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16824       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16825     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16826 }
16827
16828 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
16829     switch (IntNo) {
16830     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16831     case Intrinsic::x86_fma_vfmadd_ps:
16832     case Intrinsic::x86_fma_vfmadd_pd:
16833     case Intrinsic::x86_fma_vfmadd_ps_256:
16834     case Intrinsic::x86_fma_vfmadd_pd_256:
16835     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
16836     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
16837       return X86ISD::FMADD;
16838     case Intrinsic::x86_fma_vfmsub_ps:
16839     case Intrinsic::x86_fma_vfmsub_pd:
16840     case Intrinsic::x86_fma_vfmsub_ps_256:
16841     case Intrinsic::x86_fma_vfmsub_pd_256:
16842     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
16843     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
16844       return X86ISD::FMSUB;
16845     case Intrinsic::x86_fma_vfnmadd_ps:
16846     case Intrinsic::x86_fma_vfnmadd_pd:
16847     case Intrinsic::x86_fma_vfnmadd_ps_256:
16848     case Intrinsic::x86_fma_vfnmadd_pd_256:
16849     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
16850     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
16851       return X86ISD::FNMADD;
16852     case Intrinsic::x86_fma_vfnmsub_ps:
16853     case Intrinsic::x86_fma_vfnmsub_pd:
16854     case Intrinsic::x86_fma_vfnmsub_ps_256:
16855     case Intrinsic::x86_fma_vfnmsub_pd_256:
16856     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
16857     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
16858       return X86ISD::FNMSUB;
16859     case Intrinsic::x86_fma_vfmaddsub_ps:
16860     case Intrinsic::x86_fma_vfmaddsub_pd:
16861     case Intrinsic::x86_fma_vfmaddsub_ps_256:
16862     case Intrinsic::x86_fma_vfmaddsub_pd_256:
16863     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
16864     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
16865       return X86ISD::FMADDSUB;
16866     case Intrinsic::x86_fma_vfmsubadd_ps:
16867     case Intrinsic::x86_fma_vfmsubadd_pd:
16868     case Intrinsic::x86_fma_vfmsubadd_ps_256:
16869     case Intrinsic::x86_fma_vfmsubadd_pd_256:
16870     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
16871     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
16872       return X86ISD::FMSUBADD;
16873     }
16874 }
16875
16876 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16877                                        SelectionDAG &DAG) {
16878   SDLoc dl(Op);
16879   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16880   EVT VT = Op.getValueType();
16881   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16882   if (IntrData) {
16883     switch(IntrData->Type) {
16884     case INTR_TYPE_1OP:
16885       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16886     case INTR_TYPE_2OP:
16887       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16888         Op.getOperand(2));
16889     case INTR_TYPE_3OP:
16890       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16891         Op.getOperand(2), Op.getOperand(3));
16892     case INTR_TYPE_1OP_MASK_RM: {
16893       SDValue Src = Op.getOperand(1);
16894       SDValue Src0 = Op.getOperand(2);
16895       SDValue Mask = Op.getOperand(3);
16896       SDValue RoundingMode = Op.getOperand(4);
16897       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16898                                               RoundingMode),
16899                                   Mask, Src0, Subtarget, DAG);
16900     }
16901     case INTR_TYPE_SCALAR_MASK_RM: {
16902       SDValue Src1 = Op.getOperand(1);
16903       SDValue Src2 = Op.getOperand(2);
16904       SDValue Src0 = Op.getOperand(3);
16905       SDValue Mask = Op.getOperand(4);
16906       SDValue RoundingMode = Op.getOperand(5);
16907       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16908                                               RoundingMode),
16909                                   Mask, Src0, Subtarget, DAG);
16910     }
16911     case INTR_TYPE_2OP_MASK: {
16912       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Op.getOperand(1),
16913                                               Op.getOperand(2)),
16914                                   Op.getOperand(4), Op.getOperand(3), Subtarget, DAG);
16915     }
16916     case CMP_MASK:
16917     case CMP_MASK_CC: {
16918       // Comparison intrinsics with masks.
16919       // Example of transformation:
16920       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16921       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16922       // (i8 (bitcast
16923       //   (v8i1 (insert_subvector undef,
16924       //           (v2i1 (and (PCMPEQM %a, %b),
16925       //                      (extract_subvector
16926       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16927       EVT VT = Op.getOperand(1).getValueType();
16928       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16929                                     VT.getVectorNumElements());
16930       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16931       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16932                                        Mask.getValueType().getSizeInBits());
16933       SDValue Cmp;
16934       if (IntrData->Type == CMP_MASK_CC) {
16935         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16936                     Op.getOperand(2), Op.getOperand(3));
16937       } else {
16938         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16939         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16940                     Op.getOperand(2));
16941       }
16942       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16943                                              DAG.getTargetConstant(0, MaskVT),
16944                                              Subtarget, DAG);
16945       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16946                                 DAG.getUNDEF(BitcastVT), CmpMask,
16947                                 DAG.getIntPtrConstant(0));
16948       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
16949     }
16950     case COMI: { // Comparison intrinsics
16951       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16952       SDValue LHS = Op.getOperand(1);
16953       SDValue RHS = Op.getOperand(2);
16954       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
16955       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16956       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16957       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16958                                   DAG.getConstant(X86CC, MVT::i8), Cond);
16959       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16960     }
16961     case VSHIFT:
16962       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16963                                  Op.getOperand(1), Op.getOperand(2), DAG);
16964     case VSHIFT_MASK:
16965       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16966                                                       Op.getSimpleValueType(),
16967                                                       Op.getOperand(1),
16968                                                       Op.getOperand(2), DAG),
16969                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16970                                   DAG);
16971     case COMPRESS_EXPAND_IN_REG: {
16972       SDValue Mask = Op.getOperand(3);
16973       SDValue DataToCompress = Op.getOperand(1);
16974       SDValue PassThru = Op.getOperand(2);
16975       if (isAllOnes(Mask)) // return data as is
16976         return Op.getOperand(1);
16977       EVT VT = Op.getValueType();
16978       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16979                                     VT.getVectorNumElements());
16980       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16981                                        Mask.getValueType().getSizeInBits());
16982       SDLoc dl(Op);
16983       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16984                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
16985                                   DAG.getIntPtrConstant(0));
16986
16987       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
16988                          PassThru);
16989     }
16990     default:
16991       break;
16992     }
16993   }
16994
16995   switch (IntNo) {
16996   default: return SDValue();    // Don't custom lower most intrinsics.
16997
16998   case Intrinsic::x86_avx512_mask_valign_q_512:
16999   case Intrinsic::x86_avx512_mask_valign_d_512:
17000     // Vector source operands are swapped.
17001     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
17002                                             Op.getValueType(), Op.getOperand(2),
17003                                             Op.getOperand(1),
17004                                             Op.getOperand(3)),
17005                                 Op.getOperand(5), Op.getOperand(4),
17006                                 Subtarget, DAG);
17007
17008   // ptest and testp intrinsics. The intrinsic these come from are designed to
17009   // return an integer value, not just an instruction so lower it to the ptest
17010   // or testp pattern and a setcc for the result.
17011   case Intrinsic::x86_sse41_ptestz:
17012   case Intrinsic::x86_sse41_ptestc:
17013   case Intrinsic::x86_sse41_ptestnzc:
17014   case Intrinsic::x86_avx_ptestz_256:
17015   case Intrinsic::x86_avx_ptestc_256:
17016   case Intrinsic::x86_avx_ptestnzc_256:
17017   case Intrinsic::x86_avx_vtestz_ps:
17018   case Intrinsic::x86_avx_vtestc_ps:
17019   case Intrinsic::x86_avx_vtestnzc_ps:
17020   case Intrinsic::x86_avx_vtestz_pd:
17021   case Intrinsic::x86_avx_vtestc_pd:
17022   case Intrinsic::x86_avx_vtestnzc_pd:
17023   case Intrinsic::x86_avx_vtestz_ps_256:
17024   case Intrinsic::x86_avx_vtestc_ps_256:
17025   case Intrinsic::x86_avx_vtestnzc_ps_256:
17026   case Intrinsic::x86_avx_vtestz_pd_256:
17027   case Intrinsic::x86_avx_vtestc_pd_256:
17028   case Intrinsic::x86_avx_vtestnzc_pd_256: {
17029     bool IsTestPacked = false;
17030     unsigned X86CC;
17031     switch (IntNo) {
17032     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17033     case Intrinsic::x86_avx_vtestz_ps:
17034     case Intrinsic::x86_avx_vtestz_pd:
17035     case Intrinsic::x86_avx_vtestz_ps_256:
17036     case Intrinsic::x86_avx_vtestz_pd_256:
17037       IsTestPacked = true; // Fallthrough
17038     case Intrinsic::x86_sse41_ptestz:
17039     case Intrinsic::x86_avx_ptestz_256:
17040       // ZF = 1
17041       X86CC = X86::COND_E;
17042       break;
17043     case Intrinsic::x86_avx_vtestc_ps:
17044     case Intrinsic::x86_avx_vtestc_pd:
17045     case Intrinsic::x86_avx_vtestc_ps_256:
17046     case Intrinsic::x86_avx_vtestc_pd_256:
17047       IsTestPacked = true; // Fallthrough
17048     case Intrinsic::x86_sse41_ptestc:
17049     case Intrinsic::x86_avx_ptestc_256:
17050       // CF = 1
17051       X86CC = X86::COND_B;
17052       break;
17053     case Intrinsic::x86_avx_vtestnzc_ps:
17054     case Intrinsic::x86_avx_vtestnzc_pd:
17055     case Intrinsic::x86_avx_vtestnzc_ps_256:
17056     case Intrinsic::x86_avx_vtestnzc_pd_256:
17057       IsTestPacked = true; // Fallthrough
17058     case Intrinsic::x86_sse41_ptestnzc:
17059     case Intrinsic::x86_avx_ptestnzc_256:
17060       // ZF and CF = 0
17061       X86CC = X86::COND_A;
17062       break;
17063     }
17064
17065     SDValue LHS = Op.getOperand(1);
17066     SDValue RHS = Op.getOperand(2);
17067     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17068     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17069     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17070     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17071     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17072   }
17073   case Intrinsic::x86_avx512_kortestz_w:
17074   case Intrinsic::x86_avx512_kortestc_w: {
17075     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17076     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
17077     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
17078     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17079     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17080     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17081     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17082   }
17083
17084   case Intrinsic::x86_sse42_pcmpistria128:
17085   case Intrinsic::x86_sse42_pcmpestria128:
17086   case Intrinsic::x86_sse42_pcmpistric128:
17087   case Intrinsic::x86_sse42_pcmpestric128:
17088   case Intrinsic::x86_sse42_pcmpistrio128:
17089   case Intrinsic::x86_sse42_pcmpestrio128:
17090   case Intrinsic::x86_sse42_pcmpistris128:
17091   case Intrinsic::x86_sse42_pcmpestris128:
17092   case Intrinsic::x86_sse42_pcmpistriz128:
17093   case Intrinsic::x86_sse42_pcmpestriz128: {
17094     unsigned Opcode;
17095     unsigned X86CC;
17096     switch (IntNo) {
17097     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17098     case Intrinsic::x86_sse42_pcmpistria128:
17099       Opcode = X86ISD::PCMPISTRI;
17100       X86CC = X86::COND_A;
17101       break;
17102     case Intrinsic::x86_sse42_pcmpestria128:
17103       Opcode = X86ISD::PCMPESTRI;
17104       X86CC = X86::COND_A;
17105       break;
17106     case Intrinsic::x86_sse42_pcmpistric128:
17107       Opcode = X86ISD::PCMPISTRI;
17108       X86CC = X86::COND_B;
17109       break;
17110     case Intrinsic::x86_sse42_pcmpestric128:
17111       Opcode = X86ISD::PCMPESTRI;
17112       X86CC = X86::COND_B;
17113       break;
17114     case Intrinsic::x86_sse42_pcmpistrio128:
17115       Opcode = X86ISD::PCMPISTRI;
17116       X86CC = X86::COND_O;
17117       break;
17118     case Intrinsic::x86_sse42_pcmpestrio128:
17119       Opcode = X86ISD::PCMPESTRI;
17120       X86CC = X86::COND_O;
17121       break;
17122     case Intrinsic::x86_sse42_pcmpistris128:
17123       Opcode = X86ISD::PCMPISTRI;
17124       X86CC = X86::COND_S;
17125       break;
17126     case Intrinsic::x86_sse42_pcmpestris128:
17127       Opcode = X86ISD::PCMPESTRI;
17128       X86CC = X86::COND_S;
17129       break;
17130     case Intrinsic::x86_sse42_pcmpistriz128:
17131       Opcode = X86ISD::PCMPISTRI;
17132       X86CC = X86::COND_E;
17133       break;
17134     case Intrinsic::x86_sse42_pcmpestriz128:
17135       Opcode = X86ISD::PCMPESTRI;
17136       X86CC = X86::COND_E;
17137       break;
17138     }
17139     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17140     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17141     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17142     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17143                                 DAG.getConstant(X86CC, MVT::i8),
17144                                 SDValue(PCMP.getNode(), 1));
17145     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17146   }
17147
17148   case Intrinsic::x86_sse42_pcmpistri128:
17149   case Intrinsic::x86_sse42_pcmpestri128: {
17150     unsigned Opcode;
17151     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17152       Opcode = X86ISD::PCMPISTRI;
17153     else
17154       Opcode = X86ISD::PCMPESTRI;
17155
17156     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17157     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17158     return DAG.getNode(Opcode, dl, VTs, NewOps);
17159   }
17160
17161   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
17162   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
17163   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
17164   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
17165   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
17166   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
17167   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
17168   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
17169   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
17170   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
17171   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
17172   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
17173     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
17174     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
17175       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
17176                                               dl, Op.getValueType(),
17177                                               Op.getOperand(1),
17178                                               Op.getOperand(2),
17179                                               Op.getOperand(3)),
17180                                   Op.getOperand(4), Op.getOperand(1),
17181                                   Subtarget, DAG);
17182     else
17183       return SDValue();
17184   }
17185
17186   case Intrinsic::x86_fma_vfmadd_ps:
17187   case Intrinsic::x86_fma_vfmadd_pd:
17188   case Intrinsic::x86_fma_vfmsub_ps:
17189   case Intrinsic::x86_fma_vfmsub_pd:
17190   case Intrinsic::x86_fma_vfnmadd_ps:
17191   case Intrinsic::x86_fma_vfnmadd_pd:
17192   case Intrinsic::x86_fma_vfnmsub_ps:
17193   case Intrinsic::x86_fma_vfnmsub_pd:
17194   case Intrinsic::x86_fma_vfmaddsub_ps:
17195   case Intrinsic::x86_fma_vfmaddsub_pd:
17196   case Intrinsic::x86_fma_vfmsubadd_ps:
17197   case Intrinsic::x86_fma_vfmsubadd_pd:
17198   case Intrinsic::x86_fma_vfmadd_ps_256:
17199   case Intrinsic::x86_fma_vfmadd_pd_256:
17200   case Intrinsic::x86_fma_vfmsub_ps_256:
17201   case Intrinsic::x86_fma_vfmsub_pd_256:
17202   case Intrinsic::x86_fma_vfnmadd_ps_256:
17203   case Intrinsic::x86_fma_vfnmadd_pd_256:
17204   case Intrinsic::x86_fma_vfnmsub_ps_256:
17205   case Intrinsic::x86_fma_vfnmsub_pd_256:
17206   case Intrinsic::x86_fma_vfmaddsub_ps_256:
17207   case Intrinsic::x86_fma_vfmaddsub_pd_256:
17208   case Intrinsic::x86_fma_vfmsubadd_ps_256:
17209   case Intrinsic::x86_fma_vfmsubadd_pd_256:
17210     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
17211                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
17212   }
17213 }
17214
17215 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17216                               SDValue Src, SDValue Mask, SDValue Base,
17217                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17218                               const X86Subtarget * Subtarget) {
17219   SDLoc dl(Op);
17220   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17221   assert(C && "Invalid scale type");
17222   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17223   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17224                              Index.getSimpleValueType().getVectorNumElements());
17225   SDValue MaskInReg;
17226   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17227   if (MaskC)
17228     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17229   else
17230     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17231   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17232   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17233   SDValue Segment = DAG.getRegister(0, MVT::i32);
17234   if (Src.getOpcode() == ISD::UNDEF)
17235     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
17236   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17237   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17238   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17239   return DAG.getMergeValues(RetOps, dl);
17240 }
17241
17242 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17243                                SDValue Src, SDValue Mask, SDValue Base,
17244                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17245   SDLoc dl(Op);
17246   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17247   assert(C && "Invalid scale type");
17248   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17249   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17250   SDValue Segment = DAG.getRegister(0, MVT::i32);
17251   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17252                              Index.getSimpleValueType().getVectorNumElements());
17253   SDValue MaskInReg;
17254   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17255   if (MaskC)
17256     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17257   else
17258     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17259   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17260   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17261   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17262   return SDValue(Res, 1);
17263 }
17264
17265 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17266                                SDValue Mask, SDValue Base, SDValue Index,
17267                                SDValue ScaleOp, SDValue Chain) {
17268   SDLoc dl(Op);
17269   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17270   assert(C && "Invalid scale type");
17271   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17272   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17273   SDValue Segment = DAG.getRegister(0, MVT::i32);
17274   EVT MaskVT =
17275     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17276   SDValue MaskInReg;
17277   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17278   if (MaskC)
17279     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17280   else
17281     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17282   //SDVTList VTs = DAG.getVTList(MVT::Other);
17283   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17284   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17285   return SDValue(Res, 0);
17286 }
17287
17288 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17289 // read performance monitor counters (x86_rdpmc).
17290 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17291                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17292                               SmallVectorImpl<SDValue> &Results) {
17293   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17294   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17295   SDValue LO, HI;
17296
17297   // The ECX register is used to select the index of the performance counter
17298   // to read.
17299   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17300                                    N->getOperand(2));
17301   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17302
17303   // Reads the content of a 64-bit performance counter and returns it in the
17304   // registers EDX:EAX.
17305   if (Subtarget->is64Bit()) {
17306     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17307     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17308                             LO.getValue(2));
17309   } else {
17310     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17311     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17312                             LO.getValue(2));
17313   }
17314   Chain = HI.getValue(1);
17315
17316   if (Subtarget->is64Bit()) {
17317     // The EAX register is loaded with the low-order 32 bits. The EDX register
17318     // is loaded with the supported high-order bits of the counter.
17319     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17320                               DAG.getConstant(32, MVT::i8));
17321     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17322     Results.push_back(Chain);
17323     return;
17324   }
17325
17326   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17327   SDValue Ops[] = { LO, HI };
17328   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17329   Results.push_back(Pair);
17330   Results.push_back(Chain);
17331 }
17332
17333 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17334 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17335 // also used to custom lower READCYCLECOUNTER nodes.
17336 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17337                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17338                               SmallVectorImpl<SDValue> &Results) {
17339   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17340   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17341   SDValue LO, HI;
17342
17343   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17344   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17345   // and the EAX register is loaded with the low-order 32 bits.
17346   if (Subtarget->is64Bit()) {
17347     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17348     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17349                             LO.getValue(2));
17350   } else {
17351     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17352     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17353                             LO.getValue(2));
17354   }
17355   SDValue Chain = HI.getValue(1);
17356
17357   if (Opcode == X86ISD::RDTSCP_DAG) {
17358     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17359
17360     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17361     // the ECX register. Add 'ecx' explicitly to the chain.
17362     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17363                                      HI.getValue(2));
17364     // Explicitly store the content of ECX at the location passed in input
17365     // to the 'rdtscp' intrinsic.
17366     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17367                          MachinePointerInfo(), false, false, 0);
17368   }
17369
17370   if (Subtarget->is64Bit()) {
17371     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17372     // the EAX register is loaded with the low-order 32 bits.
17373     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17374                               DAG.getConstant(32, MVT::i8));
17375     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17376     Results.push_back(Chain);
17377     return;
17378   }
17379
17380   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17381   SDValue Ops[] = { LO, HI };
17382   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17383   Results.push_back(Pair);
17384   Results.push_back(Chain);
17385 }
17386
17387 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17388                                      SelectionDAG &DAG) {
17389   SmallVector<SDValue, 2> Results;
17390   SDLoc DL(Op);
17391   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17392                           Results);
17393   return DAG.getMergeValues(Results, DL);
17394 }
17395
17396
17397 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17398                                       SelectionDAG &DAG) {
17399   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17400
17401   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17402   if (!IntrData)
17403     return SDValue();
17404
17405   SDLoc dl(Op);
17406   switch(IntrData->Type) {
17407   default:
17408     llvm_unreachable("Unknown Intrinsic Type");
17409     break;
17410   case RDSEED:
17411   case RDRAND: {
17412     // Emit the node with the right value type.
17413     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17414     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17415
17416     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17417     // Otherwise return the value from Rand, which is always 0, casted to i32.
17418     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17419                       DAG.getConstant(1, Op->getValueType(1)),
17420                       DAG.getConstant(X86::COND_B, MVT::i32),
17421                       SDValue(Result.getNode(), 1) };
17422     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17423                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17424                                   Ops);
17425
17426     // Return { result, isValid, chain }.
17427     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17428                        SDValue(Result.getNode(), 2));
17429   }
17430   case GATHER: {
17431   //gather(v1, mask, index, base, scale);
17432     SDValue Chain = Op.getOperand(0);
17433     SDValue Src   = Op.getOperand(2);
17434     SDValue Base  = Op.getOperand(3);
17435     SDValue Index = Op.getOperand(4);
17436     SDValue Mask  = Op.getOperand(5);
17437     SDValue Scale = Op.getOperand(6);
17438     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
17439                           Subtarget);
17440   }
17441   case SCATTER: {
17442   //scatter(base, mask, index, v1, scale);
17443     SDValue Chain = Op.getOperand(0);
17444     SDValue Base  = Op.getOperand(2);
17445     SDValue Mask  = Op.getOperand(3);
17446     SDValue Index = Op.getOperand(4);
17447     SDValue Src   = Op.getOperand(5);
17448     SDValue Scale = Op.getOperand(6);
17449     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
17450   }
17451   case PREFETCH: {
17452     SDValue Hint = Op.getOperand(6);
17453     unsigned HintVal;
17454     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
17455         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
17456       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
17457     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17458     SDValue Chain = Op.getOperand(0);
17459     SDValue Mask  = Op.getOperand(2);
17460     SDValue Index = Op.getOperand(3);
17461     SDValue Base  = Op.getOperand(4);
17462     SDValue Scale = Op.getOperand(5);
17463     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17464   }
17465   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17466   case RDTSC: {
17467     SmallVector<SDValue, 2> Results;
17468     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
17469     return DAG.getMergeValues(Results, dl);
17470   }
17471   // Read Performance Monitoring Counters.
17472   case RDPMC: {
17473     SmallVector<SDValue, 2> Results;
17474     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17475     return DAG.getMergeValues(Results, dl);
17476   }
17477   // XTEST intrinsics.
17478   case XTEST: {
17479     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17480     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17481     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17482                                 DAG.getConstant(X86::COND_NE, MVT::i8),
17483                                 InTrans);
17484     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17485     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17486                        Ret, SDValue(InTrans.getNode(), 1));
17487   }
17488   // ADC/ADCX/SBB
17489   case ADX: {
17490     SmallVector<SDValue, 2> Results;
17491     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17492     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17493     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17494                                 DAG.getConstant(-1, MVT::i8));
17495     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17496                               Op.getOperand(4), GenCF.getValue(1));
17497     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17498                                  Op.getOperand(5), MachinePointerInfo(),
17499                                  false, false, 0);
17500     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17501                                 DAG.getConstant(X86::COND_B, MVT::i8),
17502                                 Res.getValue(1));
17503     Results.push_back(SetCC);
17504     Results.push_back(Store);
17505     return DAG.getMergeValues(Results, dl);
17506   }
17507   case COMPRESS_TO_MEM: {
17508     SDLoc dl(Op);
17509     SDValue Mask = Op.getOperand(4);
17510     SDValue DataToCompress = Op.getOperand(3);
17511     SDValue Addr = Op.getOperand(2);
17512     SDValue Chain = Op.getOperand(0);
17513
17514     if (isAllOnes(Mask)) // return just a store
17515       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17516                           MachinePointerInfo(), false, false, 0);
17517
17518     EVT VT = DataToCompress.getValueType();
17519     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17520                                   VT.getVectorNumElements());
17521     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17522                                      Mask.getValueType().getSizeInBits());
17523     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17524                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17525                                 DAG.getIntPtrConstant(0));
17526
17527     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
17528                                       DataToCompress, DAG.getUNDEF(VT));
17529     return DAG.getStore(Chain, dl, Compressed, Addr,
17530                         MachinePointerInfo(), false, false, 0);
17531   }
17532   case EXPAND_FROM_MEM: {
17533     SDLoc dl(Op);
17534     SDValue Mask = Op.getOperand(4);
17535     SDValue PathThru = Op.getOperand(3);
17536     SDValue Addr = Op.getOperand(2);
17537     SDValue Chain = Op.getOperand(0);
17538     EVT VT = Op.getValueType();
17539
17540     if (isAllOnes(Mask)) // return just a load
17541       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17542                          false, 0);
17543     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17544                                   VT.getVectorNumElements());
17545     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
17546                                      Mask.getValueType().getSizeInBits());
17547     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17548                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
17549                                 DAG.getIntPtrConstant(0));
17550
17551     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17552                                    false, false, false, 0);
17553
17554     SmallVector<SDValue, 2> Results;
17555     Results.push_back(DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand,
17556                                   PathThru));
17557     Results.push_back(Chain);
17558     return DAG.getMergeValues(Results, dl);
17559   }
17560   }
17561 }
17562
17563 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17564                                            SelectionDAG &DAG) const {
17565   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17566   MFI->setReturnAddressIsTaken(true);
17567
17568   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17569     return SDValue();
17570
17571   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17572   SDLoc dl(Op);
17573   EVT PtrVT = getPointerTy();
17574
17575   if (Depth > 0) {
17576     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17577     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17578         DAG.getSubtarget().getRegisterInfo());
17579     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
17580     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17581                        DAG.getNode(ISD::ADD, dl, PtrVT,
17582                                    FrameAddr, Offset),
17583                        MachinePointerInfo(), false, false, false, 0);
17584   }
17585
17586   // Just load the return address.
17587   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17588   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17589                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17590 }
17591
17592 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17593   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17594   MFI->setFrameAddressIsTaken(true);
17595
17596   EVT VT = Op.getValueType();
17597   SDLoc dl(Op);  // FIXME probably not meaningful
17598   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17599   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17600       DAG.getSubtarget().getRegisterInfo());
17601   unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(
17602       DAG.getMachineFunction());
17603   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17604           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17605          "Invalid Frame Register!");
17606   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17607   while (Depth--)
17608     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17609                             MachinePointerInfo(),
17610                             false, false, false, 0);
17611   return FrameAddr;
17612 }
17613
17614 // FIXME? Maybe this could be a TableGen attribute on some registers and
17615 // this table could be generated automatically from RegInfo.
17616 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
17617                                               EVT VT) const {
17618   unsigned Reg = StringSwitch<unsigned>(RegName)
17619                        .Case("esp", X86::ESP)
17620                        .Case("rsp", X86::RSP)
17621                        .Default(0);
17622   if (Reg)
17623     return Reg;
17624   report_fatal_error("Invalid register name global variable");
17625 }
17626
17627 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17628                                                      SelectionDAG &DAG) const {
17629   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17630       DAG.getSubtarget().getRegisterInfo());
17631   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
17632 }
17633
17634 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17635   SDValue Chain     = Op.getOperand(0);
17636   SDValue Offset    = Op.getOperand(1);
17637   SDValue Handler   = Op.getOperand(2);
17638   SDLoc dl      (Op);
17639
17640   EVT PtrVT = getPointerTy();
17641   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17642       DAG.getSubtarget().getRegisterInfo());
17643   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17644   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17645           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17646          "Invalid Frame Register!");
17647   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17648   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17649
17650   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17651                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
17652   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17653   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17654                        false, false, 0);
17655   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17656
17657   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17658                      DAG.getRegister(StoreAddrReg, PtrVT));
17659 }
17660
17661 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17662                                                SelectionDAG &DAG) const {
17663   SDLoc DL(Op);
17664   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17665                      DAG.getVTList(MVT::i32, MVT::Other),
17666                      Op.getOperand(0), Op.getOperand(1));
17667 }
17668
17669 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17670                                                 SelectionDAG &DAG) const {
17671   SDLoc DL(Op);
17672   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17673                      Op.getOperand(0), Op.getOperand(1));
17674 }
17675
17676 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17677   return Op.getOperand(0);
17678 }
17679
17680 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17681                                                 SelectionDAG &DAG) const {
17682   SDValue Root = Op.getOperand(0);
17683   SDValue Trmp = Op.getOperand(1); // trampoline
17684   SDValue FPtr = Op.getOperand(2); // nested function
17685   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17686   SDLoc dl (Op);
17687
17688   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17689   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
17690
17691   if (Subtarget->is64Bit()) {
17692     SDValue OutChains[6];
17693
17694     // Large code-model.
17695     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17696     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17697
17698     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17699     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17700
17701     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17702
17703     // Load the pointer to the nested function into R11.
17704     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17705     SDValue Addr = Trmp;
17706     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17707                                 Addr, MachinePointerInfo(TrmpAddr),
17708                                 false, false, 0);
17709
17710     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17711                        DAG.getConstant(2, MVT::i64));
17712     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17713                                 MachinePointerInfo(TrmpAddr, 2),
17714                                 false, false, 2);
17715
17716     // Load the 'nest' parameter value into R10.
17717     // R10 is specified in X86CallingConv.td
17718     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17719     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17720                        DAG.getConstant(10, MVT::i64));
17721     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17722                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17723                                 false, false, 0);
17724
17725     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17726                        DAG.getConstant(12, MVT::i64));
17727     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17728                                 MachinePointerInfo(TrmpAddr, 12),
17729                                 false, false, 2);
17730
17731     // Jump to the nested function.
17732     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17733     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17734                        DAG.getConstant(20, MVT::i64));
17735     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17736                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17737                                 false, false, 0);
17738
17739     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17740     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17741                        DAG.getConstant(22, MVT::i64));
17742     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
17743                                 MachinePointerInfo(TrmpAddr, 22),
17744                                 false, false, 0);
17745
17746     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17747   } else {
17748     const Function *Func =
17749       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17750     CallingConv::ID CC = Func->getCallingConv();
17751     unsigned NestReg;
17752
17753     switch (CC) {
17754     default:
17755       llvm_unreachable("Unsupported calling convention");
17756     case CallingConv::C:
17757     case CallingConv::X86_StdCall: {
17758       // Pass 'nest' parameter in ECX.
17759       // Must be kept in sync with X86CallingConv.td
17760       NestReg = X86::ECX;
17761
17762       // Check that ECX wasn't needed by an 'inreg' parameter.
17763       FunctionType *FTy = Func->getFunctionType();
17764       const AttributeSet &Attrs = Func->getAttributes();
17765
17766       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17767         unsigned InRegCount = 0;
17768         unsigned Idx = 1;
17769
17770         for (FunctionType::param_iterator I = FTy->param_begin(),
17771              E = FTy->param_end(); I != E; ++I, ++Idx)
17772           if (Attrs.hasAttribute(Idx, Attribute::InReg))
17773             // FIXME: should only count parameters that are lowered to integers.
17774             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
17775
17776         if (InRegCount > 2) {
17777           report_fatal_error("Nest register in use - reduce number of inreg"
17778                              " parameters!");
17779         }
17780       }
17781       break;
17782     }
17783     case CallingConv::X86_FastCall:
17784     case CallingConv::X86_ThisCall:
17785     case CallingConv::Fast:
17786       // Pass 'nest' parameter in EAX.
17787       // Must be kept in sync with X86CallingConv.td
17788       NestReg = X86::EAX;
17789       break;
17790     }
17791
17792     SDValue OutChains[4];
17793     SDValue Addr, Disp;
17794
17795     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17796                        DAG.getConstant(10, MVT::i32));
17797     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17798
17799     // This is storing the opcode for MOV32ri.
17800     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17801     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17802     OutChains[0] = DAG.getStore(Root, dl,
17803                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
17804                                 Trmp, MachinePointerInfo(TrmpAddr),
17805                                 false, false, 0);
17806
17807     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17808                        DAG.getConstant(1, MVT::i32));
17809     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17810                                 MachinePointerInfo(TrmpAddr, 1),
17811                                 false, false, 1);
17812
17813     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17814     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17815                        DAG.getConstant(5, MVT::i32));
17816     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
17817                                 MachinePointerInfo(TrmpAddr, 5),
17818                                 false, false, 1);
17819
17820     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17821                        DAG.getConstant(6, MVT::i32));
17822     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17823                                 MachinePointerInfo(TrmpAddr, 6),
17824                                 false, false, 1);
17825
17826     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17827   }
17828 }
17829
17830 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17831                                             SelectionDAG &DAG) const {
17832   /*
17833    The rounding mode is in bits 11:10 of FPSR, and has the following
17834    settings:
17835      00 Round to nearest
17836      01 Round to -inf
17837      10 Round to +inf
17838      11 Round to 0
17839
17840   FLT_ROUNDS, on the other hand, expects the following:
17841     -1 Undefined
17842      0 Round to 0
17843      1 Round to nearest
17844      2 Round to +inf
17845      3 Round to -inf
17846
17847   To perform the conversion, we do:
17848     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17849   */
17850
17851   MachineFunction &MF = DAG.getMachineFunction();
17852   const TargetMachine &TM = MF.getTarget();
17853   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
17854   unsigned StackAlignment = TFI.getStackAlignment();
17855   MVT VT = Op.getSimpleValueType();
17856   SDLoc DL(Op);
17857
17858   // Save FP Control Word to stack slot
17859   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17860   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
17861
17862   MachineMemOperand *MMO =
17863    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
17864                            MachineMemOperand::MOStore, 2, 2);
17865
17866   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17867   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17868                                           DAG.getVTList(MVT::Other),
17869                                           Ops, MVT::i16, MMO);
17870
17871   // Load FP Control Word from stack slot
17872   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17873                             MachinePointerInfo(), false, false, false, 0);
17874
17875   // Transform as necessary
17876   SDValue CWD1 =
17877     DAG.getNode(ISD::SRL, DL, MVT::i16,
17878                 DAG.getNode(ISD::AND, DL, MVT::i16,
17879                             CWD, DAG.getConstant(0x800, MVT::i16)),
17880                 DAG.getConstant(11, MVT::i8));
17881   SDValue CWD2 =
17882     DAG.getNode(ISD::SRL, DL, MVT::i16,
17883                 DAG.getNode(ISD::AND, DL, MVT::i16,
17884                             CWD, DAG.getConstant(0x400, MVT::i16)),
17885                 DAG.getConstant(9, MVT::i8));
17886
17887   SDValue RetVal =
17888     DAG.getNode(ISD::AND, DL, MVT::i16,
17889                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17890                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17891                             DAG.getConstant(1, MVT::i16)),
17892                 DAG.getConstant(3, MVT::i16));
17893
17894   return DAG.getNode((VT.getSizeInBits() < 16 ?
17895                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17896 }
17897
17898 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17899   MVT VT = Op.getSimpleValueType();
17900   EVT OpVT = VT;
17901   unsigned NumBits = VT.getSizeInBits();
17902   SDLoc dl(Op);
17903
17904   Op = Op.getOperand(0);
17905   if (VT == MVT::i8) {
17906     // Zero extend to i32 since there is not an i8 bsr.
17907     OpVT = MVT::i32;
17908     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17909   }
17910
17911   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17912   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17913   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17914
17915   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17916   SDValue Ops[] = {
17917     Op,
17918     DAG.getConstant(NumBits+NumBits-1, OpVT),
17919     DAG.getConstant(X86::COND_E, MVT::i8),
17920     Op.getValue(1)
17921   };
17922   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17923
17924   // Finally xor with NumBits-1.
17925   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17926
17927   if (VT == MVT::i8)
17928     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17929   return Op;
17930 }
17931
17932 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17933   MVT VT = Op.getSimpleValueType();
17934   EVT OpVT = VT;
17935   unsigned NumBits = VT.getSizeInBits();
17936   SDLoc dl(Op);
17937
17938   Op = Op.getOperand(0);
17939   if (VT == MVT::i8) {
17940     // Zero extend to i32 since there is not an i8 bsr.
17941     OpVT = MVT::i32;
17942     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17943   }
17944
17945   // Issue a bsr (scan bits in reverse).
17946   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17947   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17948
17949   // And xor with NumBits-1.
17950   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17951
17952   if (VT == MVT::i8)
17953     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17954   return Op;
17955 }
17956
17957 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17958   MVT VT = Op.getSimpleValueType();
17959   unsigned NumBits = VT.getSizeInBits();
17960   SDLoc dl(Op);
17961   Op = Op.getOperand(0);
17962
17963   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17964   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17965   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17966
17967   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17968   SDValue Ops[] = {
17969     Op,
17970     DAG.getConstant(NumBits, VT),
17971     DAG.getConstant(X86::COND_E, MVT::i8),
17972     Op.getValue(1)
17973   };
17974   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17975 }
17976
17977 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17978 // ones, and then concatenate the result back.
17979 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17980   MVT VT = Op.getSimpleValueType();
17981
17982   assert(VT.is256BitVector() && VT.isInteger() &&
17983          "Unsupported value type for operation");
17984
17985   unsigned NumElems = VT.getVectorNumElements();
17986   SDLoc dl(Op);
17987
17988   // Extract the LHS vectors
17989   SDValue LHS = Op.getOperand(0);
17990   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17991   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17992
17993   // Extract the RHS vectors
17994   SDValue RHS = Op.getOperand(1);
17995   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17996   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17997
17998   MVT EltVT = VT.getVectorElementType();
17999   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18000
18001   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18002                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18003                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18004 }
18005
18006 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18007   assert(Op.getSimpleValueType().is256BitVector() &&
18008          Op.getSimpleValueType().isInteger() &&
18009          "Only handle AVX 256-bit vector integer operation");
18010   return Lower256IntArith(Op, DAG);
18011 }
18012
18013 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18014   assert(Op.getSimpleValueType().is256BitVector() &&
18015          Op.getSimpleValueType().isInteger() &&
18016          "Only handle AVX 256-bit vector integer operation");
18017   return Lower256IntArith(Op, DAG);
18018 }
18019
18020 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18021                         SelectionDAG &DAG) {
18022   SDLoc dl(Op);
18023   MVT VT = Op.getSimpleValueType();
18024
18025   // Decompose 256-bit ops into smaller 128-bit ops.
18026   if (VT.is256BitVector() && !Subtarget->hasInt256())
18027     return Lower256IntArith(Op, DAG);
18028
18029   SDValue A = Op.getOperand(0);
18030   SDValue B = Op.getOperand(1);
18031
18032   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18033   if (VT == MVT::v4i32) {
18034     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18035            "Should not custom lower when pmuldq is available!");
18036
18037     // Extract the odd parts.
18038     static const int UnpackMask[] = { 1, -1, 3, -1 };
18039     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18040     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18041
18042     // Multiply the even parts.
18043     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18044     // Now multiply odd parts.
18045     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18046
18047     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
18048     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
18049
18050     // Merge the two vectors back together with a shuffle. This expands into 2
18051     // shuffles.
18052     static const int ShufMask[] = { 0, 4, 2, 6 };
18053     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18054   }
18055
18056   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18057          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18058
18059   //  Ahi = psrlqi(a, 32);
18060   //  Bhi = psrlqi(b, 32);
18061   //
18062   //  AloBlo = pmuludq(a, b);
18063   //  AloBhi = pmuludq(a, Bhi);
18064   //  AhiBlo = pmuludq(Ahi, b);
18065
18066   //  AloBhi = psllqi(AloBhi, 32);
18067   //  AhiBlo = psllqi(AhiBlo, 32);
18068   //  return AloBlo + AloBhi + AhiBlo;
18069
18070   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18071   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18072
18073   // Bit cast to 32-bit vectors for MULUDQ
18074   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18075                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18076   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
18077   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
18078   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
18079   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
18080
18081   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18082   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18083   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18084
18085   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18086   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18087
18088   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18089   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18090 }
18091
18092 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18093   assert(Subtarget->isTargetWin64() && "Unexpected target");
18094   EVT VT = Op.getValueType();
18095   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18096          "Unexpected return type for lowering");
18097
18098   RTLIB::Libcall LC;
18099   bool isSigned;
18100   switch (Op->getOpcode()) {
18101   default: llvm_unreachable("Unexpected request for libcall!");
18102   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18103   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18104   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18105   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18106   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18107   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18108   }
18109
18110   SDLoc dl(Op);
18111   SDValue InChain = DAG.getEntryNode();
18112
18113   TargetLowering::ArgListTy Args;
18114   TargetLowering::ArgListEntry Entry;
18115   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18116     EVT ArgVT = Op->getOperand(i).getValueType();
18117     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18118            "Unexpected argument type for lowering");
18119     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18120     Entry.Node = StackPtr;
18121     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18122                            false, false, 16);
18123     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18124     Entry.Ty = PointerType::get(ArgTy,0);
18125     Entry.isSExt = false;
18126     Entry.isZExt = false;
18127     Args.push_back(Entry);
18128   }
18129
18130   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18131                                          getPointerTy());
18132
18133   TargetLowering::CallLoweringInfo CLI(DAG);
18134   CLI.setDebugLoc(dl).setChain(InChain)
18135     .setCallee(getLibcallCallingConv(LC),
18136                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18137                Callee, std::move(Args), 0)
18138     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18139
18140   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18141   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
18142 }
18143
18144 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18145                              SelectionDAG &DAG) {
18146   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18147   EVT VT = Op0.getValueType();
18148   SDLoc dl(Op);
18149
18150   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18151          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18152
18153   // PMULxD operations multiply each even value (starting at 0) of LHS with
18154   // the related value of RHS and produce a widen result.
18155   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18156   // => <2 x i64> <ae|cg>
18157   //
18158   // In other word, to have all the results, we need to perform two PMULxD:
18159   // 1. one with the even values.
18160   // 2. one with the odd values.
18161   // To achieve #2, with need to place the odd values at an even position.
18162   //
18163   // Place the odd value at an even position (basically, shift all values 1
18164   // step to the left):
18165   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18166   // <a|b|c|d> => <b|undef|d|undef>
18167   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18168   // <e|f|g|h> => <f|undef|h|undef>
18169   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18170
18171   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18172   // ints.
18173   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18174   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18175   unsigned Opcode =
18176       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18177   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18178   // => <2 x i64> <ae|cg>
18179   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
18180                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18181   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18182   // => <2 x i64> <bf|dh>
18183   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
18184                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18185
18186   // Shuffle it back into the right order.
18187   SDValue Highs, Lows;
18188   if (VT == MVT::v8i32) {
18189     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18190     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18191     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18192     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18193   } else {
18194     const int HighMask[] = {1, 5, 3, 7};
18195     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18196     const int LowMask[] = {0, 4, 2, 6};
18197     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18198   }
18199
18200   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18201   // unsigned multiply.
18202   if (IsSigned && !Subtarget->hasSSE41()) {
18203     SDValue ShAmt =
18204         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
18205     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18206                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18207     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18208                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18209
18210     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18211     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18212   }
18213
18214   // The first result of MUL_LOHI is actually the low value, followed by the
18215   // high value.
18216   SDValue Ops[] = {Lows, Highs};
18217   return DAG.getMergeValues(Ops, dl);
18218 }
18219
18220 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18221                                          const X86Subtarget *Subtarget) {
18222   MVT VT = Op.getSimpleValueType();
18223   SDLoc dl(Op);
18224   SDValue R = Op.getOperand(0);
18225   SDValue Amt = Op.getOperand(1);
18226
18227   // Optimize shl/srl/sra with constant shift amount.
18228   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18229     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18230       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18231
18232       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
18233           (Subtarget->hasInt256() &&
18234            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18235           (Subtarget->hasAVX512() &&
18236            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18237         if (Op.getOpcode() == ISD::SHL)
18238           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18239                                             DAG);
18240         if (Op.getOpcode() == ISD::SRL)
18241           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18242                                             DAG);
18243         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
18244           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18245                                             DAG);
18246       }
18247
18248       if (VT == MVT::v16i8) {
18249         if (Op.getOpcode() == ISD::SHL) {
18250           // Make a large shift.
18251           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18252                                                    MVT::v8i16, R, ShiftAmt,
18253                                                    DAG);
18254           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18255           // Zero out the rightmost bits.
18256           SmallVector<SDValue, 16> V(16,
18257                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18258                                                      MVT::i8));
18259           return DAG.getNode(ISD::AND, dl, VT, SHL,
18260                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18261         }
18262         if (Op.getOpcode() == ISD::SRL) {
18263           // Make a large shift.
18264           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18265                                                    MVT::v8i16, R, ShiftAmt,
18266                                                    DAG);
18267           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18268           // Zero out the leftmost bits.
18269           SmallVector<SDValue, 16> V(16,
18270                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18271                                                      MVT::i8));
18272           return DAG.getNode(ISD::AND, dl, VT, SRL,
18273                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18274         }
18275         if (Op.getOpcode() == ISD::SRA) {
18276           if (ShiftAmt == 7) {
18277             // R s>> 7  ===  R s< 0
18278             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18279             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18280           }
18281
18282           // R s>> a === ((R u>> a) ^ m) - m
18283           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18284           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
18285                                                          MVT::i8));
18286           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18287           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18288           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18289           return Res;
18290         }
18291         llvm_unreachable("Unknown shift opcode.");
18292       }
18293
18294       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
18295         if (Op.getOpcode() == ISD::SHL) {
18296           // Make a large shift.
18297           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18298                                                    MVT::v16i16, R, ShiftAmt,
18299                                                    DAG);
18300           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18301           // Zero out the rightmost bits.
18302           SmallVector<SDValue, 32> V(32,
18303                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18304                                                      MVT::i8));
18305           return DAG.getNode(ISD::AND, dl, VT, SHL,
18306                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18307         }
18308         if (Op.getOpcode() == ISD::SRL) {
18309           // Make a large shift.
18310           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18311                                                    MVT::v16i16, R, ShiftAmt,
18312                                                    DAG);
18313           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18314           // Zero out the leftmost bits.
18315           SmallVector<SDValue, 32> V(32,
18316                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18317                                                      MVT::i8));
18318           return DAG.getNode(ISD::AND, dl, VT, SRL,
18319                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18320         }
18321         if (Op.getOpcode() == ISD::SRA) {
18322           if (ShiftAmt == 7) {
18323             // R s>> 7  ===  R s< 0
18324             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18325             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18326           }
18327
18328           // R s>> a === ((R u>> a) ^ m) - m
18329           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18330           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
18331                                                          MVT::i8));
18332           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18333           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18334           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18335           return Res;
18336         }
18337         llvm_unreachable("Unknown shift opcode.");
18338       }
18339     }
18340   }
18341
18342   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18343   if (!Subtarget->is64Bit() &&
18344       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18345       Amt.getOpcode() == ISD::BITCAST &&
18346       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18347     Amt = Amt.getOperand(0);
18348     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18349                      VT.getVectorNumElements();
18350     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18351     uint64_t ShiftAmt = 0;
18352     for (unsigned i = 0; i != Ratio; ++i) {
18353       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
18354       if (!C)
18355         return SDValue();
18356       // 6 == Log2(64)
18357       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18358     }
18359     // Check remaining shift amounts.
18360     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18361       uint64_t ShAmt = 0;
18362       for (unsigned j = 0; j != Ratio; ++j) {
18363         ConstantSDNode *C =
18364           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18365         if (!C)
18366           return SDValue();
18367         // 6 == Log2(64)
18368         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18369       }
18370       if (ShAmt != ShiftAmt)
18371         return SDValue();
18372     }
18373     switch (Op.getOpcode()) {
18374     default:
18375       llvm_unreachable("Unknown shift opcode!");
18376     case ISD::SHL:
18377       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18378                                         DAG);
18379     case ISD::SRL:
18380       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18381                                         DAG);
18382     case ISD::SRA:
18383       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18384                                         DAG);
18385     }
18386   }
18387
18388   return SDValue();
18389 }
18390
18391 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18392                                         const X86Subtarget* Subtarget) {
18393   MVT VT = Op.getSimpleValueType();
18394   SDLoc dl(Op);
18395   SDValue R = Op.getOperand(0);
18396   SDValue Amt = Op.getOperand(1);
18397
18398   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
18399       VT == MVT::v4i32 || VT == MVT::v8i16 ||
18400       (Subtarget->hasInt256() &&
18401        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
18402         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18403        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18404     SDValue BaseShAmt;
18405     EVT EltVT = VT.getVectorElementType();
18406
18407     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18408       // Check if this build_vector node is doing a splat.
18409       // If so, then set BaseShAmt equal to the splat value.
18410       BaseShAmt = BV->getSplatValue();
18411       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18412         BaseShAmt = SDValue();
18413     } else {
18414       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18415         Amt = Amt.getOperand(0);
18416
18417       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18418       if (SVN && SVN->isSplat()) {
18419         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18420         SDValue InVec = Amt.getOperand(0);
18421         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18422           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18423                  "Unexpected shuffle index found!");
18424           BaseShAmt = InVec.getOperand(SplatIdx);
18425         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18426            if (ConstantSDNode *C =
18427                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18428              if (C->getZExtValue() == SplatIdx)
18429                BaseShAmt = InVec.getOperand(1);
18430            }
18431         }
18432
18433         if (!BaseShAmt)
18434           // Avoid introducing an extract element from a shuffle.
18435           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18436                                     DAG.getIntPtrConstant(SplatIdx));
18437       }
18438     }
18439
18440     if (BaseShAmt.getNode()) {
18441       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18442       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18443         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18444       else if (EltVT.bitsLT(MVT::i32))
18445         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18446
18447       switch (Op.getOpcode()) {
18448       default:
18449         llvm_unreachable("Unknown shift opcode!");
18450       case ISD::SHL:
18451         switch (VT.SimpleTy) {
18452         default: return SDValue();
18453         case MVT::v2i64:
18454         case MVT::v4i32:
18455         case MVT::v8i16:
18456         case MVT::v4i64:
18457         case MVT::v8i32:
18458         case MVT::v16i16:
18459         case MVT::v16i32:
18460         case MVT::v8i64:
18461           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
18462         }
18463       case ISD::SRA:
18464         switch (VT.SimpleTy) {
18465         default: return SDValue();
18466         case MVT::v4i32:
18467         case MVT::v8i16:
18468         case MVT::v8i32:
18469         case MVT::v16i16:
18470         case MVT::v16i32:
18471         case MVT::v8i64:
18472           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
18473         }
18474       case ISD::SRL:
18475         switch (VT.SimpleTy) {
18476         default: return SDValue();
18477         case MVT::v2i64:
18478         case MVT::v4i32:
18479         case MVT::v8i16:
18480         case MVT::v4i64:
18481         case MVT::v8i32:
18482         case MVT::v16i16:
18483         case MVT::v16i32:
18484         case MVT::v8i64:
18485           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
18486         }
18487       }
18488     }
18489   }
18490
18491   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18492   if (!Subtarget->is64Bit() &&
18493       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
18494       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
18495       Amt.getOpcode() == ISD::BITCAST &&
18496       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18497     Amt = Amt.getOperand(0);
18498     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18499                      VT.getVectorNumElements();
18500     std::vector<SDValue> Vals(Ratio);
18501     for (unsigned i = 0; i != Ratio; ++i)
18502       Vals[i] = Amt.getOperand(i);
18503     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18504       for (unsigned j = 0; j != Ratio; ++j)
18505         if (Vals[j] != Amt.getOperand(i + j))
18506           return SDValue();
18507     }
18508     switch (Op.getOpcode()) {
18509     default:
18510       llvm_unreachable("Unknown shift opcode!");
18511     case ISD::SHL:
18512       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
18513     case ISD::SRL:
18514       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
18515     case ISD::SRA:
18516       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
18517     }
18518   }
18519
18520   return SDValue();
18521 }
18522
18523 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18524                           SelectionDAG &DAG) {
18525   MVT VT = Op.getSimpleValueType();
18526   SDLoc dl(Op);
18527   SDValue R = Op.getOperand(0);
18528   SDValue Amt = Op.getOperand(1);
18529   SDValue V;
18530
18531   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18532   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18533
18534   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
18535   if (V.getNode())
18536     return V;
18537
18538   V = LowerScalarVariableShift(Op, DAG, Subtarget);
18539   if (V.getNode())
18540       return V;
18541
18542   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
18543     return Op;
18544   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
18545   if (Subtarget->hasInt256()) {
18546     if (Op.getOpcode() == ISD::SRL &&
18547         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18548          VT == MVT::v4i64 || VT == MVT::v8i32))
18549       return Op;
18550     if (Op.getOpcode() == ISD::SHL &&
18551         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18552          VT == MVT::v4i64 || VT == MVT::v8i32))
18553       return Op;
18554     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
18555       return Op;
18556   }
18557
18558   // If possible, lower this packed shift into a vector multiply instead of
18559   // expanding it into a sequence of scalar shifts.
18560   // Do this only if the vector shift count is a constant build_vector.
18561   if (Op.getOpcode() == ISD::SHL &&
18562       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18563        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18564       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18565     SmallVector<SDValue, 8> Elts;
18566     EVT SVT = VT.getScalarType();
18567     unsigned SVTBits = SVT.getSizeInBits();
18568     const APInt &One = APInt(SVTBits, 1);
18569     unsigned NumElems = VT.getVectorNumElements();
18570
18571     for (unsigned i=0; i !=NumElems; ++i) {
18572       SDValue Op = Amt->getOperand(i);
18573       if (Op->getOpcode() == ISD::UNDEF) {
18574         Elts.push_back(Op);
18575         continue;
18576       }
18577
18578       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18579       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18580       uint64_t ShAmt = C.getZExtValue();
18581       if (ShAmt >= SVTBits) {
18582         Elts.push_back(DAG.getUNDEF(SVT));
18583         continue;
18584       }
18585       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
18586     }
18587     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18588     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18589   }
18590
18591   // Lower SHL with variable shift amount.
18592   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18593     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
18594
18595     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
18596     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
18597     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18598     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18599   }
18600
18601   // If possible, lower this shift as a sequence of two shifts by
18602   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18603   // Example:
18604   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18605   //
18606   // Could be rewritten as:
18607   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18608   //
18609   // The advantage is that the two shifts from the example would be
18610   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18611   // the vector shift into four scalar shifts plus four pairs of vector
18612   // insert/extract.
18613   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18614       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18615     unsigned TargetOpcode = X86ISD::MOVSS;
18616     bool CanBeSimplified;
18617     // The splat value for the first packed shift (the 'X' from the example).
18618     SDValue Amt1 = Amt->getOperand(0);
18619     // The splat value for the second packed shift (the 'Y' from the example).
18620     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18621                                         Amt->getOperand(2);
18622
18623     // See if it is possible to replace this node with a sequence of
18624     // two shifts followed by a MOVSS/MOVSD
18625     if (VT == MVT::v4i32) {
18626       // Check if it is legal to use a MOVSS.
18627       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18628                         Amt2 == Amt->getOperand(3);
18629       if (!CanBeSimplified) {
18630         // Otherwise, check if we can still simplify this node using a MOVSD.
18631         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18632                           Amt->getOperand(2) == Amt->getOperand(3);
18633         TargetOpcode = X86ISD::MOVSD;
18634         Amt2 = Amt->getOperand(2);
18635       }
18636     } else {
18637       // Do similar checks for the case where the machine value type
18638       // is MVT::v8i16.
18639       CanBeSimplified = Amt1 == Amt->getOperand(1);
18640       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18641         CanBeSimplified = Amt2 == Amt->getOperand(i);
18642
18643       if (!CanBeSimplified) {
18644         TargetOpcode = X86ISD::MOVSD;
18645         CanBeSimplified = true;
18646         Amt2 = Amt->getOperand(4);
18647         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18648           CanBeSimplified = Amt1 == Amt->getOperand(i);
18649         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18650           CanBeSimplified = Amt2 == Amt->getOperand(j);
18651       }
18652     }
18653
18654     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18655         isa<ConstantSDNode>(Amt2)) {
18656       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18657       EVT CastVT = MVT::v4i32;
18658       SDValue Splat1 =
18659         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
18660       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18661       SDValue Splat2 =
18662         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
18663       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18664       if (TargetOpcode == X86ISD::MOVSD)
18665         CastVT = MVT::v2i64;
18666       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
18667       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
18668       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18669                                             BitCast1, DAG);
18670       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
18671     }
18672   }
18673
18674   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
18675     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
18676
18677     // a = a << 5;
18678     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
18679     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
18680
18681     // Turn 'a' into a mask suitable for VSELECT
18682     SDValue VSelM = DAG.getConstant(0x80, VT);
18683     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18684     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18685
18686     SDValue CM1 = DAG.getConstant(0x0f, VT);
18687     SDValue CM2 = DAG.getConstant(0x3f, VT);
18688
18689     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
18690     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
18691     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
18692     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18693     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18694
18695     // a += a
18696     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18697     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18698     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18699
18700     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
18701     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
18702     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
18703     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18704     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18705
18706     // a += a
18707     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18708     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18709     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18710
18711     // return VSELECT(r, r+r, a);
18712     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
18713                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
18714     return R;
18715   }
18716
18717   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18718   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18719   // solution better.
18720   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18721     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
18722     unsigned ExtOpc =
18723         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18724     R = DAG.getNode(ExtOpc, dl, NewVT, R);
18725     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
18726     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18727                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
18728     }
18729
18730   // Decompose 256-bit shifts into smaller 128-bit shifts.
18731   if (VT.is256BitVector()) {
18732     unsigned NumElems = VT.getVectorNumElements();
18733     MVT EltVT = VT.getVectorElementType();
18734     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18735
18736     // Extract the two vectors
18737     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18738     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18739
18740     // Recreate the shift amount vectors
18741     SDValue Amt1, Amt2;
18742     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18743       // Constant shift amount
18744       SmallVector<SDValue, 4> Amt1Csts;
18745       SmallVector<SDValue, 4> Amt2Csts;
18746       for (unsigned i = 0; i != NumElems/2; ++i)
18747         Amt1Csts.push_back(Amt->getOperand(i));
18748       for (unsigned i = NumElems/2; i != NumElems; ++i)
18749         Amt2Csts.push_back(Amt->getOperand(i));
18750
18751       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18752       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18753     } else {
18754       // Variable shift amount
18755       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18756       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18757     }
18758
18759     // Issue new vector shifts for the smaller types
18760     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18761     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18762
18763     // Concatenate the result back
18764     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18765   }
18766
18767   return SDValue();
18768 }
18769
18770 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18771   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18772   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18773   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18774   // has only one use.
18775   SDNode *N = Op.getNode();
18776   SDValue LHS = N->getOperand(0);
18777   SDValue RHS = N->getOperand(1);
18778   unsigned BaseOp = 0;
18779   unsigned Cond = 0;
18780   SDLoc DL(Op);
18781   switch (Op.getOpcode()) {
18782   default: llvm_unreachable("Unknown ovf instruction!");
18783   case ISD::SADDO:
18784     // A subtract of one will be selected as a INC. Note that INC doesn't
18785     // set CF, so we can't do this for UADDO.
18786     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18787       if (C->isOne()) {
18788         BaseOp = X86ISD::INC;
18789         Cond = X86::COND_O;
18790         break;
18791       }
18792     BaseOp = X86ISD::ADD;
18793     Cond = X86::COND_O;
18794     break;
18795   case ISD::UADDO:
18796     BaseOp = X86ISD::ADD;
18797     Cond = X86::COND_B;
18798     break;
18799   case ISD::SSUBO:
18800     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18801     // set CF, so we can't do this for USUBO.
18802     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18803       if (C->isOne()) {
18804         BaseOp = X86ISD::DEC;
18805         Cond = X86::COND_O;
18806         break;
18807       }
18808     BaseOp = X86ISD::SUB;
18809     Cond = X86::COND_O;
18810     break;
18811   case ISD::USUBO:
18812     BaseOp = X86ISD::SUB;
18813     Cond = X86::COND_B;
18814     break;
18815   case ISD::SMULO:
18816     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18817     Cond = X86::COND_O;
18818     break;
18819   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18820     if (N->getValueType(0) == MVT::i8) {
18821       BaseOp = X86ISD::UMUL8;
18822       Cond = X86::COND_O;
18823       break;
18824     }
18825     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18826                                  MVT::i32);
18827     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18828
18829     SDValue SetCC =
18830       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18831                   DAG.getConstant(X86::COND_O, MVT::i32),
18832                   SDValue(Sum.getNode(), 2));
18833
18834     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18835   }
18836   }
18837
18838   // Also sets EFLAGS.
18839   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18840   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18841
18842   SDValue SetCC =
18843     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18844                 DAG.getConstant(Cond, MVT::i32),
18845                 SDValue(Sum.getNode(), 1));
18846
18847   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18848 }
18849
18850 // Sign extension of the low part of vector elements. This may be used either
18851 // when sign extend instructions are not available or if the vector element
18852 // sizes already match the sign-extended size. If the vector elements are in
18853 // their pre-extended size and sign extend instructions are available, that will
18854 // be handled by LowerSIGN_EXTEND.
18855 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
18856                                                   SelectionDAG &DAG) const {
18857   SDLoc dl(Op);
18858   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
18859   MVT VT = Op.getSimpleValueType();
18860
18861   if (!Subtarget->hasSSE2() || !VT.isVector())
18862     return SDValue();
18863
18864   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
18865                       ExtraVT.getScalarType().getSizeInBits();
18866
18867   switch (VT.SimpleTy) {
18868     default: return SDValue();
18869     case MVT::v8i32:
18870     case MVT::v16i16:
18871       if (!Subtarget->hasFp256())
18872         return SDValue();
18873       if (!Subtarget->hasInt256()) {
18874         // needs to be split
18875         unsigned NumElems = VT.getVectorNumElements();
18876
18877         // Extract the LHS vectors
18878         SDValue LHS = Op.getOperand(0);
18879         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18880         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18881
18882         MVT EltVT = VT.getVectorElementType();
18883         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18884
18885         EVT ExtraEltVT = ExtraVT.getVectorElementType();
18886         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
18887         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
18888                                    ExtraNumElems/2);
18889         SDValue Extra = DAG.getValueType(ExtraVT);
18890
18891         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
18892         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
18893
18894         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
18895       }
18896       // fall through
18897     case MVT::v4i32:
18898     case MVT::v8i16: {
18899       SDValue Op0 = Op.getOperand(0);
18900
18901       // This is a sign extension of some low part of vector elements without
18902       // changing the size of the vector elements themselves:
18903       // Shift-Left + Shift-Right-Algebraic.
18904       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
18905                                                BitsDiff, DAG);
18906       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
18907                                         DAG);
18908     }
18909   }
18910 }
18911
18912 /// Returns true if the operand type is exactly twice the native width, and
18913 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18914 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18915 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18916 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
18917   const X86Subtarget &Subtarget =
18918       getTargetMachine().getSubtarget<X86Subtarget>();
18919   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18920
18921   if (OpWidth == 64)
18922     return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18923   else if (OpWidth == 128)
18924     return Subtarget.hasCmpxchg16b();
18925   else
18926     return false;
18927 }
18928
18929 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18930   return needsCmpXchgNb(SI->getValueOperand()->getType());
18931 }
18932
18933 // Note: this turns large loads into lock cmpxchg8b/16b.
18934 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18935 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18936   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18937   return needsCmpXchgNb(PTy->getElementType());
18938 }
18939
18940 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18941   const X86Subtarget &Subtarget =
18942       getTargetMachine().getSubtarget<X86Subtarget>();
18943   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
18944   const Type *MemType = AI->getType();
18945
18946   // If the operand is too big, we must see if cmpxchg8/16b is available
18947   // and default to library calls otherwise.
18948   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18949     return needsCmpXchgNb(MemType);
18950
18951   AtomicRMWInst::BinOp Op = AI->getOperation();
18952   switch (Op) {
18953   default:
18954     llvm_unreachable("Unknown atomic operation");
18955   case AtomicRMWInst::Xchg:
18956   case AtomicRMWInst::Add:
18957   case AtomicRMWInst::Sub:
18958     // It's better to use xadd, xsub or xchg for these in all cases.
18959     return false;
18960   case AtomicRMWInst::Or:
18961   case AtomicRMWInst::And:
18962   case AtomicRMWInst::Xor:
18963     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18964     // prefix to a normal instruction for these operations.
18965     return !AI->use_empty();
18966   case AtomicRMWInst::Nand:
18967   case AtomicRMWInst::Max:
18968   case AtomicRMWInst::Min:
18969   case AtomicRMWInst::UMax:
18970   case AtomicRMWInst::UMin:
18971     // These always require a non-trivial set of data operations on x86. We must
18972     // use a cmpxchg loop.
18973     return true;
18974   }
18975 }
18976
18977 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18978   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18979   // no-sse2). There isn't any reason to disable it if the target processor
18980   // supports it.
18981   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18982 }
18983
18984 LoadInst *
18985 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18986   const X86Subtarget &Subtarget =
18987       getTargetMachine().getSubtarget<X86Subtarget>();
18988   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
18989   const Type *MemType = AI->getType();
18990   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18991   // there is no benefit in turning such RMWs into loads, and it is actually
18992   // harmful as it introduces a mfence.
18993   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18994     return nullptr;
18995
18996   auto Builder = IRBuilder<>(AI);
18997   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18998   auto SynchScope = AI->getSynchScope();
18999   // We must restrict the ordering to avoid generating loads with Release or
19000   // ReleaseAcquire orderings.
19001   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19002   auto Ptr = AI->getPointerOperand();
19003
19004   // Before the load we need a fence. Here is an example lifted from
19005   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19006   // is required:
19007   // Thread 0:
19008   //   x.store(1, relaxed);
19009   //   r1 = y.fetch_add(0, release);
19010   // Thread 1:
19011   //   y.fetch_add(42, acquire);
19012   //   r2 = x.load(relaxed);
19013   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19014   // lowered to just a load without a fence. A mfence flushes the store buffer,
19015   // making the optimization clearly correct.
19016   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19017   // otherwise, we might be able to be more agressive on relaxed idempotent
19018   // rmw. In practice, they do not look useful, so we don't try to be
19019   // especially clever.
19020   if (SynchScope == SingleThread) {
19021     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19022     // the IR level, so we must wrap it in an intrinsic.
19023     return nullptr;
19024   } else if (hasMFENCE(Subtarget)) {
19025     Function *MFence = llvm::Intrinsic::getDeclaration(M,
19026             Intrinsic::x86_sse2_mfence);
19027     Builder.CreateCall(MFence);
19028   } else {
19029     // FIXME: it might make sense to use a locked operation here but on a
19030     // different cache-line to prevent cache-line bouncing. In practice it
19031     // is probably a small win, and x86 processors without mfence are rare
19032     // enough that we do not bother.
19033     return nullptr;
19034   }
19035
19036   // Finally we can emit the atomic load.
19037   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19038           AI->getType()->getPrimitiveSizeInBits());
19039   Loaded->setAtomic(Order, SynchScope);
19040   AI->replaceAllUsesWith(Loaded);
19041   AI->eraseFromParent();
19042   return Loaded;
19043 }
19044
19045 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19046                                  SelectionDAG &DAG) {
19047   SDLoc dl(Op);
19048   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19049     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19050   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19051     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19052
19053   // The only fence that needs an instruction is a sequentially-consistent
19054   // cross-thread fence.
19055   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19056     if (hasMFENCE(*Subtarget))
19057       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19058
19059     SDValue Chain = Op.getOperand(0);
19060     SDValue Zero = DAG.getConstant(0, MVT::i32);
19061     SDValue Ops[] = {
19062       DAG.getRegister(X86::ESP, MVT::i32), // Base
19063       DAG.getTargetConstant(1, MVT::i8),   // Scale
19064       DAG.getRegister(0, MVT::i32),        // Index
19065       DAG.getTargetConstant(0, MVT::i32),  // Disp
19066       DAG.getRegister(0, MVT::i32),        // Segment.
19067       Zero,
19068       Chain
19069     };
19070     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19071     return SDValue(Res, 0);
19072   }
19073
19074   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19075   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19076 }
19077
19078 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19079                              SelectionDAG &DAG) {
19080   MVT T = Op.getSimpleValueType();
19081   SDLoc DL(Op);
19082   unsigned Reg = 0;
19083   unsigned size = 0;
19084   switch(T.SimpleTy) {
19085   default: llvm_unreachable("Invalid value type!");
19086   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19087   case MVT::i16: Reg = X86::AX;  size = 2; break;
19088   case MVT::i32: Reg = X86::EAX; size = 4; break;
19089   case MVT::i64:
19090     assert(Subtarget->is64Bit() && "Node not type legal!");
19091     Reg = X86::RAX; size = 8;
19092     break;
19093   }
19094   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19095                                   Op.getOperand(2), SDValue());
19096   SDValue Ops[] = { cpIn.getValue(0),
19097                     Op.getOperand(1),
19098                     Op.getOperand(3),
19099                     DAG.getTargetConstant(size, MVT::i8),
19100                     cpIn.getValue(1) };
19101   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19102   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19103   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19104                                            Ops, T, MMO);
19105
19106   SDValue cpOut =
19107     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19108   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19109                                       MVT::i32, cpOut.getValue(2));
19110   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19111                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19112
19113   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19114   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19115   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19116   return SDValue();
19117 }
19118
19119 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19120                             SelectionDAG &DAG) {
19121   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19122   MVT DstVT = Op.getSimpleValueType();
19123
19124   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19125     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19126     if (DstVT != MVT::f64)
19127       // This conversion needs to be expanded.
19128       return SDValue();
19129
19130     SDValue InVec = Op->getOperand(0);
19131     SDLoc dl(Op);
19132     unsigned NumElts = SrcVT.getVectorNumElements();
19133     EVT SVT = SrcVT.getVectorElementType();
19134
19135     // Widen the vector in input in the case of MVT::v2i32.
19136     // Example: from MVT::v2i32 to MVT::v4i32.
19137     SmallVector<SDValue, 16> Elts;
19138     for (unsigned i = 0, e = NumElts; i != e; ++i)
19139       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19140                                  DAG.getIntPtrConstant(i)));
19141
19142     // Explicitly mark the extra elements as Undef.
19143     SDValue Undef = DAG.getUNDEF(SVT);
19144     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
19145       Elts.push_back(Undef);
19146
19147     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19148     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19149     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
19150     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19151                        DAG.getIntPtrConstant(0));
19152   }
19153
19154   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19155          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19156   assert((DstVT == MVT::i64 ||
19157           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19158          "Unexpected custom BITCAST");
19159   // i64 <=> MMX conversions are Legal.
19160   if (SrcVT==MVT::i64 && DstVT.isVector())
19161     return Op;
19162   if (DstVT==MVT::i64 && SrcVT.isVector())
19163     return Op;
19164   // MMX <=> MMX conversions are Legal.
19165   if (SrcVT.isVector() && DstVT.isVector())
19166     return Op;
19167   // All other conversions need to be expanded.
19168   return SDValue();
19169 }
19170
19171 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19172   SDNode *Node = Op.getNode();
19173   SDLoc dl(Node);
19174   EVT T = Node->getValueType(0);
19175   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19176                               DAG.getConstant(0, T), Node->getOperand(2));
19177   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19178                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19179                        Node->getOperand(0),
19180                        Node->getOperand(1), negOp,
19181                        cast<AtomicSDNode>(Node)->getMemOperand(),
19182                        cast<AtomicSDNode>(Node)->getOrdering(),
19183                        cast<AtomicSDNode>(Node)->getSynchScope());
19184 }
19185
19186 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19187   SDNode *Node = Op.getNode();
19188   SDLoc dl(Node);
19189   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19190
19191   // Convert seq_cst store -> xchg
19192   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19193   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19194   //        (The only way to get a 16-byte store is cmpxchg16b)
19195   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19196   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19197       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19198     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19199                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19200                                  Node->getOperand(0),
19201                                  Node->getOperand(1), Node->getOperand(2),
19202                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19203                                  cast<AtomicSDNode>(Node)->getOrdering(),
19204                                  cast<AtomicSDNode>(Node)->getSynchScope());
19205     return Swap.getValue(1);
19206   }
19207   // Other atomic stores have a simple pattern.
19208   return Op;
19209 }
19210
19211 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19212   EVT VT = Op.getNode()->getSimpleValueType(0);
19213
19214   // Let legalize expand this if it isn't a legal type yet.
19215   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19216     return SDValue();
19217
19218   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19219
19220   unsigned Opc;
19221   bool ExtraOp = false;
19222   switch (Op.getOpcode()) {
19223   default: llvm_unreachable("Invalid code");
19224   case ISD::ADDC: Opc = X86ISD::ADD; break;
19225   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19226   case ISD::SUBC: Opc = X86ISD::SUB; break;
19227   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19228   }
19229
19230   if (!ExtraOp)
19231     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19232                        Op.getOperand(1));
19233   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19234                      Op.getOperand(1), Op.getOperand(2));
19235 }
19236
19237 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19238                             SelectionDAG &DAG) {
19239   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19240
19241   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19242   // which returns the values as { float, float } (in XMM0) or
19243   // { double, double } (which is returned in XMM0, XMM1).
19244   SDLoc dl(Op);
19245   SDValue Arg = Op.getOperand(0);
19246   EVT ArgVT = Arg.getValueType();
19247   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19248
19249   TargetLowering::ArgListTy Args;
19250   TargetLowering::ArgListEntry Entry;
19251
19252   Entry.Node = Arg;
19253   Entry.Ty = ArgTy;
19254   Entry.isSExt = false;
19255   Entry.isZExt = false;
19256   Args.push_back(Entry);
19257
19258   bool isF64 = ArgVT == MVT::f64;
19259   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19260   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19261   // the results are returned via SRet in memory.
19262   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19263   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19264   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
19265
19266   Type *RetTy = isF64
19267     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19268     : (Type*)VectorType::get(ArgTy, 4);
19269
19270   TargetLowering::CallLoweringInfo CLI(DAG);
19271   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19272     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19273
19274   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19275
19276   if (isF64)
19277     // Returned in xmm0 and xmm1.
19278     return CallResult.first;
19279
19280   // Returned in bits 0:31 and 32:64 xmm0.
19281   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19282                                CallResult.first, DAG.getIntPtrConstant(0));
19283   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19284                                CallResult.first, DAG.getIntPtrConstant(1));
19285   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19286   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19287 }
19288
19289 /// LowerOperation - Provide custom lowering hooks for some operations.
19290 ///
19291 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19292   switch (Op.getOpcode()) {
19293   default: llvm_unreachable("Should not custom lower this!");
19294   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
19295   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19296   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19297     return LowerCMP_SWAP(Op, Subtarget, DAG);
19298   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19299   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19300   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19301   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
19302   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
19303   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19304   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19305   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19306   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19307   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19308   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19309   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19310   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19311   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19312   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19313   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19314   case ISD::SHL_PARTS:
19315   case ISD::SRA_PARTS:
19316   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19317   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19318   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19319   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19320   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19321   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19322   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19323   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19324   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19325   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19326   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19327   case ISD::FABS:
19328   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19329   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19330   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19331   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19332   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19333   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19334   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19335   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19336   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19337   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19338   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19339   case ISD::INTRINSIC_VOID:
19340   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19341   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19342   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19343   case ISD::FRAME_TO_ARGS_OFFSET:
19344                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19345   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19346   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19347   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19348   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19349   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19350   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19351   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19352   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19353   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19354   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
19355   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19356   case ISD::UMUL_LOHI:
19357   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19358   case ISD::SRA:
19359   case ISD::SRL:
19360   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19361   case ISD::SADDO:
19362   case ISD::UADDO:
19363   case ISD::SSUBO:
19364   case ISD::USUBO:
19365   case ISD::SMULO:
19366   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19367   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19368   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19369   case ISD::ADDC:
19370   case ISD::ADDE:
19371   case ISD::SUBC:
19372   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19373   case ISD::ADD:                return LowerADD(Op, DAG);
19374   case ISD::SUB:                return LowerSUB(Op, DAG);
19375   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19376   }
19377 }
19378
19379 /// ReplaceNodeResults - Replace a node with an illegal result type
19380 /// with a new node built out of custom code.
19381 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19382                                            SmallVectorImpl<SDValue>&Results,
19383                                            SelectionDAG &DAG) const {
19384   SDLoc dl(N);
19385   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19386   switch (N->getOpcode()) {
19387   default:
19388     llvm_unreachable("Do not know how to custom type legalize this operation!");
19389   case ISD::SIGN_EXTEND_INREG:
19390   case ISD::ADDC:
19391   case ISD::ADDE:
19392   case ISD::SUBC:
19393   case ISD::SUBE:
19394     // We don't want to expand or promote these.
19395     return;
19396   case ISD::SDIV:
19397   case ISD::UDIV:
19398   case ISD::SREM:
19399   case ISD::UREM:
19400   case ISD::SDIVREM:
19401   case ISD::UDIVREM: {
19402     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19403     Results.push_back(V);
19404     return;
19405   }
19406   case ISD::FP_TO_SINT:
19407   case ISD::FP_TO_UINT: {
19408     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19409
19410     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
19411       return;
19412
19413     std::pair<SDValue,SDValue> Vals =
19414         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19415     SDValue FIST = Vals.first, StackSlot = Vals.second;
19416     if (FIST.getNode()) {
19417       EVT VT = N->getValueType(0);
19418       // Return a load from the stack slot.
19419       if (StackSlot.getNode())
19420         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19421                                       MachinePointerInfo(),
19422                                       false, false, false, 0));
19423       else
19424         Results.push_back(FIST);
19425     }
19426     return;
19427   }
19428   case ISD::UINT_TO_FP: {
19429     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19430     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19431         N->getValueType(0) != MVT::v2f32)
19432       return;
19433     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19434                                  N->getOperand(0));
19435     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
19436                                      MVT::f64);
19437     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19438     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19439                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
19440     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
19441     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19442     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19443     return;
19444   }
19445   case ISD::FP_ROUND: {
19446     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19447         return;
19448     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19449     Results.push_back(V);
19450     return;
19451   }
19452   case ISD::INTRINSIC_W_CHAIN: {
19453     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19454     switch (IntNo) {
19455     default : llvm_unreachable("Do not know how to custom type "
19456                                "legalize this intrinsic operation!");
19457     case Intrinsic::x86_rdtsc:
19458       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19459                                      Results);
19460     case Intrinsic::x86_rdtscp:
19461       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19462                                      Results);
19463     case Intrinsic::x86_rdpmc:
19464       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19465     }
19466   }
19467   case ISD::READCYCLECOUNTER: {
19468     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19469                                    Results);
19470   }
19471   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19472     EVT T = N->getValueType(0);
19473     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19474     bool Regs64bit = T == MVT::i128;
19475     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19476     SDValue cpInL, cpInH;
19477     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19478                         DAG.getConstant(0, HalfT));
19479     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19480                         DAG.getConstant(1, HalfT));
19481     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19482                              Regs64bit ? X86::RAX : X86::EAX,
19483                              cpInL, SDValue());
19484     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19485                              Regs64bit ? X86::RDX : X86::EDX,
19486                              cpInH, cpInL.getValue(1));
19487     SDValue swapInL, swapInH;
19488     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19489                           DAG.getConstant(0, HalfT));
19490     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19491                           DAG.getConstant(1, HalfT));
19492     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19493                                Regs64bit ? X86::RBX : X86::EBX,
19494                                swapInL, cpInH.getValue(1));
19495     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19496                                Regs64bit ? X86::RCX : X86::ECX,
19497                                swapInH, swapInL.getValue(1));
19498     SDValue Ops[] = { swapInH.getValue(0),
19499                       N->getOperand(1),
19500                       swapInH.getValue(1) };
19501     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19502     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19503     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19504                                   X86ISD::LCMPXCHG8_DAG;
19505     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19506     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19507                                         Regs64bit ? X86::RAX : X86::EAX,
19508                                         HalfT, Result.getValue(1));
19509     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19510                                         Regs64bit ? X86::RDX : X86::EDX,
19511                                         HalfT, cpOutL.getValue(2));
19512     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19513
19514     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19515                                         MVT::i32, cpOutH.getValue(2));
19516     SDValue Success =
19517         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19518                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19519     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19520
19521     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19522     Results.push_back(Success);
19523     Results.push_back(EFLAGS.getValue(1));
19524     return;
19525   }
19526   case ISD::ATOMIC_SWAP:
19527   case ISD::ATOMIC_LOAD_ADD:
19528   case ISD::ATOMIC_LOAD_SUB:
19529   case ISD::ATOMIC_LOAD_AND:
19530   case ISD::ATOMIC_LOAD_OR:
19531   case ISD::ATOMIC_LOAD_XOR:
19532   case ISD::ATOMIC_LOAD_NAND:
19533   case ISD::ATOMIC_LOAD_MIN:
19534   case ISD::ATOMIC_LOAD_MAX:
19535   case ISD::ATOMIC_LOAD_UMIN:
19536   case ISD::ATOMIC_LOAD_UMAX:
19537   case ISD::ATOMIC_LOAD: {
19538     // Delegate to generic TypeLegalization. Situations we can really handle
19539     // should have already been dealt with by AtomicExpandPass.cpp.
19540     break;
19541   }
19542   case ISD::BITCAST: {
19543     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19544     EVT DstVT = N->getValueType(0);
19545     EVT SrcVT = N->getOperand(0)->getValueType(0);
19546
19547     if (SrcVT != MVT::f64 ||
19548         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19549       return;
19550
19551     unsigned NumElts = DstVT.getVectorNumElements();
19552     EVT SVT = DstVT.getVectorElementType();
19553     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19554     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19555                                    MVT::v2f64, N->getOperand(0));
19556     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
19557
19558     if (ExperimentalVectorWideningLegalization) {
19559       // If we are legalizing vectors by widening, we already have the desired
19560       // legal vector type, just return it.
19561       Results.push_back(ToVecInt);
19562       return;
19563     }
19564
19565     SmallVector<SDValue, 8> Elts;
19566     for (unsigned i = 0, e = NumElts; i != e; ++i)
19567       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19568                                    ToVecInt, DAG.getIntPtrConstant(i)));
19569
19570     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19571   }
19572   }
19573 }
19574
19575 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19576   switch (Opcode) {
19577   default: return nullptr;
19578   case X86ISD::BSF:                return "X86ISD::BSF";
19579   case X86ISD::BSR:                return "X86ISD::BSR";
19580   case X86ISD::SHLD:               return "X86ISD::SHLD";
19581   case X86ISD::SHRD:               return "X86ISD::SHRD";
19582   case X86ISD::FAND:               return "X86ISD::FAND";
19583   case X86ISD::FANDN:              return "X86ISD::FANDN";
19584   case X86ISD::FOR:                return "X86ISD::FOR";
19585   case X86ISD::FXOR:               return "X86ISD::FXOR";
19586   case X86ISD::FSRL:               return "X86ISD::FSRL";
19587   case X86ISD::FILD:               return "X86ISD::FILD";
19588   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19589   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19590   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19591   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19592   case X86ISD::FLD:                return "X86ISD::FLD";
19593   case X86ISD::FST:                return "X86ISD::FST";
19594   case X86ISD::CALL:               return "X86ISD::CALL";
19595   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19596   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19597   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19598   case X86ISD::BT:                 return "X86ISD::BT";
19599   case X86ISD::CMP:                return "X86ISD::CMP";
19600   case X86ISD::COMI:               return "X86ISD::COMI";
19601   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19602   case X86ISD::CMPM:               return "X86ISD::CMPM";
19603   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19604   case X86ISD::SETCC:              return "X86ISD::SETCC";
19605   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19606   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19607   case X86ISD::CMOV:               return "X86ISD::CMOV";
19608   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19609   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19610   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19611   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19612   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19613   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19614   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19615   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19616   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19617   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19618   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19619   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19620   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19621   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19622   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19623   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19624   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19625   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19626   case X86ISD::HADD:               return "X86ISD::HADD";
19627   case X86ISD::HSUB:               return "X86ISD::HSUB";
19628   case X86ISD::FHADD:              return "X86ISD::FHADD";
19629   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19630   case X86ISD::UMAX:               return "X86ISD::UMAX";
19631   case X86ISD::UMIN:               return "X86ISD::UMIN";
19632   case X86ISD::SMAX:               return "X86ISD::SMAX";
19633   case X86ISD::SMIN:               return "X86ISD::SMIN";
19634   case X86ISD::FMAX:               return "X86ISD::FMAX";
19635   case X86ISD::FMIN:               return "X86ISD::FMIN";
19636   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19637   case X86ISD::FMINC:              return "X86ISD::FMINC";
19638   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19639   case X86ISD::FRCP:               return "X86ISD::FRCP";
19640   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19641   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19642   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19643   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19644   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19645   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19646   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19647   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19648   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19649   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19650   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19651   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19652   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19653   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19654   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19655   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19656   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19657   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
19658   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19659   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19660   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19661   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19662   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19663   case X86ISD::VSHL:               return "X86ISD::VSHL";
19664   case X86ISD::VSRL:               return "X86ISD::VSRL";
19665   case X86ISD::VSRA:               return "X86ISD::VSRA";
19666   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19667   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19668   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19669   case X86ISD::CMPP:               return "X86ISD::CMPP";
19670   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19671   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19672   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19673   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19674   case X86ISD::ADD:                return "X86ISD::ADD";
19675   case X86ISD::SUB:                return "X86ISD::SUB";
19676   case X86ISD::ADC:                return "X86ISD::ADC";
19677   case X86ISD::SBB:                return "X86ISD::SBB";
19678   case X86ISD::SMUL:               return "X86ISD::SMUL";
19679   case X86ISD::UMUL:               return "X86ISD::UMUL";
19680   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19681   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19682   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19683   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19684   case X86ISD::INC:                return "X86ISD::INC";
19685   case X86ISD::DEC:                return "X86ISD::DEC";
19686   case X86ISD::OR:                 return "X86ISD::OR";
19687   case X86ISD::XOR:                return "X86ISD::XOR";
19688   case X86ISD::AND:                return "X86ISD::AND";
19689   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19690   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19691   case X86ISD::PTEST:              return "X86ISD::PTEST";
19692   case X86ISD::TESTP:              return "X86ISD::TESTP";
19693   case X86ISD::TESTM:              return "X86ISD::TESTM";
19694   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19695   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19696   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19697   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19698   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19699   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19700   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19701   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19702   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19703   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19704   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19705   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19706   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19707   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19708   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19709   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19710   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19711   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19712   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19713   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19714   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19715   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19716   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19717   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
19718   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19719   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19720   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19721   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19722   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19723   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19724   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19725   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19726   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19727   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19728   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19729   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19730   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19731   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19732   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19733   case X86ISD::SAHF:               return "X86ISD::SAHF";
19734   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19735   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19736   case X86ISD::FMADD:              return "X86ISD::FMADD";
19737   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19738   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19739   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19740   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19741   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19742   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19743   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19744   case X86ISD::XTEST:              return "X86ISD::XTEST";
19745   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19746   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19747   }
19748 }
19749
19750 // isLegalAddressingMode - Return true if the addressing mode represented
19751 // by AM is legal for this target, for a load/store of the specified type.
19752 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
19753                                               Type *Ty) const {
19754   // X86 supports extremely general addressing modes.
19755   CodeModel::Model M = getTargetMachine().getCodeModel();
19756   Reloc::Model R = getTargetMachine().getRelocationModel();
19757
19758   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19759   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19760     return false;
19761
19762   if (AM.BaseGV) {
19763     unsigned GVFlags =
19764       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19765
19766     // If a reference to this global requires an extra load, we can't fold it.
19767     if (isGlobalStubReference(GVFlags))
19768       return false;
19769
19770     // If BaseGV requires a register for the PIC base, we cannot also have a
19771     // BaseReg specified.
19772     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19773       return false;
19774
19775     // If lower 4G is not available, then we must use rip-relative addressing.
19776     if ((M != CodeModel::Small || R != Reloc::Static) &&
19777         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19778       return false;
19779   }
19780
19781   switch (AM.Scale) {
19782   case 0:
19783   case 1:
19784   case 2:
19785   case 4:
19786   case 8:
19787     // These scales always work.
19788     break;
19789   case 3:
19790   case 5:
19791   case 9:
19792     // These scales are formed with basereg+scalereg.  Only accept if there is
19793     // no basereg yet.
19794     if (AM.HasBaseReg)
19795       return false;
19796     break;
19797   default:  // Other stuff never works.
19798     return false;
19799   }
19800
19801   return true;
19802 }
19803
19804 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19805   unsigned Bits = Ty->getScalarSizeInBits();
19806
19807   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19808   // particularly cheaper than those without.
19809   if (Bits == 8)
19810     return false;
19811
19812   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19813   // variable shifts just as cheap as scalar ones.
19814   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19815     return false;
19816
19817   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19818   // fully general vector.
19819   return true;
19820 }
19821
19822 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19823   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19824     return false;
19825   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19826   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19827   return NumBits1 > NumBits2;
19828 }
19829
19830 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19831   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19832     return false;
19833
19834   if (!isTypeLegal(EVT::getEVT(Ty1)))
19835     return false;
19836
19837   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19838
19839   // Assuming the caller doesn't have a zeroext or signext return parameter,
19840   // truncation all the way down to i1 is valid.
19841   return true;
19842 }
19843
19844 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19845   return isInt<32>(Imm);
19846 }
19847
19848 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19849   // Can also use sub to handle negated immediates.
19850   return isInt<32>(Imm);
19851 }
19852
19853 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19854   if (!VT1.isInteger() || !VT2.isInteger())
19855     return false;
19856   unsigned NumBits1 = VT1.getSizeInBits();
19857   unsigned NumBits2 = VT2.getSizeInBits();
19858   return NumBits1 > NumBits2;
19859 }
19860
19861 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19862   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19863   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19864 }
19865
19866 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19867   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19868   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19869 }
19870
19871 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19872   EVT VT1 = Val.getValueType();
19873   if (isZExtFree(VT1, VT2))
19874     return true;
19875
19876   if (Val.getOpcode() != ISD::LOAD)
19877     return false;
19878
19879   if (!VT1.isSimple() || !VT1.isInteger() ||
19880       !VT2.isSimple() || !VT2.isInteger())
19881     return false;
19882
19883   switch (VT1.getSimpleVT().SimpleTy) {
19884   default: break;
19885   case MVT::i8:
19886   case MVT::i16:
19887   case MVT::i32:
19888     // X86 has 8, 16, and 32-bit zero-extending loads.
19889     return true;
19890   }
19891
19892   return false;
19893 }
19894
19895 bool
19896 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19897   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
19898     return false;
19899
19900   VT = VT.getScalarType();
19901
19902   if (!VT.isSimple())
19903     return false;
19904
19905   switch (VT.getSimpleVT().SimpleTy) {
19906   case MVT::f32:
19907   case MVT::f64:
19908     return true;
19909   default:
19910     break;
19911   }
19912
19913   return false;
19914 }
19915
19916 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19917   // i16 instructions are longer (0x66 prefix) and potentially slower.
19918   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19919 }
19920
19921 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19922 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19923 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19924 /// are assumed to be legal.
19925 bool
19926 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19927                                       EVT VT) const {
19928   if (!VT.isSimple())
19929     return false;
19930
19931   MVT SVT = VT.getSimpleVT();
19932
19933   // Very little shuffling can be done for 64-bit vectors right now.
19934   if (VT.getSizeInBits() == 64)
19935     return false;
19936
19937   // If this is a single-input shuffle with no 128 bit lane crossings we can
19938   // lower it into pshufb.
19939   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
19940       (SVT.is256BitVector() && Subtarget->hasInt256())) {
19941     bool isLegal = true;
19942     for (unsigned I = 0, E = M.size(); I != E; ++I) {
19943       if (M[I] >= (int)SVT.getVectorNumElements() ||
19944           ShuffleCrosses128bitLane(SVT, I, M[I])) {
19945         isLegal = false;
19946         break;
19947       }
19948     }
19949     if (isLegal)
19950       return true;
19951   }
19952
19953   // FIXME: blends, shifts.
19954   return (SVT.getVectorNumElements() == 2 ||
19955           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
19956           isMOVLMask(M, SVT) ||
19957           isCommutedMOVLMask(M, SVT) ||
19958           isMOVHLPSMask(M, SVT) ||
19959           isSHUFPMask(M, SVT) ||
19960           isSHUFPMask(M, SVT, /* Commuted */ true) ||
19961           isPSHUFDMask(M, SVT) ||
19962           isPSHUFDMask(M, SVT, /* SecondOperand */ true) ||
19963           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
19964           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
19965           isPALIGNRMask(M, SVT, Subtarget) ||
19966           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
19967           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
19968           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
19969           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
19970           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()) ||
19971           (Subtarget->hasSSE41() && isINSERTPSMask(M, SVT)));
19972 }
19973
19974 bool
19975 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19976                                           EVT VT) const {
19977   if (!VT.isSimple())
19978     return false;
19979
19980   MVT SVT = VT.getSimpleVT();
19981   unsigned NumElts = SVT.getVectorNumElements();
19982   // FIXME: This collection of masks seems suspect.
19983   if (NumElts == 2)
19984     return true;
19985   if (NumElts == 4 && SVT.is128BitVector()) {
19986     return (isMOVLMask(Mask, SVT)  ||
19987             isCommutedMOVLMask(Mask, SVT, true) ||
19988             isSHUFPMask(Mask, SVT) ||
19989             isSHUFPMask(Mask, SVT, /* Commuted */ true) ||
19990             isBlendMask(Mask, SVT, Subtarget->hasSSE41(),
19991                         Subtarget->hasInt256()));
19992   }
19993   return false;
19994 }
19995
19996 //===----------------------------------------------------------------------===//
19997 //                           X86 Scheduler Hooks
19998 //===----------------------------------------------------------------------===//
19999
20000 /// Utility function to emit xbegin specifying the start of an RTM region.
20001 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20002                                      const TargetInstrInfo *TII) {
20003   DebugLoc DL = MI->getDebugLoc();
20004
20005   const BasicBlock *BB = MBB->getBasicBlock();
20006   MachineFunction::iterator I = MBB;
20007   ++I;
20008
20009   // For the v = xbegin(), we generate
20010   //
20011   // thisMBB:
20012   //  xbegin sinkMBB
20013   //
20014   // mainMBB:
20015   //  eax = -1
20016   //
20017   // sinkMBB:
20018   //  v = eax
20019
20020   MachineBasicBlock *thisMBB = MBB;
20021   MachineFunction *MF = MBB->getParent();
20022   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20023   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20024   MF->insert(I, mainMBB);
20025   MF->insert(I, sinkMBB);
20026
20027   // Transfer the remainder of BB and its successor edges to sinkMBB.
20028   sinkMBB->splice(sinkMBB->begin(), MBB,
20029                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20030   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20031
20032   // thisMBB:
20033   //  xbegin sinkMBB
20034   //  # fallthrough to mainMBB
20035   //  # abortion to sinkMBB
20036   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20037   thisMBB->addSuccessor(mainMBB);
20038   thisMBB->addSuccessor(sinkMBB);
20039
20040   // mainMBB:
20041   //  EAX = -1
20042   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20043   mainMBB->addSuccessor(sinkMBB);
20044
20045   // sinkMBB:
20046   // EAX is live into the sinkMBB
20047   sinkMBB->addLiveIn(X86::EAX);
20048   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20049           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20050     .addReg(X86::EAX);
20051
20052   MI->eraseFromParent();
20053   return sinkMBB;
20054 }
20055
20056 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20057 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20058 // in the .td file.
20059 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20060                                        const TargetInstrInfo *TII) {
20061   unsigned Opc;
20062   switch (MI->getOpcode()) {
20063   default: llvm_unreachable("illegal opcode!");
20064   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20065   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20066   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20067   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20068   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20069   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20070   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20071   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20072   }
20073
20074   DebugLoc dl = MI->getDebugLoc();
20075   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20076
20077   unsigned NumArgs = MI->getNumOperands();
20078   for (unsigned i = 1; i < NumArgs; ++i) {
20079     MachineOperand &Op = MI->getOperand(i);
20080     if (!(Op.isReg() && Op.isImplicit()))
20081       MIB.addOperand(Op);
20082   }
20083   if (MI->hasOneMemOperand())
20084     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20085
20086   BuildMI(*BB, MI, dl,
20087     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20088     .addReg(X86::XMM0);
20089
20090   MI->eraseFromParent();
20091   return BB;
20092 }
20093
20094 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20095 // defs in an instruction pattern
20096 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20097                                        const TargetInstrInfo *TII) {
20098   unsigned Opc;
20099   switch (MI->getOpcode()) {
20100   default: llvm_unreachable("illegal opcode!");
20101   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20102   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20103   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20104   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20105   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20106   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20107   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20108   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20109   }
20110
20111   DebugLoc dl = MI->getDebugLoc();
20112   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20113
20114   unsigned NumArgs = MI->getNumOperands(); // remove the results
20115   for (unsigned i = 1; i < NumArgs; ++i) {
20116     MachineOperand &Op = MI->getOperand(i);
20117     if (!(Op.isReg() && Op.isImplicit()))
20118       MIB.addOperand(Op);
20119   }
20120   if (MI->hasOneMemOperand())
20121     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20122
20123   BuildMI(*BB, MI, dl,
20124     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20125     .addReg(X86::ECX);
20126
20127   MI->eraseFromParent();
20128   return BB;
20129 }
20130
20131 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20132                                        const TargetInstrInfo *TII,
20133                                        const X86Subtarget* Subtarget) {
20134   DebugLoc dl = MI->getDebugLoc();
20135
20136   // Address into RAX/EAX, other two args into ECX, EDX.
20137   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20138   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20139   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20140   for (int i = 0; i < X86::AddrNumOperands; ++i)
20141     MIB.addOperand(MI->getOperand(i));
20142
20143   unsigned ValOps = X86::AddrNumOperands;
20144   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20145     .addReg(MI->getOperand(ValOps).getReg());
20146   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20147     .addReg(MI->getOperand(ValOps+1).getReg());
20148
20149   // The instruction doesn't actually take any operands though.
20150   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20151
20152   MI->eraseFromParent(); // The pseudo is gone now.
20153   return BB;
20154 }
20155
20156 MachineBasicBlock *
20157 X86TargetLowering::EmitVAARG64WithCustomInserter(
20158                    MachineInstr *MI,
20159                    MachineBasicBlock *MBB) const {
20160   // Emit va_arg instruction on X86-64.
20161
20162   // Operands to this pseudo-instruction:
20163   // 0  ) Output        : destination address (reg)
20164   // 1-5) Input         : va_list address (addr, i64mem)
20165   // 6  ) ArgSize       : Size (in bytes) of vararg type
20166   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20167   // 8  ) Align         : Alignment of type
20168   // 9  ) EFLAGS (implicit-def)
20169
20170   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20171   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
20172
20173   unsigned DestReg = MI->getOperand(0).getReg();
20174   MachineOperand &Base = MI->getOperand(1);
20175   MachineOperand &Scale = MI->getOperand(2);
20176   MachineOperand &Index = MI->getOperand(3);
20177   MachineOperand &Disp = MI->getOperand(4);
20178   MachineOperand &Segment = MI->getOperand(5);
20179   unsigned ArgSize = MI->getOperand(6).getImm();
20180   unsigned ArgMode = MI->getOperand(7).getImm();
20181   unsigned Align = MI->getOperand(8).getImm();
20182
20183   // Memory Reference
20184   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20185   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20186   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20187
20188   // Machine Information
20189   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20190   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20191   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20192   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20193   DebugLoc DL = MI->getDebugLoc();
20194
20195   // struct va_list {
20196   //   i32   gp_offset
20197   //   i32   fp_offset
20198   //   i64   overflow_area (address)
20199   //   i64   reg_save_area (address)
20200   // }
20201   // sizeof(va_list) = 24
20202   // alignment(va_list) = 8
20203
20204   unsigned TotalNumIntRegs = 6;
20205   unsigned TotalNumXMMRegs = 8;
20206   bool UseGPOffset = (ArgMode == 1);
20207   bool UseFPOffset = (ArgMode == 2);
20208   unsigned MaxOffset = TotalNumIntRegs * 8 +
20209                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20210
20211   /* Align ArgSize to a multiple of 8 */
20212   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20213   bool NeedsAlign = (Align > 8);
20214
20215   MachineBasicBlock *thisMBB = MBB;
20216   MachineBasicBlock *overflowMBB;
20217   MachineBasicBlock *offsetMBB;
20218   MachineBasicBlock *endMBB;
20219
20220   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20221   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20222   unsigned OffsetReg = 0;
20223
20224   if (!UseGPOffset && !UseFPOffset) {
20225     // If we only pull from the overflow region, we don't create a branch.
20226     // We don't need to alter control flow.
20227     OffsetDestReg = 0; // unused
20228     OverflowDestReg = DestReg;
20229
20230     offsetMBB = nullptr;
20231     overflowMBB = thisMBB;
20232     endMBB = thisMBB;
20233   } else {
20234     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20235     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20236     // If not, pull from overflow_area. (branch to overflowMBB)
20237     //
20238     //       thisMBB
20239     //         |     .
20240     //         |        .
20241     //     offsetMBB   overflowMBB
20242     //         |        .
20243     //         |     .
20244     //        endMBB
20245
20246     // Registers for the PHI in endMBB
20247     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20248     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20249
20250     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20251     MachineFunction *MF = MBB->getParent();
20252     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20253     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20254     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20255
20256     MachineFunction::iterator MBBIter = MBB;
20257     ++MBBIter;
20258
20259     // Insert the new basic blocks
20260     MF->insert(MBBIter, offsetMBB);
20261     MF->insert(MBBIter, overflowMBB);
20262     MF->insert(MBBIter, endMBB);
20263
20264     // Transfer the remainder of MBB and its successor edges to endMBB.
20265     endMBB->splice(endMBB->begin(), thisMBB,
20266                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20267     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20268
20269     // Make offsetMBB and overflowMBB successors of thisMBB
20270     thisMBB->addSuccessor(offsetMBB);
20271     thisMBB->addSuccessor(overflowMBB);
20272
20273     // endMBB is a successor of both offsetMBB and overflowMBB
20274     offsetMBB->addSuccessor(endMBB);
20275     overflowMBB->addSuccessor(endMBB);
20276
20277     // Load the offset value into a register
20278     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20279     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20280       .addOperand(Base)
20281       .addOperand(Scale)
20282       .addOperand(Index)
20283       .addDisp(Disp, UseFPOffset ? 4 : 0)
20284       .addOperand(Segment)
20285       .setMemRefs(MMOBegin, MMOEnd);
20286
20287     // Check if there is enough room left to pull this argument.
20288     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20289       .addReg(OffsetReg)
20290       .addImm(MaxOffset + 8 - ArgSizeA8);
20291
20292     // Branch to "overflowMBB" if offset >= max
20293     // Fall through to "offsetMBB" otherwise
20294     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20295       .addMBB(overflowMBB);
20296   }
20297
20298   // In offsetMBB, emit code to use the reg_save_area.
20299   if (offsetMBB) {
20300     assert(OffsetReg != 0);
20301
20302     // Read the reg_save_area address.
20303     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20304     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20305       .addOperand(Base)
20306       .addOperand(Scale)
20307       .addOperand(Index)
20308       .addDisp(Disp, 16)
20309       .addOperand(Segment)
20310       .setMemRefs(MMOBegin, MMOEnd);
20311
20312     // Zero-extend the offset
20313     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20314       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20315         .addImm(0)
20316         .addReg(OffsetReg)
20317         .addImm(X86::sub_32bit);
20318
20319     // Add the offset to the reg_save_area to get the final address.
20320     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20321       .addReg(OffsetReg64)
20322       .addReg(RegSaveReg);
20323
20324     // Compute the offset for the next argument
20325     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20326     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20327       .addReg(OffsetReg)
20328       .addImm(UseFPOffset ? 16 : 8);
20329
20330     // Store it back into the va_list.
20331     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20332       .addOperand(Base)
20333       .addOperand(Scale)
20334       .addOperand(Index)
20335       .addDisp(Disp, UseFPOffset ? 4 : 0)
20336       .addOperand(Segment)
20337       .addReg(NextOffsetReg)
20338       .setMemRefs(MMOBegin, MMOEnd);
20339
20340     // Jump to endMBB
20341     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
20342       .addMBB(endMBB);
20343   }
20344
20345   //
20346   // Emit code to use overflow area
20347   //
20348
20349   // Load the overflow_area address into a register.
20350   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20351   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20352     .addOperand(Base)
20353     .addOperand(Scale)
20354     .addOperand(Index)
20355     .addDisp(Disp, 8)
20356     .addOperand(Segment)
20357     .setMemRefs(MMOBegin, MMOEnd);
20358
20359   // If we need to align it, do so. Otherwise, just copy the address
20360   // to OverflowDestReg.
20361   if (NeedsAlign) {
20362     // Align the overflow address
20363     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20364     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20365
20366     // aligned_addr = (addr + (align-1)) & ~(align-1)
20367     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20368       .addReg(OverflowAddrReg)
20369       .addImm(Align-1);
20370
20371     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20372       .addReg(TmpReg)
20373       .addImm(~(uint64_t)(Align-1));
20374   } else {
20375     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20376       .addReg(OverflowAddrReg);
20377   }
20378
20379   // Compute the next overflow address after this argument.
20380   // (the overflow address should be kept 8-byte aligned)
20381   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20382   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20383     .addReg(OverflowDestReg)
20384     .addImm(ArgSizeA8);
20385
20386   // Store the new overflow address.
20387   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20388     .addOperand(Base)
20389     .addOperand(Scale)
20390     .addOperand(Index)
20391     .addDisp(Disp, 8)
20392     .addOperand(Segment)
20393     .addReg(NextAddrReg)
20394     .setMemRefs(MMOBegin, MMOEnd);
20395
20396   // If we branched, emit the PHI to the front of endMBB.
20397   if (offsetMBB) {
20398     BuildMI(*endMBB, endMBB->begin(), DL,
20399             TII->get(X86::PHI), DestReg)
20400       .addReg(OffsetDestReg).addMBB(offsetMBB)
20401       .addReg(OverflowDestReg).addMBB(overflowMBB);
20402   }
20403
20404   // Erase the pseudo instruction
20405   MI->eraseFromParent();
20406
20407   return endMBB;
20408 }
20409
20410 MachineBasicBlock *
20411 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20412                                                  MachineInstr *MI,
20413                                                  MachineBasicBlock *MBB) const {
20414   // Emit code to save XMM registers to the stack. The ABI says that the
20415   // number of registers to save is given in %al, so it's theoretically
20416   // possible to do an indirect jump trick to avoid saving all of them,
20417   // however this code takes a simpler approach and just executes all
20418   // of the stores if %al is non-zero. It's less code, and it's probably
20419   // easier on the hardware branch predictor, and stores aren't all that
20420   // expensive anyway.
20421
20422   // Create the new basic blocks. One block contains all the XMM stores,
20423   // and one block is the final destination regardless of whether any
20424   // stores were performed.
20425   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20426   MachineFunction *F = MBB->getParent();
20427   MachineFunction::iterator MBBIter = MBB;
20428   ++MBBIter;
20429   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20430   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20431   F->insert(MBBIter, XMMSaveMBB);
20432   F->insert(MBBIter, EndMBB);
20433
20434   // Transfer the remainder of MBB and its successor edges to EndMBB.
20435   EndMBB->splice(EndMBB->begin(), MBB,
20436                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20437   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20438
20439   // The original block will now fall through to the XMM save block.
20440   MBB->addSuccessor(XMMSaveMBB);
20441   // The XMMSaveMBB will fall through to the end block.
20442   XMMSaveMBB->addSuccessor(EndMBB);
20443
20444   // Now add the instructions.
20445   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20446   DebugLoc DL = MI->getDebugLoc();
20447
20448   unsigned CountReg = MI->getOperand(0).getReg();
20449   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20450   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20451
20452   if (!Subtarget->isTargetWin64()) {
20453     // If %al is 0, branch around the XMM save block.
20454     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20455     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
20456     MBB->addSuccessor(EndMBB);
20457   }
20458
20459   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20460   // that was just emitted, but clearly shouldn't be "saved".
20461   assert((MI->getNumOperands() <= 3 ||
20462           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20463           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20464          && "Expected last argument to be EFLAGS");
20465   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20466   // In the XMM save block, save all the XMM argument registers.
20467   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20468     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20469     MachineMemOperand *MMO =
20470       F->getMachineMemOperand(
20471           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
20472         MachineMemOperand::MOStore,
20473         /*Size=*/16, /*Align=*/16);
20474     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20475       .addFrameIndex(RegSaveFrameIndex)
20476       .addImm(/*Scale=*/1)
20477       .addReg(/*IndexReg=*/0)
20478       .addImm(/*Disp=*/Offset)
20479       .addReg(/*Segment=*/0)
20480       .addReg(MI->getOperand(i).getReg())
20481       .addMemOperand(MMO);
20482   }
20483
20484   MI->eraseFromParent();   // The pseudo instruction is gone now.
20485
20486   return EndMBB;
20487 }
20488
20489 // The EFLAGS operand of SelectItr might be missing a kill marker
20490 // because there were multiple uses of EFLAGS, and ISel didn't know
20491 // which to mark. Figure out whether SelectItr should have had a
20492 // kill marker, and set it if it should. Returns the correct kill
20493 // marker value.
20494 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20495                                      MachineBasicBlock* BB,
20496                                      const TargetRegisterInfo* TRI) {
20497   // Scan forward through BB for a use/def of EFLAGS.
20498   MachineBasicBlock::iterator miI(std::next(SelectItr));
20499   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20500     const MachineInstr& mi = *miI;
20501     if (mi.readsRegister(X86::EFLAGS))
20502       return false;
20503     if (mi.definesRegister(X86::EFLAGS))
20504       break; // Should have kill-flag - update below.
20505   }
20506
20507   // If we hit the end of the block, check whether EFLAGS is live into a
20508   // successor.
20509   if (miI == BB->end()) {
20510     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20511                                           sEnd = BB->succ_end();
20512          sItr != sEnd; ++sItr) {
20513       MachineBasicBlock* succ = *sItr;
20514       if (succ->isLiveIn(X86::EFLAGS))
20515         return false;
20516     }
20517   }
20518
20519   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20520   // out. SelectMI should have a kill flag on EFLAGS.
20521   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20522   return true;
20523 }
20524
20525 MachineBasicBlock *
20526 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20527                                      MachineBasicBlock *BB) const {
20528   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20529   DebugLoc DL = MI->getDebugLoc();
20530
20531   // To "insert" a SELECT_CC instruction, we actually have to insert the
20532   // diamond control-flow pattern.  The incoming instruction knows the
20533   // destination vreg to set, the condition code register to branch on, the
20534   // true/false values to select between, and a branch opcode to use.
20535   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20536   MachineFunction::iterator It = BB;
20537   ++It;
20538
20539   //  thisMBB:
20540   //  ...
20541   //   TrueVal = ...
20542   //   cmpTY ccX, r1, r2
20543   //   bCC copy1MBB
20544   //   fallthrough --> copy0MBB
20545   MachineBasicBlock *thisMBB = BB;
20546   MachineFunction *F = BB->getParent();
20547   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20548   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20549   F->insert(It, copy0MBB);
20550   F->insert(It, sinkMBB);
20551
20552   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20553   // live into the sink and copy blocks.
20554   const TargetRegisterInfo *TRI =
20555       BB->getParent()->getSubtarget().getRegisterInfo();
20556   if (!MI->killsRegister(X86::EFLAGS) &&
20557       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
20558     copy0MBB->addLiveIn(X86::EFLAGS);
20559     sinkMBB->addLiveIn(X86::EFLAGS);
20560   }
20561
20562   // Transfer the remainder of BB and its successor edges to sinkMBB.
20563   sinkMBB->splice(sinkMBB->begin(), BB,
20564                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
20565   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20566
20567   // Add the true and fallthrough blocks as its successors.
20568   BB->addSuccessor(copy0MBB);
20569   BB->addSuccessor(sinkMBB);
20570
20571   // Create the conditional branch instruction.
20572   unsigned Opc =
20573     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20574   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20575
20576   //  copy0MBB:
20577   //   %FalseValue = ...
20578   //   # fallthrough to sinkMBB
20579   copy0MBB->addSuccessor(sinkMBB);
20580
20581   //  sinkMBB:
20582   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20583   //  ...
20584   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20585           TII->get(X86::PHI), MI->getOperand(0).getReg())
20586     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20587     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20588
20589   MI->eraseFromParent();   // The pseudo instruction is gone now.
20590   return sinkMBB;
20591 }
20592
20593 MachineBasicBlock *
20594 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20595                                         MachineBasicBlock *BB) const {
20596   MachineFunction *MF = BB->getParent();
20597   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20598   DebugLoc DL = MI->getDebugLoc();
20599   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20600
20601   assert(MF->shouldSplitStack());
20602
20603   const bool Is64Bit = Subtarget->is64Bit();
20604   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20605
20606   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20607   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20608
20609   // BB:
20610   //  ... [Till the alloca]
20611   // If stacklet is not large enough, jump to mallocMBB
20612   //
20613   // bumpMBB:
20614   //  Allocate by subtracting from RSP
20615   //  Jump to continueMBB
20616   //
20617   // mallocMBB:
20618   //  Allocate by call to runtime
20619   //
20620   // continueMBB:
20621   //  ...
20622   //  [rest of original BB]
20623   //
20624
20625   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20626   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20627   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20628
20629   MachineRegisterInfo &MRI = MF->getRegInfo();
20630   const TargetRegisterClass *AddrRegClass =
20631     getRegClassFor(getPointerTy());
20632
20633   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20634     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20635     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20636     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20637     sizeVReg = MI->getOperand(1).getReg(),
20638     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20639
20640   MachineFunction::iterator MBBIter = BB;
20641   ++MBBIter;
20642
20643   MF->insert(MBBIter, bumpMBB);
20644   MF->insert(MBBIter, mallocMBB);
20645   MF->insert(MBBIter, continueMBB);
20646
20647   continueMBB->splice(continueMBB->begin(), BB,
20648                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20649   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20650
20651   // Add code to the main basic block to check if the stack limit has been hit,
20652   // and if so, jump to mallocMBB otherwise to bumpMBB.
20653   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20654   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20655     .addReg(tmpSPVReg).addReg(sizeVReg);
20656   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20657     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20658     .addReg(SPLimitVReg);
20659   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
20660
20661   // bumpMBB simply decreases the stack pointer, since we know the current
20662   // stacklet has enough space.
20663   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20664     .addReg(SPLimitVReg);
20665   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20666     .addReg(SPLimitVReg);
20667   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20668
20669   // Calls into a routine in libgcc to allocate more space from the heap.
20670   const uint32_t *RegMask = MF->getTarget()
20671                                 .getSubtargetImpl()
20672                                 ->getRegisterInfo()
20673                                 ->getCallPreservedMask(CallingConv::C);
20674   if (IsLP64) {
20675     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20676       .addReg(sizeVReg);
20677     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20678       .addExternalSymbol("__morestack_allocate_stack_space")
20679       .addRegMask(RegMask)
20680       .addReg(X86::RDI, RegState::Implicit)
20681       .addReg(X86::RAX, RegState::ImplicitDefine);
20682   } else if (Is64Bit) {
20683     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20684       .addReg(sizeVReg);
20685     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20686       .addExternalSymbol("__morestack_allocate_stack_space")
20687       .addRegMask(RegMask)
20688       .addReg(X86::EDI, RegState::Implicit)
20689       .addReg(X86::EAX, RegState::ImplicitDefine);
20690   } else {
20691     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20692       .addImm(12);
20693     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20694     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20695       .addExternalSymbol("__morestack_allocate_stack_space")
20696       .addRegMask(RegMask)
20697       .addReg(X86::EAX, RegState::ImplicitDefine);
20698   }
20699
20700   if (!Is64Bit)
20701     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20702       .addImm(16);
20703
20704   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20705     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20706   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20707
20708   // Set up the CFG correctly.
20709   BB->addSuccessor(bumpMBB);
20710   BB->addSuccessor(mallocMBB);
20711   mallocMBB->addSuccessor(continueMBB);
20712   bumpMBB->addSuccessor(continueMBB);
20713
20714   // Take care of the PHI nodes.
20715   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20716           MI->getOperand(0).getReg())
20717     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20718     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20719
20720   // Delete the original pseudo instruction.
20721   MI->eraseFromParent();
20722
20723   // And we're done.
20724   return continueMBB;
20725 }
20726
20727 MachineBasicBlock *
20728 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20729                                         MachineBasicBlock *BB) const {
20730   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20731   DebugLoc DL = MI->getDebugLoc();
20732
20733   assert(!Subtarget->isTargetMachO());
20734
20735   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
20736   // non-trivial part is impdef of ESP.
20737
20738   if (Subtarget->isTargetWin64()) {
20739     if (Subtarget->isTargetCygMing()) {
20740       // ___chkstk(Mingw64):
20741       // Clobbers R10, R11, RAX and EFLAGS.
20742       // Updates RSP.
20743       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20744         .addExternalSymbol("___chkstk")
20745         .addReg(X86::RAX, RegState::Implicit)
20746         .addReg(X86::RSP, RegState::Implicit)
20747         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
20748         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
20749         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20750     } else {
20751       // __chkstk(MSVCRT): does not update stack pointer.
20752       // Clobbers R10, R11 and EFLAGS.
20753       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20754         .addExternalSymbol("__chkstk")
20755         .addReg(X86::RAX, RegState::Implicit)
20756         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20757       // RAX has the offset to be subtracted from RSP.
20758       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
20759         .addReg(X86::RSP)
20760         .addReg(X86::RAX);
20761     }
20762   } else {
20763     const char *StackProbeSymbol = (Subtarget->isTargetKnownWindowsMSVC() ||
20764                                     Subtarget->isTargetWindowsItanium())
20765                                        ? "_chkstk"
20766                                        : "_alloca";
20767
20768     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
20769       .addExternalSymbol(StackProbeSymbol)
20770       .addReg(X86::EAX, RegState::Implicit)
20771       .addReg(X86::ESP, RegState::Implicit)
20772       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
20773       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
20774       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20775   }
20776
20777   MI->eraseFromParent();   // The pseudo instruction is gone now.
20778   return BB;
20779 }
20780
20781 MachineBasicBlock *
20782 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20783                                       MachineBasicBlock *BB) const {
20784   // This is pretty easy.  We're taking the value that we received from
20785   // our load from the relocation, sticking it in either RDI (x86-64)
20786   // or EAX and doing an indirect call.  The return value will then
20787   // be in the normal return register.
20788   MachineFunction *F = BB->getParent();
20789   const X86InstrInfo *TII =
20790       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
20791   DebugLoc DL = MI->getDebugLoc();
20792
20793   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20794   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20795
20796   // Get a register mask for the lowered call.
20797   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20798   // proper register mask.
20799   const uint32_t *RegMask = F->getTarget()
20800                                 .getSubtargetImpl()
20801                                 ->getRegisterInfo()
20802                                 ->getCallPreservedMask(CallingConv::C);
20803   if (Subtarget->is64Bit()) {
20804     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20805                                       TII->get(X86::MOV64rm), X86::RDI)
20806     .addReg(X86::RIP)
20807     .addImm(0).addReg(0)
20808     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20809                       MI->getOperand(3).getTargetFlags())
20810     .addReg(0);
20811     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20812     addDirectMem(MIB, X86::RDI);
20813     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20814   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20815     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20816                                       TII->get(X86::MOV32rm), X86::EAX)
20817     .addReg(0)
20818     .addImm(0).addReg(0)
20819     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20820                       MI->getOperand(3).getTargetFlags())
20821     .addReg(0);
20822     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20823     addDirectMem(MIB, X86::EAX);
20824     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20825   } else {
20826     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20827                                       TII->get(X86::MOV32rm), X86::EAX)
20828     .addReg(TII->getGlobalBaseReg(F))
20829     .addImm(0).addReg(0)
20830     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20831                       MI->getOperand(3).getTargetFlags())
20832     .addReg(0);
20833     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20834     addDirectMem(MIB, X86::EAX);
20835     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20836   }
20837
20838   MI->eraseFromParent(); // The pseudo instruction is gone now.
20839   return BB;
20840 }
20841
20842 MachineBasicBlock *
20843 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20844                                     MachineBasicBlock *MBB) const {
20845   DebugLoc DL = MI->getDebugLoc();
20846   MachineFunction *MF = MBB->getParent();
20847   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20848   MachineRegisterInfo &MRI = MF->getRegInfo();
20849
20850   const BasicBlock *BB = MBB->getBasicBlock();
20851   MachineFunction::iterator I = MBB;
20852   ++I;
20853
20854   // Memory Reference
20855   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20856   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20857
20858   unsigned DstReg;
20859   unsigned MemOpndSlot = 0;
20860
20861   unsigned CurOp = 0;
20862
20863   DstReg = MI->getOperand(CurOp++).getReg();
20864   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20865   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20866   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20867   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20868
20869   MemOpndSlot = CurOp;
20870
20871   MVT PVT = getPointerTy();
20872   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20873          "Invalid Pointer Size!");
20874
20875   // For v = setjmp(buf), we generate
20876   //
20877   // thisMBB:
20878   //  buf[LabelOffset] = restoreMBB
20879   //  SjLjSetup restoreMBB
20880   //
20881   // mainMBB:
20882   //  v_main = 0
20883   //
20884   // sinkMBB:
20885   //  v = phi(main, restore)
20886   //
20887   // restoreMBB:
20888   //  if base pointer being used, load it from frame
20889   //  v_restore = 1
20890
20891   MachineBasicBlock *thisMBB = MBB;
20892   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20893   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20894   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20895   MF->insert(I, mainMBB);
20896   MF->insert(I, sinkMBB);
20897   MF->push_back(restoreMBB);
20898
20899   MachineInstrBuilder MIB;
20900
20901   // Transfer the remainder of BB and its successor edges to sinkMBB.
20902   sinkMBB->splice(sinkMBB->begin(), MBB,
20903                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20904   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20905
20906   // thisMBB:
20907   unsigned PtrStoreOpc = 0;
20908   unsigned LabelReg = 0;
20909   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20910   Reloc::Model RM = MF->getTarget().getRelocationModel();
20911   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20912                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20913
20914   // Prepare IP either in reg or imm.
20915   if (!UseImmLabel) {
20916     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20917     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20918     LabelReg = MRI.createVirtualRegister(PtrRC);
20919     if (Subtarget->is64Bit()) {
20920       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20921               .addReg(X86::RIP)
20922               .addImm(0)
20923               .addReg(0)
20924               .addMBB(restoreMBB)
20925               .addReg(0);
20926     } else {
20927       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20928       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20929               .addReg(XII->getGlobalBaseReg(MF))
20930               .addImm(0)
20931               .addReg(0)
20932               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20933               .addReg(0);
20934     }
20935   } else
20936     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20937   // Store IP
20938   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20939   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20940     if (i == X86::AddrDisp)
20941       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20942     else
20943       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20944   }
20945   if (!UseImmLabel)
20946     MIB.addReg(LabelReg);
20947   else
20948     MIB.addMBB(restoreMBB);
20949   MIB.setMemRefs(MMOBegin, MMOEnd);
20950   // Setup
20951   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20952           .addMBB(restoreMBB);
20953
20954   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
20955       MF->getSubtarget().getRegisterInfo());
20956   MIB.addRegMask(RegInfo->getNoPreservedMask());
20957   thisMBB->addSuccessor(mainMBB);
20958   thisMBB->addSuccessor(restoreMBB);
20959
20960   // mainMBB:
20961   //  EAX = 0
20962   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20963   mainMBB->addSuccessor(sinkMBB);
20964
20965   // sinkMBB:
20966   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20967           TII->get(X86::PHI), DstReg)
20968     .addReg(mainDstReg).addMBB(mainMBB)
20969     .addReg(restoreDstReg).addMBB(restoreMBB);
20970
20971   // restoreMBB:
20972   if (RegInfo->hasBasePointer(*MF)) {
20973     const X86Subtarget &STI = MF->getTarget().getSubtarget<X86Subtarget>();
20974     const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
20975     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20976     X86FI->setRestoreBasePointer(MF);
20977     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20978     unsigned BasePtr = RegInfo->getBaseRegister();
20979     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20980     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20981                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20982       .setMIFlag(MachineInstr::FrameSetup);
20983   }
20984   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20985   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
20986   restoreMBB->addSuccessor(sinkMBB);
20987
20988   MI->eraseFromParent();
20989   return sinkMBB;
20990 }
20991
20992 MachineBasicBlock *
20993 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20994                                      MachineBasicBlock *MBB) const {
20995   DebugLoc DL = MI->getDebugLoc();
20996   MachineFunction *MF = MBB->getParent();
20997   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20998   MachineRegisterInfo &MRI = MF->getRegInfo();
20999
21000   // Memory Reference
21001   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21002   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21003
21004   MVT PVT = getPointerTy();
21005   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21006          "Invalid Pointer Size!");
21007
21008   const TargetRegisterClass *RC =
21009     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21010   unsigned Tmp = MRI.createVirtualRegister(RC);
21011   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21012   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
21013       MF->getSubtarget().getRegisterInfo());
21014   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21015   unsigned SP = RegInfo->getStackRegister();
21016
21017   MachineInstrBuilder MIB;
21018
21019   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21020   const int64_t SPOffset = 2 * PVT.getStoreSize();
21021
21022   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21023   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21024
21025   // Reload FP
21026   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21027   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21028     MIB.addOperand(MI->getOperand(i));
21029   MIB.setMemRefs(MMOBegin, MMOEnd);
21030   // Reload IP
21031   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21032   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21033     if (i == X86::AddrDisp)
21034       MIB.addDisp(MI->getOperand(i), LabelOffset);
21035     else
21036       MIB.addOperand(MI->getOperand(i));
21037   }
21038   MIB.setMemRefs(MMOBegin, MMOEnd);
21039   // Reload SP
21040   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21041   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21042     if (i == X86::AddrDisp)
21043       MIB.addDisp(MI->getOperand(i), SPOffset);
21044     else
21045       MIB.addOperand(MI->getOperand(i));
21046   }
21047   MIB.setMemRefs(MMOBegin, MMOEnd);
21048   // Jump
21049   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21050
21051   MI->eraseFromParent();
21052   return MBB;
21053 }
21054
21055 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21056 // accumulator loops. Writing back to the accumulator allows the coalescer
21057 // to remove extra copies in the loop.
21058 MachineBasicBlock *
21059 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21060                                  MachineBasicBlock *MBB) const {
21061   MachineOperand &AddendOp = MI->getOperand(3);
21062
21063   // Bail out early if the addend isn't a register - we can't switch these.
21064   if (!AddendOp.isReg())
21065     return MBB;
21066
21067   MachineFunction &MF = *MBB->getParent();
21068   MachineRegisterInfo &MRI = MF.getRegInfo();
21069
21070   // Check whether the addend is defined by a PHI:
21071   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21072   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21073   if (!AddendDef.isPHI())
21074     return MBB;
21075
21076   // Look for the following pattern:
21077   // loop:
21078   //   %addend = phi [%entry, 0], [%loop, %result]
21079   //   ...
21080   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21081
21082   // Replace with:
21083   //   loop:
21084   //   %addend = phi [%entry, 0], [%loop, %result]
21085   //   ...
21086   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21087
21088   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21089     assert(AddendDef.getOperand(i).isReg());
21090     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21091     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21092     if (&PHISrcInst == MI) {
21093       // Found a matching instruction.
21094       unsigned NewFMAOpc = 0;
21095       switch (MI->getOpcode()) {
21096         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21097         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21098         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21099         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21100         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21101         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21102         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21103         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21104         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21105         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21106         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21107         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21108         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21109         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21110         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21111         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21112         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21113         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21114         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21115         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21116
21117         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21118         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21119         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21120         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21121         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21122         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21123         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21124         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21125         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21126         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21127         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21128         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21129         default: llvm_unreachable("Unrecognized FMA variant.");
21130       }
21131
21132       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
21133       MachineInstrBuilder MIB =
21134         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21135         .addOperand(MI->getOperand(0))
21136         .addOperand(MI->getOperand(3))
21137         .addOperand(MI->getOperand(2))
21138         .addOperand(MI->getOperand(1));
21139       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21140       MI->eraseFromParent();
21141     }
21142   }
21143
21144   return MBB;
21145 }
21146
21147 MachineBasicBlock *
21148 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21149                                                MachineBasicBlock *BB) const {
21150   switch (MI->getOpcode()) {
21151   default: llvm_unreachable("Unexpected instr type to insert");
21152   case X86::TAILJMPd64:
21153   case X86::TAILJMPr64:
21154   case X86::TAILJMPm64:
21155     llvm_unreachable("TAILJMP64 would not be touched here.");
21156   case X86::TCRETURNdi64:
21157   case X86::TCRETURNri64:
21158   case X86::TCRETURNmi64:
21159     return BB;
21160   case X86::WIN_ALLOCA:
21161     return EmitLoweredWinAlloca(MI, BB);
21162   case X86::SEG_ALLOCA_32:
21163   case X86::SEG_ALLOCA_64:
21164     return EmitLoweredSegAlloca(MI, BB);
21165   case X86::TLSCall_32:
21166   case X86::TLSCall_64:
21167     return EmitLoweredTLSCall(MI, BB);
21168   case X86::CMOV_GR8:
21169   case X86::CMOV_FR32:
21170   case X86::CMOV_FR64:
21171   case X86::CMOV_V4F32:
21172   case X86::CMOV_V2F64:
21173   case X86::CMOV_V2I64:
21174   case X86::CMOV_V8F32:
21175   case X86::CMOV_V4F64:
21176   case X86::CMOV_V4I64:
21177   case X86::CMOV_V16F32:
21178   case X86::CMOV_V8F64:
21179   case X86::CMOV_V8I64:
21180   case X86::CMOV_GR16:
21181   case X86::CMOV_GR32:
21182   case X86::CMOV_RFP32:
21183   case X86::CMOV_RFP64:
21184   case X86::CMOV_RFP80:
21185     return EmitLoweredSelect(MI, BB);
21186
21187   case X86::FP32_TO_INT16_IN_MEM:
21188   case X86::FP32_TO_INT32_IN_MEM:
21189   case X86::FP32_TO_INT64_IN_MEM:
21190   case X86::FP64_TO_INT16_IN_MEM:
21191   case X86::FP64_TO_INT32_IN_MEM:
21192   case X86::FP64_TO_INT64_IN_MEM:
21193   case X86::FP80_TO_INT16_IN_MEM:
21194   case X86::FP80_TO_INT32_IN_MEM:
21195   case X86::FP80_TO_INT64_IN_MEM: {
21196     MachineFunction *F = BB->getParent();
21197     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
21198     DebugLoc DL = MI->getDebugLoc();
21199
21200     // Change the floating point control register to use "round towards zero"
21201     // mode when truncating to an integer value.
21202     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21203     addFrameReference(BuildMI(*BB, MI, DL,
21204                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21205
21206     // Load the old value of the high byte of the control word...
21207     unsigned OldCW =
21208       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21209     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21210                       CWFrameIdx);
21211
21212     // Set the high part to be round to zero...
21213     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21214       .addImm(0xC7F);
21215
21216     // Reload the modified control word now...
21217     addFrameReference(BuildMI(*BB, MI, DL,
21218                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21219
21220     // Restore the memory image of control word to original value
21221     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21222       .addReg(OldCW);
21223
21224     // Get the X86 opcode to use.
21225     unsigned Opc;
21226     switch (MI->getOpcode()) {
21227     default: llvm_unreachable("illegal opcode!");
21228     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21229     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21230     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21231     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21232     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21233     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21234     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21235     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21236     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21237     }
21238
21239     X86AddressMode AM;
21240     MachineOperand &Op = MI->getOperand(0);
21241     if (Op.isReg()) {
21242       AM.BaseType = X86AddressMode::RegBase;
21243       AM.Base.Reg = Op.getReg();
21244     } else {
21245       AM.BaseType = X86AddressMode::FrameIndexBase;
21246       AM.Base.FrameIndex = Op.getIndex();
21247     }
21248     Op = MI->getOperand(1);
21249     if (Op.isImm())
21250       AM.Scale = Op.getImm();
21251     Op = MI->getOperand(2);
21252     if (Op.isImm())
21253       AM.IndexReg = Op.getImm();
21254     Op = MI->getOperand(3);
21255     if (Op.isGlobal()) {
21256       AM.GV = Op.getGlobal();
21257     } else {
21258       AM.Disp = Op.getImm();
21259     }
21260     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21261                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21262
21263     // Reload the original control word now.
21264     addFrameReference(BuildMI(*BB, MI, DL,
21265                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21266
21267     MI->eraseFromParent();   // The pseudo instruction is gone now.
21268     return BB;
21269   }
21270     // String/text processing lowering.
21271   case X86::PCMPISTRM128REG:
21272   case X86::VPCMPISTRM128REG:
21273   case X86::PCMPISTRM128MEM:
21274   case X86::VPCMPISTRM128MEM:
21275   case X86::PCMPESTRM128REG:
21276   case X86::VPCMPESTRM128REG:
21277   case X86::PCMPESTRM128MEM:
21278   case X86::VPCMPESTRM128MEM:
21279     assert(Subtarget->hasSSE42() &&
21280            "Target must have SSE4.2 or AVX features enabled");
21281     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21282
21283   // String/text processing lowering.
21284   case X86::PCMPISTRIREG:
21285   case X86::VPCMPISTRIREG:
21286   case X86::PCMPISTRIMEM:
21287   case X86::VPCMPISTRIMEM:
21288   case X86::PCMPESTRIREG:
21289   case X86::VPCMPESTRIREG:
21290   case X86::PCMPESTRIMEM:
21291   case X86::VPCMPESTRIMEM:
21292     assert(Subtarget->hasSSE42() &&
21293            "Target must have SSE4.2 or AVX features enabled");
21294     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21295
21296   // Thread synchronization.
21297   case X86::MONITOR:
21298     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
21299                        Subtarget);
21300
21301   // xbegin
21302   case X86::XBEGIN:
21303     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21304
21305   case X86::VASTART_SAVE_XMM_REGS:
21306     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21307
21308   case X86::VAARG_64:
21309     return EmitVAARG64WithCustomInserter(MI, BB);
21310
21311   case X86::EH_SjLj_SetJmp32:
21312   case X86::EH_SjLj_SetJmp64:
21313     return emitEHSjLjSetJmp(MI, BB);
21314
21315   case X86::EH_SjLj_LongJmp32:
21316   case X86::EH_SjLj_LongJmp64:
21317     return emitEHSjLjLongJmp(MI, BB);
21318
21319   case TargetOpcode::STATEPOINT:
21320     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21321     // this point in the process.  We diverge later.
21322     return emitPatchPoint(MI, BB);
21323
21324   case TargetOpcode::STACKMAP:
21325   case TargetOpcode::PATCHPOINT:
21326     return emitPatchPoint(MI, BB);
21327
21328   case X86::VFMADDPDr213r:
21329   case X86::VFMADDPSr213r:
21330   case X86::VFMADDSDr213r:
21331   case X86::VFMADDSSr213r:
21332   case X86::VFMSUBPDr213r:
21333   case X86::VFMSUBPSr213r:
21334   case X86::VFMSUBSDr213r:
21335   case X86::VFMSUBSSr213r:
21336   case X86::VFNMADDPDr213r:
21337   case X86::VFNMADDPSr213r:
21338   case X86::VFNMADDSDr213r:
21339   case X86::VFNMADDSSr213r:
21340   case X86::VFNMSUBPDr213r:
21341   case X86::VFNMSUBPSr213r:
21342   case X86::VFNMSUBSDr213r:
21343   case X86::VFNMSUBSSr213r:
21344   case X86::VFMADDSUBPDr213r:
21345   case X86::VFMADDSUBPSr213r:
21346   case X86::VFMSUBADDPDr213r:
21347   case X86::VFMSUBADDPSr213r:
21348   case X86::VFMADDPDr213rY:
21349   case X86::VFMADDPSr213rY:
21350   case X86::VFMSUBPDr213rY:
21351   case X86::VFMSUBPSr213rY:
21352   case X86::VFNMADDPDr213rY:
21353   case X86::VFNMADDPSr213rY:
21354   case X86::VFNMSUBPDr213rY:
21355   case X86::VFNMSUBPSr213rY:
21356   case X86::VFMADDSUBPDr213rY:
21357   case X86::VFMADDSUBPSr213rY:
21358   case X86::VFMSUBADDPDr213rY:
21359   case X86::VFMSUBADDPSr213rY:
21360     return emitFMA3Instr(MI, BB);
21361   }
21362 }
21363
21364 //===----------------------------------------------------------------------===//
21365 //                           X86 Optimization Hooks
21366 //===----------------------------------------------------------------------===//
21367
21368 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21369                                                       APInt &KnownZero,
21370                                                       APInt &KnownOne,
21371                                                       const SelectionDAG &DAG,
21372                                                       unsigned Depth) const {
21373   unsigned BitWidth = KnownZero.getBitWidth();
21374   unsigned Opc = Op.getOpcode();
21375   assert((Opc >= ISD::BUILTIN_OP_END ||
21376           Opc == ISD::INTRINSIC_WO_CHAIN ||
21377           Opc == ISD::INTRINSIC_W_CHAIN ||
21378           Opc == ISD::INTRINSIC_VOID) &&
21379          "Should use MaskedValueIsZero if you don't know whether Op"
21380          " is a target node!");
21381
21382   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21383   switch (Opc) {
21384   default: break;
21385   case X86ISD::ADD:
21386   case X86ISD::SUB:
21387   case X86ISD::ADC:
21388   case X86ISD::SBB:
21389   case X86ISD::SMUL:
21390   case X86ISD::UMUL:
21391   case X86ISD::INC:
21392   case X86ISD::DEC:
21393   case X86ISD::OR:
21394   case X86ISD::XOR:
21395   case X86ISD::AND:
21396     // These nodes' second result is a boolean.
21397     if (Op.getResNo() == 0)
21398       break;
21399     // Fallthrough
21400   case X86ISD::SETCC:
21401     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21402     break;
21403   case ISD::INTRINSIC_WO_CHAIN: {
21404     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21405     unsigned NumLoBits = 0;
21406     switch (IntId) {
21407     default: break;
21408     case Intrinsic::x86_sse_movmsk_ps:
21409     case Intrinsic::x86_avx_movmsk_ps_256:
21410     case Intrinsic::x86_sse2_movmsk_pd:
21411     case Intrinsic::x86_avx_movmsk_pd_256:
21412     case Intrinsic::x86_mmx_pmovmskb:
21413     case Intrinsic::x86_sse2_pmovmskb_128:
21414     case Intrinsic::x86_avx2_pmovmskb: {
21415       // High bits of movmskp{s|d}, pmovmskb are known zero.
21416       switch (IntId) {
21417         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21418         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21419         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21420         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21421         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21422         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21423         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21424         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21425       }
21426       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21427       break;
21428     }
21429     }
21430     break;
21431   }
21432   }
21433 }
21434
21435 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21436   SDValue Op,
21437   const SelectionDAG &,
21438   unsigned Depth) const {
21439   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21440   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21441     return Op.getValueType().getScalarType().getSizeInBits();
21442
21443   // Fallback case.
21444   return 1;
21445 }
21446
21447 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21448 /// node is a GlobalAddress + offset.
21449 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21450                                        const GlobalValue* &GA,
21451                                        int64_t &Offset) const {
21452   if (N->getOpcode() == X86ISD::Wrapper) {
21453     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21454       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21455       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21456       return true;
21457     }
21458   }
21459   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21460 }
21461
21462 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21463 /// same as extracting the high 128-bit part of 256-bit vector and then
21464 /// inserting the result into the low part of a new 256-bit vector
21465 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21466   EVT VT = SVOp->getValueType(0);
21467   unsigned NumElems = VT.getVectorNumElements();
21468
21469   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21470   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21471     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21472         SVOp->getMaskElt(j) >= 0)
21473       return false;
21474
21475   return true;
21476 }
21477
21478 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21479 /// same as extracting the low 128-bit part of 256-bit vector and then
21480 /// inserting the result into the high part of a new 256-bit vector
21481 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21482   EVT VT = SVOp->getValueType(0);
21483   unsigned NumElems = VT.getVectorNumElements();
21484
21485   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21486   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21487     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21488         SVOp->getMaskElt(j) >= 0)
21489       return false;
21490
21491   return true;
21492 }
21493
21494 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21495 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21496                                         TargetLowering::DAGCombinerInfo &DCI,
21497                                         const X86Subtarget* Subtarget) {
21498   SDLoc dl(N);
21499   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21500   SDValue V1 = SVOp->getOperand(0);
21501   SDValue V2 = SVOp->getOperand(1);
21502   EVT VT = SVOp->getValueType(0);
21503   unsigned NumElems = VT.getVectorNumElements();
21504
21505   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21506       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21507     //
21508     //                   0,0,0,...
21509     //                      |
21510     //    V      UNDEF    BUILD_VECTOR    UNDEF
21511     //     \      /           \           /
21512     //  CONCAT_VECTOR         CONCAT_VECTOR
21513     //         \                  /
21514     //          \                /
21515     //          RESULT: V + zero extended
21516     //
21517     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21518         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21519         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21520       return SDValue();
21521
21522     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21523       return SDValue();
21524
21525     // To match the shuffle mask, the first half of the mask should
21526     // be exactly the first vector, and all the rest a splat with the
21527     // first element of the second one.
21528     for (unsigned i = 0; i != NumElems/2; ++i)
21529       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21530           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21531         return SDValue();
21532
21533     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21534     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21535       if (Ld->hasNUsesOfValue(1, 0)) {
21536         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21537         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21538         SDValue ResNode =
21539           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21540                                   Ld->getMemoryVT(),
21541                                   Ld->getPointerInfo(),
21542                                   Ld->getAlignment(),
21543                                   false/*isVolatile*/, true/*ReadMem*/,
21544                                   false/*WriteMem*/);
21545
21546         // Make sure the newly-created LOAD is in the same position as Ld in
21547         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21548         // and update uses of Ld's output chain to use the TokenFactor.
21549         if (Ld->hasAnyUseOfValue(1)) {
21550           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21551                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21552           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21553           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21554                                  SDValue(ResNode.getNode(), 1));
21555         }
21556
21557         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
21558       }
21559     }
21560
21561     // Emit a zeroed vector and insert the desired subvector on its
21562     // first half.
21563     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21564     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21565     return DCI.CombineTo(N, InsV);
21566   }
21567
21568   //===--------------------------------------------------------------------===//
21569   // Combine some shuffles into subvector extracts and inserts:
21570   //
21571
21572   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21573   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21574     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21575     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21576     return DCI.CombineTo(N, InsV);
21577   }
21578
21579   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21580   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21581     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21582     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21583     return DCI.CombineTo(N, InsV);
21584   }
21585
21586   return SDValue();
21587 }
21588
21589 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21590 /// possible.
21591 ///
21592 /// This is the leaf of the recursive combinine below. When we have found some
21593 /// chain of single-use x86 shuffle instructions and accumulated the combined
21594 /// shuffle mask represented by them, this will try to pattern match that mask
21595 /// into either a single instruction if there is a special purpose instruction
21596 /// for this operation, or into a PSHUFB instruction which is a fully general
21597 /// instruction but should only be used to replace chains over a certain depth.
21598 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21599                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21600                                    TargetLowering::DAGCombinerInfo &DCI,
21601                                    const X86Subtarget *Subtarget) {
21602   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21603
21604   // Find the operand that enters the chain. Note that multiple uses are OK
21605   // here, we're not going to remove the operand we find.
21606   SDValue Input = Op.getOperand(0);
21607   while (Input.getOpcode() == ISD::BITCAST)
21608     Input = Input.getOperand(0);
21609
21610   MVT VT = Input.getSimpleValueType();
21611   MVT RootVT = Root.getSimpleValueType();
21612   SDLoc DL(Root);
21613
21614   // Just remove no-op shuffle masks.
21615   if (Mask.size() == 1) {
21616     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
21617                   /*AddTo*/ true);
21618     return true;
21619   }
21620
21621   // Use the float domain if the operand type is a floating point type.
21622   bool FloatDomain = VT.isFloatingPoint();
21623
21624   // For floating point shuffles, we don't have free copies in the shuffle
21625   // instructions or the ability to load as part of the instruction, so
21626   // canonicalize their shuffles to UNPCK or MOV variants.
21627   //
21628   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21629   // vectors because it can have a load folded into it that UNPCK cannot. This
21630   // doesn't preclude something switching to the shorter encoding post-RA.
21631   if (FloatDomain) {
21632     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
21633       bool Lo = Mask.equals(0, 0);
21634       unsigned Shuffle;
21635       MVT ShuffleVT;
21636       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21637       // is no slower than UNPCKLPD but has the option to fold the input operand
21638       // into even an unaligned memory load.
21639       if (Lo && Subtarget->hasSSE3()) {
21640         Shuffle = X86ISD::MOVDDUP;
21641         ShuffleVT = MVT::v2f64;
21642       } else {
21643         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21644         // than the UNPCK variants.
21645         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21646         ShuffleVT = MVT::v4f32;
21647       }
21648       if (Depth == 1 && Root->getOpcode() == Shuffle)
21649         return false; // Nothing to do!
21650       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21651       DCI.AddToWorklist(Op.getNode());
21652       if (Shuffle == X86ISD::MOVDDUP)
21653         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21654       else
21655         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21656       DCI.AddToWorklist(Op.getNode());
21657       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21658                     /*AddTo*/ true);
21659       return true;
21660     }
21661     if (Subtarget->hasSSE3() &&
21662         (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
21663       bool Lo = Mask.equals(0, 0, 2, 2);
21664       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21665       MVT ShuffleVT = MVT::v4f32;
21666       if (Depth == 1 && Root->getOpcode() == Shuffle)
21667         return false; // Nothing to do!
21668       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21669       DCI.AddToWorklist(Op.getNode());
21670       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21671       DCI.AddToWorklist(Op.getNode());
21672       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21673                     /*AddTo*/ true);
21674       return true;
21675     }
21676     if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
21677       bool Lo = Mask.equals(0, 0, 1, 1);
21678       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21679       MVT ShuffleVT = MVT::v4f32;
21680       if (Depth == 1 && Root->getOpcode() == Shuffle)
21681         return false; // Nothing to do!
21682       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21683       DCI.AddToWorklist(Op.getNode());
21684       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21685       DCI.AddToWorklist(Op.getNode());
21686       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21687                     /*AddTo*/ true);
21688       return true;
21689     }
21690   }
21691
21692   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21693   // variants as none of these have single-instruction variants that are
21694   // superior to the UNPCK formulation.
21695   if (!FloatDomain &&
21696       (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
21697        Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
21698        Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
21699        Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
21700                    15))) {
21701     bool Lo = Mask[0] == 0;
21702     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21703     if (Depth == 1 && Root->getOpcode() == Shuffle)
21704       return false; // Nothing to do!
21705     MVT ShuffleVT;
21706     switch (Mask.size()) {
21707     case 8:
21708       ShuffleVT = MVT::v8i16;
21709       break;
21710     case 16:
21711       ShuffleVT = MVT::v16i8;
21712       break;
21713     default:
21714       llvm_unreachable("Impossible mask size!");
21715     };
21716     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21717     DCI.AddToWorklist(Op.getNode());
21718     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21719     DCI.AddToWorklist(Op.getNode());
21720     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21721                   /*AddTo*/ true);
21722     return true;
21723   }
21724
21725   // Don't try to re-form single instruction chains under any circumstances now
21726   // that we've done encoding canonicalization for them.
21727   if (Depth < 2)
21728     return false;
21729
21730   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21731   // can replace them with a single PSHUFB instruction profitably. Intel's
21732   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21733   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21734   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21735     SmallVector<SDValue, 16> PSHUFBMask;
21736     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
21737     int Ratio = 16 / Mask.size();
21738     for (unsigned i = 0; i < 16; ++i) {
21739       if (Mask[i / Ratio] == SM_SentinelUndef) {
21740         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21741         continue;
21742       }
21743       int M = Mask[i / Ratio] != SM_SentinelZero
21744                   ? Ratio * Mask[i / Ratio] + i % Ratio
21745                   : 255;
21746       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
21747     }
21748     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
21749     DCI.AddToWorklist(Op.getNode());
21750     SDValue PSHUFBMaskOp =
21751         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
21752     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21753     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
21754     DCI.AddToWorklist(Op.getNode());
21755     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21756                   /*AddTo*/ true);
21757     return true;
21758   }
21759
21760   // Failed to find any combines.
21761   return false;
21762 }
21763
21764 /// \brief Fully generic combining of x86 shuffle instructions.
21765 ///
21766 /// This should be the last combine run over the x86 shuffle instructions. Once
21767 /// they have been fully optimized, this will recursively consider all chains
21768 /// of single-use shuffle instructions, build a generic model of the cumulative
21769 /// shuffle operation, and check for simpler instructions which implement this
21770 /// operation. We use this primarily for two purposes:
21771 ///
21772 /// 1) Collapse generic shuffles to specialized single instructions when
21773 ///    equivalent. In most cases, this is just an encoding size win, but
21774 ///    sometimes we will collapse multiple generic shuffles into a single
21775 ///    special-purpose shuffle.
21776 /// 2) Look for sequences of shuffle instructions with 3 or more total
21777 ///    instructions, and replace them with the slightly more expensive SSSE3
21778 ///    PSHUFB instruction if available. We do this as the last combining step
21779 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21780 ///    a suitable short sequence of other instructions. The PHUFB will either
21781 ///    use a register or have to read from memory and so is slightly (but only
21782 ///    slightly) more expensive than the other shuffle instructions.
21783 ///
21784 /// Because this is inherently a quadratic operation (for each shuffle in
21785 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21786 /// This should never be an issue in practice as the shuffle lowering doesn't
21787 /// produce sequences of more than 8 instructions.
21788 ///
21789 /// FIXME: We will currently miss some cases where the redundant shuffling
21790 /// would simplify under the threshold for PSHUFB formation because of
21791 /// combine-ordering. To fix this, we should do the redundant instruction
21792 /// combining in this recursive walk.
21793 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21794                                           ArrayRef<int> RootMask,
21795                                           int Depth, bool HasPSHUFB,
21796                                           SelectionDAG &DAG,
21797                                           TargetLowering::DAGCombinerInfo &DCI,
21798                                           const X86Subtarget *Subtarget) {
21799   // Bound the depth of our recursive combine because this is ultimately
21800   // quadratic in nature.
21801   if (Depth > 8)
21802     return false;
21803
21804   // Directly rip through bitcasts to find the underlying operand.
21805   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21806     Op = Op.getOperand(0);
21807
21808   MVT VT = Op.getSimpleValueType();
21809   if (!VT.isVector())
21810     return false; // Bail if we hit a non-vector.
21811   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
21812   // version should be added.
21813   if (VT.getSizeInBits() != 128)
21814     return false;
21815
21816   assert(Root.getSimpleValueType().isVector() &&
21817          "Shuffles operate on vector types!");
21818   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21819          "Can only combine shuffles of the same vector register size.");
21820
21821   if (!isTargetShuffle(Op.getOpcode()))
21822     return false;
21823   SmallVector<int, 16> OpMask;
21824   bool IsUnary;
21825   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21826   // We only can combine unary shuffles which we can decode the mask for.
21827   if (!HaveMask || !IsUnary)
21828     return false;
21829
21830   assert(VT.getVectorNumElements() == OpMask.size() &&
21831          "Different mask size from vector size!");
21832   assert(((RootMask.size() > OpMask.size() &&
21833            RootMask.size() % OpMask.size() == 0) ||
21834           (OpMask.size() > RootMask.size() &&
21835            OpMask.size() % RootMask.size() == 0) ||
21836           OpMask.size() == RootMask.size()) &&
21837          "The smaller number of elements must divide the larger.");
21838   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21839   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21840   assert(((RootRatio == 1 && OpRatio == 1) ||
21841           (RootRatio == 1) != (OpRatio == 1)) &&
21842          "Must not have a ratio for both incoming and op masks!");
21843
21844   SmallVector<int, 16> Mask;
21845   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21846
21847   // Merge this shuffle operation's mask into our accumulated mask. Note that
21848   // this shuffle's mask will be the first applied to the input, followed by the
21849   // root mask to get us all the way to the root value arrangement. The reason
21850   // for this order is that we are recursing up the operation chain.
21851   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21852     int RootIdx = i / RootRatio;
21853     if (RootMask[RootIdx] < 0) {
21854       // This is a zero or undef lane, we're done.
21855       Mask.push_back(RootMask[RootIdx]);
21856       continue;
21857     }
21858
21859     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21860     int OpIdx = RootMaskedIdx / OpRatio;
21861     if (OpMask[OpIdx] < 0) {
21862       // The incoming lanes are zero or undef, it doesn't matter which ones we
21863       // are using.
21864       Mask.push_back(OpMask[OpIdx]);
21865       continue;
21866     }
21867
21868     // Ok, we have non-zero lanes, map them through.
21869     Mask.push_back(OpMask[OpIdx] * OpRatio +
21870                    RootMaskedIdx % OpRatio);
21871   }
21872
21873   // See if we can recurse into the operand to combine more things.
21874   switch (Op.getOpcode()) {
21875     case X86ISD::PSHUFB:
21876       HasPSHUFB = true;
21877     case X86ISD::PSHUFD:
21878     case X86ISD::PSHUFHW:
21879     case X86ISD::PSHUFLW:
21880       if (Op.getOperand(0).hasOneUse() &&
21881           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21882                                         HasPSHUFB, DAG, DCI, Subtarget))
21883         return true;
21884       break;
21885
21886     case X86ISD::UNPCKL:
21887     case X86ISD::UNPCKH:
21888       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21889       // We can't check for single use, we have to check that this shuffle is the only user.
21890       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21891           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21892                                         HasPSHUFB, DAG, DCI, Subtarget))
21893           return true;
21894       break;
21895   }
21896
21897   // Minor canonicalization of the accumulated shuffle mask to make it easier
21898   // to match below. All this does is detect masks with squential pairs of
21899   // elements, and shrink them to the half-width mask. It does this in a loop
21900   // so it will reduce the size of the mask to the minimal width mask which
21901   // performs an equivalent shuffle.
21902   SmallVector<int, 16> WidenedMask;
21903   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21904     Mask = std::move(WidenedMask);
21905     WidenedMask.clear();
21906   }
21907
21908   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21909                                 Subtarget);
21910 }
21911
21912 /// \brief Get the PSHUF-style mask from PSHUF node.
21913 ///
21914 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21915 /// PSHUF-style masks that can be reused with such instructions.
21916 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21917   SmallVector<int, 4> Mask;
21918   bool IsUnary;
21919   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
21920   (void)HaveMask;
21921   assert(HaveMask);
21922
21923   switch (N.getOpcode()) {
21924   case X86ISD::PSHUFD:
21925     return Mask;
21926   case X86ISD::PSHUFLW:
21927     Mask.resize(4);
21928     return Mask;
21929   case X86ISD::PSHUFHW:
21930     Mask.erase(Mask.begin(), Mask.begin() + 4);
21931     for (int &M : Mask)
21932       M -= 4;
21933     return Mask;
21934   default:
21935     llvm_unreachable("No valid shuffle instruction found!");
21936   }
21937 }
21938
21939 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21940 ///
21941 /// We walk up the chain and look for a combinable shuffle, skipping over
21942 /// shuffles that we could hoist this shuffle's transformation past without
21943 /// altering anything.
21944 static SDValue
21945 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21946                              SelectionDAG &DAG,
21947                              TargetLowering::DAGCombinerInfo &DCI) {
21948   assert(N.getOpcode() == X86ISD::PSHUFD &&
21949          "Called with something other than an x86 128-bit half shuffle!");
21950   SDLoc DL(N);
21951
21952   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21953   // of the shuffles in the chain so that we can form a fresh chain to replace
21954   // this one.
21955   SmallVector<SDValue, 8> Chain;
21956   SDValue V = N.getOperand(0);
21957   for (; V.hasOneUse(); V = V.getOperand(0)) {
21958     switch (V.getOpcode()) {
21959     default:
21960       return SDValue(); // Nothing combined!
21961
21962     case ISD::BITCAST:
21963       // Skip bitcasts as we always know the type for the target specific
21964       // instructions.
21965       continue;
21966
21967     case X86ISD::PSHUFD:
21968       // Found another dword shuffle.
21969       break;
21970
21971     case X86ISD::PSHUFLW:
21972       // Check that the low words (being shuffled) are the identity in the
21973       // dword shuffle, and the high words are self-contained.
21974       if (Mask[0] != 0 || Mask[1] != 1 ||
21975           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21976         return SDValue();
21977
21978       Chain.push_back(V);
21979       continue;
21980
21981     case X86ISD::PSHUFHW:
21982       // Check that the high words (being shuffled) are the identity in the
21983       // dword shuffle, and the low words are self-contained.
21984       if (Mask[2] != 2 || Mask[3] != 3 ||
21985           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21986         return SDValue();
21987
21988       Chain.push_back(V);
21989       continue;
21990
21991     case X86ISD::UNPCKL:
21992     case X86ISD::UNPCKH:
21993       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21994       // shuffle into a preceding word shuffle.
21995       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
21996         return SDValue();
21997
21998       // Search for a half-shuffle which we can combine with.
21999       unsigned CombineOp =
22000           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22001       if (V.getOperand(0) != V.getOperand(1) ||
22002           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22003         return SDValue();
22004       Chain.push_back(V);
22005       V = V.getOperand(0);
22006       do {
22007         switch (V.getOpcode()) {
22008         default:
22009           return SDValue(); // Nothing to combine.
22010
22011         case X86ISD::PSHUFLW:
22012         case X86ISD::PSHUFHW:
22013           if (V.getOpcode() == CombineOp)
22014             break;
22015
22016           Chain.push_back(V);
22017
22018           // Fallthrough!
22019         case ISD::BITCAST:
22020           V = V.getOperand(0);
22021           continue;
22022         }
22023         break;
22024       } while (V.hasOneUse());
22025       break;
22026     }
22027     // Break out of the loop if we break out of the switch.
22028     break;
22029   }
22030
22031   if (!V.hasOneUse())
22032     // We fell out of the loop without finding a viable combining instruction.
22033     return SDValue();
22034
22035   // Merge this node's mask and our incoming mask.
22036   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22037   for (int &M : Mask)
22038     M = VMask[M];
22039   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22040                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22041
22042   // Rebuild the chain around this new shuffle.
22043   while (!Chain.empty()) {
22044     SDValue W = Chain.pop_back_val();
22045
22046     if (V.getValueType() != W.getOperand(0).getValueType())
22047       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
22048
22049     switch (W.getOpcode()) {
22050     default:
22051       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22052
22053     case X86ISD::UNPCKL:
22054     case X86ISD::UNPCKH:
22055       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22056       break;
22057
22058     case X86ISD::PSHUFD:
22059     case X86ISD::PSHUFLW:
22060     case X86ISD::PSHUFHW:
22061       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22062       break;
22063     }
22064   }
22065   if (V.getValueType() != N.getValueType())
22066     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
22067
22068   // Return the new chain to replace N.
22069   return V;
22070 }
22071
22072 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22073 ///
22074 /// We walk up the chain, skipping shuffles of the other half and looking
22075 /// through shuffles which switch halves trying to find a shuffle of the same
22076 /// pair of dwords.
22077 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22078                                         SelectionDAG &DAG,
22079                                         TargetLowering::DAGCombinerInfo &DCI) {
22080   assert(
22081       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22082       "Called with something other than an x86 128-bit half shuffle!");
22083   SDLoc DL(N);
22084   unsigned CombineOpcode = N.getOpcode();
22085
22086   // Walk up a single-use chain looking for a combinable shuffle.
22087   SDValue V = N.getOperand(0);
22088   for (; V.hasOneUse(); V = V.getOperand(0)) {
22089     switch (V.getOpcode()) {
22090     default:
22091       return false; // Nothing combined!
22092
22093     case ISD::BITCAST:
22094       // Skip bitcasts as we always know the type for the target specific
22095       // instructions.
22096       continue;
22097
22098     case X86ISD::PSHUFLW:
22099     case X86ISD::PSHUFHW:
22100       if (V.getOpcode() == CombineOpcode)
22101         break;
22102
22103       // Other-half shuffles are no-ops.
22104       continue;
22105     }
22106     // Break out of the loop if we break out of the switch.
22107     break;
22108   }
22109
22110   if (!V.hasOneUse())
22111     // We fell out of the loop without finding a viable combining instruction.
22112     return false;
22113
22114   // Combine away the bottom node as its shuffle will be accumulated into
22115   // a preceding shuffle.
22116   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22117
22118   // Record the old value.
22119   SDValue Old = V;
22120
22121   // Merge this node's mask and our incoming mask (adjusted to account for all
22122   // the pshufd instructions encountered).
22123   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22124   for (int &M : Mask)
22125     M = VMask[M];
22126   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22127                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22128
22129   // Check that the shuffles didn't cancel each other out. If not, we need to
22130   // combine to the new one.
22131   if (Old != V)
22132     // Replace the combinable shuffle with the combined one, updating all users
22133     // so that we re-evaluate the chain here.
22134     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22135
22136   return true;
22137 }
22138
22139 /// \brief Try to combine x86 target specific shuffles.
22140 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22141                                            TargetLowering::DAGCombinerInfo &DCI,
22142                                            const X86Subtarget *Subtarget) {
22143   SDLoc DL(N);
22144   MVT VT = N.getSimpleValueType();
22145   SmallVector<int, 4> Mask;
22146
22147   switch (N.getOpcode()) {
22148   case X86ISD::PSHUFD:
22149   case X86ISD::PSHUFLW:
22150   case X86ISD::PSHUFHW:
22151     Mask = getPSHUFShuffleMask(N);
22152     assert(Mask.size() == 4);
22153     break;
22154   default:
22155     return SDValue();
22156   }
22157
22158   // Nuke no-op shuffles that show up after combining.
22159   if (isNoopShuffleMask(Mask))
22160     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22161
22162   // Look for simplifications involving one or two shuffle instructions.
22163   SDValue V = N.getOperand(0);
22164   switch (N.getOpcode()) {
22165   default:
22166     break;
22167   case X86ISD::PSHUFLW:
22168   case X86ISD::PSHUFHW:
22169     assert(VT == MVT::v8i16);
22170     (void)VT;
22171
22172     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22173       return SDValue(); // We combined away this shuffle, so we're done.
22174
22175     // See if this reduces to a PSHUFD which is no more expensive and can
22176     // combine with more operations. Note that it has to at least flip the
22177     // dwords as otherwise it would have been removed as a no-op.
22178     if (Mask[0] == 2 && Mask[1] == 3 && Mask[2] == 0 && Mask[3] == 1) {
22179       int DMask[] = {0, 1, 2, 3};
22180       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22181       DMask[DOffset + 0] = DOffset + 1;
22182       DMask[DOffset + 1] = DOffset + 0;
22183       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
22184       DCI.AddToWorklist(V.getNode());
22185       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
22186                       getV4X86ShuffleImm8ForMask(DMask, DAG));
22187       DCI.AddToWorklist(V.getNode());
22188       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
22189     }
22190
22191     // Look for shuffle patterns which can be implemented as a single unpack.
22192     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22193     // only works when we have a PSHUFD followed by two half-shuffles.
22194     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22195         (V.getOpcode() == X86ISD::PSHUFLW ||
22196          V.getOpcode() == X86ISD::PSHUFHW) &&
22197         V.getOpcode() != N.getOpcode() &&
22198         V.hasOneUse()) {
22199       SDValue D = V.getOperand(0);
22200       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22201         D = D.getOperand(0);
22202       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22203         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22204         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22205         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22206         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22207         int WordMask[8];
22208         for (int i = 0; i < 4; ++i) {
22209           WordMask[i + NOffset] = Mask[i] + NOffset;
22210           WordMask[i + VOffset] = VMask[i] + VOffset;
22211         }
22212         // Map the word mask through the DWord mask.
22213         int MappedMask[8];
22214         for (int i = 0; i < 8; ++i)
22215           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22216         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
22217         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
22218         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
22219                        std::begin(UnpackLoMask)) ||
22220             std::equal(std::begin(MappedMask), std::end(MappedMask),
22221                        std::begin(UnpackHiMask))) {
22222           // We can replace all three shuffles with an unpack.
22223           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
22224           DCI.AddToWorklist(V.getNode());
22225           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22226                                                 : X86ISD::UNPCKH,
22227                              DL, MVT::v8i16, V, V);
22228         }
22229       }
22230     }
22231
22232     break;
22233
22234   case X86ISD::PSHUFD:
22235     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22236       return NewN;
22237
22238     break;
22239   }
22240
22241   return SDValue();
22242 }
22243
22244 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22245 ///
22246 /// We combine this directly on the abstract vector shuffle nodes so it is
22247 /// easier to generically match. We also insert dummy vector shuffle nodes for
22248 /// the operands which explicitly discard the lanes which are unused by this
22249 /// operation to try to flow through the rest of the combiner the fact that
22250 /// they're unused.
22251 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22252   SDLoc DL(N);
22253   EVT VT = N->getValueType(0);
22254
22255   // We only handle target-independent shuffles.
22256   // FIXME: It would be easy and harmless to use the target shuffle mask
22257   // extraction tool to support more.
22258   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22259     return SDValue();
22260
22261   auto *SVN = cast<ShuffleVectorSDNode>(N);
22262   ArrayRef<int> Mask = SVN->getMask();
22263   SDValue V1 = N->getOperand(0);
22264   SDValue V2 = N->getOperand(1);
22265
22266   // We require the first shuffle operand to be the SUB node, and the second to
22267   // be the ADD node.
22268   // FIXME: We should support the commuted patterns.
22269   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22270     return SDValue();
22271
22272   // If there are other uses of these operations we can't fold them.
22273   if (!V1->hasOneUse() || !V2->hasOneUse())
22274     return SDValue();
22275
22276   // Ensure that both operations have the same operands. Note that we can
22277   // commute the FADD operands.
22278   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22279   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22280       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22281     return SDValue();
22282
22283   // We're looking for blends between FADD and FSUB nodes. We insist on these
22284   // nodes being lined up in a specific expected pattern.
22285   if (!(isShuffleEquivalent(Mask, 0, 3) ||
22286         isShuffleEquivalent(Mask, 0, 5, 2, 7) ||
22287         isShuffleEquivalent(Mask, 0, 9, 2, 11, 4, 13, 6, 15)))
22288     return SDValue();
22289
22290   // Only specific types are legal at this point, assert so we notice if and
22291   // when these change.
22292   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22293           VT == MVT::v4f64) &&
22294          "Unknown vector type encountered!");
22295
22296   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22297 }
22298
22299 /// PerformShuffleCombine - Performs several different shuffle combines.
22300 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22301                                      TargetLowering::DAGCombinerInfo &DCI,
22302                                      const X86Subtarget *Subtarget) {
22303   SDLoc dl(N);
22304   SDValue N0 = N->getOperand(0);
22305   SDValue N1 = N->getOperand(1);
22306   EVT VT = N->getValueType(0);
22307
22308   // Don't create instructions with illegal types after legalize types has run.
22309   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22310   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22311     return SDValue();
22312
22313   // If we have legalized the vector types, look for blends of FADD and FSUB
22314   // nodes that we can fuse into an ADDSUB node.
22315   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22316     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22317       return AddSub;
22318
22319   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22320   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22321       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22322     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22323
22324   // During Type Legalization, when promoting illegal vector types,
22325   // the backend might introduce new shuffle dag nodes and bitcasts.
22326   //
22327   // This code performs the following transformation:
22328   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22329   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22330   //
22331   // We do this only if both the bitcast and the BINOP dag nodes have
22332   // one use. Also, perform this transformation only if the new binary
22333   // operation is legal. This is to avoid introducing dag nodes that
22334   // potentially need to be further expanded (or custom lowered) into a
22335   // less optimal sequence of dag nodes.
22336   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22337       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22338       N0.getOpcode() == ISD::BITCAST) {
22339     SDValue BC0 = N0.getOperand(0);
22340     EVT SVT = BC0.getValueType();
22341     unsigned Opcode = BC0.getOpcode();
22342     unsigned NumElts = VT.getVectorNumElements();
22343
22344     if (BC0.hasOneUse() && SVT.isVector() &&
22345         SVT.getVectorNumElements() * 2 == NumElts &&
22346         TLI.isOperationLegal(Opcode, VT)) {
22347       bool CanFold = false;
22348       switch (Opcode) {
22349       default : break;
22350       case ISD::ADD :
22351       case ISD::FADD :
22352       case ISD::SUB :
22353       case ISD::FSUB :
22354       case ISD::MUL :
22355       case ISD::FMUL :
22356         CanFold = true;
22357       }
22358
22359       unsigned SVTNumElts = SVT.getVectorNumElements();
22360       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22361       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22362         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22363       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22364         CanFold = SVOp->getMaskElt(i) < 0;
22365
22366       if (CanFold) {
22367         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
22368         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
22369         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22370         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22371       }
22372     }
22373   }
22374
22375   // Only handle 128 wide vector from here on.
22376   if (!VT.is128BitVector())
22377     return SDValue();
22378
22379   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22380   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22381   // consecutive, non-overlapping, and in the right order.
22382   SmallVector<SDValue, 16> Elts;
22383   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22384     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22385
22386   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
22387   if (LD.getNode())
22388     return LD;
22389
22390   if (isTargetShuffle(N->getOpcode())) {
22391     SDValue Shuffle =
22392         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22393     if (Shuffle.getNode())
22394       return Shuffle;
22395
22396     // Try recursively combining arbitrary sequences of x86 shuffle
22397     // instructions into higher-order shuffles. We do this after combining
22398     // specific PSHUF instruction sequences into their minimal form so that we
22399     // can evaluate how many specialized shuffle instructions are involved in
22400     // a particular chain.
22401     SmallVector<int, 1> NonceMask; // Just a placeholder.
22402     NonceMask.push_back(0);
22403     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22404                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22405                                       DCI, Subtarget))
22406       return SDValue(); // This routine will use CombineTo to replace N.
22407   }
22408
22409   return SDValue();
22410 }
22411
22412 /// PerformTruncateCombine - Converts truncate operation to
22413 /// a sequence of vector shuffle operations.
22414 /// It is possible when we truncate 256-bit vector to 128-bit vector
22415 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
22416                                       TargetLowering::DAGCombinerInfo &DCI,
22417                                       const X86Subtarget *Subtarget)  {
22418   return SDValue();
22419 }
22420
22421 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22422 /// specific shuffle of a load can be folded into a single element load.
22423 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22424 /// shuffles have been custom lowered so we need to handle those here.
22425 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22426                                          TargetLowering::DAGCombinerInfo &DCI) {
22427   if (DCI.isBeforeLegalizeOps())
22428     return SDValue();
22429
22430   SDValue InVec = N->getOperand(0);
22431   SDValue EltNo = N->getOperand(1);
22432
22433   if (!isa<ConstantSDNode>(EltNo))
22434     return SDValue();
22435
22436   EVT OriginalVT = InVec.getValueType();
22437
22438   if (InVec.getOpcode() == ISD::BITCAST) {
22439     // Don't duplicate a load with other uses.
22440     if (!InVec.hasOneUse())
22441       return SDValue();
22442     EVT BCVT = InVec.getOperand(0).getValueType();
22443     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22444       return SDValue();
22445     InVec = InVec.getOperand(0);
22446   }
22447
22448   EVT CurrentVT = InVec.getValueType();
22449
22450   if (!isTargetShuffle(InVec.getOpcode()))
22451     return SDValue();
22452
22453   // Don't duplicate a load with other uses.
22454   if (!InVec.hasOneUse())
22455     return SDValue();
22456
22457   SmallVector<int, 16> ShuffleMask;
22458   bool UnaryShuffle;
22459   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22460                             ShuffleMask, UnaryShuffle))
22461     return SDValue();
22462
22463   // Select the input vector, guarding against out of range extract vector.
22464   unsigned NumElems = CurrentVT.getVectorNumElements();
22465   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22466   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22467   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22468                                          : InVec.getOperand(1);
22469
22470   // If inputs to shuffle are the same for both ops, then allow 2 uses
22471   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22472
22473   if (LdNode.getOpcode() == ISD::BITCAST) {
22474     // Don't duplicate a load with other uses.
22475     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22476       return SDValue();
22477
22478     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22479     LdNode = LdNode.getOperand(0);
22480   }
22481
22482   if (!ISD::isNormalLoad(LdNode.getNode()))
22483     return SDValue();
22484
22485   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22486
22487   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22488     return SDValue();
22489
22490   EVT EltVT = N->getValueType(0);
22491   // If there's a bitcast before the shuffle, check if the load type and
22492   // alignment is valid.
22493   unsigned Align = LN0->getAlignment();
22494   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22495   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
22496       EltVT.getTypeForEVT(*DAG.getContext()));
22497
22498   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22499     return SDValue();
22500
22501   // All checks match so transform back to vector_shuffle so that DAG combiner
22502   // can finish the job
22503   SDLoc dl(N);
22504
22505   // Create shuffle node taking into account the case that its a unary shuffle
22506   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22507                                    : InVec.getOperand(1);
22508   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22509                                  InVec.getOperand(0), Shuffle,
22510                                  &ShuffleMask[0]);
22511   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
22512   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22513                      EltNo);
22514 }
22515
22516 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22517 /// generation and convert it from being a bunch of shuffles and extracts
22518 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22519 /// storing the value and loading scalars back, while for x64 we should
22520 /// use 64-bit extracts and shifts.
22521 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22522                                          TargetLowering::DAGCombinerInfo &DCI) {
22523   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
22524   if (NewOp.getNode())
22525     return NewOp;
22526
22527   SDValue InputVector = N->getOperand(0);
22528
22529   // Detect whether we are trying to convert from mmx to i32 and the bitcast
22530   // from mmx to v2i32 has a single usage.
22531   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
22532       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
22533       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
22534     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22535                        N->getValueType(0),
22536                        InputVector.getNode()->getOperand(0));
22537
22538   // Only operate on vectors of 4 elements, where the alternative shuffling
22539   // gets to be more expensive.
22540   if (InputVector.getValueType() != MVT::v4i32)
22541     return SDValue();
22542
22543   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22544   // single use which is a sign-extend or zero-extend, and all elements are
22545   // used.
22546   SmallVector<SDNode *, 4> Uses;
22547   unsigned ExtractedElements = 0;
22548   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22549        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22550     if (UI.getUse().getResNo() != InputVector.getResNo())
22551       return SDValue();
22552
22553     SDNode *Extract = *UI;
22554     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22555       return SDValue();
22556
22557     if (Extract->getValueType(0) != MVT::i32)
22558       return SDValue();
22559     if (!Extract->hasOneUse())
22560       return SDValue();
22561     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22562         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22563       return SDValue();
22564     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22565       return SDValue();
22566
22567     // Record which element was extracted.
22568     ExtractedElements |=
22569       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22570
22571     Uses.push_back(Extract);
22572   }
22573
22574   // If not all the elements were used, this may not be worthwhile.
22575   if (ExtractedElements != 15)
22576     return SDValue();
22577
22578   // Ok, we've now decided to do the transformation.
22579   // If 64-bit shifts are legal, use the extract-shift sequence,
22580   // otherwise bounce the vector off the cache.
22581   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22582   SDValue Vals[4];
22583   SDLoc dl(InputVector);
22584   
22585   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22586     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
22587     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
22588     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22589       DAG.getConstant(0, VecIdxTy));
22590     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22591       DAG.getConstant(1, VecIdxTy));
22592
22593     SDValue ShAmt = DAG.getConstant(32, 
22594       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
22595     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22596     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22597       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22598     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22599     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22600       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22601   } else {
22602     // Store the value to a temporary stack slot.
22603     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22604     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22605       MachinePointerInfo(), false, false, 0);
22606
22607     EVT ElementType = InputVector.getValueType().getVectorElementType();
22608     unsigned EltSize = ElementType.getSizeInBits() / 8;
22609
22610     // Replace each use (extract) with a load of the appropriate element.
22611     for (unsigned i = 0; i < 4; ++i) {
22612       uint64_t Offset = EltSize * i;
22613       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
22614
22615       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
22616                                        StackPtr, OffsetVal);
22617
22618       // Load the scalar.
22619       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22620                             ScalarAddr, MachinePointerInfo(),
22621                             false, false, false, 0);
22622
22623     }
22624   }
22625
22626   // Replace the extracts
22627   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22628     UE = Uses.end(); UI != UE; ++UI) {
22629     SDNode *Extract = *UI;
22630
22631     SDValue Idx = Extract->getOperand(1);
22632     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22633     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22634   }
22635
22636   // The replacement was made in place; don't return anything.
22637   return SDValue();
22638 }
22639
22640 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22641 static std::pair<unsigned, bool>
22642 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22643                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22644   if (!VT.isVector())
22645     return std::make_pair(0, false);
22646
22647   bool NeedSplit = false;
22648   switch (VT.getSimpleVT().SimpleTy) {
22649   default: return std::make_pair(0, false);
22650   case MVT::v4i64:
22651   case MVT::v2i64:
22652     if (!Subtarget->hasVLX())
22653       return std::make_pair(0, false);
22654     break;
22655   case MVT::v64i8:
22656   case MVT::v32i16:
22657     if (!Subtarget->hasBWI())
22658       return std::make_pair(0, false);
22659     break;
22660   case MVT::v16i32:
22661   case MVT::v8i64:
22662     if (!Subtarget->hasAVX512())
22663       return std::make_pair(0, false);
22664     break;
22665   case MVT::v32i8:
22666   case MVT::v16i16:
22667   case MVT::v8i32:
22668     if (!Subtarget->hasAVX2())
22669       NeedSplit = true;
22670     if (!Subtarget->hasAVX())
22671       return std::make_pair(0, false);
22672     break;
22673   case MVT::v16i8:
22674   case MVT::v8i16:
22675   case MVT::v4i32:
22676     if (!Subtarget->hasSSE2())
22677       return std::make_pair(0, false);
22678   }
22679
22680   // SSE2 has only a small subset of the operations.
22681   bool hasUnsigned = Subtarget->hasSSE41() ||
22682                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22683   bool hasSigned = Subtarget->hasSSE41() ||
22684                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22685
22686   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22687
22688   unsigned Opc = 0;
22689   // Check for x CC y ? x : y.
22690   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22691       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22692     switch (CC) {
22693     default: break;
22694     case ISD::SETULT:
22695     case ISD::SETULE:
22696       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22697     case ISD::SETUGT:
22698     case ISD::SETUGE:
22699       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22700     case ISD::SETLT:
22701     case ISD::SETLE:
22702       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22703     case ISD::SETGT:
22704     case ISD::SETGE:
22705       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22706     }
22707   // Check for x CC y ? y : x -- a min/max with reversed arms.
22708   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22709              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22710     switch (CC) {
22711     default: break;
22712     case ISD::SETULT:
22713     case ISD::SETULE:
22714       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22715     case ISD::SETUGT:
22716     case ISD::SETUGE:
22717       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22718     case ISD::SETLT:
22719     case ISD::SETLE:
22720       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22721     case ISD::SETGT:
22722     case ISD::SETGE:
22723       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22724     }
22725   }
22726
22727   return std::make_pair(Opc, NeedSplit);
22728 }
22729
22730 static SDValue
22731 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22732                                       const X86Subtarget *Subtarget) {
22733   SDLoc dl(N);
22734   SDValue Cond = N->getOperand(0);
22735   SDValue LHS = N->getOperand(1);
22736   SDValue RHS = N->getOperand(2);
22737
22738   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22739     SDValue CondSrc = Cond->getOperand(0);
22740     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22741       Cond = CondSrc->getOperand(0);
22742   }
22743
22744   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22745     return SDValue();
22746
22747   // A vselect where all conditions and data are constants can be optimized into
22748   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22749   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22750       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22751     return SDValue();
22752
22753   unsigned MaskValue = 0;
22754   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22755     return SDValue();
22756
22757   MVT VT = N->getSimpleValueType(0);
22758   unsigned NumElems = VT.getVectorNumElements();
22759   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22760   for (unsigned i = 0; i < NumElems; ++i) {
22761     // Be sure we emit undef where we can.
22762     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22763       ShuffleMask[i] = -1;
22764     else
22765       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22766   }
22767
22768   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22769   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22770     return SDValue();
22771   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22772 }
22773
22774 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22775 /// nodes.
22776 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22777                                     TargetLowering::DAGCombinerInfo &DCI,
22778                                     const X86Subtarget *Subtarget) {
22779   SDLoc DL(N);
22780   SDValue Cond = N->getOperand(0);
22781   // Get the LHS/RHS of the select.
22782   SDValue LHS = N->getOperand(1);
22783   SDValue RHS = N->getOperand(2);
22784   EVT VT = LHS.getValueType();
22785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22786
22787   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22788   // instructions match the semantics of the common C idiom x<y?x:y but not
22789   // x<=y?x:y, because of how they handle negative zero (which can be
22790   // ignored in unsafe-math mode).
22791   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22792       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
22793       (Subtarget->hasSSE2() ||
22794        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22795     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22796
22797     unsigned Opcode = 0;
22798     // Check for x CC y ? x : y.
22799     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22800         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22801       switch (CC) {
22802       default: break;
22803       case ISD::SETULT:
22804         // Converting this to a min would handle NaNs incorrectly, and swapping
22805         // the operands would cause it to handle comparisons between positive
22806         // and negative zero incorrectly.
22807         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22808           if (!DAG.getTarget().Options.UnsafeFPMath &&
22809               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22810             break;
22811           std::swap(LHS, RHS);
22812         }
22813         Opcode = X86ISD::FMIN;
22814         break;
22815       case ISD::SETOLE:
22816         // Converting this to a min would handle comparisons between positive
22817         // and negative zero incorrectly.
22818         if (!DAG.getTarget().Options.UnsafeFPMath &&
22819             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22820           break;
22821         Opcode = X86ISD::FMIN;
22822         break;
22823       case ISD::SETULE:
22824         // Converting this to a min would handle both negative zeros and NaNs
22825         // incorrectly, but we can swap the operands to fix both.
22826         std::swap(LHS, RHS);
22827       case ISD::SETOLT:
22828       case ISD::SETLT:
22829       case ISD::SETLE:
22830         Opcode = X86ISD::FMIN;
22831         break;
22832
22833       case ISD::SETOGE:
22834         // Converting this to a max would handle comparisons between positive
22835         // and negative zero incorrectly.
22836         if (!DAG.getTarget().Options.UnsafeFPMath &&
22837             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22838           break;
22839         Opcode = X86ISD::FMAX;
22840         break;
22841       case ISD::SETUGT:
22842         // Converting this to a max would handle NaNs incorrectly, and swapping
22843         // the operands would cause it to handle comparisons between positive
22844         // and negative zero incorrectly.
22845         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22846           if (!DAG.getTarget().Options.UnsafeFPMath &&
22847               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22848             break;
22849           std::swap(LHS, RHS);
22850         }
22851         Opcode = X86ISD::FMAX;
22852         break;
22853       case ISD::SETUGE:
22854         // Converting this to a max would handle both negative zeros and NaNs
22855         // incorrectly, but we can swap the operands to fix both.
22856         std::swap(LHS, RHS);
22857       case ISD::SETOGT:
22858       case ISD::SETGT:
22859       case ISD::SETGE:
22860         Opcode = X86ISD::FMAX;
22861         break;
22862       }
22863     // Check for x CC y ? y : x -- a min/max with reversed arms.
22864     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22865                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22866       switch (CC) {
22867       default: break;
22868       case ISD::SETOGE:
22869         // Converting this to a min would handle comparisons between positive
22870         // and negative zero incorrectly, and swapping the operands would
22871         // cause it to handle NaNs incorrectly.
22872         if (!DAG.getTarget().Options.UnsafeFPMath &&
22873             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22874           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22875             break;
22876           std::swap(LHS, RHS);
22877         }
22878         Opcode = X86ISD::FMIN;
22879         break;
22880       case ISD::SETUGT:
22881         // Converting this to a min would handle NaNs incorrectly.
22882         if (!DAG.getTarget().Options.UnsafeFPMath &&
22883             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22884           break;
22885         Opcode = X86ISD::FMIN;
22886         break;
22887       case ISD::SETUGE:
22888         // Converting this to a min would handle both negative zeros and NaNs
22889         // incorrectly, but we can swap the operands to fix both.
22890         std::swap(LHS, RHS);
22891       case ISD::SETOGT:
22892       case ISD::SETGT:
22893       case ISD::SETGE:
22894         Opcode = X86ISD::FMIN;
22895         break;
22896
22897       case ISD::SETULT:
22898         // Converting this to a max would handle NaNs incorrectly.
22899         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22900           break;
22901         Opcode = X86ISD::FMAX;
22902         break;
22903       case ISD::SETOLE:
22904         // Converting this to a max would handle comparisons between positive
22905         // and negative zero incorrectly, and swapping the operands would
22906         // cause it to handle NaNs incorrectly.
22907         if (!DAG.getTarget().Options.UnsafeFPMath &&
22908             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22909           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22910             break;
22911           std::swap(LHS, RHS);
22912         }
22913         Opcode = X86ISD::FMAX;
22914         break;
22915       case ISD::SETULE:
22916         // Converting this to a max would handle both negative zeros and NaNs
22917         // incorrectly, but we can swap the operands to fix both.
22918         std::swap(LHS, RHS);
22919       case ISD::SETOLT:
22920       case ISD::SETLT:
22921       case ISD::SETLE:
22922         Opcode = X86ISD::FMAX;
22923         break;
22924       }
22925     }
22926
22927     if (Opcode)
22928       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22929   }
22930
22931   EVT CondVT = Cond.getValueType();
22932   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22933       CondVT.getVectorElementType() == MVT::i1) {
22934     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22935     // lowering on KNL. In this case we convert it to
22936     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22937     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22938     // Since SKX these selects have a proper lowering.
22939     EVT OpVT = LHS.getValueType();
22940     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22941         (OpVT.getVectorElementType() == MVT::i8 ||
22942          OpVT.getVectorElementType() == MVT::i16) &&
22943         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22944       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22945       DCI.AddToWorklist(Cond.getNode());
22946       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22947     }
22948   }
22949   // If this is a select between two integer constants, try to do some
22950   // optimizations.
22951   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22952     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22953       // Don't do this for crazy integer types.
22954       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22955         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22956         // so that TrueC (the true value) is larger than FalseC.
22957         bool NeedsCondInvert = false;
22958
22959         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22960             // Efficiently invertible.
22961             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22962              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22963               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22964           NeedsCondInvert = true;
22965           std::swap(TrueC, FalseC);
22966         }
22967
22968         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22969         if (FalseC->getAPIntValue() == 0 &&
22970             TrueC->getAPIntValue().isPowerOf2()) {
22971           if (NeedsCondInvert) // Invert the condition if needed.
22972             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22973                                DAG.getConstant(1, Cond.getValueType()));
22974
22975           // Zero extend the condition if needed.
22976           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22977
22978           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22979           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22980                              DAG.getConstant(ShAmt, MVT::i8));
22981         }
22982
22983         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22984         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22985           if (NeedsCondInvert) // Invert the condition if needed.
22986             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22987                                DAG.getConstant(1, Cond.getValueType()));
22988
22989           // Zero extend the condition if needed.
22990           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22991                              FalseC->getValueType(0), Cond);
22992           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22993                              SDValue(FalseC, 0));
22994         }
22995
22996         // Optimize cases that will turn into an LEA instruction.  This requires
22997         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22998         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22999           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23000           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23001
23002           bool isFastMultiplier = false;
23003           if (Diff < 10) {
23004             switch ((unsigned char)Diff) {
23005               default: break;
23006               case 1:  // result = add base, cond
23007               case 2:  // result = lea base(    , cond*2)
23008               case 3:  // result = lea base(cond, cond*2)
23009               case 4:  // result = lea base(    , cond*4)
23010               case 5:  // result = lea base(cond, cond*4)
23011               case 8:  // result = lea base(    , cond*8)
23012               case 9:  // result = lea base(cond, cond*8)
23013                 isFastMultiplier = true;
23014                 break;
23015             }
23016           }
23017
23018           if (isFastMultiplier) {
23019             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23020             if (NeedsCondInvert) // Invert the condition if needed.
23021               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23022                                  DAG.getConstant(1, Cond.getValueType()));
23023
23024             // Zero extend the condition if needed.
23025             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23026                                Cond);
23027             // Scale the condition by the difference.
23028             if (Diff != 1)
23029               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23030                                  DAG.getConstant(Diff, Cond.getValueType()));
23031
23032             // Add the base if non-zero.
23033             if (FalseC->getAPIntValue() != 0)
23034               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23035                                  SDValue(FalseC, 0));
23036             return Cond;
23037           }
23038         }
23039       }
23040   }
23041
23042   // Canonicalize max and min:
23043   // (x > y) ? x : y -> (x >= y) ? x : y
23044   // (x < y) ? x : y -> (x <= y) ? x : y
23045   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23046   // the need for an extra compare
23047   // against zero. e.g.
23048   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23049   // subl   %esi, %edi
23050   // testl  %edi, %edi
23051   // movl   $0, %eax
23052   // cmovgl %edi, %eax
23053   // =>
23054   // xorl   %eax, %eax
23055   // subl   %esi, $edi
23056   // cmovsl %eax, %edi
23057   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23058       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23059       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23060     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23061     switch (CC) {
23062     default: break;
23063     case ISD::SETLT:
23064     case ISD::SETGT: {
23065       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23066       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23067                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23068       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23069     }
23070     }
23071   }
23072
23073   // Early exit check
23074   if (!TLI.isTypeLegal(VT))
23075     return SDValue();
23076
23077   // Match VSELECTs into subs with unsigned saturation.
23078   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23079       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23080       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23081        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23082     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23083
23084     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23085     // left side invert the predicate to simplify logic below.
23086     SDValue Other;
23087     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23088       Other = RHS;
23089       CC = ISD::getSetCCInverse(CC, true);
23090     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23091       Other = LHS;
23092     }
23093
23094     if (Other.getNode() && Other->getNumOperands() == 2 &&
23095         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23096       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23097       SDValue CondRHS = Cond->getOperand(1);
23098
23099       // Look for a general sub with unsigned saturation first.
23100       // x >= y ? x-y : 0 --> subus x, y
23101       // x >  y ? x-y : 0 --> subus x, y
23102       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23103           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23104         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23105
23106       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23107         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23108           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23109             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23110               // If the RHS is a constant we have to reverse the const
23111               // canonicalization.
23112               // x > C-1 ? x+-C : 0 --> subus x, C
23113               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23114                   CondRHSConst->getAPIntValue() ==
23115                       (-OpRHSConst->getAPIntValue() - 1))
23116                 return DAG.getNode(
23117                     X86ISD::SUBUS, DL, VT, OpLHS,
23118                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
23119
23120           // Another special case: If C was a sign bit, the sub has been
23121           // canonicalized into a xor.
23122           // FIXME: Would it be better to use computeKnownBits to determine
23123           //        whether it's safe to decanonicalize the xor?
23124           // x s< 0 ? x^C : 0 --> subus x, C
23125           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23126               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23127               OpRHSConst->getAPIntValue().isSignBit())
23128             // Note that we have to rebuild the RHS constant here to ensure we
23129             // don't rely on particular values of undef lanes.
23130             return DAG.getNode(
23131                 X86ISD::SUBUS, DL, VT, OpLHS,
23132                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
23133         }
23134     }
23135   }
23136
23137   // Try to match a min/max vector operation.
23138   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
23139     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
23140     unsigned Opc = ret.first;
23141     bool NeedSplit = ret.second;
23142
23143     if (Opc && NeedSplit) {
23144       unsigned NumElems = VT.getVectorNumElements();
23145       // Extract the LHS vectors
23146       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
23147       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
23148
23149       // Extract the RHS vectors
23150       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
23151       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
23152
23153       // Create min/max for each subvector
23154       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
23155       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
23156
23157       // Merge the result
23158       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
23159     } else if (Opc)
23160       return DAG.getNode(Opc, DL, VT, LHS, RHS);
23161   }
23162
23163   // Simplify vector selection if condition value type matches vselect
23164   // operand type
23165   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23166     assert(Cond.getValueType().isVector() &&
23167            "vector select expects a vector selector!");
23168
23169     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23170     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23171
23172     // Try invert the condition if true value is not all 1s and false value
23173     // is not all 0s.
23174     if (!TValIsAllOnes && !FValIsAllZeros &&
23175         // Check if the selector will be produced by CMPP*/PCMP*
23176         Cond.getOpcode() == ISD::SETCC &&
23177         // Check if SETCC has already been promoted
23178         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
23179       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23180       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23181
23182       if (TValIsAllZeros || FValIsAllOnes) {
23183         SDValue CC = Cond.getOperand(2);
23184         ISD::CondCode NewCC =
23185           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23186                                Cond.getOperand(0).getValueType().isInteger());
23187         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23188         std::swap(LHS, RHS);
23189         TValIsAllOnes = FValIsAllOnes;
23190         FValIsAllZeros = TValIsAllZeros;
23191       }
23192     }
23193
23194     if (TValIsAllOnes || FValIsAllZeros) {
23195       SDValue Ret;
23196
23197       if (TValIsAllOnes && FValIsAllZeros)
23198         Ret = Cond;
23199       else if (TValIsAllOnes)
23200         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
23201                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
23202       else if (FValIsAllZeros)
23203         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23204                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
23205
23206       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
23207     }
23208   }
23209
23210   // If we know that this node is legal then we know that it is going to be
23211   // matched by one of the SSE/AVX BLEND instructions. These instructions only
23212   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
23213   // to simplify previous instructions.
23214   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23215       !DCI.isBeforeLegalize() &&
23216       // We explicitly check against v8i16 and v16i16 because, although
23217       // they're marked as Custom, they might only be legal when Cond is a
23218       // build_vector of constants. This will be taken care in a later
23219       // condition.
23220       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
23221        VT != MVT::v8i16) &&
23222       // Don't optimize vector of constants. Those are handled by
23223       // the generic code and all the bits must be properly set for
23224       // the generic optimizer.
23225       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23226     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23227
23228     // Don't optimize vector selects that map to mask-registers.
23229     if (BitWidth == 1)
23230       return SDValue();
23231
23232     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23233     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23234
23235     APInt KnownZero, KnownOne;
23236     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23237                                           DCI.isBeforeLegalizeOps());
23238     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23239         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23240                                  TLO)) {
23241       // If we changed the computation somewhere in the DAG, this change
23242       // will affect all users of Cond.
23243       // Make sure it is fine and update all the nodes so that we do not
23244       // use the generic VSELECT anymore. Otherwise, we may perform
23245       // wrong optimizations as we messed up with the actual expectation
23246       // for the vector boolean values.
23247       if (Cond != TLO.Old) {
23248         // Check all uses of that condition operand to check whether it will be
23249         // consumed by non-BLEND instructions, which may depend on all bits are
23250         // set properly.
23251         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23252              I != E; ++I)
23253           if (I->getOpcode() != ISD::VSELECT)
23254             // TODO: Add other opcodes eventually lowered into BLEND.
23255             return SDValue();
23256
23257         // Update all the users of the condition, before committing the change,
23258         // so that the VSELECT optimizations that expect the correct vector
23259         // boolean value will not be triggered.
23260         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23261              I != E; ++I)
23262           DAG.ReplaceAllUsesOfValueWith(
23263               SDValue(*I, 0),
23264               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23265                           Cond, I->getOperand(1), I->getOperand(2)));
23266         DCI.CommitTargetLoweringOpt(TLO);
23267         return SDValue();
23268       }
23269       // At this point, only Cond is changed. Change the condition
23270       // just for N to keep the opportunity to optimize all other
23271       // users their own way.
23272       DAG.ReplaceAllUsesOfValueWith(
23273           SDValue(N, 0),
23274           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23275                       TLO.New, N->getOperand(1), N->getOperand(2)));
23276       return SDValue();
23277     }
23278   }
23279
23280   // We should generate an X86ISD::BLENDI from a vselect if its argument
23281   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23282   // constants. This specific pattern gets generated when we split a
23283   // selector for a 512 bit vector in a machine without AVX512 (but with
23284   // 256-bit vectors), during legalization:
23285   //
23286   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23287   //
23288   // Iff we find this pattern and the build_vectors are built from
23289   // constants, we translate the vselect into a shuffle_vector that we
23290   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23291   if ((N->getOpcode() == ISD::VSELECT ||
23292        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23293       !DCI.isBeforeLegalize()) {
23294     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23295     if (Shuffle.getNode())
23296       return Shuffle;
23297   }
23298
23299   return SDValue();
23300 }
23301
23302 // Check whether a boolean test is testing a boolean value generated by
23303 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23304 // code.
23305 //
23306 // Simplify the following patterns:
23307 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23308 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23309 // to (Op EFLAGS Cond)
23310 //
23311 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23312 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23313 // to (Op EFLAGS !Cond)
23314 //
23315 // where Op could be BRCOND or CMOV.
23316 //
23317 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23318   // Quit if not CMP and SUB with its value result used.
23319   if (Cmp.getOpcode() != X86ISD::CMP &&
23320       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23321       return SDValue();
23322
23323   // Quit if not used as a boolean value.
23324   if (CC != X86::COND_E && CC != X86::COND_NE)
23325     return SDValue();
23326
23327   // Check CMP operands. One of them should be 0 or 1 and the other should be
23328   // an SetCC or extended from it.
23329   SDValue Op1 = Cmp.getOperand(0);
23330   SDValue Op2 = Cmp.getOperand(1);
23331
23332   SDValue SetCC;
23333   const ConstantSDNode* C = nullptr;
23334   bool needOppositeCond = (CC == X86::COND_E);
23335   bool checkAgainstTrue = false; // Is it a comparison against 1?
23336
23337   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23338     SetCC = Op2;
23339   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23340     SetCC = Op1;
23341   else // Quit if all operands are not constants.
23342     return SDValue();
23343
23344   if (C->getZExtValue() == 1) {
23345     needOppositeCond = !needOppositeCond;
23346     checkAgainstTrue = true;
23347   } else if (C->getZExtValue() != 0)
23348     // Quit if the constant is neither 0 or 1.
23349     return SDValue();
23350
23351   bool truncatedToBoolWithAnd = false;
23352   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23353   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23354          SetCC.getOpcode() == ISD::TRUNCATE ||
23355          SetCC.getOpcode() == ISD::AND) {
23356     if (SetCC.getOpcode() == ISD::AND) {
23357       int OpIdx = -1;
23358       ConstantSDNode *CS;
23359       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23360           CS->getZExtValue() == 1)
23361         OpIdx = 1;
23362       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23363           CS->getZExtValue() == 1)
23364         OpIdx = 0;
23365       if (OpIdx == -1)
23366         break;
23367       SetCC = SetCC.getOperand(OpIdx);
23368       truncatedToBoolWithAnd = true;
23369     } else
23370       SetCC = SetCC.getOperand(0);
23371   }
23372
23373   switch (SetCC.getOpcode()) {
23374   case X86ISD::SETCC_CARRY:
23375     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23376     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23377     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23378     // truncated to i1 using 'and'.
23379     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23380       break;
23381     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23382            "Invalid use of SETCC_CARRY!");
23383     // FALL THROUGH
23384   case X86ISD::SETCC:
23385     // Set the condition code or opposite one if necessary.
23386     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23387     if (needOppositeCond)
23388       CC = X86::GetOppositeBranchCondition(CC);
23389     return SetCC.getOperand(1);
23390   case X86ISD::CMOV: {
23391     // Check whether false/true value has canonical one, i.e. 0 or 1.
23392     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23393     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23394     // Quit if true value is not a constant.
23395     if (!TVal)
23396       return SDValue();
23397     // Quit if false value is not a constant.
23398     if (!FVal) {
23399       SDValue Op = SetCC.getOperand(0);
23400       // Skip 'zext' or 'trunc' node.
23401       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23402           Op.getOpcode() == ISD::TRUNCATE)
23403         Op = Op.getOperand(0);
23404       // A special case for rdrand/rdseed, where 0 is set if false cond is
23405       // found.
23406       if ((Op.getOpcode() != X86ISD::RDRAND &&
23407            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23408         return SDValue();
23409     }
23410     // Quit if false value is not the constant 0 or 1.
23411     bool FValIsFalse = true;
23412     if (FVal && FVal->getZExtValue() != 0) {
23413       if (FVal->getZExtValue() != 1)
23414         return SDValue();
23415       // If FVal is 1, opposite cond is needed.
23416       needOppositeCond = !needOppositeCond;
23417       FValIsFalse = false;
23418     }
23419     // Quit if TVal is not the constant opposite of FVal.
23420     if (FValIsFalse && TVal->getZExtValue() != 1)
23421       return SDValue();
23422     if (!FValIsFalse && TVal->getZExtValue() != 0)
23423       return SDValue();
23424     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23425     if (needOppositeCond)
23426       CC = X86::GetOppositeBranchCondition(CC);
23427     return SetCC.getOperand(3);
23428   }
23429   }
23430
23431   return SDValue();
23432 }
23433
23434 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23435 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23436                                   TargetLowering::DAGCombinerInfo &DCI,
23437                                   const X86Subtarget *Subtarget) {
23438   SDLoc DL(N);
23439
23440   // If the flag operand isn't dead, don't touch this CMOV.
23441   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23442     return SDValue();
23443
23444   SDValue FalseOp = N->getOperand(0);
23445   SDValue TrueOp = N->getOperand(1);
23446   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23447   SDValue Cond = N->getOperand(3);
23448
23449   if (CC == X86::COND_E || CC == X86::COND_NE) {
23450     switch (Cond.getOpcode()) {
23451     default: break;
23452     case X86ISD::BSR:
23453     case X86ISD::BSF:
23454       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23455       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23456         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23457     }
23458   }
23459
23460   SDValue Flags;
23461
23462   Flags = checkBoolTestSetCCCombine(Cond, CC);
23463   if (Flags.getNode() &&
23464       // Extra check as FCMOV only supports a subset of X86 cond.
23465       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23466     SDValue Ops[] = { FalseOp, TrueOp,
23467                       DAG.getConstant(CC, MVT::i8), Flags };
23468     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23469   }
23470
23471   // If this is a select between two integer constants, try to do some
23472   // optimizations.  Note that the operands are ordered the opposite of SELECT
23473   // operands.
23474   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23475     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23476       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23477       // larger than FalseC (the false value).
23478       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23479         CC = X86::GetOppositeBranchCondition(CC);
23480         std::swap(TrueC, FalseC);
23481         std::swap(TrueOp, FalseOp);
23482       }
23483
23484       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23485       // This is efficient for any integer data type (including i8/i16) and
23486       // shift amount.
23487       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23488         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23489                            DAG.getConstant(CC, MVT::i8), Cond);
23490
23491         // Zero extend the condition if needed.
23492         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23493
23494         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23495         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23496                            DAG.getConstant(ShAmt, MVT::i8));
23497         if (N->getNumValues() == 2)  // Dead flag value?
23498           return DCI.CombineTo(N, Cond, SDValue());
23499         return Cond;
23500       }
23501
23502       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23503       // for any integer data type, including i8/i16.
23504       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23505         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23506                            DAG.getConstant(CC, MVT::i8), Cond);
23507
23508         // Zero extend the condition if needed.
23509         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23510                            FalseC->getValueType(0), Cond);
23511         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23512                            SDValue(FalseC, 0));
23513
23514         if (N->getNumValues() == 2)  // Dead flag value?
23515           return DCI.CombineTo(N, Cond, SDValue());
23516         return Cond;
23517       }
23518
23519       // Optimize cases that will turn into an LEA instruction.  This requires
23520       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23521       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23522         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23523         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23524
23525         bool isFastMultiplier = false;
23526         if (Diff < 10) {
23527           switch ((unsigned char)Diff) {
23528           default: break;
23529           case 1:  // result = add base, cond
23530           case 2:  // result = lea base(    , cond*2)
23531           case 3:  // result = lea base(cond, cond*2)
23532           case 4:  // result = lea base(    , cond*4)
23533           case 5:  // result = lea base(cond, cond*4)
23534           case 8:  // result = lea base(    , cond*8)
23535           case 9:  // result = lea base(cond, cond*8)
23536             isFastMultiplier = true;
23537             break;
23538           }
23539         }
23540
23541         if (isFastMultiplier) {
23542           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23543           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23544                              DAG.getConstant(CC, MVT::i8), Cond);
23545           // Zero extend the condition if needed.
23546           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23547                              Cond);
23548           // Scale the condition by the difference.
23549           if (Diff != 1)
23550             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23551                                DAG.getConstant(Diff, Cond.getValueType()));
23552
23553           // Add the base if non-zero.
23554           if (FalseC->getAPIntValue() != 0)
23555             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23556                                SDValue(FalseC, 0));
23557           if (N->getNumValues() == 2)  // Dead flag value?
23558             return DCI.CombineTo(N, Cond, SDValue());
23559           return Cond;
23560         }
23561       }
23562     }
23563   }
23564
23565   // Handle these cases:
23566   //   (select (x != c), e, c) -> select (x != c), e, x),
23567   //   (select (x == c), c, e) -> select (x == c), x, e)
23568   // where the c is an integer constant, and the "select" is the combination
23569   // of CMOV and CMP.
23570   //
23571   // The rationale for this change is that the conditional-move from a constant
23572   // needs two instructions, however, conditional-move from a register needs
23573   // only one instruction.
23574   //
23575   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23576   //  some instruction-combining opportunities. This opt needs to be
23577   //  postponed as late as possible.
23578   //
23579   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23580     // the DCI.xxxx conditions are provided to postpone the optimization as
23581     // late as possible.
23582
23583     ConstantSDNode *CmpAgainst = nullptr;
23584     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23585         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23586         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23587
23588       if (CC == X86::COND_NE &&
23589           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23590         CC = X86::GetOppositeBranchCondition(CC);
23591         std::swap(TrueOp, FalseOp);
23592       }
23593
23594       if (CC == X86::COND_E &&
23595           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23596         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23597                           DAG.getConstant(CC, MVT::i8), Cond };
23598         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23599       }
23600     }
23601   }
23602
23603   return SDValue();
23604 }
23605
23606 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23607                                                 const X86Subtarget *Subtarget) {
23608   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23609   switch (IntNo) {
23610   default: return SDValue();
23611   // SSE/AVX/AVX2 blend intrinsics.
23612   case Intrinsic::x86_avx2_pblendvb:
23613   case Intrinsic::x86_avx2_pblendw:
23614   case Intrinsic::x86_avx2_pblendd_128:
23615   case Intrinsic::x86_avx2_pblendd_256:
23616     // Don't try to simplify this intrinsic if we don't have AVX2.
23617     if (!Subtarget->hasAVX2())
23618       return SDValue();
23619     // FALL-THROUGH
23620   case Intrinsic::x86_avx_blend_pd_256:
23621   case Intrinsic::x86_avx_blend_ps_256:
23622   case Intrinsic::x86_avx_blendv_pd_256:
23623   case Intrinsic::x86_avx_blendv_ps_256:
23624     // Don't try to simplify this intrinsic if we don't have AVX.
23625     if (!Subtarget->hasAVX())
23626       return SDValue();
23627     // FALL-THROUGH
23628   case Intrinsic::x86_sse41_pblendw:
23629   case Intrinsic::x86_sse41_blendpd:
23630   case Intrinsic::x86_sse41_blendps:
23631   case Intrinsic::x86_sse41_blendvps:
23632   case Intrinsic::x86_sse41_blendvpd:
23633   case Intrinsic::x86_sse41_pblendvb: {
23634     SDValue Op0 = N->getOperand(1);
23635     SDValue Op1 = N->getOperand(2);
23636     SDValue Mask = N->getOperand(3);
23637
23638     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23639     if (!Subtarget->hasSSE41())
23640       return SDValue();
23641
23642     // fold (blend A, A, Mask) -> A
23643     if (Op0 == Op1)
23644       return Op0;
23645     // fold (blend A, B, allZeros) -> A
23646     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23647       return Op0;
23648     // fold (blend A, B, allOnes) -> B
23649     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23650       return Op1;
23651
23652     // Simplify the case where the mask is a constant i32 value.
23653     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23654       if (C->isNullValue())
23655         return Op0;
23656       if (C->isAllOnesValue())
23657         return Op1;
23658     }
23659
23660     return SDValue();
23661   }
23662
23663   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23664   case Intrinsic::x86_sse2_psrai_w:
23665   case Intrinsic::x86_sse2_psrai_d:
23666   case Intrinsic::x86_avx2_psrai_w:
23667   case Intrinsic::x86_avx2_psrai_d:
23668   case Intrinsic::x86_sse2_psra_w:
23669   case Intrinsic::x86_sse2_psra_d:
23670   case Intrinsic::x86_avx2_psra_w:
23671   case Intrinsic::x86_avx2_psra_d: {
23672     SDValue Op0 = N->getOperand(1);
23673     SDValue Op1 = N->getOperand(2);
23674     EVT VT = Op0.getValueType();
23675     assert(VT.isVector() && "Expected a vector type!");
23676
23677     if (isa<BuildVectorSDNode>(Op1))
23678       Op1 = Op1.getOperand(0);
23679
23680     if (!isa<ConstantSDNode>(Op1))
23681       return SDValue();
23682
23683     EVT SVT = VT.getVectorElementType();
23684     unsigned SVTBits = SVT.getSizeInBits();
23685
23686     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23687     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23688     uint64_t ShAmt = C.getZExtValue();
23689
23690     // Don't try to convert this shift into a ISD::SRA if the shift
23691     // count is bigger than or equal to the element size.
23692     if (ShAmt >= SVTBits)
23693       return SDValue();
23694
23695     // Trivial case: if the shift count is zero, then fold this
23696     // into the first operand.
23697     if (ShAmt == 0)
23698       return Op0;
23699
23700     // Replace this packed shift intrinsic with a target independent
23701     // shift dag node.
23702     SDValue Splat = DAG.getConstant(C, VT);
23703     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
23704   }
23705   }
23706 }
23707
23708 /// PerformMulCombine - Optimize a single multiply with constant into two
23709 /// in order to implement it with two cheaper instructions, e.g.
23710 /// LEA + SHL, LEA + LEA.
23711 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23712                                  TargetLowering::DAGCombinerInfo &DCI) {
23713   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23714     return SDValue();
23715
23716   EVT VT = N->getValueType(0);
23717   if (VT != MVT::i64)
23718     return SDValue();
23719
23720   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23721   if (!C)
23722     return SDValue();
23723   uint64_t MulAmt = C->getZExtValue();
23724   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23725     return SDValue();
23726
23727   uint64_t MulAmt1 = 0;
23728   uint64_t MulAmt2 = 0;
23729   if ((MulAmt % 9) == 0) {
23730     MulAmt1 = 9;
23731     MulAmt2 = MulAmt / 9;
23732   } else if ((MulAmt % 5) == 0) {
23733     MulAmt1 = 5;
23734     MulAmt2 = MulAmt / 5;
23735   } else if ((MulAmt % 3) == 0) {
23736     MulAmt1 = 3;
23737     MulAmt2 = MulAmt / 3;
23738   }
23739   if (MulAmt2 &&
23740       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23741     SDLoc DL(N);
23742
23743     if (isPowerOf2_64(MulAmt2) &&
23744         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23745       // If second multiplifer is pow2, issue it first. We want the multiply by
23746       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23747       // is an add.
23748       std::swap(MulAmt1, MulAmt2);
23749
23750     SDValue NewMul;
23751     if (isPowerOf2_64(MulAmt1))
23752       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23753                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
23754     else
23755       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23756                            DAG.getConstant(MulAmt1, VT));
23757
23758     if (isPowerOf2_64(MulAmt2))
23759       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23760                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
23761     else
23762       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23763                            DAG.getConstant(MulAmt2, VT));
23764
23765     // Do not add new nodes to DAG combiner worklist.
23766     DCI.CombineTo(N, NewMul, false);
23767   }
23768   return SDValue();
23769 }
23770
23771 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23772   SDValue N0 = N->getOperand(0);
23773   SDValue N1 = N->getOperand(1);
23774   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23775   EVT VT = N0.getValueType();
23776
23777   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23778   // since the result of setcc_c is all zero's or all ones.
23779   if (VT.isInteger() && !VT.isVector() &&
23780       N1C && N0.getOpcode() == ISD::AND &&
23781       N0.getOperand(1).getOpcode() == ISD::Constant) {
23782     SDValue N00 = N0.getOperand(0);
23783     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23784         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23785           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23786          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23787       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23788       APInt ShAmt = N1C->getAPIntValue();
23789       Mask = Mask.shl(ShAmt);
23790       if (Mask != 0)
23791         return DAG.getNode(ISD::AND, SDLoc(N), VT,
23792                            N00, DAG.getConstant(Mask, VT));
23793     }
23794   }
23795
23796   // Hardware support for vector shifts is sparse which makes us scalarize the
23797   // vector operations in many cases. Also, on sandybridge ADD is faster than
23798   // shl.
23799   // (shl V, 1) -> add V,V
23800   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23801     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23802       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23803       // We shift all of the values by one. In many cases we do not have
23804       // hardware support for this operation. This is better expressed as an ADD
23805       // of two values.
23806       if (N1SplatC->getZExtValue() == 1)
23807         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23808     }
23809
23810   return SDValue();
23811 }
23812
23813 /// \brief Returns a vector of 0s if the node in input is a vector logical
23814 /// shift by a constant amount which is known to be bigger than or equal
23815 /// to the vector element size in bits.
23816 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23817                                       const X86Subtarget *Subtarget) {
23818   EVT VT = N->getValueType(0);
23819
23820   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23821       (!Subtarget->hasInt256() ||
23822        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23823     return SDValue();
23824
23825   SDValue Amt = N->getOperand(1);
23826   SDLoc DL(N);
23827   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23828     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23829       APInt ShiftAmt = AmtSplat->getAPIntValue();
23830       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23831
23832       // SSE2/AVX2 logical shifts always return a vector of 0s
23833       // if the shift amount is bigger than or equal to
23834       // the element size. The constant shift amount will be
23835       // encoded as a 8-bit immediate.
23836       if (ShiftAmt.trunc(8).uge(MaxAmount))
23837         return getZeroVector(VT, Subtarget, DAG, DL);
23838     }
23839
23840   return SDValue();
23841 }
23842
23843 /// PerformShiftCombine - Combine shifts.
23844 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23845                                    TargetLowering::DAGCombinerInfo &DCI,
23846                                    const X86Subtarget *Subtarget) {
23847   if (N->getOpcode() == ISD::SHL) {
23848     SDValue V = PerformSHLCombine(N, DAG);
23849     if (V.getNode()) return V;
23850   }
23851
23852   if (N->getOpcode() != ISD::SRA) {
23853     // Try to fold this logical shift into a zero vector.
23854     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
23855     if (V.getNode()) return V;
23856   }
23857
23858   return SDValue();
23859 }
23860
23861 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23862 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23863 // and friends.  Likewise for OR -> CMPNEQSS.
23864 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23865                             TargetLowering::DAGCombinerInfo &DCI,
23866                             const X86Subtarget *Subtarget) {
23867   unsigned opcode;
23868
23869   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23870   // we're requiring SSE2 for both.
23871   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23872     SDValue N0 = N->getOperand(0);
23873     SDValue N1 = N->getOperand(1);
23874     SDValue CMP0 = N0->getOperand(1);
23875     SDValue CMP1 = N1->getOperand(1);
23876     SDLoc DL(N);
23877
23878     // The SETCCs should both refer to the same CMP.
23879     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23880       return SDValue();
23881
23882     SDValue CMP00 = CMP0->getOperand(0);
23883     SDValue CMP01 = CMP0->getOperand(1);
23884     EVT     VT    = CMP00.getValueType();
23885
23886     if (VT == MVT::f32 || VT == MVT::f64) {
23887       bool ExpectingFlags = false;
23888       // Check for any users that want flags:
23889       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23890            !ExpectingFlags && UI != UE; ++UI)
23891         switch (UI->getOpcode()) {
23892         default:
23893         case ISD::BR_CC:
23894         case ISD::BRCOND:
23895         case ISD::SELECT:
23896           ExpectingFlags = true;
23897           break;
23898         case ISD::CopyToReg:
23899         case ISD::SIGN_EXTEND:
23900         case ISD::ZERO_EXTEND:
23901         case ISD::ANY_EXTEND:
23902           break;
23903         }
23904
23905       if (!ExpectingFlags) {
23906         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23907         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23908
23909         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23910           X86::CondCode tmp = cc0;
23911           cc0 = cc1;
23912           cc1 = tmp;
23913         }
23914
23915         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23916             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23917           // FIXME: need symbolic constants for these magic numbers.
23918           // See X86ATTInstPrinter.cpp:printSSECC().
23919           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23920           if (Subtarget->hasAVX512()) {
23921             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23922                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
23923             if (N->getValueType(0) != MVT::i1)
23924               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23925                                  FSetCC);
23926             return FSetCC;
23927           }
23928           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23929                                               CMP00.getValueType(), CMP00, CMP01,
23930                                               DAG.getConstant(x86cc, MVT::i8));
23931
23932           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23933           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23934
23935           if (is64BitFP && !Subtarget->is64Bit()) {
23936             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23937             // 64-bit integer, since that's not a legal type. Since
23938             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23939             // bits, but can do this little dance to extract the lowest 32 bits
23940             // and work with those going forward.
23941             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23942                                            OnesOrZeroesF);
23943             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
23944                                            Vector64);
23945             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23946                                         Vector32, DAG.getIntPtrConstant(0));
23947             IntVT = MVT::i32;
23948           }
23949
23950           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
23951           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23952                                       DAG.getConstant(1, IntVT));
23953           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
23954           return OneBitOfTruth;
23955         }
23956       }
23957     }
23958   }
23959   return SDValue();
23960 }
23961
23962 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23963 /// so it can be folded inside ANDNP.
23964 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23965   EVT VT = N->getValueType(0);
23966
23967   // Match direct AllOnes for 128 and 256-bit vectors
23968   if (ISD::isBuildVectorAllOnes(N))
23969     return true;
23970
23971   // Look through a bit convert.
23972   if (N->getOpcode() == ISD::BITCAST)
23973     N = N->getOperand(0).getNode();
23974
23975   // Sometimes the operand may come from a insert_subvector building a 256-bit
23976   // allones vector
23977   if (VT.is256BitVector() &&
23978       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23979     SDValue V1 = N->getOperand(0);
23980     SDValue V2 = N->getOperand(1);
23981
23982     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23983         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23984         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23985         ISD::isBuildVectorAllOnes(V2.getNode()))
23986       return true;
23987   }
23988
23989   return false;
23990 }
23991
23992 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23993 // register. In most cases we actually compare or select YMM-sized registers
23994 // and mixing the two types creates horrible code. This method optimizes
23995 // some of the transition sequences.
23996 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23997                                  TargetLowering::DAGCombinerInfo &DCI,
23998                                  const X86Subtarget *Subtarget) {
23999   EVT VT = N->getValueType(0);
24000   if (!VT.is256BitVector())
24001     return SDValue();
24002
24003   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24004           N->getOpcode() == ISD::ZERO_EXTEND ||
24005           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24006
24007   SDValue Narrow = N->getOperand(0);
24008   EVT NarrowVT = Narrow->getValueType(0);
24009   if (!NarrowVT.is128BitVector())
24010     return SDValue();
24011
24012   if (Narrow->getOpcode() != ISD::XOR &&
24013       Narrow->getOpcode() != ISD::AND &&
24014       Narrow->getOpcode() != ISD::OR)
24015     return SDValue();
24016
24017   SDValue N0  = Narrow->getOperand(0);
24018   SDValue N1  = Narrow->getOperand(1);
24019   SDLoc DL(Narrow);
24020
24021   // The Left side has to be a trunc.
24022   if (N0.getOpcode() != ISD::TRUNCATE)
24023     return SDValue();
24024
24025   // The type of the truncated inputs.
24026   EVT WideVT = N0->getOperand(0)->getValueType(0);
24027   if (WideVT != VT)
24028     return SDValue();
24029
24030   // The right side has to be a 'trunc' or a constant vector.
24031   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24032   ConstantSDNode *RHSConstSplat = nullptr;
24033   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24034     RHSConstSplat = RHSBV->getConstantSplatNode();
24035   if (!RHSTrunc && !RHSConstSplat)
24036     return SDValue();
24037
24038   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24039
24040   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24041     return SDValue();
24042
24043   // Set N0 and N1 to hold the inputs to the new wide operation.
24044   N0 = N0->getOperand(0);
24045   if (RHSConstSplat) {
24046     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24047                      SDValue(RHSConstSplat, 0));
24048     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24049     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24050   } else if (RHSTrunc) {
24051     N1 = N1->getOperand(0);
24052   }
24053
24054   // Generate the wide operation.
24055   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24056   unsigned Opcode = N->getOpcode();
24057   switch (Opcode) {
24058   case ISD::ANY_EXTEND:
24059     return Op;
24060   case ISD::ZERO_EXTEND: {
24061     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24062     APInt Mask = APInt::getAllOnesValue(InBits);
24063     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24064     return DAG.getNode(ISD::AND, DL, VT,
24065                        Op, DAG.getConstant(Mask, VT));
24066   }
24067   case ISD::SIGN_EXTEND:
24068     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24069                        Op, DAG.getValueType(NarrowVT));
24070   default:
24071     llvm_unreachable("Unexpected opcode");
24072   }
24073 }
24074
24075 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24076                                  TargetLowering::DAGCombinerInfo &DCI,
24077                                  const X86Subtarget *Subtarget) {
24078   EVT VT = N->getValueType(0);
24079   if (DCI.isBeforeLegalizeOps())
24080     return SDValue();
24081
24082   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24083   if (R.getNode())
24084     return R;
24085
24086   // Create BEXTR instructions
24087   // BEXTR is ((X >> imm) & (2**size-1))
24088   if (VT == MVT::i32 || VT == MVT::i64) {
24089     SDValue N0 = N->getOperand(0);
24090     SDValue N1 = N->getOperand(1);
24091     SDLoc DL(N);
24092
24093     // Check for BEXTR.
24094     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24095         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24096       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24097       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24098       if (MaskNode && ShiftNode) {
24099         uint64_t Mask = MaskNode->getZExtValue();
24100         uint64_t Shift = ShiftNode->getZExtValue();
24101         if (isMask_64(Mask)) {
24102           uint64_t MaskSize = CountPopulation_64(Mask);
24103           if (Shift + MaskSize <= VT.getSizeInBits())
24104             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24105                                DAG.getConstant(Shift | (MaskSize << 8), VT));
24106         }
24107       }
24108     } // BEXTR
24109
24110     return SDValue();
24111   }
24112
24113   // Want to form ANDNP nodes:
24114   // 1) In the hopes of then easily combining them with OR and AND nodes
24115   //    to form PBLEND/PSIGN.
24116   // 2) To match ANDN packed intrinsics
24117   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24118     return SDValue();
24119
24120   SDValue N0 = N->getOperand(0);
24121   SDValue N1 = N->getOperand(1);
24122   SDLoc DL(N);
24123
24124   // Check LHS for vnot
24125   if (N0.getOpcode() == ISD::XOR &&
24126       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24127       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24128     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24129
24130   // Check RHS for vnot
24131   if (N1.getOpcode() == ISD::XOR &&
24132       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24133       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24134     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24135
24136   return SDValue();
24137 }
24138
24139 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24140                                 TargetLowering::DAGCombinerInfo &DCI,
24141                                 const X86Subtarget *Subtarget) {
24142   if (DCI.isBeforeLegalizeOps())
24143     return SDValue();
24144
24145   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24146   if (R.getNode())
24147     return R;
24148
24149   SDValue N0 = N->getOperand(0);
24150   SDValue N1 = N->getOperand(1);
24151   EVT VT = N->getValueType(0);
24152
24153   // look for psign/blend
24154   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24155     if (!Subtarget->hasSSSE3() ||
24156         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24157       return SDValue();
24158
24159     // Canonicalize pandn to RHS
24160     if (N0.getOpcode() == X86ISD::ANDNP)
24161       std::swap(N0, N1);
24162     // or (and (m, y), (pandn m, x))
24163     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24164       SDValue Mask = N1.getOperand(0);
24165       SDValue X    = N1.getOperand(1);
24166       SDValue Y;
24167       if (N0.getOperand(0) == Mask)
24168         Y = N0.getOperand(1);
24169       if (N0.getOperand(1) == Mask)
24170         Y = N0.getOperand(0);
24171
24172       // Check to see if the mask appeared in both the AND and ANDNP and
24173       if (!Y.getNode())
24174         return SDValue();
24175
24176       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24177       // Look through mask bitcast.
24178       if (Mask.getOpcode() == ISD::BITCAST)
24179         Mask = Mask.getOperand(0);
24180       if (X.getOpcode() == ISD::BITCAST)
24181         X = X.getOperand(0);
24182       if (Y.getOpcode() == ISD::BITCAST)
24183         Y = Y.getOperand(0);
24184
24185       EVT MaskVT = Mask.getValueType();
24186
24187       // Validate that the Mask operand is a vector sra node.
24188       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24189       // there is no psrai.b
24190       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24191       unsigned SraAmt = ~0;
24192       if (Mask.getOpcode() == ISD::SRA) {
24193         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24194           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24195             SraAmt = AmtConst->getZExtValue();
24196       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24197         SDValue SraC = Mask.getOperand(1);
24198         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24199       }
24200       if ((SraAmt + 1) != EltBits)
24201         return SDValue();
24202
24203       SDLoc DL(N);
24204
24205       // Now we know we at least have a plendvb with the mask val.  See if
24206       // we can form a psignb/w/d.
24207       // psign = x.type == y.type == mask.type && y = sub(0, x);
24208       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24209           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24210           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24211         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24212                "Unsupported VT for PSIGN");
24213         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24214         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24215       }
24216       // PBLENDVB only available on SSE 4.1
24217       if (!Subtarget->hasSSE41())
24218         return SDValue();
24219
24220       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24221
24222       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
24223       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
24224       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
24225       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24226       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24227     }
24228   }
24229
24230   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24231     return SDValue();
24232
24233   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24234   MachineFunction &MF = DAG.getMachineFunction();
24235   bool OptForSize = MF.getFunction()->getAttributes().
24236     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
24237
24238   // SHLD/SHRD instructions have lower register pressure, but on some
24239   // platforms they have higher latency than the equivalent
24240   // series of shifts/or that would otherwise be generated.
24241   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24242   // have higher latencies and we are not optimizing for size.
24243   if (!OptForSize && Subtarget->isSHLDSlow())
24244     return SDValue();
24245
24246   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24247     std::swap(N0, N1);
24248   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24249     return SDValue();
24250   if (!N0.hasOneUse() || !N1.hasOneUse())
24251     return SDValue();
24252
24253   SDValue ShAmt0 = N0.getOperand(1);
24254   if (ShAmt0.getValueType() != MVT::i8)
24255     return SDValue();
24256   SDValue ShAmt1 = N1.getOperand(1);
24257   if (ShAmt1.getValueType() != MVT::i8)
24258     return SDValue();
24259   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24260     ShAmt0 = ShAmt0.getOperand(0);
24261   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24262     ShAmt1 = ShAmt1.getOperand(0);
24263
24264   SDLoc DL(N);
24265   unsigned Opc = X86ISD::SHLD;
24266   SDValue Op0 = N0.getOperand(0);
24267   SDValue Op1 = N1.getOperand(0);
24268   if (ShAmt0.getOpcode() == ISD::SUB) {
24269     Opc = X86ISD::SHRD;
24270     std::swap(Op0, Op1);
24271     std::swap(ShAmt0, ShAmt1);
24272   }
24273
24274   unsigned Bits = VT.getSizeInBits();
24275   if (ShAmt1.getOpcode() == ISD::SUB) {
24276     SDValue Sum = ShAmt1.getOperand(0);
24277     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24278       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24279       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24280         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24281       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24282         return DAG.getNode(Opc, DL, VT,
24283                            Op0, Op1,
24284                            DAG.getNode(ISD::TRUNCATE, DL,
24285                                        MVT::i8, ShAmt0));
24286     }
24287   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24288     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24289     if (ShAmt0C &&
24290         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24291       return DAG.getNode(Opc, DL, VT,
24292                          N0.getOperand(0), N1.getOperand(0),
24293                          DAG.getNode(ISD::TRUNCATE, DL,
24294                                        MVT::i8, ShAmt0));
24295   }
24296
24297   return SDValue();
24298 }
24299
24300 // Generate NEG and CMOV for integer abs.
24301 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24302   EVT VT = N->getValueType(0);
24303
24304   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24305   // 8-bit integer abs to NEG and CMOV.
24306   if (VT.isInteger() && VT.getSizeInBits() == 8)
24307     return SDValue();
24308
24309   SDValue N0 = N->getOperand(0);
24310   SDValue N1 = N->getOperand(1);
24311   SDLoc DL(N);
24312
24313   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24314   // and change it to SUB and CMOV.
24315   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24316       N0.getOpcode() == ISD::ADD &&
24317       N0.getOperand(1) == N1 &&
24318       N1.getOpcode() == ISD::SRA &&
24319       N1.getOperand(0) == N0.getOperand(0))
24320     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24321       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24322         // Generate SUB & CMOV.
24323         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24324                                   DAG.getConstant(0, VT), N0.getOperand(0));
24325
24326         SDValue Ops[] = { N0.getOperand(0), Neg,
24327                           DAG.getConstant(X86::COND_GE, MVT::i8),
24328                           SDValue(Neg.getNode(), 1) };
24329         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24330       }
24331   return SDValue();
24332 }
24333
24334 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24335 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24336                                  TargetLowering::DAGCombinerInfo &DCI,
24337                                  const X86Subtarget *Subtarget) {
24338   if (DCI.isBeforeLegalizeOps())
24339     return SDValue();
24340
24341   if (Subtarget->hasCMov()) {
24342     SDValue RV = performIntegerAbsCombine(N, DAG);
24343     if (RV.getNode())
24344       return RV;
24345   }
24346
24347   return SDValue();
24348 }
24349
24350 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24351 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24352                                   TargetLowering::DAGCombinerInfo &DCI,
24353                                   const X86Subtarget *Subtarget) {
24354   LoadSDNode *Ld = cast<LoadSDNode>(N);
24355   EVT RegVT = Ld->getValueType(0);
24356   EVT MemVT = Ld->getMemoryVT();
24357   SDLoc dl(Ld);
24358   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24359
24360   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24361   // into two 16-byte operations.
24362   ISD::LoadExtType Ext = Ld->getExtensionType();
24363   unsigned Alignment = Ld->getAlignment();
24364   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24365   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24366       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24367     unsigned NumElems = RegVT.getVectorNumElements();
24368     if (NumElems < 2)
24369       return SDValue();
24370
24371     SDValue Ptr = Ld->getBasePtr();
24372     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
24373
24374     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24375                                   NumElems/2);
24376     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24377                                 Ld->getPointerInfo(), Ld->isVolatile(),
24378                                 Ld->isNonTemporal(), Ld->isInvariant(),
24379                                 Alignment);
24380     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24381     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24382                                 Ld->getPointerInfo(), Ld->isVolatile(),
24383                                 Ld->isNonTemporal(), Ld->isInvariant(),
24384                                 std::min(16U, Alignment));
24385     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24386                              Load1.getValue(1),
24387                              Load2.getValue(1));
24388
24389     SDValue NewVec = DAG.getUNDEF(RegVT);
24390     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24391     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24392     return DCI.CombineTo(N, NewVec, TF, true);
24393   }
24394
24395   return SDValue();
24396 }
24397
24398 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24399 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24400                                    const X86Subtarget *Subtarget) {
24401   StoreSDNode *St = cast<StoreSDNode>(N);
24402   EVT VT = St->getValue().getValueType();
24403   EVT StVT = St->getMemoryVT();
24404   SDLoc dl(St);
24405   SDValue StoredVal = St->getOperand(1);
24406   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24407
24408   // If we are saving a concatenation of two XMM registers and 32-byte stores
24409   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24410   unsigned Alignment = St->getAlignment();
24411   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24412   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24413       StVT == VT && !IsAligned) {
24414     unsigned NumElems = VT.getVectorNumElements();
24415     if (NumElems < 2)
24416       return SDValue();
24417
24418     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24419     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24420
24421     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
24422     SDValue Ptr0 = St->getBasePtr();
24423     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24424
24425     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24426                                 St->getPointerInfo(), St->isVolatile(),
24427                                 St->isNonTemporal(), Alignment);
24428     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24429                                 St->getPointerInfo(), St->isVolatile(),
24430                                 St->isNonTemporal(),
24431                                 std::min(16U, Alignment));
24432     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24433   }
24434
24435   // Optimize trunc store (of multiple scalars) to shuffle and store.
24436   // First, pack all of the elements in one place. Next, store to memory
24437   // in fewer chunks.
24438   if (St->isTruncatingStore() && VT.isVector()) {
24439     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24440     unsigned NumElems = VT.getVectorNumElements();
24441     assert(StVT != VT && "Cannot truncate to the same type");
24442     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24443     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24444
24445     // From, To sizes and ElemCount must be pow of two
24446     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24447     // We are going to use the original vector elt for storing.
24448     // Accumulated smaller vector elements must be a multiple of the store size.
24449     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24450
24451     unsigned SizeRatio  = FromSz / ToSz;
24452
24453     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24454
24455     // Create a type on which we perform the shuffle
24456     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24457             StVT.getScalarType(), NumElems*SizeRatio);
24458
24459     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24460
24461     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
24462     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24463     for (unsigned i = 0; i != NumElems; ++i)
24464       ShuffleVec[i] = i * SizeRatio;
24465
24466     // Can't shuffle using an illegal type.
24467     if (!TLI.isTypeLegal(WideVecVT))
24468       return SDValue();
24469
24470     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24471                                          DAG.getUNDEF(WideVecVT),
24472                                          &ShuffleVec[0]);
24473     // At this point all of the data is stored at the bottom of the
24474     // register. We now need to save it to mem.
24475
24476     // Find the largest store unit
24477     MVT StoreType = MVT::i8;
24478     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
24479          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
24480       MVT Tp = (MVT::SimpleValueType)tp;
24481       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24482         StoreType = Tp;
24483     }
24484
24485     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24486     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24487         (64 <= NumElems * ToSz))
24488       StoreType = MVT::f64;
24489
24490     // Bitcast the original vector into a vector of store-size units
24491     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24492             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24493     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24494     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
24495     SmallVector<SDValue, 8> Chains;
24496     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
24497                                         TLI.getPointerTy());
24498     SDValue Ptr = St->getBasePtr();
24499
24500     // Perform one or more big stores into memory.
24501     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24502       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24503                                    StoreType, ShuffWide,
24504                                    DAG.getIntPtrConstant(i));
24505       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24506                                 St->getPointerInfo(), St->isVolatile(),
24507                                 St->isNonTemporal(), St->getAlignment());
24508       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24509       Chains.push_back(Ch);
24510     }
24511
24512     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24513   }
24514
24515   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24516   // the FP state in cases where an emms may be missing.
24517   // A preferable solution to the general problem is to figure out the right
24518   // places to insert EMMS.  This qualifies as a quick hack.
24519
24520   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24521   if (VT.getSizeInBits() != 64)
24522     return SDValue();
24523
24524   const Function *F = DAG.getMachineFunction().getFunction();
24525   bool NoImplicitFloatOps = F->getAttributes().
24526     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
24527   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
24528                      && Subtarget->hasSSE2();
24529   if ((VT.isVector() ||
24530        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24531       isa<LoadSDNode>(St->getValue()) &&
24532       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24533       St->getChain().hasOneUse() && !St->isVolatile()) {
24534     SDNode* LdVal = St->getValue().getNode();
24535     LoadSDNode *Ld = nullptr;
24536     int TokenFactorIndex = -1;
24537     SmallVector<SDValue, 8> Ops;
24538     SDNode* ChainVal = St->getChain().getNode();
24539     // Must be a store of a load.  We currently handle two cases:  the load
24540     // is a direct child, and it's under an intervening TokenFactor.  It is
24541     // possible to dig deeper under nested TokenFactors.
24542     if (ChainVal == LdVal)
24543       Ld = cast<LoadSDNode>(St->getChain());
24544     else if (St->getValue().hasOneUse() &&
24545              ChainVal->getOpcode() == ISD::TokenFactor) {
24546       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24547         if (ChainVal->getOperand(i).getNode() == LdVal) {
24548           TokenFactorIndex = i;
24549           Ld = cast<LoadSDNode>(St->getValue());
24550         } else
24551           Ops.push_back(ChainVal->getOperand(i));
24552       }
24553     }
24554
24555     if (!Ld || !ISD::isNormalLoad(Ld))
24556       return SDValue();
24557
24558     // If this is not the MMX case, i.e. we are just turning i64 load/store
24559     // into f64 load/store, avoid the transformation if there are multiple
24560     // uses of the loaded value.
24561     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24562       return SDValue();
24563
24564     SDLoc LdDL(Ld);
24565     SDLoc StDL(N);
24566     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24567     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24568     // pair instead.
24569     if (Subtarget->is64Bit() || F64IsLegal) {
24570       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24571       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24572                                   Ld->getPointerInfo(), Ld->isVolatile(),
24573                                   Ld->isNonTemporal(), Ld->isInvariant(),
24574                                   Ld->getAlignment());
24575       SDValue NewChain = NewLd.getValue(1);
24576       if (TokenFactorIndex != -1) {
24577         Ops.push_back(NewChain);
24578         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24579       }
24580       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24581                           St->getPointerInfo(),
24582                           St->isVolatile(), St->isNonTemporal(),
24583                           St->getAlignment());
24584     }
24585
24586     // Otherwise, lower to two pairs of 32-bit loads / stores.
24587     SDValue LoAddr = Ld->getBasePtr();
24588     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24589                                  DAG.getConstant(4, MVT::i32));
24590
24591     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24592                                Ld->getPointerInfo(),
24593                                Ld->isVolatile(), Ld->isNonTemporal(),
24594                                Ld->isInvariant(), Ld->getAlignment());
24595     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24596                                Ld->getPointerInfo().getWithOffset(4),
24597                                Ld->isVolatile(), Ld->isNonTemporal(),
24598                                Ld->isInvariant(),
24599                                MinAlign(Ld->getAlignment(), 4));
24600
24601     SDValue NewChain = LoLd.getValue(1);
24602     if (TokenFactorIndex != -1) {
24603       Ops.push_back(LoLd);
24604       Ops.push_back(HiLd);
24605       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24606     }
24607
24608     LoAddr = St->getBasePtr();
24609     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24610                          DAG.getConstant(4, MVT::i32));
24611
24612     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24613                                 St->getPointerInfo(),
24614                                 St->isVolatile(), St->isNonTemporal(),
24615                                 St->getAlignment());
24616     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24617                                 St->getPointerInfo().getWithOffset(4),
24618                                 St->isVolatile(),
24619                                 St->isNonTemporal(),
24620                                 MinAlign(St->getAlignment(), 4));
24621     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24622   }
24623   return SDValue();
24624 }
24625
24626 /// Return 'true' if this vector operation is "horizontal"
24627 /// and return the operands for the horizontal operation in LHS and RHS.  A
24628 /// horizontal operation performs the binary operation on successive elements
24629 /// of its first operand, then on successive elements of its second operand,
24630 /// returning the resulting values in a vector.  For example, if
24631 ///   A = < float a0, float a1, float a2, float a3 >
24632 /// and
24633 ///   B = < float b0, float b1, float b2, float b3 >
24634 /// then the result of doing a horizontal operation on A and B is
24635 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24636 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24637 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24638 /// set to A, RHS to B, and the routine returns 'true'.
24639 /// Note that the binary operation should have the property that if one of the
24640 /// operands is UNDEF then the result is UNDEF.
24641 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24642   // Look for the following pattern: if
24643   //   A = < float a0, float a1, float a2, float a3 >
24644   //   B = < float b0, float b1, float b2, float b3 >
24645   // and
24646   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24647   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24648   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24649   // which is A horizontal-op B.
24650
24651   // At least one of the operands should be a vector shuffle.
24652   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24653       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24654     return false;
24655
24656   MVT VT = LHS.getSimpleValueType();
24657
24658   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24659          "Unsupported vector type for horizontal add/sub");
24660
24661   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24662   // operate independently on 128-bit lanes.
24663   unsigned NumElts = VT.getVectorNumElements();
24664   unsigned NumLanes = VT.getSizeInBits()/128;
24665   unsigned NumLaneElts = NumElts / NumLanes;
24666   assert((NumLaneElts % 2 == 0) &&
24667          "Vector type should have an even number of elements in each lane");
24668   unsigned HalfLaneElts = NumLaneElts/2;
24669
24670   // View LHS in the form
24671   //   LHS = VECTOR_SHUFFLE A, B, LMask
24672   // If LHS is not a shuffle then pretend it is the shuffle
24673   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24674   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24675   // type VT.
24676   SDValue A, B;
24677   SmallVector<int, 16> LMask(NumElts);
24678   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24679     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24680       A = LHS.getOperand(0);
24681     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24682       B = LHS.getOperand(1);
24683     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24684     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24685   } else {
24686     if (LHS.getOpcode() != ISD::UNDEF)
24687       A = LHS;
24688     for (unsigned i = 0; i != NumElts; ++i)
24689       LMask[i] = i;
24690   }
24691
24692   // Likewise, view RHS in the form
24693   //   RHS = VECTOR_SHUFFLE C, D, RMask
24694   SDValue C, D;
24695   SmallVector<int, 16> RMask(NumElts);
24696   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24697     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24698       C = RHS.getOperand(0);
24699     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24700       D = RHS.getOperand(1);
24701     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24702     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24703   } else {
24704     if (RHS.getOpcode() != ISD::UNDEF)
24705       C = RHS;
24706     for (unsigned i = 0; i != NumElts; ++i)
24707       RMask[i] = i;
24708   }
24709
24710   // Check that the shuffles are both shuffling the same vectors.
24711   if (!(A == C && B == D) && !(A == D && B == C))
24712     return false;
24713
24714   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24715   if (!A.getNode() && !B.getNode())
24716     return false;
24717
24718   // If A and B occur in reverse order in RHS, then "swap" them (which means
24719   // rewriting the mask).
24720   if (A != C)
24721     CommuteVectorShuffleMask(RMask, NumElts);
24722
24723   // At this point LHS and RHS are equivalent to
24724   //   LHS = VECTOR_SHUFFLE A, B, LMask
24725   //   RHS = VECTOR_SHUFFLE A, B, RMask
24726   // Check that the masks correspond to performing a horizontal operation.
24727   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24728     for (unsigned i = 0; i != NumLaneElts; ++i) {
24729       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24730
24731       // Ignore any UNDEF components.
24732       if (LIdx < 0 || RIdx < 0 ||
24733           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24734           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24735         continue;
24736
24737       // Check that successive elements are being operated on.  If not, this is
24738       // not a horizontal operation.
24739       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24740       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24741       if (!(LIdx == Index && RIdx == Index + 1) &&
24742           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24743         return false;
24744     }
24745   }
24746
24747   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24748   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24749   return true;
24750 }
24751
24752 /// Do target-specific dag combines on floating point adds.
24753 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24754                                   const X86Subtarget *Subtarget) {
24755   EVT VT = N->getValueType(0);
24756   SDValue LHS = N->getOperand(0);
24757   SDValue RHS = N->getOperand(1);
24758
24759   // Try to synthesize horizontal adds from adds of shuffles.
24760   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24761        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24762       isHorizontalBinOp(LHS, RHS, true))
24763     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24764   return SDValue();
24765 }
24766
24767 /// Do target-specific dag combines on floating point subs.
24768 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24769                                   const X86Subtarget *Subtarget) {
24770   EVT VT = N->getValueType(0);
24771   SDValue LHS = N->getOperand(0);
24772   SDValue RHS = N->getOperand(1);
24773
24774   // Try to synthesize horizontal subs from subs of shuffles.
24775   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24776        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24777       isHorizontalBinOp(LHS, RHS, false))
24778     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24779   return SDValue();
24780 }
24781
24782 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24783 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24784   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24785   // F[X]OR(0.0, x) -> x
24786   // F[X]OR(x, 0.0) -> x
24787   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24788     if (C->getValueAPF().isPosZero())
24789       return N->getOperand(1);
24790   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24791     if (C->getValueAPF().isPosZero())
24792       return N->getOperand(0);
24793   return SDValue();
24794 }
24795
24796 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24797 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24798   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24799
24800   // Only perform optimizations if UnsafeMath is used.
24801   if (!DAG.getTarget().Options.UnsafeFPMath)
24802     return SDValue();
24803
24804   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24805   // into FMINC and FMAXC, which are Commutative operations.
24806   unsigned NewOp = 0;
24807   switch (N->getOpcode()) {
24808     default: llvm_unreachable("unknown opcode");
24809     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24810     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24811   }
24812
24813   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24814                      N->getOperand(0), N->getOperand(1));
24815 }
24816
24817 /// Do target-specific dag combines on X86ISD::FAND nodes.
24818 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24819   // FAND(0.0, x) -> 0.0
24820   // FAND(x, 0.0) -> 0.0
24821   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24822     if (C->getValueAPF().isPosZero())
24823       return N->getOperand(0);
24824   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24825     if (C->getValueAPF().isPosZero())
24826       return N->getOperand(1);
24827   return SDValue();
24828 }
24829
24830 /// Do target-specific dag combines on X86ISD::FANDN nodes
24831 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24832   // FANDN(x, 0.0) -> 0.0
24833   // FANDN(0.0, x) -> x
24834   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24835     if (C->getValueAPF().isPosZero())
24836       return N->getOperand(1);
24837   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24838     if (C->getValueAPF().isPosZero())
24839       return N->getOperand(1);
24840   return SDValue();
24841 }
24842
24843 static SDValue PerformBTCombine(SDNode *N,
24844                                 SelectionDAG &DAG,
24845                                 TargetLowering::DAGCombinerInfo &DCI) {
24846   // BT ignores high bits in the bit index operand.
24847   SDValue Op1 = N->getOperand(1);
24848   if (Op1.hasOneUse()) {
24849     unsigned BitWidth = Op1.getValueSizeInBits();
24850     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24851     APInt KnownZero, KnownOne;
24852     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24853                                           !DCI.isBeforeLegalizeOps());
24854     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24855     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24856         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24857       DCI.CommitTargetLoweringOpt(TLO);
24858   }
24859   return SDValue();
24860 }
24861
24862 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24863   SDValue Op = N->getOperand(0);
24864   if (Op.getOpcode() == ISD::BITCAST)
24865     Op = Op.getOperand(0);
24866   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24867   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24868       VT.getVectorElementType().getSizeInBits() ==
24869       OpVT.getVectorElementType().getSizeInBits()) {
24870     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24871   }
24872   return SDValue();
24873 }
24874
24875 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24876                                                const X86Subtarget *Subtarget) {
24877   EVT VT = N->getValueType(0);
24878   if (!VT.isVector())
24879     return SDValue();
24880
24881   SDValue N0 = N->getOperand(0);
24882   SDValue N1 = N->getOperand(1);
24883   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24884   SDLoc dl(N);
24885
24886   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24887   // both SSE and AVX2 since there is no sign-extended shift right
24888   // operation on a vector with 64-bit elements.
24889   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24890   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24891   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24892       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24893     SDValue N00 = N0.getOperand(0);
24894
24895     // EXTLOAD has a better solution on AVX2,
24896     // it may be replaced with X86ISD::VSEXT node.
24897     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24898       if (!ISD::isNormalLoad(N00.getNode()))
24899         return SDValue();
24900
24901     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24902         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24903                                   N00, N1);
24904       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24905     }
24906   }
24907   return SDValue();
24908 }
24909
24910 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24911                                   TargetLowering::DAGCombinerInfo &DCI,
24912                                   const X86Subtarget *Subtarget) {
24913   SDValue N0 = N->getOperand(0);
24914   EVT VT = N->getValueType(0);
24915
24916   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24917   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24918   // This exposes the sext to the sdivrem lowering, so that it directly extends
24919   // from AH (which we otherwise need to do contortions to access).
24920   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24921       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
24922     SDLoc dl(N);
24923     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24924     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
24925                             N0.getOperand(0), N0.getOperand(1));
24926     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24927     return R.getValue(1);
24928   }
24929
24930   if (!DCI.isBeforeLegalizeOps())
24931     return SDValue();
24932
24933   if (!Subtarget->hasFp256())
24934     return SDValue();
24935
24936   if (VT.isVector() && VT.getSizeInBits() == 256) {
24937     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
24938     if (R.getNode())
24939       return R;
24940   }
24941
24942   return SDValue();
24943 }
24944
24945 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24946                                  const X86Subtarget* Subtarget) {
24947   SDLoc dl(N);
24948   EVT VT = N->getValueType(0);
24949
24950   // Let legalize expand this if it isn't a legal type yet.
24951   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24952     return SDValue();
24953
24954   EVT ScalarVT = VT.getScalarType();
24955   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24956       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
24957     return SDValue();
24958
24959   SDValue A = N->getOperand(0);
24960   SDValue B = N->getOperand(1);
24961   SDValue C = N->getOperand(2);
24962
24963   bool NegA = (A.getOpcode() == ISD::FNEG);
24964   bool NegB = (B.getOpcode() == ISD::FNEG);
24965   bool NegC = (C.getOpcode() == ISD::FNEG);
24966
24967   // Negative multiplication when NegA xor NegB
24968   bool NegMul = (NegA != NegB);
24969   if (NegA)
24970     A = A.getOperand(0);
24971   if (NegB)
24972     B = B.getOperand(0);
24973   if (NegC)
24974     C = C.getOperand(0);
24975
24976   unsigned Opcode;
24977   if (!NegMul)
24978     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24979   else
24980     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24981
24982   return DAG.getNode(Opcode, dl, VT, A, B, C);
24983 }
24984
24985 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24986                                   TargetLowering::DAGCombinerInfo &DCI,
24987                                   const X86Subtarget *Subtarget) {
24988   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24989   //           (and (i32 x86isd::setcc_carry), 1)
24990   // This eliminates the zext. This transformation is necessary because
24991   // ISD::SETCC is always legalized to i8.
24992   SDLoc dl(N);
24993   SDValue N0 = N->getOperand(0);
24994   EVT VT = N->getValueType(0);
24995
24996   if (N0.getOpcode() == ISD::AND &&
24997       N0.hasOneUse() &&
24998       N0.getOperand(0).hasOneUse()) {
24999     SDValue N00 = N0.getOperand(0);
25000     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25001       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25002       if (!C || C->getZExtValue() != 1)
25003         return SDValue();
25004       return DAG.getNode(ISD::AND, dl, VT,
25005                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25006                                      N00.getOperand(0), N00.getOperand(1)),
25007                          DAG.getConstant(1, VT));
25008     }
25009   }
25010
25011   if (N0.getOpcode() == ISD::TRUNCATE &&
25012       N0.hasOneUse() &&
25013       N0.getOperand(0).hasOneUse()) {
25014     SDValue N00 = N0.getOperand(0);
25015     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25016       return DAG.getNode(ISD::AND, dl, VT,
25017                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25018                                      N00.getOperand(0), N00.getOperand(1)),
25019                          DAG.getConstant(1, VT));
25020     }
25021   }
25022   if (VT.is256BitVector()) {
25023     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
25024     if (R.getNode())
25025       return R;
25026   }
25027
25028   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25029   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25030   // This exposes the zext to the udivrem lowering, so that it directly extends
25031   // from AH (which we otherwise need to do contortions to access).
25032   if (N0.getOpcode() == ISD::UDIVREM &&
25033       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25034       (VT == MVT::i32 || VT == MVT::i64)) {
25035     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25036     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25037                             N0.getOperand(0), N0.getOperand(1));
25038     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25039     return R.getValue(1);
25040   }
25041
25042   return SDValue();
25043 }
25044
25045 // Optimize x == -y --> x+y == 0
25046 //          x != -y --> x+y != 0
25047 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25048                                       const X86Subtarget* Subtarget) {
25049   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25050   SDValue LHS = N->getOperand(0);
25051   SDValue RHS = N->getOperand(1);
25052   EVT VT = N->getValueType(0);
25053   SDLoc DL(N);
25054
25055   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25056     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25057       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25058         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25059                                    LHS.getValueType(), RHS, LHS.getOperand(1));
25060         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25061                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25062       }
25063   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25064     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25065       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25066         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25067                                    RHS.getValueType(), LHS, RHS.getOperand(1));
25068         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25069                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25070       }
25071
25072   if (VT.getScalarType() == MVT::i1) {
25073     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25074       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25075     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
25076     if (!IsSEXT0 && !IsVZero0)
25077       return SDValue();
25078     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
25079       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25080     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25081
25082     if (!IsSEXT1 && !IsVZero1)
25083       return SDValue();
25084
25085     if (IsSEXT0 && IsVZero1) {
25086       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
25087       if (CC == ISD::SETEQ)
25088         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25089       return LHS.getOperand(0);
25090     }
25091     if (IsSEXT1 && IsVZero0) {
25092       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
25093       if (CC == ISD::SETEQ)
25094         return DAG.getNOT(DL, RHS.getOperand(0), VT);
25095       return RHS.getOperand(0);
25096     }
25097   }
25098
25099   return SDValue();
25100 }
25101
25102 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25103                                       const X86Subtarget *Subtarget) {
25104   SDLoc dl(N);
25105   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25106   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25107          "X86insertps is only defined for v4x32");
25108
25109   SDValue Ld = N->getOperand(1);
25110   if (MayFoldLoad(Ld)) {
25111     // Extract the countS bits from the immediate so we can get the proper
25112     // address when narrowing the vector load to a specific element.
25113     // When the second source op is a memory address, interps doesn't use
25114     // countS and just gets an f32 from that address.
25115     unsigned DestIndex =
25116         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25117     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25118   } else
25119     return SDValue();
25120
25121   // Create this as a scalar to vector to match the instruction pattern.
25122   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25123   // countS bits are ignored when loading from memory on insertps, which
25124   // means we don't need to explicitly set them to 0.
25125   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25126                      LoadScalarToVector, N->getOperand(2));
25127 }
25128
25129 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25130 // as "sbb reg,reg", since it can be extended without zext and produces
25131 // an all-ones bit which is more useful than 0/1 in some cases.
25132 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25133                                MVT VT) {
25134   if (VT == MVT::i8)
25135     return DAG.getNode(ISD::AND, DL, VT,
25136                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25137                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
25138                        DAG.getConstant(1, VT));
25139   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25140   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25141                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25142                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
25143 }
25144
25145 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25146 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25147                                    TargetLowering::DAGCombinerInfo &DCI,
25148                                    const X86Subtarget *Subtarget) {
25149   SDLoc DL(N);
25150   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25151   SDValue EFLAGS = N->getOperand(1);
25152
25153   if (CC == X86::COND_A) {
25154     // Try to convert COND_A into COND_B in an attempt to facilitate
25155     // materializing "setb reg".
25156     //
25157     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25158     // cannot take an immediate as its first operand.
25159     //
25160     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25161         EFLAGS.getValueType().isInteger() &&
25162         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25163       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25164                                    EFLAGS.getNode()->getVTList(),
25165                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25166       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25167       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25168     }
25169   }
25170
25171   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25172   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25173   // cases.
25174   if (CC == X86::COND_B)
25175     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25176
25177   SDValue Flags;
25178
25179   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25180   if (Flags.getNode()) {
25181     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25182     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25183   }
25184
25185   return SDValue();
25186 }
25187
25188 // Optimize branch condition evaluation.
25189 //
25190 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25191                                     TargetLowering::DAGCombinerInfo &DCI,
25192                                     const X86Subtarget *Subtarget) {
25193   SDLoc DL(N);
25194   SDValue Chain = N->getOperand(0);
25195   SDValue Dest = N->getOperand(1);
25196   SDValue EFLAGS = N->getOperand(3);
25197   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25198
25199   SDValue Flags;
25200
25201   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25202   if (Flags.getNode()) {
25203     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25204     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25205                        Flags);
25206   }
25207
25208   return SDValue();
25209 }
25210
25211 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25212                                                          SelectionDAG &DAG) {
25213   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25214   // optimize away operation when it's from a constant.
25215   //
25216   // The general transformation is:
25217   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25218   //       AND(VECTOR_CMP(x,y), constant2)
25219   //    constant2 = UNARYOP(constant)
25220
25221   // Early exit if this isn't a vector operation, the operand of the
25222   // unary operation isn't a bitwise AND, or if the sizes of the operations
25223   // aren't the same.
25224   EVT VT = N->getValueType(0);
25225   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25226       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25227       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25228     return SDValue();
25229
25230   // Now check that the other operand of the AND is a constant. We could
25231   // make the transformation for non-constant splats as well, but it's unclear
25232   // that would be a benefit as it would not eliminate any operations, just
25233   // perform one more step in scalar code before moving to the vector unit.
25234   if (BuildVectorSDNode *BV =
25235           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25236     // Bail out if the vector isn't a constant.
25237     if (!BV->isConstant())
25238       return SDValue();
25239
25240     // Everything checks out. Build up the new and improved node.
25241     SDLoc DL(N);
25242     EVT IntVT = BV->getValueType(0);
25243     // Create a new constant of the appropriate type for the transformed
25244     // DAG.
25245     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25246     // The AND node needs bitcasts to/from an integer vector type around it.
25247     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
25248     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25249                                  N->getOperand(0)->getOperand(0), MaskConst);
25250     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
25251     return Res;
25252   }
25253
25254   return SDValue();
25255 }
25256
25257 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25258                                         const X86TargetLowering *XTLI) {
25259   // First try to optimize away the conversion entirely when it's
25260   // conditionally from a constant. Vectors only.
25261   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
25262   if (Res != SDValue())
25263     return Res;
25264
25265   // Now move on to more general possibilities.
25266   SDValue Op0 = N->getOperand(0);
25267   EVT InVT = Op0->getValueType(0);
25268
25269   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
25270   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
25271     SDLoc dl(N);
25272     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
25273     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25274     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
25275   }
25276
25277   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25278   // a 32-bit target where SSE doesn't support i64->FP operations.
25279   if (Op0.getOpcode() == ISD::LOAD) {
25280     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25281     EVT VT = Ld->getValueType(0);
25282     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
25283         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25284         !XTLI->getSubtarget()->is64Bit() &&
25285         VT == MVT::i64) {
25286       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
25287                                           Ld->getChain(), Op0, DAG);
25288       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25289       return FILDChain;
25290     }
25291   }
25292   return SDValue();
25293 }
25294
25295 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25296 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25297                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25298   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25299   // the result is either zero or one (depending on the input carry bit).
25300   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25301   if (X86::isZeroNode(N->getOperand(0)) &&
25302       X86::isZeroNode(N->getOperand(1)) &&
25303       // We don't have a good way to replace an EFLAGS use, so only do this when
25304       // dead right now.
25305       SDValue(N, 1).use_empty()) {
25306     SDLoc DL(N);
25307     EVT VT = N->getValueType(0);
25308     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
25309     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25310                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25311                                            DAG.getConstant(X86::COND_B,MVT::i8),
25312                                            N->getOperand(2)),
25313                                DAG.getConstant(1, VT));
25314     return DCI.CombineTo(N, Res1, CarryOut);
25315   }
25316
25317   return SDValue();
25318 }
25319
25320 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25321 //      (add Y, (setne X, 0)) -> sbb -1, Y
25322 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25323 //      (sub (setne X, 0), Y) -> adc -1, Y
25324 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25325   SDLoc DL(N);
25326
25327   // Look through ZExts.
25328   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25329   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25330     return SDValue();
25331
25332   SDValue SetCC = Ext.getOperand(0);
25333   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25334     return SDValue();
25335
25336   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25337   if (CC != X86::COND_E && CC != X86::COND_NE)
25338     return SDValue();
25339
25340   SDValue Cmp = SetCC.getOperand(1);
25341   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25342       !X86::isZeroNode(Cmp.getOperand(1)) ||
25343       !Cmp.getOperand(0).getValueType().isInteger())
25344     return SDValue();
25345
25346   SDValue CmpOp0 = Cmp.getOperand(0);
25347   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25348                                DAG.getConstant(1, CmpOp0.getValueType()));
25349
25350   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25351   if (CC == X86::COND_NE)
25352     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25353                        DL, OtherVal.getValueType(), OtherVal,
25354                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
25355   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25356                      DL, OtherVal.getValueType(), OtherVal,
25357                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
25358 }
25359
25360 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25361 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25362                                  const X86Subtarget *Subtarget) {
25363   EVT VT = N->getValueType(0);
25364   SDValue Op0 = N->getOperand(0);
25365   SDValue Op1 = N->getOperand(1);
25366
25367   // Try to synthesize horizontal adds from adds of shuffles.
25368   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25369        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25370       isHorizontalBinOp(Op0, Op1, true))
25371     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25372
25373   return OptimizeConditionalInDecrement(N, DAG);
25374 }
25375
25376 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25377                                  const X86Subtarget *Subtarget) {
25378   SDValue Op0 = N->getOperand(0);
25379   SDValue Op1 = N->getOperand(1);
25380
25381   // X86 can't encode an immediate LHS of a sub. See if we can push the
25382   // negation into a preceding instruction.
25383   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25384     // If the RHS of the sub is a XOR with one use and a constant, invert the
25385     // immediate. Then add one to the LHS of the sub so we can turn
25386     // X-Y -> X+~Y+1, saving one register.
25387     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25388         isa<ConstantSDNode>(Op1.getOperand(1))) {
25389       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25390       EVT VT = Op0.getValueType();
25391       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25392                                    Op1.getOperand(0),
25393                                    DAG.getConstant(~XorC, VT));
25394       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25395                          DAG.getConstant(C->getAPIntValue()+1, VT));
25396     }
25397   }
25398
25399   // Try to synthesize horizontal adds from adds of shuffles.
25400   EVT VT = N->getValueType(0);
25401   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25402        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25403       isHorizontalBinOp(Op0, Op1, true))
25404     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25405
25406   return OptimizeConditionalInDecrement(N, DAG);
25407 }
25408
25409 /// performVZEXTCombine - Performs build vector combines
25410 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25411                                    TargetLowering::DAGCombinerInfo &DCI,
25412                                    const X86Subtarget *Subtarget) {
25413   SDLoc DL(N);
25414   MVT VT = N->getSimpleValueType(0);
25415   SDValue Op = N->getOperand(0);
25416   MVT OpVT = Op.getSimpleValueType();
25417   MVT OpEltVT = OpVT.getVectorElementType();
25418   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25419
25420   // (vzext (bitcast (vzext (x)) -> (vzext x)
25421   SDValue V = Op;
25422   while (V.getOpcode() == ISD::BITCAST)
25423     V = V.getOperand(0);
25424
25425   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25426     MVT InnerVT = V.getSimpleValueType();
25427     MVT InnerEltVT = InnerVT.getVectorElementType();
25428
25429     // If the element sizes match exactly, we can just do one larger vzext. This
25430     // is always an exact type match as vzext operates on integer types.
25431     if (OpEltVT == InnerEltVT) {
25432       assert(OpVT == InnerVT && "Types must match for vzext!");
25433       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25434     }
25435
25436     // The only other way we can combine them is if only a single element of the
25437     // inner vzext is used in the input to the outer vzext.
25438     if (InnerEltVT.getSizeInBits() < InputBits)
25439       return SDValue();
25440
25441     // In this case, the inner vzext is completely dead because we're going to
25442     // only look at bits inside of the low element. Just do the outer vzext on
25443     // a bitcast of the input to the inner.
25444     return DAG.getNode(X86ISD::VZEXT, DL, VT,
25445                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
25446   }
25447
25448   // Check if we can bypass extracting and re-inserting an element of an input
25449   // vector. Essentialy:
25450   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25451   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25452       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25453       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25454     SDValue ExtractedV = V.getOperand(0);
25455     SDValue OrigV = ExtractedV.getOperand(0);
25456     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25457       if (ExtractIdx->getZExtValue() == 0) {
25458         MVT OrigVT = OrigV.getSimpleValueType();
25459         // Extract a subvector if necessary...
25460         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25461           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25462           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25463                                     OrigVT.getVectorNumElements() / Ratio);
25464           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25465                               DAG.getIntPtrConstant(0));
25466         }
25467         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
25468         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25469       }
25470   }
25471
25472   return SDValue();
25473 }
25474
25475 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25476                                              DAGCombinerInfo &DCI) const {
25477   SelectionDAG &DAG = DCI.DAG;
25478   switch (N->getOpcode()) {
25479   default: break;
25480   case ISD::EXTRACT_VECTOR_ELT:
25481     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25482   case ISD::VSELECT:
25483   case ISD::SELECT:
25484   case X86ISD::SHRUNKBLEND:
25485     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25486   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25487   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25488   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25489   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25490   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25491   case ISD::SHL:
25492   case ISD::SRA:
25493   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25494   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25495   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25496   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25497   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25498   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25499   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
25500   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25501   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25502   case X86ISD::FXOR:
25503   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25504   case X86ISD::FMIN:
25505   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25506   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25507   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25508   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25509   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25510   case ISD::ANY_EXTEND:
25511   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25512   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25513   case ISD::SIGN_EXTEND_INREG:
25514     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25515   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
25516   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25517   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25518   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25519   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25520   case X86ISD::SHUFP:       // Handle all target specific shuffles
25521   case X86ISD::PALIGNR:
25522   case X86ISD::UNPCKH:
25523   case X86ISD::UNPCKL:
25524   case X86ISD::MOVHLPS:
25525   case X86ISD::MOVLHPS:
25526   case X86ISD::PSHUFB:
25527   case X86ISD::PSHUFD:
25528   case X86ISD::PSHUFHW:
25529   case X86ISD::PSHUFLW:
25530   case X86ISD::MOVSS:
25531   case X86ISD::MOVSD:
25532   case X86ISD::VPERMILPI:
25533   case X86ISD::VPERM2X128:
25534   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25535   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25536   case ISD::INTRINSIC_WO_CHAIN:
25537     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25538   case X86ISD::INSERTPS:
25539     return PerformINSERTPSCombine(N, DAG, Subtarget);
25540   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
25541   }
25542
25543   return SDValue();
25544 }
25545
25546 /// isTypeDesirableForOp - Return true if the target has native support for
25547 /// the specified value type and it is 'desirable' to use the type for the
25548 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25549 /// instruction encodings are longer and some i16 instructions are slow.
25550 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25551   if (!isTypeLegal(VT))
25552     return false;
25553   if (VT != MVT::i16)
25554     return true;
25555
25556   switch (Opc) {
25557   default:
25558     return true;
25559   case ISD::LOAD:
25560   case ISD::SIGN_EXTEND:
25561   case ISD::ZERO_EXTEND:
25562   case ISD::ANY_EXTEND:
25563   case ISD::SHL:
25564   case ISD::SRL:
25565   case ISD::SUB:
25566   case ISD::ADD:
25567   case ISD::MUL:
25568   case ISD::AND:
25569   case ISD::OR:
25570   case ISD::XOR:
25571     return false;
25572   }
25573 }
25574
25575 /// IsDesirableToPromoteOp - This method query the target whether it is
25576 /// beneficial for dag combiner to promote the specified node. If true, it
25577 /// should return the desired promotion type by reference.
25578 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25579   EVT VT = Op.getValueType();
25580   if (VT != MVT::i16)
25581     return false;
25582
25583   bool Promote = false;
25584   bool Commute = false;
25585   switch (Op.getOpcode()) {
25586   default: break;
25587   case ISD::LOAD: {
25588     LoadSDNode *LD = cast<LoadSDNode>(Op);
25589     // If the non-extending load has a single use and it's not live out, then it
25590     // might be folded.
25591     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25592                                                      Op.hasOneUse()*/) {
25593       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25594              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25595         // The only case where we'd want to promote LOAD (rather then it being
25596         // promoted as an operand is when it's only use is liveout.
25597         if (UI->getOpcode() != ISD::CopyToReg)
25598           return false;
25599       }
25600     }
25601     Promote = true;
25602     break;
25603   }
25604   case ISD::SIGN_EXTEND:
25605   case ISD::ZERO_EXTEND:
25606   case ISD::ANY_EXTEND:
25607     Promote = true;
25608     break;
25609   case ISD::SHL:
25610   case ISD::SRL: {
25611     SDValue N0 = Op.getOperand(0);
25612     // Look out for (store (shl (load), x)).
25613     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25614       return false;
25615     Promote = true;
25616     break;
25617   }
25618   case ISD::ADD:
25619   case ISD::MUL:
25620   case ISD::AND:
25621   case ISD::OR:
25622   case ISD::XOR:
25623     Commute = true;
25624     // fallthrough
25625   case ISD::SUB: {
25626     SDValue N0 = Op.getOperand(0);
25627     SDValue N1 = Op.getOperand(1);
25628     if (!Commute && MayFoldLoad(N1))
25629       return false;
25630     // Avoid disabling potential load folding opportunities.
25631     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25632       return false;
25633     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25634       return false;
25635     Promote = true;
25636   }
25637   }
25638
25639   PVT = MVT::i32;
25640   return Promote;
25641 }
25642
25643 //===----------------------------------------------------------------------===//
25644 //                           X86 Inline Assembly Support
25645 //===----------------------------------------------------------------------===//
25646
25647 namespace {
25648   // Helper to match a string separated by whitespace.
25649   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
25650     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
25651
25652     for (unsigned i = 0, e = args.size(); i != e; ++i) {
25653       StringRef piece(*args[i]);
25654       if (!s.startswith(piece)) // Check if the piece matches.
25655         return false;
25656
25657       s = s.substr(piece.size());
25658       StringRef::size_type pos = s.find_first_not_of(" \t");
25659       if (pos == 0) // We matched a prefix.
25660         return false;
25661
25662       s = s.substr(pos);
25663     }
25664
25665     return s.empty();
25666   }
25667   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
25668 }
25669
25670 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25671
25672   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25673     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25674         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25675         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25676
25677       if (AsmPieces.size() == 3)
25678         return true;
25679       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25680         return true;
25681     }
25682   }
25683   return false;
25684 }
25685
25686 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25687   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25688
25689   std::string AsmStr = IA->getAsmString();
25690
25691   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25692   if (!Ty || Ty->getBitWidth() % 16 != 0)
25693     return false;
25694
25695   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25696   SmallVector<StringRef, 4> AsmPieces;
25697   SplitString(AsmStr, AsmPieces, ";\n");
25698
25699   switch (AsmPieces.size()) {
25700   default: return false;
25701   case 1:
25702     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25703     // we will turn this bswap into something that will be lowered to logical
25704     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25705     // lower so don't worry about this.
25706     // bswap $0
25707     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
25708         matchAsm(AsmPieces[0], "bswapl", "$0") ||
25709         matchAsm(AsmPieces[0], "bswapq", "$0") ||
25710         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
25711         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
25712         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
25713       // No need to check constraints, nothing other than the equivalent of
25714       // "=r,0" would be valid here.
25715       return IntrinsicLowering::LowerToByteSwap(CI);
25716     }
25717
25718     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25719     if (CI->getType()->isIntegerTy(16) &&
25720         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25721         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
25722          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
25723       AsmPieces.clear();
25724       const std::string &ConstraintsStr = IA->getConstraintString();
25725       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25726       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25727       if (clobbersFlagRegisters(AsmPieces))
25728         return IntrinsicLowering::LowerToByteSwap(CI);
25729     }
25730     break;
25731   case 3:
25732     if (CI->getType()->isIntegerTy(32) &&
25733         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25734         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
25735         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
25736         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
25737       AsmPieces.clear();
25738       const std::string &ConstraintsStr = IA->getConstraintString();
25739       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25740       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25741       if (clobbersFlagRegisters(AsmPieces))
25742         return IntrinsicLowering::LowerToByteSwap(CI);
25743     }
25744
25745     if (CI->getType()->isIntegerTy(64)) {
25746       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25747       if (Constraints.size() >= 2 &&
25748           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25749           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25750         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25751         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
25752             matchAsm(AsmPieces[1], "bswap", "%edx") &&
25753             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
25754           return IntrinsicLowering::LowerToByteSwap(CI);
25755       }
25756     }
25757     break;
25758   }
25759   return false;
25760 }
25761
25762 /// getConstraintType - Given a constraint letter, return the type of
25763 /// constraint it is for this target.
25764 X86TargetLowering::ConstraintType
25765 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
25766   if (Constraint.size() == 1) {
25767     switch (Constraint[0]) {
25768     case 'R':
25769     case 'q':
25770     case 'Q':
25771     case 'f':
25772     case 't':
25773     case 'u':
25774     case 'y':
25775     case 'x':
25776     case 'Y':
25777     case 'l':
25778       return C_RegisterClass;
25779     case 'a':
25780     case 'b':
25781     case 'c':
25782     case 'd':
25783     case 'S':
25784     case 'D':
25785     case 'A':
25786       return C_Register;
25787     case 'I':
25788     case 'J':
25789     case 'K':
25790     case 'L':
25791     case 'M':
25792     case 'N':
25793     case 'G':
25794     case 'C':
25795     case 'e':
25796     case 'Z':
25797       return C_Other;
25798     default:
25799       break;
25800     }
25801   }
25802   return TargetLowering::getConstraintType(Constraint);
25803 }
25804
25805 /// Examine constraint type and operand type and determine a weight value.
25806 /// This object must already have been set up with the operand type
25807 /// and the current alternative constraint selected.
25808 TargetLowering::ConstraintWeight
25809   X86TargetLowering::getSingleConstraintMatchWeight(
25810     AsmOperandInfo &info, const char *constraint) const {
25811   ConstraintWeight weight = CW_Invalid;
25812   Value *CallOperandVal = info.CallOperandVal;
25813     // If we don't have a value, we can't do a match,
25814     // but allow it at the lowest weight.
25815   if (!CallOperandVal)
25816     return CW_Default;
25817   Type *type = CallOperandVal->getType();
25818   // Look at the constraint type.
25819   switch (*constraint) {
25820   default:
25821     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25822   case 'R':
25823   case 'q':
25824   case 'Q':
25825   case 'a':
25826   case 'b':
25827   case 'c':
25828   case 'd':
25829   case 'S':
25830   case 'D':
25831   case 'A':
25832     if (CallOperandVal->getType()->isIntegerTy())
25833       weight = CW_SpecificReg;
25834     break;
25835   case 'f':
25836   case 't':
25837   case 'u':
25838     if (type->isFloatingPointTy())
25839       weight = CW_SpecificReg;
25840     break;
25841   case 'y':
25842     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25843       weight = CW_SpecificReg;
25844     break;
25845   case 'x':
25846   case 'Y':
25847     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25848         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25849       weight = CW_Register;
25850     break;
25851   case 'I':
25852     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25853       if (C->getZExtValue() <= 31)
25854         weight = CW_Constant;
25855     }
25856     break;
25857   case 'J':
25858     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25859       if (C->getZExtValue() <= 63)
25860         weight = CW_Constant;
25861     }
25862     break;
25863   case 'K':
25864     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25865       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25866         weight = CW_Constant;
25867     }
25868     break;
25869   case 'L':
25870     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25871       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25872         weight = CW_Constant;
25873     }
25874     break;
25875   case 'M':
25876     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25877       if (C->getZExtValue() <= 3)
25878         weight = CW_Constant;
25879     }
25880     break;
25881   case 'N':
25882     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25883       if (C->getZExtValue() <= 0xff)
25884         weight = CW_Constant;
25885     }
25886     break;
25887   case 'G':
25888   case 'C':
25889     if (dyn_cast<ConstantFP>(CallOperandVal)) {
25890       weight = CW_Constant;
25891     }
25892     break;
25893   case 'e':
25894     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25895       if ((C->getSExtValue() >= -0x80000000LL) &&
25896           (C->getSExtValue() <= 0x7fffffffLL))
25897         weight = CW_Constant;
25898     }
25899     break;
25900   case 'Z':
25901     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25902       if (C->getZExtValue() <= 0xffffffff)
25903         weight = CW_Constant;
25904     }
25905     break;
25906   }
25907   return weight;
25908 }
25909
25910 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25911 /// with another that has more specific requirements based on the type of the
25912 /// corresponding operand.
25913 const char *X86TargetLowering::
25914 LowerXConstraint(EVT ConstraintVT) const {
25915   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25916   // 'f' like normal targets.
25917   if (ConstraintVT.isFloatingPoint()) {
25918     if (Subtarget->hasSSE2())
25919       return "Y";
25920     if (Subtarget->hasSSE1())
25921       return "x";
25922   }
25923
25924   return TargetLowering::LowerXConstraint(ConstraintVT);
25925 }
25926
25927 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25928 /// vector.  If it is invalid, don't add anything to Ops.
25929 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25930                                                      std::string &Constraint,
25931                                                      std::vector<SDValue>&Ops,
25932                                                      SelectionDAG &DAG) const {
25933   SDValue Result;
25934
25935   // Only support length 1 constraints for now.
25936   if (Constraint.length() > 1) return;
25937
25938   char ConstraintLetter = Constraint[0];
25939   switch (ConstraintLetter) {
25940   default: break;
25941   case 'I':
25942     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25943       if (C->getZExtValue() <= 31) {
25944         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25945         break;
25946       }
25947     }
25948     return;
25949   case 'J':
25950     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25951       if (C->getZExtValue() <= 63) {
25952         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25953         break;
25954       }
25955     }
25956     return;
25957   case 'K':
25958     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25959       if (isInt<8>(C->getSExtValue())) {
25960         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25961         break;
25962       }
25963     }
25964     return;
25965   case 'N':
25966     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25967       if (C->getZExtValue() <= 255) {
25968         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25969         break;
25970       }
25971     }
25972     return;
25973   case 'e': {
25974     // 32-bit signed value
25975     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25976       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25977                                            C->getSExtValue())) {
25978         // Widen to 64 bits here to get it sign extended.
25979         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
25980         break;
25981       }
25982     // FIXME gcc accepts some relocatable values here too, but only in certain
25983     // memory models; it's complicated.
25984     }
25985     return;
25986   }
25987   case 'Z': {
25988     // 32-bit unsigned value
25989     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25990       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25991                                            C->getZExtValue())) {
25992         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25993         break;
25994       }
25995     }
25996     // FIXME gcc accepts some relocatable values here too, but only in certain
25997     // memory models; it's complicated.
25998     return;
25999   }
26000   case 'i': {
26001     // Literal immediates are always ok.
26002     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26003       // Widen to 64 bits here to get it sign extended.
26004       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
26005       break;
26006     }
26007
26008     // In any sort of PIC mode addresses need to be computed at runtime by
26009     // adding in a register or some sort of table lookup.  These can't
26010     // be used as immediates.
26011     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26012       return;
26013
26014     // If we are in non-pic codegen mode, we allow the address of a global (with
26015     // an optional displacement) to be used with 'i'.
26016     GlobalAddressSDNode *GA = nullptr;
26017     int64_t Offset = 0;
26018
26019     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26020     while (1) {
26021       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26022         Offset += GA->getOffset();
26023         break;
26024       } else if (Op.getOpcode() == ISD::ADD) {
26025         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26026           Offset += C->getZExtValue();
26027           Op = Op.getOperand(0);
26028           continue;
26029         }
26030       } else if (Op.getOpcode() == ISD::SUB) {
26031         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26032           Offset += -C->getZExtValue();
26033           Op = Op.getOperand(0);
26034           continue;
26035         }
26036       }
26037
26038       // Otherwise, this isn't something we can handle, reject it.
26039       return;
26040     }
26041
26042     const GlobalValue *GV = GA->getGlobal();
26043     // If we require an extra load to get this address, as in PIC mode, we
26044     // can't accept it.
26045     if (isGlobalStubReference(
26046             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26047       return;
26048
26049     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26050                                         GA->getValueType(0), Offset);
26051     break;
26052   }
26053   }
26054
26055   if (Result.getNode()) {
26056     Ops.push_back(Result);
26057     return;
26058   }
26059   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26060 }
26061
26062 std::pair<unsigned, const TargetRegisterClass*>
26063 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
26064                                                 MVT VT) const {
26065   // First, see if this is a constraint that directly corresponds to an LLVM
26066   // register class.
26067   if (Constraint.size() == 1) {
26068     // GCC Constraint Letters
26069     switch (Constraint[0]) {
26070     default: break;
26071       // TODO: Slight differences here in allocation order and leaving
26072       // RIP in the class. Do they matter any more here than they do
26073       // in the normal allocation?
26074     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26075       if (Subtarget->is64Bit()) {
26076         if (VT == MVT::i32 || VT == MVT::f32)
26077           return std::make_pair(0U, &X86::GR32RegClass);
26078         if (VT == MVT::i16)
26079           return std::make_pair(0U, &X86::GR16RegClass);
26080         if (VT == MVT::i8 || VT == MVT::i1)
26081           return std::make_pair(0U, &X86::GR8RegClass);
26082         if (VT == MVT::i64 || VT == MVT::f64)
26083           return std::make_pair(0U, &X86::GR64RegClass);
26084         break;
26085       }
26086       // 32-bit fallthrough
26087     case 'Q':   // Q_REGS
26088       if (VT == MVT::i32 || VT == MVT::f32)
26089         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26090       if (VT == MVT::i16)
26091         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26092       if (VT == MVT::i8 || VT == MVT::i1)
26093         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26094       if (VT == MVT::i64)
26095         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26096       break;
26097     case 'r':   // GENERAL_REGS
26098     case 'l':   // INDEX_REGS
26099       if (VT == MVT::i8 || VT == MVT::i1)
26100         return std::make_pair(0U, &X86::GR8RegClass);
26101       if (VT == MVT::i16)
26102         return std::make_pair(0U, &X86::GR16RegClass);
26103       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26104         return std::make_pair(0U, &X86::GR32RegClass);
26105       return std::make_pair(0U, &X86::GR64RegClass);
26106     case 'R':   // LEGACY_REGS
26107       if (VT == MVT::i8 || VT == MVT::i1)
26108         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26109       if (VT == MVT::i16)
26110         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26111       if (VT == MVT::i32 || !Subtarget->is64Bit())
26112         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26113       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26114     case 'f':  // FP Stack registers.
26115       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26116       // value to the correct fpstack register class.
26117       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26118         return std::make_pair(0U, &X86::RFP32RegClass);
26119       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26120         return std::make_pair(0U, &X86::RFP64RegClass);
26121       return std::make_pair(0U, &X86::RFP80RegClass);
26122     case 'y':   // MMX_REGS if MMX allowed.
26123       if (!Subtarget->hasMMX()) break;
26124       return std::make_pair(0U, &X86::VR64RegClass);
26125     case 'Y':   // SSE_REGS if SSE2 allowed
26126       if (!Subtarget->hasSSE2()) break;
26127       // FALL THROUGH.
26128     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26129       if (!Subtarget->hasSSE1()) break;
26130
26131       switch (VT.SimpleTy) {
26132       default: break;
26133       // Scalar SSE types.
26134       case MVT::f32:
26135       case MVT::i32:
26136         return std::make_pair(0U, &X86::FR32RegClass);
26137       case MVT::f64:
26138       case MVT::i64:
26139         return std::make_pair(0U, &X86::FR64RegClass);
26140       // Vector types.
26141       case MVT::v16i8:
26142       case MVT::v8i16:
26143       case MVT::v4i32:
26144       case MVT::v2i64:
26145       case MVT::v4f32:
26146       case MVT::v2f64:
26147         return std::make_pair(0U, &X86::VR128RegClass);
26148       // AVX types.
26149       case MVT::v32i8:
26150       case MVT::v16i16:
26151       case MVT::v8i32:
26152       case MVT::v4i64:
26153       case MVT::v8f32:
26154       case MVT::v4f64:
26155         return std::make_pair(0U, &X86::VR256RegClass);
26156       case MVT::v8f64:
26157       case MVT::v16f32:
26158       case MVT::v16i32:
26159       case MVT::v8i64:
26160         return std::make_pair(0U, &X86::VR512RegClass);
26161       }
26162       break;
26163     }
26164   }
26165
26166   // Use the default implementation in TargetLowering to convert the register
26167   // constraint into a member of a register class.
26168   std::pair<unsigned, const TargetRegisterClass*> Res;
26169   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
26170
26171   // Not found as a standard register?
26172   if (!Res.second) {
26173     // Map st(0) -> st(7) -> ST0
26174     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26175         tolower(Constraint[1]) == 's' &&
26176         tolower(Constraint[2]) == 't' &&
26177         Constraint[3] == '(' &&
26178         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26179         Constraint[5] == ')' &&
26180         Constraint[6] == '}') {
26181
26182       Res.first = X86::FP0+Constraint[4]-'0';
26183       Res.second = &X86::RFP80RegClass;
26184       return Res;
26185     }
26186
26187     // GCC allows "st(0)" to be called just plain "st".
26188     if (StringRef("{st}").equals_lower(Constraint)) {
26189       Res.first = X86::FP0;
26190       Res.second = &X86::RFP80RegClass;
26191       return Res;
26192     }
26193
26194     // flags -> EFLAGS
26195     if (StringRef("{flags}").equals_lower(Constraint)) {
26196       Res.first = X86::EFLAGS;
26197       Res.second = &X86::CCRRegClass;
26198       return Res;
26199     }
26200
26201     // 'A' means EAX + EDX.
26202     if (Constraint == "A") {
26203       Res.first = X86::EAX;
26204       Res.second = &X86::GR32_ADRegClass;
26205       return Res;
26206     }
26207     return Res;
26208   }
26209
26210   // Otherwise, check to see if this is a register class of the wrong value
26211   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26212   // turn into {ax},{dx}.
26213   if (Res.second->hasType(VT))
26214     return Res;   // Correct type already, nothing to do.
26215
26216   // All of the single-register GCC register classes map their values onto
26217   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
26218   // really want an 8-bit or 32-bit register, map to the appropriate register
26219   // class and return the appropriate register.
26220   if (Res.second == &X86::GR16RegClass) {
26221     if (VT == MVT::i8 || VT == MVT::i1) {
26222       unsigned DestReg = 0;
26223       switch (Res.first) {
26224       default: break;
26225       case X86::AX: DestReg = X86::AL; break;
26226       case X86::DX: DestReg = X86::DL; break;
26227       case X86::CX: DestReg = X86::CL; break;
26228       case X86::BX: DestReg = X86::BL; break;
26229       }
26230       if (DestReg) {
26231         Res.first = DestReg;
26232         Res.second = &X86::GR8RegClass;
26233       }
26234     } else if (VT == MVT::i32 || VT == MVT::f32) {
26235       unsigned DestReg = 0;
26236       switch (Res.first) {
26237       default: break;
26238       case X86::AX: DestReg = X86::EAX; break;
26239       case X86::DX: DestReg = X86::EDX; break;
26240       case X86::CX: DestReg = X86::ECX; break;
26241       case X86::BX: DestReg = X86::EBX; break;
26242       case X86::SI: DestReg = X86::ESI; break;
26243       case X86::DI: DestReg = X86::EDI; break;
26244       case X86::BP: DestReg = X86::EBP; break;
26245       case X86::SP: DestReg = X86::ESP; break;
26246       }
26247       if (DestReg) {
26248         Res.first = DestReg;
26249         Res.second = &X86::GR32RegClass;
26250       }
26251     } else if (VT == MVT::i64 || VT == MVT::f64) {
26252       unsigned DestReg = 0;
26253       switch (Res.first) {
26254       default: break;
26255       case X86::AX: DestReg = X86::RAX; break;
26256       case X86::DX: DestReg = X86::RDX; break;
26257       case X86::CX: DestReg = X86::RCX; break;
26258       case X86::BX: DestReg = X86::RBX; break;
26259       case X86::SI: DestReg = X86::RSI; break;
26260       case X86::DI: DestReg = X86::RDI; break;
26261       case X86::BP: DestReg = X86::RBP; break;
26262       case X86::SP: DestReg = X86::RSP; break;
26263       }
26264       if (DestReg) {
26265         Res.first = DestReg;
26266         Res.second = &X86::GR64RegClass;
26267       }
26268     }
26269   } else if (Res.second == &X86::FR32RegClass ||
26270              Res.second == &X86::FR64RegClass ||
26271              Res.second == &X86::VR128RegClass ||
26272              Res.second == &X86::VR256RegClass ||
26273              Res.second == &X86::FR32XRegClass ||
26274              Res.second == &X86::FR64XRegClass ||
26275              Res.second == &X86::VR128XRegClass ||
26276              Res.second == &X86::VR256XRegClass ||
26277              Res.second == &X86::VR512RegClass) {
26278     // Handle references to XMM physical registers that got mapped into the
26279     // wrong class.  This can happen with constraints like {xmm0} where the
26280     // target independent register mapper will just pick the first match it can
26281     // find, ignoring the required type.
26282
26283     if (VT == MVT::f32 || VT == MVT::i32)
26284       Res.second = &X86::FR32RegClass;
26285     else if (VT == MVT::f64 || VT == MVT::i64)
26286       Res.second = &X86::FR64RegClass;
26287     else if (X86::VR128RegClass.hasType(VT))
26288       Res.second = &X86::VR128RegClass;
26289     else if (X86::VR256RegClass.hasType(VT))
26290       Res.second = &X86::VR256RegClass;
26291     else if (X86::VR512RegClass.hasType(VT))
26292       Res.second = &X86::VR512RegClass;
26293   }
26294
26295   return Res;
26296 }
26297
26298 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
26299                                             Type *Ty) const {
26300   // Scaling factors are not free at all.
26301   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26302   // will take 2 allocations in the out of order engine instead of 1
26303   // for plain addressing mode, i.e. inst (reg1).
26304   // E.g.,
26305   // vaddps (%rsi,%drx), %ymm0, %ymm1
26306   // Requires two allocations (one for the load, one for the computation)
26307   // whereas:
26308   // vaddps (%rsi), %ymm0, %ymm1
26309   // Requires just 1 allocation, i.e., freeing allocations for other operations
26310   // and having less micro operations to execute.
26311   //
26312   // For some X86 architectures, this is even worse because for instance for
26313   // stores, the complex addressing mode forces the instruction to use the
26314   // "load" ports instead of the dedicated "store" port.
26315   // E.g., on Haswell:
26316   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26317   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26318   if (isLegalAddressingMode(AM, Ty))
26319     // Scale represents reg2 * scale, thus account for 1
26320     // as soon as we use a second register.
26321     return AM.Scale != 0;
26322   return -1;
26323 }
26324
26325 bool X86TargetLowering::isTargetFTOL() const {
26326   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26327 }