[x86] Don't form overly fragmented blends when splitting and
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallBitVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/VariadicFunction.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
54 #include <bitset>
55 #include <numeric>
56 #include <cctype>
57 using namespace llvm;
58
59 #define DEBUG_TYPE "x86-isel"
60
61 STATISTIC(NumTailCalls, "Number of tail calls");
62
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64     "x86-experimental-vector-widening-legalization", cl::init(false),
65     cl::desc("Enable an experimental vector type legalization through widening "
66              "rather than promotion."),
67     cl::Hidden);
68
69 static cl::opt<bool> ExperimentalVectorShuffleLowering(
70     "x86-experimental-vector-shuffle-lowering", cl::init(true),
71     cl::desc("Enable an experimental vector shuffle lowering code path."),
72     cl::Hidden);
73
74 static cl::opt<int> ReciprocalEstimateRefinementSteps(
75     "x86-recip-refinement-steps", cl::init(1),
76     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
77              "result of the hardware reciprocal estimate instruction."),
78     cl::NotHidden);
79
80 // Forward declarations.
81 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
82                        SDValue V2);
83
84 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
85                                 SelectionDAG &DAG, SDLoc dl,
86                                 unsigned vectorWidth) {
87   assert((vectorWidth == 128 || vectorWidth == 256) &&
88          "Unsupported vector width");
89   EVT VT = Vec.getValueType();
90   EVT ElVT = VT.getVectorElementType();
91   unsigned Factor = VT.getSizeInBits()/vectorWidth;
92   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
93                                   VT.getVectorNumElements()/Factor);
94
95   // Extract from UNDEF is UNDEF.
96   if (Vec.getOpcode() == ISD::UNDEF)
97     return DAG.getUNDEF(ResultVT);
98
99   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
100   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
101
102   // This is the index of the first element of the vectorWidth-bit chunk
103   // we want.
104   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
105                                * ElemsPerChunk);
106
107   // If the input is a buildvector just emit a smaller one.
108   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
109     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
110                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
111                                     ElemsPerChunk));
112
113   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
114   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
115                                VecIdx);
116
117   return Result;
118
119 }
120 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
121 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
122 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
123 /// instructions or a simple subregister reference. Idx is an index in the
124 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
125 /// lowering EXTRACT_VECTOR_ELT operations easier.
126 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert((Vec.getValueType().is256BitVector() ||
129           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
130   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
131 }
132
133 /// Generate a DAG to grab 256-bits from a 512-bit vector.
134 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
135                                    SelectionDAG &DAG, SDLoc dl) {
136   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
137   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
138 }
139
140 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
141                                unsigned IdxVal, SelectionDAG &DAG,
142                                SDLoc dl, unsigned vectorWidth) {
143   assert((vectorWidth == 128 || vectorWidth == 256) &&
144          "Unsupported vector width");
145   // Inserting UNDEF is Result
146   if (Vec.getOpcode() == ISD::UNDEF)
147     return Result;
148   EVT VT = Vec.getValueType();
149   EVT ElVT = VT.getVectorElementType();
150   EVT ResultVT = Result.getValueType();
151
152   // Insert the relevant vectorWidth bits.
153   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
154
155   // This is the index of the first element of the vectorWidth-bit chunk
156   // we want.
157   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
158                                * ElemsPerChunk);
159
160   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
161   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
162                      VecIdx);
163 }
164 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
165 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
166 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
167 /// simple superregister reference.  Idx is an index in the 128 bits
168 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
169 /// lowering INSERT_VECTOR_ELT operations easier.
170 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
171                                   unsigned IdxVal, SelectionDAG &DAG,
172                                   SDLoc dl) {
173   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
174   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
175 }
176
177 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
178                                   unsigned IdxVal, SelectionDAG &DAG,
179                                   SDLoc dl) {
180   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
181   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
182 }
183
184 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
185 /// instructions. This is used because creating CONCAT_VECTOR nodes of
186 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
187 /// large BUILD_VECTORS.
188 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
189                                    unsigned NumElems, SelectionDAG &DAG,
190                                    SDLoc dl) {
191   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
192   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
193 }
194
195 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
196                                    unsigned NumElems, SelectionDAG &DAG,
197                                    SDLoc dl) {
198   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
199   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
200 }
201
202 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
203   if (TT.isOSBinFormatMachO()) {
204     if (TT.getArch() == Triple::x86_64)
205       return new X86_64MachoTargetObjectFile();
206     return new TargetLoweringObjectFileMachO();
207   }
208
209   if (TT.isOSLinux())
210     return new X86LinuxTargetObjectFile();
211   if (TT.isOSBinFormatELF())
212     return new TargetLoweringObjectFileELF();
213   if (TT.isKnownWindowsMSVCEnvironment())
214     return new X86WindowsTargetObjectFile();
215   if (TT.isOSBinFormatCOFF())
216     return new TargetLoweringObjectFileCOFF();
217   llvm_unreachable("unknown subtarget type");
218 }
219
220 // FIXME: This should stop caching the target machine as soon as
221 // we can remove resetOperationActions et al.
222 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM)
223     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
224   Subtarget = &TM.getSubtarget<X86Subtarget>();
225   X86ScalarSSEf64 = Subtarget->hasSSE2();
226   X86ScalarSSEf32 = Subtarget->hasSSE1();
227   TD = getDataLayout();
228
229   resetOperationActions();
230 }
231
232 void X86TargetLowering::resetOperationActions() {
233   const TargetMachine &TM = getTargetMachine();
234   static bool FirstTimeThrough = true;
235
236   // If none of the target options have changed, then we don't need to reset the
237   // operation actions.
238   if (!FirstTimeThrough && TO == TM.Options) return;
239
240   if (!FirstTimeThrough) {
241     // Reinitialize the actions.
242     initActions();
243     FirstTimeThrough = false;
244   }
245
246   TO = TM.Options;
247
248   // Set up the TargetLowering object.
249   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
250
251   // X86 is weird, it always uses i8 for shift amounts and setcc results.
252   setBooleanContents(ZeroOrOneBooleanContent);
253   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
254   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
255
256   // For 64-bit since we have so many registers use the ILP scheduler, for
257   // 32-bit code use the register pressure specific scheduling.
258   // For Atom, always use ILP scheduling.
259   if (Subtarget->isAtom())
260     setSchedulingPreference(Sched::ILP);
261   else if (Subtarget->is64Bit())
262     setSchedulingPreference(Sched::ILP);
263   else
264     setSchedulingPreference(Sched::RegPressure);
265   const X86RegisterInfo *RegInfo =
266       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
267   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
268
269   // Bypass expensive divides on Atom when compiling with O2
270   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
271     addBypassSlowDiv(32, 8);
272     if (Subtarget->is64Bit())
273       addBypassSlowDiv(64, 16);
274   }
275
276   if (Subtarget->isTargetKnownWindowsMSVC()) {
277     // Setup Windows compiler runtime calls.
278     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
279     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
280     setLibcallName(RTLIB::SREM_I64, "_allrem");
281     setLibcallName(RTLIB::UREM_I64, "_aullrem");
282     setLibcallName(RTLIB::MUL_I64, "_allmul");
283     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
284     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
285     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
286     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
287     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
288
289     // The _ftol2 runtime function has an unusual calling conv, which
290     // is modeled by a special pseudo-instruction.
291     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
292     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
293     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
294     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
295   }
296
297   if (Subtarget->isTargetDarwin()) {
298     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
299     setUseUnderscoreSetJmp(false);
300     setUseUnderscoreLongJmp(false);
301   } else if (Subtarget->isTargetWindowsGNU()) {
302     // MS runtime is weird: it exports _setjmp, but longjmp!
303     setUseUnderscoreSetJmp(true);
304     setUseUnderscoreLongJmp(false);
305   } else {
306     setUseUnderscoreSetJmp(true);
307     setUseUnderscoreLongJmp(true);
308   }
309
310   // Set up the register classes.
311   addRegisterClass(MVT::i8, &X86::GR8RegClass);
312   addRegisterClass(MVT::i16, &X86::GR16RegClass);
313   addRegisterClass(MVT::i32, &X86::GR32RegClass);
314   if (Subtarget->is64Bit())
315     addRegisterClass(MVT::i64, &X86::GR64RegClass);
316
317   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
318
319   // We don't accept any truncstore of integer registers.
320   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
321   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
322   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
323   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
324   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
325   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
326
327   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
328
329   // SETOEQ and SETUNE require checking two conditions.
330   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
331   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
332   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
333   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
334   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
335   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
336
337   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
338   // operation.
339   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
340   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
341   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
342
343   if (Subtarget->is64Bit()) {
344     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
345     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
346   } else if (!TM.Options.UseSoftFloat) {
347     // We have an algorithm for SSE2->double, and we turn this into a
348     // 64-bit FILD followed by conditional FADD for other targets.
349     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
350     // We have an algorithm for SSE2, and we turn this into a 64-bit
351     // FILD for other targets.
352     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
353   }
354
355   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
356   // this operation.
357   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
358   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
359
360   if (!TM.Options.UseSoftFloat) {
361     // SSE has no i16 to fp conversion, only i32
362     if (X86ScalarSSEf32) {
363       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
364       // f32 and f64 cases are Legal, f80 case is not
365       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
366     } else {
367       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
368       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
369     }
370   } else {
371     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
372     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
373   }
374
375   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
376   // are Legal, f80 is custom lowered.
377   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
378   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
379
380   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
381   // this operation.
382   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
383   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
384
385   if (X86ScalarSSEf32) {
386     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
387     // f32 and f64 cases are Legal, f80 case is not
388     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
389   } else {
390     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
391     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
392   }
393
394   // Handle FP_TO_UINT by promoting the destination to a larger signed
395   // conversion.
396   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
397   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
398   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
399
400   if (Subtarget->is64Bit()) {
401     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
402     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
403   } else if (!TM.Options.UseSoftFloat) {
404     // Since AVX is a superset of SSE3, only check for SSE here.
405     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
406       // Expand FP_TO_UINT into a select.
407       // FIXME: We would like to use a Custom expander here eventually to do
408       // the optimal thing for SSE vs. the default expansion in the legalizer.
409       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
410     else
411       // With SSE3 we can use fisttpll to convert to a signed i64; without
412       // SSE, we're stuck with a fistpll.
413       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
414   }
415
416   if (isTargetFTOL()) {
417     // Use the _ftol2 runtime function, which has a pseudo-instruction
418     // to handle its weird calling convention.
419     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
420   }
421
422   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
423   if (!X86ScalarSSEf64) {
424     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
425     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
426     if (Subtarget->is64Bit()) {
427       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
428       // Without SSE, i64->f64 goes through memory.
429       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
430     }
431   }
432
433   // Scalar integer divide and remainder are lowered to use operations that
434   // produce two results, to match the available instructions. This exposes
435   // the two-result form to trivial CSE, which is able to combine x/y and x%y
436   // into a single instruction.
437   //
438   // Scalar integer multiply-high is also lowered to use two-result
439   // operations, to match the available instructions. However, plain multiply
440   // (low) operations are left as Legal, as there are single-result
441   // instructions for this in x86. Using the two-result multiply instructions
442   // when both high and low results are needed must be arranged by dagcombine.
443   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
444     MVT VT = IntVTs[i];
445     setOperationAction(ISD::MULHS, VT, Expand);
446     setOperationAction(ISD::MULHU, VT, Expand);
447     setOperationAction(ISD::SDIV, VT, Expand);
448     setOperationAction(ISD::UDIV, VT, Expand);
449     setOperationAction(ISD::SREM, VT, Expand);
450     setOperationAction(ISD::UREM, VT, Expand);
451
452     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
453     setOperationAction(ISD::ADDC, VT, Custom);
454     setOperationAction(ISD::ADDE, VT, Custom);
455     setOperationAction(ISD::SUBC, VT, Custom);
456     setOperationAction(ISD::SUBE, VT, Custom);
457   }
458
459   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
460   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
461   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
462   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
463   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
464   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
465   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
466   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
467   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
468   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
469   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
470   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
471   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
472   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
473   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
474   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
475   if (Subtarget->is64Bit())
476     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
477   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
478   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
479   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
480   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
481   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
482   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
483   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
484   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
485
486   // Promote the i8 variants and force them on up to i32 which has a shorter
487   // encoding.
488   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
489   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
490   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
491   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
492   if (Subtarget->hasBMI()) {
493     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
494     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
495     if (Subtarget->is64Bit())
496       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
497   } else {
498     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
499     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
500     if (Subtarget->is64Bit())
501       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
502   }
503
504   if (Subtarget->hasLZCNT()) {
505     // When promoting the i8 variants, force them to i32 for a shorter
506     // encoding.
507     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
508     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
510     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
512     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
513     if (Subtarget->is64Bit())
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
515   } else {
516     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
517     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
518     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
519     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
520     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
521     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
522     if (Subtarget->is64Bit()) {
523       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
524       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
525     }
526   }
527
528   // Special handling for half-precision floating point conversions.
529   // If we don't have F16C support, then lower half float conversions
530   // into library calls.
531   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
532     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
533     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
534   }
535
536   // There's never any support for operations beyond MVT::f32.
537   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
538   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
539   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
540   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
541
542   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
543   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
544   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
545   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
546
547   if (Subtarget->hasPOPCNT()) {
548     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
549   } else {
550     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
551     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
552     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
553     if (Subtarget->is64Bit())
554       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
555   }
556
557   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
558
559   if (!Subtarget->hasMOVBE())
560     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
561
562   // These should be promoted to a larger select which is supported.
563   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
564   // X86 wants to expand cmov itself.
565   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
566   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
567   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
568   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
569   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
570   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
571   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
572   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
573   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
574   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
575   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
576   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
577   if (Subtarget->is64Bit()) {
578     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
579     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
580   }
581   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
582   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
583   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
584   // support continuation, user-level threading, and etc.. As a result, no
585   // other SjLj exception interfaces are implemented and please don't build
586   // your own exception handling based on them.
587   // LLVM/Clang supports zero-cost DWARF exception handling.
588   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
589   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
590
591   // Darwin ABI issue.
592   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
593   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
594   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
595   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
596   if (Subtarget->is64Bit())
597     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
598   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
599   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
600   if (Subtarget->is64Bit()) {
601     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
602     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
603     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
604     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
605     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
606   }
607   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
608   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
609   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
610   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
611   if (Subtarget->is64Bit()) {
612     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
613     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
614     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
615   }
616
617   if (Subtarget->hasSSE1())
618     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
619
620   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
621
622   // Expand certain atomics
623   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
624     MVT VT = IntVTs[i];
625     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
626     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
627     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
628   }
629
630   if (Subtarget->hasCmpxchg16b()) {
631     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
632   }
633
634   // FIXME - use subtarget debug flags
635   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
636       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
637     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
638   }
639
640   if (Subtarget->is64Bit()) {
641     setExceptionPointerRegister(X86::RAX);
642     setExceptionSelectorRegister(X86::RDX);
643   } else {
644     setExceptionPointerRegister(X86::EAX);
645     setExceptionSelectorRegister(X86::EDX);
646   }
647   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
648   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
649
650   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
651   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
652
653   setOperationAction(ISD::TRAP, MVT::Other, Legal);
654   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
655
656   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
657   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
658   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
659   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
660     // TargetInfo::X86_64ABIBuiltinVaList
661     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
662     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
663   } else {
664     // TargetInfo::CharPtrBuiltinVaList
665     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
666     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
667   }
668
669   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
670   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
671
672   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
673
674   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
675     // f32 and f64 use SSE.
676     // Set up the FP register classes.
677     addRegisterClass(MVT::f32, &X86::FR32RegClass);
678     addRegisterClass(MVT::f64, &X86::FR64RegClass);
679
680     // Use ANDPD to simulate FABS.
681     setOperationAction(ISD::FABS , MVT::f64, Custom);
682     setOperationAction(ISD::FABS , MVT::f32, Custom);
683
684     // Use XORP to simulate FNEG.
685     setOperationAction(ISD::FNEG , MVT::f64, Custom);
686     setOperationAction(ISD::FNEG , MVT::f32, Custom);
687
688     // Use ANDPD and ORPD to simulate FCOPYSIGN.
689     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
690     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
691
692     // Lower this to FGETSIGNx86 plus an AND.
693     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
694     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
695
696     // We don't support sin/cos/fmod
697     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
698     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
699     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
700     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
701     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
702     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
703
704     // Expand FP immediates into loads from the stack, except for the special
705     // cases we handle.
706     addLegalFPImmediate(APFloat(+0.0)); // xorpd
707     addLegalFPImmediate(APFloat(+0.0f)); // xorps
708   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
709     // Use SSE for f32, x87 for f64.
710     // Set up the FP register classes.
711     addRegisterClass(MVT::f32, &X86::FR32RegClass);
712     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
713
714     // Use ANDPS to simulate FABS.
715     setOperationAction(ISD::FABS , MVT::f32, Custom);
716
717     // Use XORP to simulate FNEG.
718     setOperationAction(ISD::FNEG , MVT::f32, Custom);
719
720     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
721
722     // Use ANDPS and ORPS to simulate FCOPYSIGN.
723     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
724     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
725
726     // We don't support sin/cos/fmod
727     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
728     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
729     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
730
731     // Special cases we handle for FP constants.
732     addLegalFPImmediate(APFloat(+0.0f)); // xorps
733     addLegalFPImmediate(APFloat(+0.0)); // FLD0
734     addLegalFPImmediate(APFloat(+1.0)); // FLD1
735     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
736     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
737
738     if (!TM.Options.UnsafeFPMath) {
739       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
740       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
741       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
742     }
743   } else if (!TM.Options.UseSoftFloat) {
744     // f32 and f64 in x87.
745     // Set up the FP register classes.
746     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
747     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
748
749     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
750     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
751     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
752     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
753
754     if (!TM.Options.UnsafeFPMath) {
755       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
756       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
757       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
758       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
759       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
760       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
761     }
762     addLegalFPImmediate(APFloat(+0.0)); // FLD0
763     addLegalFPImmediate(APFloat(+1.0)); // FLD1
764     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
765     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
766     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
767     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
768     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
769     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
770   }
771
772   // We don't support FMA.
773   setOperationAction(ISD::FMA, MVT::f64, Expand);
774   setOperationAction(ISD::FMA, MVT::f32, Expand);
775
776   // Long double always uses X87.
777   if (!TM.Options.UseSoftFloat) {
778     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
779     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
780     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
781     {
782       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
783       addLegalFPImmediate(TmpFlt);  // FLD0
784       TmpFlt.changeSign();
785       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
786
787       bool ignored;
788       APFloat TmpFlt2(+1.0);
789       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
790                       &ignored);
791       addLegalFPImmediate(TmpFlt2);  // FLD1
792       TmpFlt2.changeSign();
793       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
794     }
795
796     if (!TM.Options.UnsafeFPMath) {
797       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
798       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
799       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
800     }
801
802     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
803     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
804     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
805     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
806     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
807     setOperationAction(ISD::FMA, MVT::f80, Expand);
808   }
809
810   // Always use a library call for pow.
811   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
812   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
813   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
814
815   setOperationAction(ISD::FLOG, MVT::f80, Expand);
816   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
817   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
818   setOperationAction(ISD::FEXP, MVT::f80, Expand);
819   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
820   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
821   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
822
823   // First set operation action for all vector types to either promote
824   // (for widening) or expand (for scalarization). Then we will selectively
825   // turn on ones that can be effectively codegen'd.
826   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
827            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
828     MVT VT = (MVT::SimpleValueType)i;
829     setOperationAction(ISD::ADD , VT, Expand);
830     setOperationAction(ISD::SUB , VT, Expand);
831     setOperationAction(ISD::FADD, VT, Expand);
832     setOperationAction(ISD::FNEG, VT, Expand);
833     setOperationAction(ISD::FSUB, VT, Expand);
834     setOperationAction(ISD::MUL , VT, Expand);
835     setOperationAction(ISD::FMUL, VT, Expand);
836     setOperationAction(ISD::SDIV, VT, Expand);
837     setOperationAction(ISD::UDIV, VT, Expand);
838     setOperationAction(ISD::FDIV, VT, Expand);
839     setOperationAction(ISD::SREM, VT, Expand);
840     setOperationAction(ISD::UREM, VT, Expand);
841     setOperationAction(ISD::LOAD, VT, Expand);
842     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
843     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
844     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
845     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
846     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
847     setOperationAction(ISD::FABS, VT, Expand);
848     setOperationAction(ISD::FSIN, VT, Expand);
849     setOperationAction(ISD::FSINCOS, VT, Expand);
850     setOperationAction(ISD::FCOS, VT, Expand);
851     setOperationAction(ISD::FSINCOS, VT, Expand);
852     setOperationAction(ISD::FREM, VT, Expand);
853     setOperationAction(ISD::FMA,  VT, Expand);
854     setOperationAction(ISD::FPOWI, VT, Expand);
855     setOperationAction(ISD::FSQRT, VT, Expand);
856     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
857     setOperationAction(ISD::FFLOOR, VT, Expand);
858     setOperationAction(ISD::FCEIL, VT, Expand);
859     setOperationAction(ISD::FTRUNC, VT, Expand);
860     setOperationAction(ISD::FRINT, VT, Expand);
861     setOperationAction(ISD::FNEARBYINT, VT, Expand);
862     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
863     setOperationAction(ISD::MULHS, VT, Expand);
864     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
865     setOperationAction(ISD::MULHU, VT, Expand);
866     setOperationAction(ISD::SDIVREM, VT, Expand);
867     setOperationAction(ISD::UDIVREM, VT, Expand);
868     setOperationAction(ISD::FPOW, VT, Expand);
869     setOperationAction(ISD::CTPOP, VT, Expand);
870     setOperationAction(ISD::CTTZ, VT, Expand);
871     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
872     setOperationAction(ISD::CTLZ, VT, Expand);
873     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
874     setOperationAction(ISD::SHL, VT, Expand);
875     setOperationAction(ISD::SRA, VT, Expand);
876     setOperationAction(ISD::SRL, VT, Expand);
877     setOperationAction(ISD::ROTL, VT, Expand);
878     setOperationAction(ISD::ROTR, VT, Expand);
879     setOperationAction(ISD::BSWAP, VT, Expand);
880     setOperationAction(ISD::SETCC, VT, Expand);
881     setOperationAction(ISD::FLOG, VT, Expand);
882     setOperationAction(ISD::FLOG2, VT, Expand);
883     setOperationAction(ISD::FLOG10, VT, Expand);
884     setOperationAction(ISD::FEXP, VT, Expand);
885     setOperationAction(ISD::FEXP2, VT, Expand);
886     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
887     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
888     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
889     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
890     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
891     setOperationAction(ISD::TRUNCATE, VT, Expand);
892     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
893     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
894     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
895     setOperationAction(ISD::VSELECT, VT, Expand);
896     setOperationAction(ISD::SELECT_CC, VT, Expand);
897     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
898              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
899       setTruncStoreAction(VT,
900                           (MVT::SimpleValueType)InnerVT, Expand);
901     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
902     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
903
904     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
905     // we have to deal with them whether we ask for Expansion or not. Setting
906     // Expand causes its own optimisation problems though, so leave them legal.
907     if (VT.getVectorElementType() == MVT::i1)
908       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
909   }
910
911   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
912   // with -msoft-float, disable use of MMX as well.
913   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
914     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
915     // No operations on x86mmx supported, everything uses intrinsics.
916   }
917
918   // MMX-sized vectors (other than x86mmx) are expected to be expanded
919   // into smaller operations.
920   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
921   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
922   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
923   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
924   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
925   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
926   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
927   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
928   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
929   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
930   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
931   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
932   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
933   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
934   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
935   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
936   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
937   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
938   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
939   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
940   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
941   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
942   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
943   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
944   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
945   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
946   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
947   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
948   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
949
950   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
951     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
952
953     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
954     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
955     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
956     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
957     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
958     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
959     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
960     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
961     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
962     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
963     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
964     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
965     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
966   }
967
968   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
969     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
970
971     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
972     // registers cannot be used even for integer operations.
973     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
974     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
975     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
976     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
977
978     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
979     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
980     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
981     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
982     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
983     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
984     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
985     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
986     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
987     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
988     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
989     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
990     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
991     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
992     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
993     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
994     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
995     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
996     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
997     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
998     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
999     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
1000
1001     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
1002     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
1003     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
1004     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
1005
1006     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
1007     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
1008     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1009     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1010     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1011
1012     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1013     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1014       MVT VT = (MVT::SimpleValueType)i;
1015       // Do not attempt to custom lower non-power-of-2 vectors
1016       if (!isPowerOf2_32(VT.getVectorNumElements()))
1017         continue;
1018       // Do not attempt to custom lower non-128-bit vectors
1019       if (!VT.is128BitVector())
1020         continue;
1021       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1022       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1023       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1024     }
1025
1026     // We support custom legalizing of sext and anyext loads for specific
1027     // memory vector types which we can load as a scalar (or sequence of
1028     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1029     // loads these must work with a single scalar load.
1030     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1031     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1032     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1033     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1034     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1035     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1036     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1037     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1038     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1039
1040     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1041     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1042     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1043     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1044     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1045     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1046
1047     if (Subtarget->is64Bit()) {
1048       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1049       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1050     }
1051
1052     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1053     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1054       MVT VT = (MVT::SimpleValueType)i;
1055
1056       // Do not attempt to promote non-128-bit vectors
1057       if (!VT.is128BitVector())
1058         continue;
1059
1060       setOperationAction(ISD::AND,    VT, Promote);
1061       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1062       setOperationAction(ISD::OR,     VT, Promote);
1063       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1064       setOperationAction(ISD::XOR,    VT, Promote);
1065       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1066       setOperationAction(ISD::LOAD,   VT, Promote);
1067       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1068       setOperationAction(ISD::SELECT, VT, Promote);
1069       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1070     }
1071
1072     // Custom lower v2i64 and v2f64 selects.
1073     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1074     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1075     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1076     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1077
1078     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1079     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1080
1081     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1082     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1083     // As there is no 64-bit GPR available, we need build a special custom
1084     // sequence to convert from v2i32 to v2f32.
1085     if (!Subtarget->is64Bit())
1086       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1087
1088     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1089     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1090
1091     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1092
1093     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1094     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1095     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1096   }
1097
1098   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1099     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1100     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1101     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1102     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1103     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1104     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1105     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1106     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1107     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1108     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1109
1110     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1111     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1112     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1113     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1114     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1115     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1116     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1117     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1118     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1119     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1120
1121     // FIXME: Do we need to handle scalar-to-vector here?
1122     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1123
1124     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1125     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1126     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1127     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1128     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1129     // There is no BLENDI for byte vectors. We don't need to custom lower
1130     // some vselects for now.
1131     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1132
1133     // SSE41 brings specific instructions for doing vector sign extend even in
1134     // cases where we don't have SRA.
1135     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1136     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1137     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1138
1139     // i8 and i16 vectors are custom because the source register and source
1140     // source memory operand types are not the same width.  f32 vectors are
1141     // custom since the immediate controlling the insert encodes additional
1142     // information.
1143     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1144     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1145     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1146     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1147
1148     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1149     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1150     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1151     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1152
1153     // FIXME: these should be Legal, but that's only for the case where
1154     // the index is constant.  For now custom expand to deal with that.
1155     if (Subtarget->is64Bit()) {
1156       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1157       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1158     }
1159   }
1160
1161   if (Subtarget->hasSSE2()) {
1162     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1163     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1164
1165     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1166     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1167
1168     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1169     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1170
1171     // In the customized shift lowering, the legal cases in AVX2 will be
1172     // recognized.
1173     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1174     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1175
1176     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1177     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1178
1179     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1180   }
1181
1182   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1183     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1184     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1185     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1186     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1187     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1188     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1189
1190     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1191     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1192     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1193
1194     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1195     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1196     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1197     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1198     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1199     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1200     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1201     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1202     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1203     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1204     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1205     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1206
1207     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1208     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1209     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1210     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1211     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1212     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1213     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1214     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1215     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1216     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1217     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1218     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1219
1220     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1221     // even though v8i16 is a legal type.
1222     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1223     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1224     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1225
1226     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1227     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1228     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1229
1230     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1231     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1232
1233     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1234
1235     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1236     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1237
1238     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1239     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1240
1241     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1242     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1243
1244     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1245     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1246     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1247     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1248
1249     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1250     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1251     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1252
1253     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1254     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1255     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1256     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1257
1258     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1259     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1260     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1261     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1262     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1263     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1264     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1265     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1266     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1267     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1268     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1269     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1270
1271     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1272       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1273       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1274       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1275       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1276       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1277       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1278     }
1279
1280     if (Subtarget->hasInt256()) {
1281       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1282       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1283       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1284       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1285
1286       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1287       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1288       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1289       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1290
1291       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1292       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1293       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1294       // Don't lower v32i8 because there is no 128-bit byte mul
1295
1296       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1297       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1298       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1299       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1300
1301       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1302       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1303
1304       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1305       // when we have a 256bit-wide blend with immediate.
1306       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1307     } else {
1308       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1309       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1310       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1311       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1312
1313       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1314       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1315       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1316       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1317
1318       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1319       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1320       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1321       // Don't lower v32i8 because there is no 128-bit byte mul
1322     }
1323
1324     // In the customized shift lowering, the legal cases in AVX2 will be
1325     // recognized.
1326     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1327     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1328
1329     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1330     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1331
1332     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1333
1334     // Custom lower several nodes for 256-bit types.
1335     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1336              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1337       MVT VT = (MVT::SimpleValueType)i;
1338
1339       // Extract subvector is special because the value type
1340       // (result) is 128-bit but the source is 256-bit wide.
1341       if (VT.is128BitVector())
1342         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1343
1344       // Do not attempt to custom lower other non-256-bit vectors
1345       if (!VT.is256BitVector())
1346         continue;
1347
1348       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1349       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1350       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1351       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1352       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1353       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1354       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1355     }
1356
1357     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1358     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1359       MVT VT = (MVT::SimpleValueType)i;
1360
1361       // Do not attempt to promote non-256-bit vectors
1362       if (!VT.is256BitVector())
1363         continue;
1364
1365       setOperationAction(ISD::AND,    VT, Promote);
1366       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1367       setOperationAction(ISD::OR,     VT, Promote);
1368       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1369       setOperationAction(ISD::XOR,    VT, Promote);
1370       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1371       setOperationAction(ISD::LOAD,   VT, Promote);
1372       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1373       setOperationAction(ISD::SELECT, VT, Promote);
1374       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1375     }
1376   }
1377
1378   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1379     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1380     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1381     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1382     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1383
1384     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1385     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1386     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1387
1388     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1389     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1390     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1391     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1392     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1393     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1394     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1395     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1397     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1398     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1399
1400     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1401     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1402     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1403     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1404     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1405     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1406
1407     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1408     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1409     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1410     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1411     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1412     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1413     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1414     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1415
1416     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1417     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1420     if (Subtarget->is64Bit()) {
1421       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1422       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1423       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1424       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1425     }
1426     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1427     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1428     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1429     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1430     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1431     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1432     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1433     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1434     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1435     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1436
1437     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1438     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1439     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1440     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1441     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1442     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1443     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1444     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1445     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1446     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1447     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1448     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1449     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1450
1451     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1452     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1453     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1454     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1455     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1456     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1457
1458     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1459     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1460
1461     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1462
1463     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1464     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1465     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1466     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1467     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1468     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1469     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1470     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1471     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1472
1473     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1474     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1475
1476     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1477     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1478
1479     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1480
1481     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1482     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1483
1484     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1485     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1486
1487     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1488     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1489
1490     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1491     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1492     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1493     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1494     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1495     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1496
1497     if (Subtarget->hasCDI()) {
1498       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1499       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1500     }
1501
1502     // Custom lower several nodes.
1503     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1504              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1505       MVT VT = (MVT::SimpleValueType)i;
1506
1507       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1508       // Extract subvector is special because the value type
1509       // (result) is 256/128-bit but the source is 512-bit wide.
1510       if (VT.is128BitVector() || VT.is256BitVector())
1511         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1512
1513       if (VT.getVectorElementType() == MVT::i1)
1514         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1515
1516       // Do not attempt to custom lower other non-512-bit vectors
1517       if (!VT.is512BitVector())
1518         continue;
1519
1520       if ( EltSize >= 32) {
1521         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1522         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1523         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1524         setOperationAction(ISD::VSELECT,             VT, Legal);
1525         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1526         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1527         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1528       }
1529     }
1530     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1531       MVT VT = (MVT::SimpleValueType)i;
1532
1533       // Do not attempt to promote non-256-bit vectors
1534       if (!VT.is512BitVector())
1535         continue;
1536
1537       setOperationAction(ISD::SELECT, VT, Promote);
1538       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1539     }
1540   }// has  AVX-512
1541
1542   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1543     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1544     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1545
1546     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1547     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1548
1549     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1550     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1551     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1552     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1553
1554     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1555       const MVT VT = (MVT::SimpleValueType)i;
1556
1557       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1558
1559       // Do not attempt to promote non-256-bit vectors
1560       if (!VT.is512BitVector())
1561         continue;
1562
1563       if ( EltSize < 32) {
1564         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1565         setOperationAction(ISD::VSELECT,             VT, Legal);
1566       }
1567     }
1568   }
1569
1570   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1571     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1572     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1573
1574     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1575     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1576     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Legal);
1577   }
1578
1579   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1580   // of this type with custom code.
1581   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1582            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1583     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1584                        Custom);
1585   }
1586
1587   // We want to custom lower some of our intrinsics.
1588   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1589   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1590   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1591   if (!Subtarget->is64Bit())
1592     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1593
1594   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1595   // handle type legalization for these operations here.
1596   //
1597   // FIXME: We really should do custom legalization for addition and
1598   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1599   // than generic legalization for 64-bit multiplication-with-overflow, though.
1600   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1601     // Add/Sub/Mul with overflow operations are custom lowered.
1602     MVT VT = IntVTs[i];
1603     setOperationAction(ISD::SADDO, VT, Custom);
1604     setOperationAction(ISD::UADDO, VT, Custom);
1605     setOperationAction(ISD::SSUBO, VT, Custom);
1606     setOperationAction(ISD::USUBO, VT, Custom);
1607     setOperationAction(ISD::SMULO, VT, Custom);
1608     setOperationAction(ISD::UMULO, VT, Custom);
1609   }
1610
1611
1612   if (!Subtarget->is64Bit()) {
1613     // These libcalls are not available in 32-bit.
1614     setLibcallName(RTLIB::SHL_I128, nullptr);
1615     setLibcallName(RTLIB::SRL_I128, nullptr);
1616     setLibcallName(RTLIB::SRA_I128, nullptr);
1617   }
1618
1619   // Combine sin / cos into one node or libcall if possible.
1620   if (Subtarget->hasSinCos()) {
1621     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1622     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1623     if (Subtarget->isTargetDarwin()) {
1624       // For MacOSX, we don't want to the normal expansion of a libcall to
1625       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1626       // traffic.
1627       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1628       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1629     }
1630   }
1631
1632   if (Subtarget->isTargetWin64()) {
1633     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1634     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1635     setOperationAction(ISD::SREM, MVT::i128, Custom);
1636     setOperationAction(ISD::UREM, MVT::i128, Custom);
1637     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1638     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1639   }
1640
1641   // We have target-specific dag combine patterns for the following nodes:
1642   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1643   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1644   setTargetDAGCombine(ISD::VSELECT);
1645   setTargetDAGCombine(ISD::SELECT);
1646   setTargetDAGCombine(ISD::SHL);
1647   setTargetDAGCombine(ISD::SRA);
1648   setTargetDAGCombine(ISD::SRL);
1649   setTargetDAGCombine(ISD::OR);
1650   setTargetDAGCombine(ISD::AND);
1651   setTargetDAGCombine(ISD::ADD);
1652   setTargetDAGCombine(ISD::FADD);
1653   setTargetDAGCombine(ISD::FSUB);
1654   setTargetDAGCombine(ISD::FMA);
1655   setTargetDAGCombine(ISD::SUB);
1656   setTargetDAGCombine(ISD::LOAD);
1657   setTargetDAGCombine(ISD::STORE);
1658   setTargetDAGCombine(ISD::ZERO_EXTEND);
1659   setTargetDAGCombine(ISD::ANY_EXTEND);
1660   setTargetDAGCombine(ISD::SIGN_EXTEND);
1661   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1662   setTargetDAGCombine(ISD::TRUNCATE);
1663   setTargetDAGCombine(ISD::SINT_TO_FP);
1664   setTargetDAGCombine(ISD::SETCC);
1665   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1666   setTargetDAGCombine(ISD::BUILD_VECTOR);
1667   if (Subtarget->is64Bit())
1668     setTargetDAGCombine(ISD::MUL);
1669   setTargetDAGCombine(ISD::XOR);
1670
1671   computeRegisterProperties();
1672
1673   // On Darwin, -Os means optimize for size without hurting performance,
1674   // do not reduce the limit.
1675   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1676   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1677   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1678   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1679   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1680   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1681   setPrefLoopAlignment(4); // 2^4 bytes.
1682
1683   // Predictable cmov don't hurt on atom because it's in-order.
1684   PredictableSelectIsExpensive = !Subtarget->isAtom();
1685
1686   setPrefFunctionAlignment(4); // 2^4 bytes.
1687
1688   verifyIntrinsicTables();
1689 }
1690
1691 // This has so far only been implemented for 64-bit MachO.
1692 bool X86TargetLowering::useLoadStackGuardNode() const {
1693   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1694          Subtarget->is64Bit();
1695 }
1696
1697 TargetLoweringBase::LegalizeTypeAction
1698 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1699   if (ExperimentalVectorWideningLegalization &&
1700       VT.getVectorNumElements() != 1 &&
1701       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1702     return TypeWidenVector;
1703
1704   return TargetLoweringBase::getPreferredVectorAction(VT);
1705 }
1706
1707 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1708   if (!VT.isVector())
1709     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1710
1711   const unsigned NumElts = VT.getVectorNumElements();
1712   const EVT EltVT = VT.getVectorElementType();
1713   if (VT.is512BitVector()) {
1714     if (Subtarget->hasAVX512())
1715       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1716           EltVT == MVT::f32 || EltVT == MVT::f64)
1717         switch(NumElts) {
1718         case  8: return MVT::v8i1;
1719         case 16: return MVT::v16i1;
1720       }
1721     if (Subtarget->hasBWI())
1722       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1723         switch(NumElts) {
1724         case 32: return MVT::v32i1;
1725         case 64: return MVT::v64i1;
1726       }
1727   }
1728
1729   if (VT.is256BitVector() || VT.is128BitVector()) {
1730     if (Subtarget->hasVLX())
1731       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1732           EltVT == MVT::f32 || EltVT == MVT::f64)
1733         switch(NumElts) {
1734         case 2: return MVT::v2i1;
1735         case 4: return MVT::v4i1;
1736         case 8: return MVT::v8i1;
1737       }
1738     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1739       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1740         switch(NumElts) {
1741         case  8: return MVT::v8i1;
1742         case 16: return MVT::v16i1;
1743         case 32: return MVT::v32i1;
1744       }
1745   }
1746
1747   return VT.changeVectorElementTypeToInteger();
1748 }
1749
1750 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1751 /// the desired ByVal argument alignment.
1752 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1753   if (MaxAlign == 16)
1754     return;
1755   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1756     if (VTy->getBitWidth() == 128)
1757       MaxAlign = 16;
1758   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1759     unsigned EltAlign = 0;
1760     getMaxByValAlign(ATy->getElementType(), EltAlign);
1761     if (EltAlign > MaxAlign)
1762       MaxAlign = EltAlign;
1763   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1764     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1765       unsigned EltAlign = 0;
1766       getMaxByValAlign(STy->getElementType(i), EltAlign);
1767       if (EltAlign > MaxAlign)
1768         MaxAlign = EltAlign;
1769       if (MaxAlign == 16)
1770         break;
1771     }
1772   }
1773 }
1774
1775 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1776 /// function arguments in the caller parameter area. For X86, aggregates
1777 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1778 /// are at 4-byte boundaries.
1779 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1780   if (Subtarget->is64Bit()) {
1781     // Max of 8 and alignment of type.
1782     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1783     if (TyAlign > 8)
1784       return TyAlign;
1785     return 8;
1786   }
1787
1788   unsigned Align = 4;
1789   if (Subtarget->hasSSE1())
1790     getMaxByValAlign(Ty, Align);
1791   return Align;
1792 }
1793
1794 /// getOptimalMemOpType - Returns the target specific optimal type for load
1795 /// and store operations as a result of memset, memcpy, and memmove
1796 /// lowering. If DstAlign is zero that means it's safe to destination
1797 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1798 /// means there isn't a need to check it against alignment requirement,
1799 /// probably because the source does not need to be loaded. If 'IsMemset' is
1800 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1801 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1802 /// source is constant so it does not need to be loaded.
1803 /// It returns EVT::Other if the type should be determined using generic
1804 /// target-independent logic.
1805 EVT
1806 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1807                                        unsigned DstAlign, unsigned SrcAlign,
1808                                        bool IsMemset, bool ZeroMemset,
1809                                        bool MemcpyStrSrc,
1810                                        MachineFunction &MF) const {
1811   const Function *F = MF.getFunction();
1812   if ((!IsMemset || ZeroMemset) &&
1813       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1814                                        Attribute::NoImplicitFloat)) {
1815     if (Size >= 16 &&
1816         (Subtarget->isUnalignedMemAccessFast() ||
1817          ((DstAlign == 0 || DstAlign >= 16) &&
1818           (SrcAlign == 0 || SrcAlign >= 16)))) {
1819       if (Size >= 32) {
1820         if (Subtarget->hasInt256())
1821           return MVT::v8i32;
1822         if (Subtarget->hasFp256())
1823           return MVT::v8f32;
1824       }
1825       if (Subtarget->hasSSE2())
1826         return MVT::v4i32;
1827       if (Subtarget->hasSSE1())
1828         return MVT::v4f32;
1829     } else if (!MemcpyStrSrc && Size >= 8 &&
1830                !Subtarget->is64Bit() &&
1831                Subtarget->hasSSE2()) {
1832       // Do not use f64 to lower memcpy if source is string constant. It's
1833       // better to use i32 to avoid the loads.
1834       return MVT::f64;
1835     }
1836   }
1837   if (Subtarget->is64Bit() && Size >= 8)
1838     return MVT::i64;
1839   return MVT::i32;
1840 }
1841
1842 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1843   if (VT == MVT::f32)
1844     return X86ScalarSSEf32;
1845   else if (VT == MVT::f64)
1846     return X86ScalarSSEf64;
1847   return true;
1848 }
1849
1850 bool
1851 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1852                                                   unsigned,
1853                                                   unsigned,
1854                                                   bool *Fast) const {
1855   if (Fast)
1856     *Fast = Subtarget->isUnalignedMemAccessFast();
1857   return true;
1858 }
1859
1860 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1861 /// current function.  The returned value is a member of the
1862 /// MachineJumpTableInfo::JTEntryKind enum.
1863 unsigned X86TargetLowering::getJumpTableEncoding() const {
1864   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1865   // symbol.
1866   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1867       Subtarget->isPICStyleGOT())
1868     return MachineJumpTableInfo::EK_Custom32;
1869
1870   // Otherwise, use the normal jump table encoding heuristics.
1871   return TargetLowering::getJumpTableEncoding();
1872 }
1873
1874 const MCExpr *
1875 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1876                                              const MachineBasicBlock *MBB,
1877                                              unsigned uid,MCContext &Ctx) const{
1878   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1879          Subtarget->isPICStyleGOT());
1880   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1881   // entries.
1882   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1883                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1884 }
1885
1886 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1887 /// jumptable.
1888 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1889                                                     SelectionDAG &DAG) const {
1890   if (!Subtarget->is64Bit())
1891     // This doesn't have SDLoc associated with it, but is not really the
1892     // same as a Register.
1893     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1894   return Table;
1895 }
1896
1897 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1898 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1899 /// MCExpr.
1900 const MCExpr *X86TargetLowering::
1901 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1902                              MCContext &Ctx) const {
1903   // X86-64 uses RIP relative addressing based on the jump table label.
1904   if (Subtarget->isPICStyleRIPRel())
1905     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1906
1907   // Otherwise, the reference is relative to the PIC base.
1908   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1909 }
1910
1911 // FIXME: Why this routine is here? Move to RegInfo!
1912 std::pair<const TargetRegisterClass*, uint8_t>
1913 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1914   const TargetRegisterClass *RRC = nullptr;
1915   uint8_t Cost = 1;
1916   switch (VT.SimpleTy) {
1917   default:
1918     return TargetLowering::findRepresentativeClass(VT);
1919   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1920     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1921     break;
1922   case MVT::x86mmx:
1923     RRC = &X86::VR64RegClass;
1924     break;
1925   case MVT::f32: case MVT::f64:
1926   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1927   case MVT::v4f32: case MVT::v2f64:
1928   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1929   case MVT::v4f64:
1930     RRC = &X86::VR128RegClass;
1931     break;
1932   }
1933   return std::make_pair(RRC, Cost);
1934 }
1935
1936 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1937                                                unsigned &Offset) const {
1938   if (!Subtarget->isTargetLinux())
1939     return false;
1940
1941   if (Subtarget->is64Bit()) {
1942     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1943     Offset = 0x28;
1944     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1945       AddressSpace = 256;
1946     else
1947       AddressSpace = 257;
1948   } else {
1949     // %gs:0x14 on i386
1950     Offset = 0x14;
1951     AddressSpace = 256;
1952   }
1953   return true;
1954 }
1955
1956 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1957                                             unsigned DestAS) const {
1958   assert(SrcAS != DestAS && "Expected different address spaces!");
1959
1960   return SrcAS < 256 && DestAS < 256;
1961 }
1962
1963 //===----------------------------------------------------------------------===//
1964 //               Return Value Calling Convention Implementation
1965 //===----------------------------------------------------------------------===//
1966
1967 #include "X86GenCallingConv.inc"
1968
1969 bool
1970 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1971                                   MachineFunction &MF, bool isVarArg,
1972                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1973                         LLVMContext &Context) const {
1974   SmallVector<CCValAssign, 16> RVLocs;
1975   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1976   return CCInfo.CheckReturn(Outs, RetCC_X86);
1977 }
1978
1979 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1980   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1981   return ScratchRegs;
1982 }
1983
1984 SDValue
1985 X86TargetLowering::LowerReturn(SDValue Chain,
1986                                CallingConv::ID CallConv, bool isVarArg,
1987                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1988                                const SmallVectorImpl<SDValue> &OutVals,
1989                                SDLoc dl, SelectionDAG &DAG) const {
1990   MachineFunction &MF = DAG.getMachineFunction();
1991   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1992
1993   SmallVector<CCValAssign, 16> RVLocs;
1994   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1995   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1996
1997   SDValue Flag;
1998   SmallVector<SDValue, 6> RetOps;
1999   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2000   // Operand #1 = Bytes To Pop
2001   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2002                    MVT::i16));
2003
2004   // Copy the result values into the output registers.
2005   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2006     CCValAssign &VA = RVLocs[i];
2007     assert(VA.isRegLoc() && "Can only return in registers!");
2008     SDValue ValToCopy = OutVals[i];
2009     EVT ValVT = ValToCopy.getValueType();
2010
2011     // Promote values to the appropriate types
2012     if (VA.getLocInfo() == CCValAssign::SExt)
2013       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2014     else if (VA.getLocInfo() == CCValAssign::ZExt)
2015       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2016     else if (VA.getLocInfo() == CCValAssign::AExt)
2017       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2018     else if (VA.getLocInfo() == CCValAssign::BCvt)
2019       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2020
2021     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2022            "Unexpected FP-extend for return value.");  
2023
2024     // If this is x86-64, and we disabled SSE, we can't return FP values,
2025     // or SSE or MMX vectors.
2026     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2027          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2028           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2029       report_fatal_error("SSE register return with SSE disabled");
2030     }
2031     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2032     // llvm-gcc has never done it right and no one has noticed, so this
2033     // should be OK for now.
2034     if (ValVT == MVT::f64 &&
2035         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2036       report_fatal_error("SSE2 register return with SSE2 disabled");
2037
2038     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2039     // the RET instruction and handled by the FP Stackifier.
2040     if (VA.getLocReg() == X86::FP0 ||
2041         VA.getLocReg() == X86::FP1) {
2042       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2043       // change the value to the FP stack register class.
2044       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2045         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2046       RetOps.push_back(ValToCopy);
2047       // Don't emit a copytoreg.
2048       continue;
2049     }
2050
2051     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2052     // which is returned in RAX / RDX.
2053     if (Subtarget->is64Bit()) {
2054       if (ValVT == MVT::x86mmx) {
2055         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2056           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2057           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2058                                   ValToCopy);
2059           // If we don't have SSE2 available, convert to v4f32 so the generated
2060           // register is legal.
2061           if (!Subtarget->hasSSE2())
2062             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2063         }
2064       }
2065     }
2066
2067     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2068     Flag = Chain.getValue(1);
2069     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2070   }
2071
2072   // The x86-64 ABIs require that for returning structs by value we copy
2073   // the sret argument into %rax/%eax (depending on ABI) for the return.
2074   // Win32 requires us to put the sret argument to %eax as well.
2075   // We saved the argument into a virtual register in the entry block,
2076   // so now we copy the value out and into %rax/%eax.
2077   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2078       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2079     MachineFunction &MF = DAG.getMachineFunction();
2080     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2081     unsigned Reg = FuncInfo->getSRetReturnReg();
2082     assert(Reg &&
2083            "SRetReturnReg should have been set in LowerFormalArguments().");
2084     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2085
2086     unsigned RetValReg
2087         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2088           X86::RAX : X86::EAX;
2089     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2090     Flag = Chain.getValue(1);
2091
2092     // RAX/EAX now acts like a return value.
2093     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2094   }
2095
2096   RetOps[0] = Chain;  // Update chain.
2097
2098   // Add the flag if we have it.
2099   if (Flag.getNode())
2100     RetOps.push_back(Flag);
2101
2102   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2103 }
2104
2105 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2106   if (N->getNumValues() != 1)
2107     return false;
2108   if (!N->hasNUsesOfValue(1, 0))
2109     return false;
2110
2111   SDValue TCChain = Chain;
2112   SDNode *Copy = *N->use_begin();
2113   if (Copy->getOpcode() == ISD::CopyToReg) {
2114     // If the copy has a glue operand, we conservatively assume it isn't safe to
2115     // perform a tail call.
2116     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2117       return false;
2118     TCChain = Copy->getOperand(0);
2119   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2120     return false;
2121
2122   bool HasRet = false;
2123   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2124        UI != UE; ++UI) {
2125     if (UI->getOpcode() != X86ISD::RET_FLAG)
2126       return false;
2127     // If we are returning more than one value, we can definitely
2128     // not make a tail call see PR19530
2129     if (UI->getNumOperands() > 4)
2130       return false;
2131     if (UI->getNumOperands() == 4 &&
2132         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2133       return false;
2134     HasRet = true;
2135   }
2136
2137   if (!HasRet)
2138     return false;
2139
2140   Chain = TCChain;
2141   return true;
2142 }
2143
2144 EVT
2145 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2146                                             ISD::NodeType ExtendKind) const {
2147   MVT ReturnMVT;
2148   // TODO: Is this also valid on 32-bit?
2149   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2150     ReturnMVT = MVT::i8;
2151   else
2152     ReturnMVT = MVT::i32;
2153
2154   EVT MinVT = getRegisterType(Context, ReturnMVT);
2155   return VT.bitsLT(MinVT) ? MinVT : VT;
2156 }
2157
2158 /// LowerCallResult - Lower the result values of a call into the
2159 /// appropriate copies out of appropriate physical registers.
2160 ///
2161 SDValue
2162 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2163                                    CallingConv::ID CallConv, bool isVarArg,
2164                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2165                                    SDLoc dl, SelectionDAG &DAG,
2166                                    SmallVectorImpl<SDValue> &InVals) const {
2167
2168   // Assign locations to each value returned by this call.
2169   SmallVector<CCValAssign, 16> RVLocs;
2170   bool Is64Bit = Subtarget->is64Bit();
2171   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2172                  *DAG.getContext());
2173   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2174
2175   // Copy all of the result registers out of their specified physreg.
2176   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2177     CCValAssign &VA = RVLocs[i];
2178     EVT CopyVT = VA.getValVT();
2179
2180     // If this is x86-64, and we disabled SSE, we can't return FP values
2181     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2182         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2183       report_fatal_error("SSE register return with SSE disabled");
2184     }
2185
2186     // If we prefer to use the value in xmm registers, copy it out as f80 and
2187     // use a truncate to move it from fp stack reg to xmm reg.
2188     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2189         isScalarFPTypeInSSEReg(VA.getValVT()))
2190       CopyVT = MVT::f80;
2191
2192     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2193                                CopyVT, InFlag).getValue(1);
2194     SDValue Val = Chain.getValue(0);
2195
2196     if (CopyVT != VA.getValVT())
2197       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2198                         // This truncation won't change the value.
2199                         DAG.getIntPtrConstant(1));
2200
2201     InFlag = Chain.getValue(2);
2202     InVals.push_back(Val);
2203   }
2204
2205   return Chain;
2206 }
2207
2208 //===----------------------------------------------------------------------===//
2209 //                C & StdCall & Fast Calling Convention implementation
2210 //===----------------------------------------------------------------------===//
2211 //  StdCall calling convention seems to be standard for many Windows' API
2212 //  routines and around. It differs from C calling convention just a little:
2213 //  callee should clean up the stack, not caller. Symbols should be also
2214 //  decorated in some fancy way :) It doesn't support any vector arguments.
2215 //  For info on fast calling convention see Fast Calling Convention (tail call)
2216 //  implementation LowerX86_32FastCCCallTo.
2217
2218 /// CallIsStructReturn - Determines whether a call uses struct return
2219 /// semantics.
2220 enum StructReturnType {
2221   NotStructReturn,
2222   RegStructReturn,
2223   StackStructReturn
2224 };
2225 static StructReturnType
2226 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2227   if (Outs.empty())
2228     return NotStructReturn;
2229
2230   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2231   if (!Flags.isSRet())
2232     return NotStructReturn;
2233   if (Flags.isInReg())
2234     return RegStructReturn;
2235   return StackStructReturn;
2236 }
2237
2238 /// ArgsAreStructReturn - Determines whether a function uses struct
2239 /// return semantics.
2240 static StructReturnType
2241 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2242   if (Ins.empty())
2243     return NotStructReturn;
2244
2245   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2246   if (!Flags.isSRet())
2247     return NotStructReturn;
2248   if (Flags.isInReg())
2249     return RegStructReturn;
2250   return StackStructReturn;
2251 }
2252
2253 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2254 /// by "Src" to address "Dst" with size and alignment information specified by
2255 /// the specific parameter attribute. The copy will be passed as a byval
2256 /// function parameter.
2257 static SDValue
2258 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2259                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2260                           SDLoc dl) {
2261   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2262
2263   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2264                        /*isVolatile*/false, /*AlwaysInline=*/true,
2265                        MachinePointerInfo(), MachinePointerInfo());
2266 }
2267
2268 /// IsTailCallConvention - Return true if the calling convention is one that
2269 /// supports tail call optimization.
2270 static bool IsTailCallConvention(CallingConv::ID CC) {
2271   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2272           CC == CallingConv::HiPE);
2273 }
2274
2275 /// \brief Return true if the calling convention is a C calling convention.
2276 static bool IsCCallConvention(CallingConv::ID CC) {
2277   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2278           CC == CallingConv::X86_64_SysV);
2279 }
2280
2281 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2282   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2283     return false;
2284
2285   CallSite CS(CI);
2286   CallingConv::ID CalleeCC = CS.getCallingConv();
2287   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2288     return false;
2289
2290   return true;
2291 }
2292
2293 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2294 /// a tailcall target by changing its ABI.
2295 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2296                                    bool GuaranteedTailCallOpt) {
2297   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2298 }
2299
2300 SDValue
2301 X86TargetLowering::LowerMemArgument(SDValue Chain,
2302                                     CallingConv::ID CallConv,
2303                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2304                                     SDLoc dl, SelectionDAG &DAG,
2305                                     const CCValAssign &VA,
2306                                     MachineFrameInfo *MFI,
2307                                     unsigned i) const {
2308   // Create the nodes corresponding to a load from this parameter slot.
2309   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2310   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2311       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2312   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2313   EVT ValVT;
2314
2315   // If value is passed by pointer we have address passed instead of the value
2316   // itself.
2317   if (VA.getLocInfo() == CCValAssign::Indirect)
2318     ValVT = VA.getLocVT();
2319   else
2320     ValVT = VA.getValVT();
2321
2322   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2323   // changed with more analysis.
2324   // In case of tail call optimization mark all arguments mutable. Since they
2325   // could be overwritten by lowering of arguments in case of a tail call.
2326   if (Flags.isByVal()) {
2327     unsigned Bytes = Flags.getByValSize();
2328     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2329     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2330     return DAG.getFrameIndex(FI, getPointerTy());
2331   } else {
2332     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2333                                     VA.getLocMemOffset(), isImmutable);
2334     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2335     return DAG.getLoad(ValVT, dl, Chain, FIN,
2336                        MachinePointerInfo::getFixedStack(FI),
2337                        false, false, false, 0);
2338   }
2339 }
2340
2341 // FIXME: Get this from tablegen.
2342 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2343                                                 const X86Subtarget *Subtarget) {
2344   assert(Subtarget->is64Bit());
2345
2346   if (Subtarget->isCallingConvWin64(CallConv)) {
2347     static const MCPhysReg GPR64ArgRegsWin64[] = {
2348       X86::RCX, X86::RDX, X86::R8,  X86::R9
2349     };
2350     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2351   }
2352
2353   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2354     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2355   };
2356   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2357 }
2358
2359 // FIXME: Get this from tablegen.
2360 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2361                                                 CallingConv::ID CallConv,
2362                                                 const X86Subtarget *Subtarget) {
2363   assert(Subtarget->is64Bit());
2364   if (Subtarget->isCallingConvWin64(CallConv)) {
2365     // The XMM registers which might contain var arg parameters are shadowed
2366     // in their paired GPR.  So we only need to save the GPR to their home
2367     // slots.
2368     // TODO: __vectorcall will change this.
2369     return None;
2370   }
2371
2372   const Function *Fn = MF.getFunction();
2373   bool NoImplicitFloatOps = Fn->getAttributes().
2374       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2375   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2376          "SSE register cannot be used when SSE is disabled!");
2377   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2378       !Subtarget->hasSSE1())
2379     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2380     // registers.
2381     return None;
2382
2383   static const MCPhysReg XMMArgRegs64Bit[] = {
2384     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2385     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2386   };
2387   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2388 }
2389
2390 SDValue
2391 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2392                                         CallingConv::ID CallConv,
2393                                         bool isVarArg,
2394                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2395                                         SDLoc dl,
2396                                         SelectionDAG &DAG,
2397                                         SmallVectorImpl<SDValue> &InVals)
2398                                           const {
2399   MachineFunction &MF = DAG.getMachineFunction();
2400   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2401
2402   const Function* Fn = MF.getFunction();
2403   if (Fn->hasExternalLinkage() &&
2404       Subtarget->isTargetCygMing() &&
2405       Fn->getName() == "main")
2406     FuncInfo->setForceFramePointer(true);
2407
2408   MachineFrameInfo *MFI = MF.getFrameInfo();
2409   bool Is64Bit = Subtarget->is64Bit();
2410   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2411
2412   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2413          "Var args not supported with calling convention fastcc, ghc or hipe");
2414
2415   // Assign locations to all of the incoming arguments.
2416   SmallVector<CCValAssign, 16> ArgLocs;
2417   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2418
2419   // Allocate shadow area for Win64
2420   if (IsWin64)
2421     CCInfo.AllocateStack(32, 8);
2422
2423   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2424
2425   unsigned LastVal = ~0U;
2426   SDValue ArgValue;
2427   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2428     CCValAssign &VA = ArgLocs[i];
2429     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2430     // places.
2431     assert(VA.getValNo() != LastVal &&
2432            "Don't support value assigned to multiple locs yet");
2433     (void)LastVal;
2434     LastVal = VA.getValNo();
2435
2436     if (VA.isRegLoc()) {
2437       EVT RegVT = VA.getLocVT();
2438       const TargetRegisterClass *RC;
2439       if (RegVT == MVT::i32)
2440         RC = &X86::GR32RegClass;
2441       else if (Is64Bit && RegVT == MVT::i64)
2442         RC = &X86::GR64RegClass;
2443       else if (RegVT == MVT::f32)
2444         RC = &X86::FR32RegClass;
2445       else if (RegVT == MVT::f64)
2446         RC = &X86::FR64RegClass;
2447       else if (RegVT.is512BitVector())
2448         RC = &X86::VR512RegClass;
2449       else if (RegVT.is256BitVector())
2450         RC = &X86::VR256RegClass;
2451       else if (RegVT.is128BitVector())
2452         RC = &X86::VR128RegClass;
2453       else if (RegVT == MVT::x86mmx)
2454         RC = &X86::VR64RegClass;
2455       else if (RegVT == MVT::i1)
2456         RC = &X86::VK1RegClass;
2457       else if (RegVT == MVT::v8i1)
2458         RC = &X86::VK8RegClass;
2459       else if (RegVT == MVT::v16i1)
2460         RC = &X86::VK16RegClass;
2461       else if (RegVT == MVT::v32i1)
2462         RC = &X86::VK32RegClass;
2463       else if (RegVT == MVT::v64i1)
2464         RC = &X86::VK64RegClass;
2465       else
2466         llvm_unreachable("Unknown argument type!");
2467
2468       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2469       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2470
2471       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2472       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2473       // right size.
2474       if (VA.getLocInfo() == CCValAssign::SExt)
2475         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2476                                DAG.getValueType(VA.getValVT()));
2477       else if (VA.getLocInfo() == CCValAssign::ZExt)
2478         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2479                                DAG.getValueType(VA.getValVT()));
2480       else if (VA.getLocInfo() == CCValAssign::BCvt)
2481         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2482
2483       if (VA.isExtInLoc()) {
2484         // Handle MMX values passed in XMM regs.
2485         if (RegVT.isVector())
2486           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2487         else
2488           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2489       }
2490     } else {
2491       assert(VA.isMemLoc());
2492       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2493     }
2494
2495     // If value is passed via pointer - do a load.
2496     if (VA.getLocInfo() == CCValAssign::Indirect)
2497       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2498                              MachinePointerInfo(), false, false, false, 0);
2499
2500     InVals.push_back(ArgValue);
2501   }
2502
2503   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2504     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2505       // The x86-64 ABIs require that for returning structs by value we copy
2506       // the sret argument into %rax/%eax (depending on ABI) for the return.
2507       // Win32 requires us to put the sret argument to %eax as well.
2508       // Save the argument into a virtual register so that we can access it
2509       // from the return points.
2510       if (Ins[i].Flags.isSRet()) {
2511         unsigned Reg = FuncInfo->getSRetReturnReg();
2512         if (!Reg) {
2513           MVT PtrTy = getPointerTy();
2514           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2515           FuncInfo->setSRetReturnReg(Reg);
2516         }
2517         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2518         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2519         break;
2520       }
2521     }
2522   }
2523
2524   unsigned StackSize = CCInfo.getNextStackOffset();
2525   // Align stack specially for tail calls.
2526   if (FuncIsMadeTailCallSafe(CallConv,
2527                              MF.getTarget().Options.GuaranteedTailCallOpt))
2528     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2529
2530   // If the function takes variable number of arguments, make a frame index for
2531   // the start of the first vararg value... for expansion of llvm.va_start. We
2532   // can skip this if there are no va_start calls.
2533   if (MFI->hasVAStart() &&
2534       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2535                    CallConv != CallingConv::X86_ThisCall))) {
2536     FuncInfo->setVarArgsFrameIndex(
2537         MFI->CreateFixedObject(1, StackSize, true));
2538   }
2539
2540   // 64-bit calling conventions support varargs and register parameters, so we
2541   // have to do extra work to spill them in the prologue or forward them to
2542   // musttail calls.
2543   if (Is64Bit && isVarArg &&
2544       (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2545     // Find the first unallocated argument registers.
2546     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2547     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2548     unsigned NumIntRegs =
2549         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2550     unsigned NumXMMRegs =
2551         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2552     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2553            "SSE register cannot be used when SSE is disabled!");
2554
2555     // Gather all the live in physical registers.
2556     SmallVector<SDValue, 6> LiveGPRs;
2557     SmallVector<SDValue, 8> LiveXMMRegs;
2558     SDValue ALVal;
2559     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2560       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2561       LiveGPRs.push_back(
2562           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2563     }
2564     if (!ArgXMMs.empty()) {
2565       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2566       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2567       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2568         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2569         LiveXMMRegs.push_back(
2570             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2571       }
2572     }
2573
2574     // Store them to the va_list returned by va_start.
2575     if (MFI->hasVAStart()) {
2576       if (IsWin64) {
2577         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2578         // Get to the caller-allocated home save location.  Add 8 to account
2579         // for the return address.
2580         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2581         FuncInfo->setRegSaveFrameIndex(
2582           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2583         // Fixup to set vararg frame on shadow area (4 x i64).
2584         if (NumIntRegs < 4)
2585           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2586       } else {
2587         // For X86-64, if there are vararg parameters that are passed via
2588         // registers, then we must store them to their spots on the stack so
2589         // they may be loaded by deferencing the result of va_next.
2590         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2591         FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2592         FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2593             ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2594       }
2595
2596       // Store the integer parameter registers.
2597       SmallVector<SDValue, 8> MemOps;
2598       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2599                                         getPointerTy());
2600       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2601       for (SDValue Val : LiveGPRs) {
2602         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2603                                   DAG.getIntPtrConstant(Offset));
2604         SDValue Store =
2605           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2606                        MachinePointerInfo::getFixedStack(
2607                          FuncInfo->getRegSaveFrameIndex(), Offset),
2608                        false, false, 0);
2609         MemOps.push_back(Store);
2610         Offset += 8;
2611       }
2612
2613       if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2614         // Now store the XMM (fp + vector) parameter registers.
2615         SmallVector<SDValue, 12> SaveXMMOps;
2616         SaveXMMOps.push_back(Chain);
2617         SaveXMMOps.push_back(ALVal);
2618         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2619                                FuncInfo->getRegSaveFrameIndex()));
2620         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2621                                FuncInfo->getVarArgsFPOffset()));
2622         SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2623                           LiveXMMRegs.end());
2624         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2625                                      MVT::Other, SaveXMMOps));
2626       }
2627
2628       if (!MemOps.empty())
2629         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2630     } else {
2631       // Add all GPRs, al, and XMMs to the list of forwards.  We will add then
2632       // to the liveout set on a musttail call.
2633       assert(MFI->hasMustTailInVarArgFunc());
2634       auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2635       typedef X86MachineFunctionInfo::Forward Forward;
2636
2637       for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2638         unsigned VReg =
2639             MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2640         Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2641         Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2642       }
2643
2644       if (!ArgXMMs.empty()) {
2645         unsigned ALVReg =
2646             MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2647         Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2648         Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2649
2650         for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2651           unsigned VReg =
2652               MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2653           Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2654           Forwards.push_back(
2655               Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2656         }
2657       }
2658     }
2659   }
2660
2661   // Some CCs need callee pop.
2662   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2663                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2664     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2665   } else {
2666     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2667     // If this is an sret function, the return should pop the hidden pointer.
2668     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2669         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2670         argsAreStructReturn(Ins) == StackStructReturn)
2671       FuncInfo->setBytesToPopOnReturn(4);
2672   }
2673
2674   if (!Is64Bit) {
2675     // RegSaveFrameIndex is X86-64 only.
2676     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2677     if (CallConv == CallingConv::X86_FastCall ||
2678         CallConv == CallingConv::X86_ThisCall)
2679       // fastcc functions can't have varargs.
2680       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2681   }
2682
2683   FuncInfo->setArgumentStackSize(StackSize);
2684
2685   return Chain;
2686 }
2687
2688 SDValue
2689 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2690                                     SDValue StackPtr, SDValue Arg,
2691                                     SDLoc dl, SelectionDAG &DAG,
2692                                     const CCValAssign &VA,
2693                                     ISD::ArgFlagsTy Flags) const {
2694   unsigned LocMemOffset = VA.getLocMemOffset();
2695   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2696   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2697   if (Flags.isByVal())
2698     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2699
2700   return DAG.getStore(Chain, dl, Arg, PtrOff,
2701                       MachinePointerInfo::getStack(LocMemOffset),
2702                       false, false, 0);
2703 }
2704
2705 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2706 /// optimization is performed and it is required.
2707 SDValue
2708 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2709                                            SDValue &OutRetAddr, SDValue Chain,
2710                                            bool IsTailCall, bool Is64Bit,
2711                                            int FPDiff, SDLoc dl) const {
2712   // Adjust the Return address stack slot.
2713   EVT VT = getPointerTy();
2714   OutRetAddr = getReturnAddressFrameIndex(DAG);
2715
2716   // Load the "old" Return address.
2717   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2718                            false, false, false, 0);
2719   return SDValue(OutRetAddr.getNode(), 1);
2720 }
2721
2722 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2723 /// optimization is performed and it is required (FPDiff!=0).
2724 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2725                                         SDValue Chain, SDValue RetAddrFrIdx,
2726                                         EVT PtrVT, unsigned SlotSize,
2727                                         int FPDiff, SDLoc dl) {
2728   // Store the return address to the appropriate stack slot.
2729   if (!FPDiff) return Chain;
2730   // Calculate the new stack slot for the return address.
2731   int NewReturnAddrFI =
2732     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2733                                          false);
2734   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2735   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2736                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2737                        false, false, 0);
2738   return Chain;
2739 }
2740
2741 SDValue
2742 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2743                              SmallVectorImpl<SDValue> &InVals) const {
2744   SelectionDAG &DAG                     = CLI.DAG;
2745   SDLoc &dl                             = CLI.DL;
2746   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2747   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2748   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2749   SDValue Chain                         = CLI.Chain;
2750   SDValue Callee                        = CLI.Callee;
2751   CallingConv::ID CallConv              = CLI.CallConv;
2752   bool &isTailCall                      = CLI.IsTailCall;
2753   bool isVarArg                         = CLI.IsVarArg;
2754
2755   MachineFunction &MF = DAG.getMachineFunction();
2756   bool Is64Bit        = Subtarget->is64Bit();
2757   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2758   StructReturnType SR = callIsStructReturn(Outs);
2759   bool IsSibcall      = false;
2760   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2761
2762   if (MF.getTarget().Options.DisableTailCalls)
2763     isTailCall = false;
2764
2765   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2766   if (IsMustTail) {
2767     // Force this to be a tail call.  The verifier rules are enough to ensure
2768     // that we can lower this successfully without moving the return address
2769     // around.
2770     isTailCall = true;
2771   } else if (isTailCall) {
2772     // Check if it's really possible to do a tail call.
2773     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2774                     isVarArg, SR != NotStructReturn,
2775                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2776                     Outs, OutVals, Ins, DAG);
2777
2778     // Sibcalls are automatically detected tailcalls which do not require
2779     // ABI changes.
2780     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2781       IsSibcall = true;
2782
2783     if (isTailCall)
2784       ++NumTailCalls;
2785   }
2786
2787   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2788          "Var args not supported with calling convention fastcc, ghc or hipe");
2789
2790   // Analyze operands of the call, assigning locations to each operand.
2791   SmallVector<CCValAssign, 16> ArgLocs;
2792   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2793
2794   // Allocate shadow area for Win64
2795   if (IsWin64)
2796     CCInfo.AllocateStack(32, 8);
2797
2798   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2799
2800   // Get a count of how many bytes are to be pushed on the stack.
2801   unsigned NumBytes = CCInfo.getNextStackOffset();
2802   if (IsSibcall)
2803     // This is a sibcall. The memory operands are available in caller's
2804     // own caller's stack.
2805     NumBytes = 0;
2806   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2807            IsTailCallConvention(CallConv))
2808     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2809
2810   int FPDiff = 0;
2811   if (isTailCall && !IsSibcall && !IsMustTail) {
2812     // Lower arguments at fp - stackoffset + fpdiff.
2813     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2814
2815     FPDiff = NumBytesCallerPushed - NumBytes;
2816
2817     // Set the delta of movement of the returnaddr stackslot.
2818     // But only set if delta is greater than previous delta.
2819     if (FPDiff < X86Info->getTCReturnAddrDelta())
2820       X86Info->setTCReturnAddrDelta(FPDiff);
2821   }
2822
2823   unsigned NumBytesToPush = NumBytes;
2824   unsigned NumBytesToPop = NumBytes;
2825
2826   // If we have an inalloca argument, all stack space has already been allocated
2827   // for us and be right at the top of the stack.  We don't support multiple
2828   // arguments passed in memory when using inalloca.
2829   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2830     NumBytesToPush = 0;
2831     if (!ArgLocs.back().isMemLoc())
2832       report_fatal_error("cannot use inalloca attribute on a register "
2833                          "parameter");
2834     if (ArgLocs.back().getLocMemOffset() != 0)
2835       report_fatal_error("any parameter with the inalloca attribute must be "
2836                          "the only memory argument");
2837   }
2838
2839   if (!IsSibcall)
2840     Chain = DAG.getCALLSEQ_START(
2841         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2842
2843   SDValue RetAddrFrIdx;
2844   // Load return address for tail calls.
2845   if (isTailCall && FPDiff)
2846     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2847                                     Is64Bit, FPDiff, dl);
2848
2849   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2850   SmallVector<SDValue, 8> MemOpChains;
2851   SDValue StackPtr;
2852
2853   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2854   // of tail call optimization arguments are handle later.
2855   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2856       DAG.getSubtarget().getRegisterInfo());
2857   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2858     // Skip inalloca arguments, they have already been written.
2859     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2860     if (Flags.isInAlloca())
2861       continue;
2862
2863     CCValAssign &VA = ArgLocs[i];
2864     EVT RegVT = VA.getLocVT();
2865     SDValue Arg = OutVals[i];
2866     bool isByVal = Flags.isByVal();
2867
2868     // Promote the value if needed.
2869     switch (VA.getLocInfo()) {
2870     default: llvm_unreachable("Unknown loc info!");
2871     case CCValAssign::Full: break;
2872     case CCValAssign::SExt:
2873       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2874       break;
2875     case CCValAssign::ZExt:
2876       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2877       break;
2878     case CCValAssign::AExt:
2879       if (RegVT.is128BitVector()) {
2880         // Special case: passing MMX values in XMM registers.
2881         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2882         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2883         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2884       } else
2885         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2886       break;
2887     case CCValAssign::BCvt:
2888       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2889       break;
2890     case CCValAssign::Indirect: {
2891       // Store the argument.
2892       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2893       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2894       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2895                            MachinePointerInfo::getFixedStack(FI),
2896                            false, false, 0);
2897       Arg = SpillSlot;
2898       break;
2899     }
2900     }
2901
2902     if (VA.isRegLoc()) {
2903       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2904       if (isVarArg && IsWin64) {
2905         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2906         // shadow reg if callee is a varargs function.
2907         unsigned ShadowReg = 0;
2908         switch (VA.getLocReg()) {
2909         case X86::XMM0: ShadowReg = X86::RCX; break;
2910         case X86::XMM1: ShadowReg = X86::RDX; break;
2911         case X86::XMM2: ShadowReg = X86::R8; break;
2912         case X86::XMM3: ShadowReg = X86::R9; break;
2913         }
2914         if (ShadowReg)
2915           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2916       }
2917     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2918       assert(VA.isMemLoc());
2919       if (!StackPtr.getNode())
2920         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2921                                       getPointerTy());
2922       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2923                                              dl, DAG, VA, Flags));
2924     }
2925   }
2926
2927   if (!MemOpChains.empty())
2928     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2929
2930   if (Subtarget->isPICStyleGOT()) {
2931     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2932     // GOT pointer.
2933     if (!isTailCall) {
2934       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2935                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2936     } else {
2937       // If we are tail calling and generating PIC/GOT style code load the
2938       // address of the callee into ECX. The value in ecx is used as target of
2939       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2940       // for tail calls on PIC/GOT architectures. Normally we would just put the
2941       // address of GOT into ebx and then call target@PLT. But for tail calls
2942       // ebx would be restored (since ebx is callee saved) before jumping to the
2943       // target@PLT.
2944
2945       // Note: The actual moving to ECX is done further down.
2946       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2947       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2948           !G->getGlobal()->hasProtectedVisibility())
2949         Callee = LowerGlobalAddress(Callee, DAG);
2950       else if (isa<ExternalSymbolSDNode>(Callee))
2951         Callee = LowerExternalSymbol(Callee, DAG);
2952     }
2953   }
2954
2955   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2956     // From AMD64 ABI document:
2957     // For calls that may call functions that use varargs or stdargs
2958     // (prototype-less calls or calls to functions containing ellipsis (...) in
2959     // the declaration) %al is used as hidden argument to specify the number
2960     // of SSE registers used. The contents of %al do not need to match exactly
2961     // the number of registers, but must be an ubound on the number of SSE
2962     // registers used and is in the range 0 - 8 inclusive.
2963
2964     // Count the number of XMM registers allocated.
2965     static const MCPhysReg XMMArgRegs[] = {
2966       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2967       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2968     };
2969     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2970     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2971            && "SSE registers cannot be used when SSE is disabled");
2972
2973     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2974                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2975   }
2976
2977   if (Is64Bit && isVarArg && IsMustTail) {
2978     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2979     for (const auto &F : Forwards) {
2980       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2981       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2982     }
2983   }
2984
2985   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2986   // don't need this because the eligibility check rejects calls that require
2987   // shuffling arguments passed in memory.
2988   if (!IsSibcall && isTailCall) {
2989     // Force all the incoming stack arguments to be loaded from the stack
2990     // before any new outgoing arguments are stored to the stack, because the
2991     // outgoing stack slots may alias the incoming argument stack slots, and
2992     // the alias isn't otherwise explicit. This is slightly more conservative
2993     // than necessary, because it means that each store effectively depends
2994     // on every argument instead of just those arguments it would clobber.
2995     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2996
2997     SmallVector<SDValue, 8> MemOpChains2;
2998     SDValue FIN;
2999     int FI = 0;
3000     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3001       CCValAssign &VA = ArgLocs[i];
3002       if (VA.isRegLoc())
3003         continue;
3004       assert(VA.isMemLoc());
3005       SDValue Arg = OutVals[i];
3006       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3007       // Skip inalloca arguments.  They don't require any work.
3008       if (Flags.isInAlloca())
3009         continue;
3010       // Create frame index.
3011       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3012       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3013       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3014       FIN = DAG.getFrameIndex(FI, getPointerTy());
3015
3016       if (Flags.isByVal()) {
3017         // Copy relative to framepointer.
3018         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3019         if (!StackPtr.getNode())
3020           StackPtr = DAG.getCopyFromReg(Chain, dl,
3021                                         RegInfo->getStackRegister(),
3022                                         getPointerTy());
3023         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3024
3025         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3026                                                          ArgChain,
3027                                                          Flags, DAG, dl));
3028       } else {
3029         // Store relative to framepointer.
3030         MemOpChains2.push_back(
3031           DAG.getStore(ArgChain, dl, Arg, FIN,
3032                        MachinePointerInfo::getFixedStack(FI),
3033                        false, false, 0));
3034       }
3035     }
3036
3037     if (!MemOpChains2.empty())
3038       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3039
3040     // Store the return address to the appropriate stack slot.
3041     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3042                                      getPointerTy(), RegInfo->getSlotSize(),
3043                                      FPDiff, dl);
3044   }
3045
3046   // Build a sequence of copy-to-reg nodes chained together with token chain
3047   // and flag operands which copy the outgoing args into registers.
3048   SDValue InFlag;
3049   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3050     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3051                              RegsToPass[i].second, InFlag);
3052     InFlag = Chain.getValue(1);
3053   }
3054
3055   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3056     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3057     // In the 64-bit large code model, we have to make all calls
3058     // through a register, since the call instruction's 32-bit
3059     // pc-relative offset may not be large enough to hold the whole
3060     // address.
3061   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3062     // If the callee is a GlobalAddress node (quite common, every direct call
3063     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3064     // it.
3065
3066     // We should use extra load for direct calls to dllimported functions in
3067     // non-JIT mode.
3068     const GlobalValue *GV = G->getGlobal();
3069     if (!GV->hasDLLImportStorageClass()) {
3070       unsigned char OpFlags = 0;
3071       bool ExtraLoad = false;
3072       unsigned WrapperKind = ISD::DELETED_NODE;
3073
3074       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3075       // external symbols most go through the PLT in PIC mode.  If the symbol
3076       // has hidden or protected visibility, or if it is static or local, then
3077       // we don't need to use the PLT - we can directly call it.
3078       if (Subtarget->isTargetELF() &&
3079           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3080           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3081         OpFlags = X86II::MO_PLT;
3082       } else if (Subtarget->isPICStyleStubAny() &&
3083                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3084                  (!Subtarget->getTargetTriple().isMacOSX() ||
3085                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3086         // PC-relative references to external symbols should go through $stub,
3087         // unless we're building with the leopard linker or later, which
3088         // automatically synthesizes these stubs.
3089         OpFlags = X86II::MO_DARWIN_STUB;
3090       } else if (Subtarget->isPICStyleRIPRel() &&
3091                  isa<Function>(GV) &&
3092                  cast<Function>(GV)->getAttributes().
3093                    hasAttribute(AttributeSet::FunctionIndex,
3094                                 Attribute::NonLazyBind)) {
3095         // If the function is marked as non-lazy, generate an indirect call
3096         // which loads from the GOT directly. This avoids runtime overhead
3097         // at the cost of eager binding (and one extra byte of encoding).
3098         OpFlags = X86II::MO_GOTPCREL;
3099         WrapperKind = X86ISD::WrapperRIP;
3100         ExtraLoad = true;
3101       }
3102
3103       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3104                                           G->getOffset(), OpFlags);
3105
3106       // Add a wrapper if needed.
3107       if (WrapperKind != ISD::DELETED_NODE)
3108         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3109       // Add extra indirection if needed.
3110       if (ExtraLoad)
3111         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3112                              MachinePointerInfo::getGOT(),
3113                              false, false, false, 0);
3114     }
3115   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3116     unsigned char OpFlags = 0;
3117
3118     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3119     // external symbols should go through the PLT.
3120     if (Subtarget->isTargetELF() &&
3121         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3122       OpFlags = X86II::MO_PLT;
3123     } else if (Subtarget->isPICStyleStubAny() &&
3124                (!Subtarget->getTargetTriple().isMacOSX() ||
3125                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3126       // PC-relative references to external symbols should go through $stub,
3127       // unless we're building with the leopard linker or later, which
3128       // automatically synthesizes these stubs.
3129       OpFlags = X86II::MO_DARWIN_STUB;
3130     }
3131
3132     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3133                                          OpFlags);
3134   } else if (Subtarget->isTarget64BitILP32() && Callee->getValueType(0) == MVT::i32) {
3135     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3136     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3137   }
3138
3139   // Returns a chain & a flag for retval copy to use.
3140   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3141   SmallVector<SDValue, 8> Ops;
3142
3143   if (!IsSibcall && isTailCall) {
3144     Chain = DAG.getCALLSEQ_END(Chain,
3145                                DAG.getIntPtrConstant(NumBytesToPop, true),
3146                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3147     InFlag = Chain.getValue(1);
3148   }
3149
3150   Ops.push_back(Chain);
3151   Ops.push_back(Callee);
3152
3153   if (isTailCall)
3154     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3155
3156   // Add argument registers to the end of the list so that they are known live
3157   // into the call.
3158   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3159     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3160                                   RegsToPass[i].second.getValueType()));
3161
3162   // Add a register mask operand representing the call-preserved registers.
3163   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3164   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3165   assert(Mask && "Missing call preserved mask for calling convention");
3166   Ops.push_back(DAG.getRegisterMask(Mask));
3167
3168   if (InFlag.getNode())
3169     Ops.push_back(InFlag);
3170
3171   if (isTailCall) {
3172     // We used to do:
3173     //// If this is the first return lowered for this function, add the regs
3174     //// to the liveout set for the function.
3175     // This isn't right, although it's probably harmless on x86; liveouts
3176     // should be computed from returns not tail calls.  Consider a void
3177     // function making a tail call to a function returning int.
3178     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3179   }
3180
3181   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3182   InFlag = Chain.getValue(1);
3183
3184   // Create the CALLSEQ_END node.
3185   unsigned NumBytesForCalleeToPop;
3186   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3187                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3188     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3189   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3190            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3191            SR == StackStructReturn)
3192     // If this is a call to a struct-return function, the callee
3193     // pops the hidden struct pointer, so we have to push it back.
3194     // This is common for Darwin/X86, Linux & Mingw32 targets.
3195     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3196     NumBytesForCalleeToPop = 4;
3197   else
3198     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3199
3200   // Returns a flag for retval copy to use.
3201   if (!IsSibcall) {
3202     Chain = DAG.getCALLSEQ_END(Chain,
3203                                DAG.getIntPtrConstant(NumBytesToPop, true),
3204                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3205                                                      true),
3206                                InFlag, dl);
3207     InFlag = Chain.getValue(1);
3208   }
3209
3210   // Handle result values, copying them out of physregs into vregs that we
3211   // return.
3212   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3213                          Ins, dl, DAG, InVals);
3214 }
3215
3216 //===----------------------------------------------------------------------===//
3217 //                Fast Calling Convention (tail call) implementation
3218 //===----------------------------------------------------------------------===//
3219
3220 //  Like std call, callee cleans arguments, convention except that ECX is
3221 //  reserved for storing the tail called function address. Only 2 registers are
3222 //  free for argument passing (inreg). Tail call optimization is performed
3223 //  provided:
3224 //                * tailcallopt is enabled
3225 //                * caller/callee are fastcc
3226 //  On X86_64 architecture with GOT-style position independent code only local
3227 //  (within module) calls are supported at the moment.
3228 //  To keep the stack aligned according to platform abi the function
3229 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3230 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3231 //  If a tail called function callee has more arguments than the caller the
3232 //  caller needs to make sure that there is room to move the RETADDR to. This is
3233 //  achieved by reserving an area the size of the argument delta right after the
3234 //  original RETADDR, but before the saved framepointer or the spilled registers
3235 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3236 //  stack layout:
3237 //    arg1
3238 //    arg2
3239 //    RETADDR
3240 //    [ new RETADDR
3241 //      move area ]
3242 //    (possible EBP)
3243 //    ESI
3244 //    EDI
3245 //    local1 ..
3246
3247 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3248 /// for a 16 byte align requirement.
3249 unsigned
3250 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3251                                                SelectionDAG& DAG) const {
3252   MachineFunction &MF = DAG.getMachineFunction();
3253   const TargetMachine &TM = MF.getTarget();
3254   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3255       TM.getSubtargetImpl()->getRegisterInfo());
3256   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3257   unsigned StackAlignment = TFI.getStackAlignment();
3258   uint64_t AlignMask = StackAlignment - 1;
3259   int64_t Offset = StackSize;
3260   unsigned SlotSize = RegInfo->getSlotSize();
3261   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3262     // Number smaller than 12 so just add the difference.
3263     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3264   } else {
3265     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3266     Offset = ((~AlignMask) & Offset) + StackAlignment +
3267       (StackAlignment-SlotSize);
3268   }
3269   return Offset;
3270 }
3271
3272 /// MatchingStackOffset - Return true if the given stack call argument is
3273 /// already available in the same position (relatively) of the caller's
3274 /// incoming argument stack.
3275 static
3276 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3277                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3278                          const X86InstrInfo *TII) {
3279   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3280   int FI = INT_MAX;
3281   if (Arg.getOpcode() == ISD::CopyFromReg) {
3282     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3283     if (!TargetRegisterInfo::isVirtualRegister(VR))
3284       return false;
3285     MachineInstr *Def = MRI->getVRegDef(VR);
3286     if (!Def)
3287       return false;
3288     if (!Flags.isByVal()) {
3289       if (!TII->isLoadFromStackSlot(Def, FI))
3290         return false;
3291     } else {
3292       unsigned Opcode = Def->getOpcode();
3293       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3294           Def->getOperand(1).isFI()) {
3295         FI = Def->getOperand(1).getIndex();
3296         Bytes = Flags.getByValSize();
3297       } else
3298         return false;
3299     }
3300   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3301     if (Flags.isByVal())
3302       // ByVal argument is passed in as a pointer but it's now being
3303       // dereferenced. e.g.
3304       // define @foo(%struct.X* %A) {
3305       //   tail call @bar(%struct.X* byval %A)
3306       // }
3307       return false;
3308     SDValue Ptr = Ld->getBasePtr();
3309     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3310     if (!FINode)
3311       return false;
3312     FI = FINode->getIndex();
3313   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3314     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3315     FI = FINode->getIndex();
3316     Bytes = Flags.getByValSize();
3317   } else
3318     return false;
3319
3320   assert(FI != INT_MAX);
3321   if (!MFI->isFixedObjectIndex(FI))
3322     return false;
3323   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3324 }
3325
3326 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3327 /// for tail call optimization. Targets which want to do tail call
3328 /// optimization should implement this function.
3329 bool
3330 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3331                                                      CallingConv::ID CalleeCC,
3332                                                      bool isVarArg,
3333                                                      bool isCalleeStructRet,
3334                                                      bool isCallerStructRet,
3335                                                      Type *RetTy,
3336                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3337                                     const SmallVectorImpl<SDValue> &OutVals,
3338                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3339                                                      SelectionDAG &DAG) const {
3340   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3341     return false;
3342
3343   // If -tailcallopt is specified, make fastcc functions tail-callable.
3344   const MachineFunction &MF = DAG.getMachineFunction();
3345   const Function *CallerF = MF.getFunction();
3346
3347   // If the function return type is x86_fp80 and the callee return type is not,
3348   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3349   // perform a tailcall optimization here.
3350   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3351     return false;
3352
3353   CallingConv::ID CallerCC = CallerF->getCallingConv();
3354   bool CCMatch = CallerCC == CalleeCC;
3355   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3356   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3357
3358   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3359     if (IsTailCallConvention(CalleeCC) && CCMatch)
3360       return true;
3361     return false;
3362   }
3363
3364   // Look for obvious safe cases to perform tail call optimization that do not
3365   // require ABI changes. This is what gcc calls sibcall.
3366
3367   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3368   // emit a special epilogue.
3369   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3370       DAG.getSubtarget().getRegisterInfo());
3371   if (RegInfo->needsStackRealignment(MF))
3372     return false;
3373
3374   // Also avoid sibcall optimization if either caller or callee uses struct
3375   // return semantics.
3376   if (isCalleeStructRet || isCallerStructRet)
3377     return false;
3378
3379   // An stdcall/thiscall caller is expected to clean up its arguments; the
3380   // callee isn't going to do that.
3381   // FIXME: this is more restrictive than needed. We could produce a tailcall
3382   // when the stack adjustment matches. For example, with a thiscall that takes
3383   // only one argument.
3384   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3385                    CallerCC == CallingConv::X86_ThisCall))
3386     return false;
3387
3388   // Do not sibcall optimize vararg calls unless all arguments are passed via
3389   // registers.
3390   if (isVarArg && !Outs.empty()) {
3391
3392     // Optimizing for varargs on Win64 is unlikely to be safe without
3393     // additional testing.
3394     if (IsCalleeWin64 || IsCallerWin64)
3395       return false;
3396
3397     SmallVector<CCValAssign, 16> ArgLocs;
3398     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3399                    *DAG.getContext());
3400
3401     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3402     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3403       if (!ArgLocs[i].isRegLoc())
3404         return false;
3405   }
3406
3407   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3408   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3409   // this into a sibcall.
3410   bool Unused = false;
3411   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3412     if (!Ins[i].Used) {
3413       Unused = true;
3414       break;
3415     }
3416   }
3417   if (Unused) {
3418     SmallVector<CCValAssign, 16> RVLocs;
3419     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3420                    *DAG.getContext());
3421     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3422     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3423       CCValAssign &VA = RVLocs[i];
3424       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3425         return false;
3426     }
3427   }
3428
3429   // If the calling conventions do not match, then we'd better make sure the
3430   // results are returned in the same way as what the caller expects.
3431   if (!CCMatch) {
3432     SmallVector<CCValAssign, 16> RVLocs1;
3433     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3434                     *DAG.getContext());
3435     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3436
3437     SmallVector<CCValAssign, 16> RVLocs2;
3438     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3439                     *DAG.getContext());
3440     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3441
3442     if (RVLocs1.size() != RVLocs2.size())
3443       return false;
3444     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3445       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3446         return false;
3447       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3448         return false;
3449       if (RVLocs1[i].isRegLoc()) {
3450         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3451           return false;
3452       } else {
3453         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3454           return false;
3455       }
3456     }
3457   }
3458
3459   // If the callee takes no arguments then go on to check the results of the
3460   // call.
3461   if (!Outs.empty()) {
3462     // Check if stack adjustment is needed. For now, do not do this if any
3463     // argument is passed on the stack.
3464     SmallVector<CCValAssign, 16> ArgLocs;
3465     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3466                    *DAG.getContext());
3467
3468     // Allocate shadow area for Win64
3469     if (IsCalleeWin64)
3470       CCInfo.AllocateStack(32, 8);
3471
3472     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3473     if (CCInfo.getNextStackOffset()) {
3474       MachineFunction &MF = DAG.getMachineFunction();
3475       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3476         return false;
3477
3478       // Check if the arguments are already laid out in the right way as
3479       // the caller's fixed stack objects.
3480       MachineFrameInfo *MFI = MF.getFrameInfo();
3481       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3482       const X86InstrInfo *TII =
3483           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3484       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3485         CCValAssign &VA = ArgLocs[i];
3486         SDValue Arg = OutVals[i];
3487         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3488         if (VA.getLocInfo() == CCValAssign::Indirect)
3489           return false;
3490         if (!VA.isRegLoc()) {
3491           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3492                                    MFI, MRI, TII))
3493             return false;
3494         }
3495       }
3496     }
3497
3498     // If the tailcall address may be in a register, then make sure it's
3499     // possible to register allocate for it. In 32-bit, the call address can
3500     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3501     // callee-saved registers are restored. These happen to be the same
3502     // registers used to pass 'inreg' arguments so watch out for those.
3503     if (!Subtarget->is64Bit() &&
3504         ((!isa<GlobalAddressSDNode>(Callee) &&
3505           !isa<ExternalSymbolSDNode>(Callee)) ||
3506          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3507       unsigned NumInRegs = 0;
3508       // In PIC we need an extra register to formulate the address computation
3509       // for the callee.
3510       unsigned MaxInRegs =
3511         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3512
3513       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3514         CCValAssign &VA = ArgLocs[i];
3515         if (!VA.isRegLoc())
3516           continue;
3517         unsigned Reg = VA.getLocReg();
3518         switch (Reg) {
3519         default: break;
3520         case X86::EAX: case X86::EDX: case X86::ECX:
3521           if (++NumInRegs == MaxInRegs)
3522             return false;
3523           break;
3524         }
3525       }
3526     }
3527   }
3528
3529   return true;
3530 }
3531
3532 FastISel *
3533 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3534                                   const TargetLibraryInfo *libInfo) const {
3535   return X86::createFastISel(funcInfo, libInfo);
3536 }
3537
3538 //===----------------------------------------------------------------------===//
3539 //                           Other Lowering Hooks
3540 //===----------------------------------------------------------------------===//
3541
3542 static bool MayFoldLoad(SDValue Op) {
3543   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3544 }
3545
3546 static bool MayFoldIntoStore(SDValue Op) {
3547   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3548 }
3549
3550 static bool isTargetShuffle(unsigned Opcode) {
3551   switch(Opcode) {
3552   default: return false;
3553   case X86ISD::BLENDI:
3554   case X86ISD::PSHUFB:
3555   case X86ISD::PSHUFD:
3556   case X86ISD::PSHUFHW:
3557   case X86ISD::PSHUFLW:
3558   case X86ISD::SHUFP:
3559   case X86ISD::PALIGNR:
3560   case X86ISD::MOVLHPS:
3561   case X86ISD::MOVLHPD:
3562   case X86ISD::MOVHLPS:
3563   case X86ISD::MOVLPS:
3564   case X86ISD::MOVLPD:
3565   case X86ISD::MOVSHDUP:
3566   case X86ISD::MOVSLDUP:
3567   case X86ISD::MOVDDUP:
3568   case X86ISD::MOVSS:
3569   case X86ISD::MOVSD:
3570   case X86ISD::UNPCKL:
3571   case X86ISD::UNPCKH:
3572   case X86ISD::VPERMILPI:
3573   case X86ISD::VPERM2X128:
3574   case X86ISD::VPERMI:
3575     return true;
3576   }
3577 }
3578
3579 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3580                                     SDValue V1, SelectionDAG &DAG) {
3581   switch(Opc) {
3582   default: llvm_unreachable("Unknown x86 shuffle node");
3583   case X86ISD::MOVSHDUP:
3584   case X86ISD::MOVSLDUP:
3585   case X86ISD::MOVDDUP:
3586     return DAG.getNode(Opc, dl, VT, V1);
3587   }
3588 }
3589
3590 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3591                                     SDValue V1, unsigned TargetMask,
3592                                     SelectionDAG &DAG) {
3593   switch(Opc) {
3594   default: llvm_unreachable("Unknown x86 shuffle node");
3595   case X86ISD::PSHUFD:
3596   case X86ISD::PSHUFHW:
3597   case X86ISD::PSHUFLW:
3598   case X86ISD::VPERMILPI:
3599   case X86ISD::VPERMI:
3600     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3601   }
3602 }
3603
3604 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3605                                     SDValue V1, SDValue V2, unsigned TargetMask,
3606                                     SelectionDAG &DAG) {
3607   switch(Opc) {
3608   default: llvm_unreachable("Unknown x86 shuffle node");
3609   case X86ISD::PALIGNR:
3610   case X86ISD::VALIGN:
3611   case X86ISD::SHUFP:
3612   case X86ISD::VPERM2X128:
3613     return DAG.getNode(Opc, dl, VT, V1, V2,
3614                        DAG.getConstant(TargetMask, MVT::i8));
3615   }
3616 }
3617
3618 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3619                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3620   switch(Opc) {
3621   default: llvm_unreachable("Unknown x86 shuffle node");
3622   case X86ISD::MOVLHPS:
3623   case X86ISD::MOVLHPD:
3624   case X86ISD::MOVHLPS:
3625   case X86ISD::MOVLPS:
3626   case X86ISD::MOVLPD:
3627   case X86ISD::MOVSS:
3628   case X86ISD::MOVSD:
3629   case X86ISD::UNPCKL:
3630   case X86ISD::UNPCKH:
3631     return DAG.getNode(Opc, dl, VT, V1, V2);
3632   }
3633 }
3634
3635 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3636   MachineFunction &MF = DAG.getMachineFunction();
3637   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3638       DAG.getSubtarget().getRegisterInfo());
3639   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3640   int ReturnAddrIndex = FuncInfo->getRAIndex();
3641
3642   if (ReturnAddrIndex == 0) {
3643     // Set up a frame object for the return address.
3644     unsigned SlotSize = RegInfo->getSlotSize();
3645     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3646                                                            -(int64_t)SlotSize,
3647                                                            false);
3648     FuncInfo->setRAIndex(ReturnAddrIndex);
3649   }
3650
3651   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3652 }
3653
3654 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3655                                        bool hasSymbolicDisplacement) {
3656   // Offset should fit into 32 bit immediate field.
3657   if (!isInt<32>(Offset))
3658     return false;
3659
3660   // If we don't have a symbolic displacement - we don't have any extra
3661   // restrictions.
3662   if (!hasSymbolicDisplacement)
3663     return true;
3664
3665   // FIXME: Some tweaks might be needed for medium code model.
3666   if (M != CodeModel::Small && M != CodeModel::Kernel)
3667     return false;
3668
3669   // For small code model we assume that latest object is 16MB before end of 31
3670   // bits boundary. We may also accept pretty large negative constants knowing
3671   // that all objects are in the positive half of address space.
3672   if (M == CodeModel::Small && Offset < 16*1024*1024)
3673     return true;
3674
3675   // For kernel code model we know that all object resist in the negative half
3676   // of 32bits address space. We may not accept negative offsets, since they may
3677   // be just off and we may accept pretty large positive ones.
3678   if (M == CodeModel::Kernel && Offset > 0)
3679     return true;
3680
3681   return false;
3682 }
3683
3684 /// isCalleePop - Determines whether the callee is required to pop its
3685 /// own arguments. Callee pop is necessary to support tail calls.
3686 bool X86::isCalleePop(CallingConv::ID CallingConv,
3687                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3688   switch (CallingConv) {
3689   default:
3690     return false;
3691   case CallingConv::X86_StdCall:
3692   case CallingConv::X86_FastCall:
3693   case CallingConv::X86_ThisCall:
3694     return !is64Bit;
3695   case CallingConv::Fast:
3696   case CallingConv::GHC:
3697   case CallingConv::HiPE:
3698     if (IsVarArg)
3699       return false;
3700     return TailCallOpt;
3701   }
3702 }
3703
3704 /// \brief Return true if the condition is an unsigned comparison operation.
3705 static bool isX86CCUnsigned(unsigned X86CC) {
3706   switch (X86CC) {
3707   default: llvm_unreachable("Invalid integer condition!");
3708   case X86::COND_E:     return true;
3709   case X86::COND_G:     return false;
3710   case X86::COND_GE:    return false;
3711   case X86::COND_L:     return false;
3712   case X86::COND_LE:    return false;
3713   case X86::COND_NE:    return true;
3714   case X86::COND_B:     return true;
3715   case X86::COND_A:     return true;
3716   case X86::COND_BE:    return true;
3717   case X86::COND_AE:    return true;
3718   }
3719   llvm_unreachable("covered switch fell through?!");
3720 }
3721
3722 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3723 /// specific condition code, returning the condition code and the LHS/RHS of the
3724 /// comparison to make.
3725 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3726                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3727   if (!isFP) {
3728     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3729       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3730         // X > -1   -> X == 0, jump !sign.
3731         RHS = DAG.getConstant(0, RHS.getValueType());
3732         return X86::COND_NS;
3733       }
3734       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3735         // X < 0   -> X == 0, jump on sign.
3736         return X86::COND_S;
3737       }
3738       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3739         // X < 1   -> X <= 0
3740         RHS = DAG.getConstant(0, RHS.getValueType());
3741         return X86::COND_LE;
3742       }
3743     }
3744
3745     switch (SetCCOpcode) {
3746     default: llvm_unreachable("Invalid integer condition!");
3747     case ISD::SETEQ:  return X86::COND_E;
3748     case ISD::SETGT:  return X86::COND_G;
3749     case ISD::SETGE:  return X86::COND_GE;
3750     case ISD::SETLT:  return X86::COND_L;
3751     case ISD::SETLE:  return X86::COND_LE;
3752     case ISD::SETNE:  return X86::COND_NE;
3753     case ISD::SETULT: return X86::COND_B;
3754     case ISD::SETUGT: return X86::COND_A;
3755     case ISD::SETULE: return X86::COND_BE;
3756     case ISD::SETUGE: return X86::COND_AE;
3757     }
3758   }
3759
3760   // First determine if it is required or is profitable to flip the operands.
3761
3762   // If LHS is a foldable load, but RHS is not, flip the condition.
3763   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3764       !ISD::isNON_EXTLoad(RHS.getNode())) {
3765     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3766     std::swap(LHS, RHS);
3767   }
3768
3769   switch (SetCCOpcode) {
3770   default: break;
3771   case ISD::SETOLT:
3772   case ISD::SETOLE:
3773   case ISD::SETUGT:
3774   case ISD::SETUGE:
3775     std::swap(LHS, RHS);
3776     break;
3777   }
3778
3779   // On a floating point condition, the flags are set as follows:
3780   // ZF  PF  CF   op
3781   //  0 | 0 | 0 | X > Y
3782   //  0 | 0 | 1 | X < Y
3783   //  1 | 0 | 0 | X == Y
3784   //  1 | 1 | 1 | unordered
3785   switch (SetCCOpcode) {
3786   default: llvm_unreachable("Condcode should be pre-legalized away");
3787   case ISD::SETUEQ:
3788   case ISD::SETEQ:   return X86::COND_E;
3789   case ISD::SETOLT:              // flipped
3790   case ISD::SETOGT:
3791   case ISD::SETGT:   return X86::COND_A;
3792   case ISD::SETOLE:              // flipped
3793   case ISD::SETOGE:
3794   case ISD::SETGE:   return X86::COND_AE;
3795   case ISD::SETUGT:              // flipped
3796   case ISD::SETULT:
3797   case ISD::SETLT:   return X86::COND_B;
3798   case ISD::SETUGE:              // flipped
3799   case ISD::SETULE:
3800   case ISD::SETLE:   return X86::COND_BE;
3801   case ISD::SETONE:
3802   case ISD::SETNE:   return X86::COND_NE;
3803   case ISD::SETUO:   return X86::COND_P;
3804   case ISD::SETO:    return X86::COND_NP;
3805   case ISD::SETOEQ:
3806   case ISD::SETUNE:  return X86::COND_INVALID;
3807   }
3808 }
3809
3810 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3811 /// code. Current x86 isa includes the following FP cmov instructions:
3812 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3813 static bool hasFPCMov(unsigned X86CC) {
3814   switch (X86CC) {
3815   default:
3816     return false;
3817   case X86::COND_B:
3818   case X86::COND_BE:
3819   case X86::COND_E:
3820   case X86::COND_P:
3821   case X86::COND_A:
3822   case X86::COND_AE:
3823   case X86::COND_NE:
3824   case X86::COND_NP:
3825     return true;
3826   }
3827 }
3828
3829 /// isFPImmLegal - Returns true if the target can instruction select the
3830 /// specified FP immediate natively. If false, the legalizer will
3831 /// materialize the FP immediate as a load from a constant pool.
3832 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3833   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3834     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3835       return true;
3836   }
3837   return false;
3838 }
3839
3840 /// \brief Returns true if it is beneficial to convert a load of a constant
3841 /// to just the constant itself.
3842 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3843                                                           Type *Ty) const {
3844   assert(Ty->isIntegerTy());
3845
3846   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3847   if (BitSize == 0 || BitSize > 64)
3848     return false;
3849   return true;
3850 }
3851
3852 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3853 /// the specified range (L, H].
3854 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3855   return (Val < 0) || (Val >= Low && Val < Hi);
3856 }
3857
3858 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3859 /// specified value.
3860 static bool isUndefOrEqual(int Val, int CmpVal) {
3861   return (Val < 0 || Val == CmpVal);
3862 }
3863
3864 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3865 /// from position Pos and ending in Pos+Size, falls within the specified
3866 /// sequential range (L, L+Pos]. or is undef.
3867 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3868                                        unsigned Pos, unsigned Size, int Low) {
3869   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3870     if (!isUndefOrEqual(Mask[i], Low))
3871       return false;
3872   return true;
3873 }
3874
3875 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3876 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3877 /// the second operand.
3878 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3879   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3880     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3881   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3882     return (Mask[0] < 2 && Mask[1] < 2);
3883   return false;
3884 }
3885
3886 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3887 /// is suitable for input to PSHUFHW.
3888 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3889   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3890     return false;
3891
3892   // Lower quadword copied in order or undef.
3893   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3894     return false;
3895
3896   // Upper quadword shuffled.
3897   for (unsigned i = 4; i != 8; ++i)
3898     if (!isUndefOrInRange(Mask[i], 4, 8))
3899       return false;
3900
3901   if (VT == MVT::v16i16) {
3902     // Lower quadword copied in order or undef.
3903     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3904       return false;
3905
3906     // Upper quadword shuffled.
3907     for (unsigned i = 12; i != 16; ++i)
3908       if (!isUndefOrInRange(Mask[i], 12, 16))
3909         return false;
3910   }
3911
3912   return true;
3913 }
3914
3915 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3916 /// is suitable for input to PSHUFLW.
3917 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3918   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3919     return false;
3920
3921   // Upper quadword copied in order.
3922   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3923     return false;
3924
3925   // Lower quadword shuffled.
3926   for (unsigned i = 0; i != 4; ++i)
3927     if (!isUndefOrInRange(Mask[i], 0, 4))
3928       return false;
3929
3930   if (VT == MVT::v16i16) {
3931     // Upper quadword copied in order.
3932     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3933       return false;
3934
3935     // Lower quadword shuffled.
3936     for (unsigned i = 8; i != 12; ++i)
3937       if (!isUndefOrInRange(Mask[i], 8, 12))
3938         return false;
3939   }
3940
3941   return true;
3942 }
3943
3944 /// \brief Return true if the mask specifies a shuffle of elements that is
3945 /// suitable for input to intralane (palignr) or interlane (valign) vector
3946 /// right-shift.
3947 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3948   unsigned NumElts = VT.getVectorNumElements();
3949   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3950   unsigned NumLaneElts = NumElts/NumLanes;
3951
3952   // Do not handle 64-bit element shuffles with palignr.
3953   if (NumLaneElts == 2)
3954     return false;
3955
3956   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3957     unsigned i;
3958     for (i = 0; i != NumLaneElts; ++i) {
3959       if (Mask[i+l] >= 0)
3960         break;
3961     }
3962
3963     // Lane is all undef, go to next lane
3964     if (i == NumLaneElts)
3965       continue;
3966
3967     int Start = Mask[i+l];
3968
3969     // Make sure its in this lane in one of the sources
3970     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3971         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3972       return false;
3973
3974     // If not lane 0, then we must match lane 0
3975     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3976       return false;
3977
3978     // Correct second source to be contiguous with first source
3979     if (Start >= (int)NumElts)
3980       Start -= NumElts - NumLaneElts;
3981
3982     // Make sure we're shifting in the right direction.
3983     if (Start <= (int)(i+l))
3984       return false;
3985
3986     Start -= i;
3987
3988     // Check the rest of the elements to see if they are consecutive.
3989     for (++i; i != NumLaneElts; ++i) {
3990       int Idx = Mask[i+l];
3991
3992       // Make sure its in this lane
3993       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3994           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3995         return false;
3996
3997       // If not lane 0, then we must match lane 0
3998       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3999         return false;
4000
4001       if (Idx >= (int)NumElts)
4002         Idx -= NumElts - NumLaneElts;
4003
4004       if (!isUndefOrEqual(Idx, Start+i))
4005         return false;
4006
4007     }
4008   }
4009
4010   return true;
4011 }
4012
4013 /// \brief Return true if the node specifies a shuffle of elements that is
4014 /// suitable for input to PALIGNR.
4015 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4016                           const X86Subtarget *Subtarget) {
4017   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4018       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4019       VT.is512BitVector())
4020     // FIXME: Add AVX512BW.
4021     return false;
4022
4023   return isAlignrMask(Mask, VT, false);
4024 }
4025
4026 /// \brief Return true if the node specifies a shuffle of elements that is
4027 /// suitable for input to VALIGN.
4028 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4029                           const X86Subtarget *Subtarget) {
4030   // FIXME: Add AVX512VL.
4031   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4032     return false;
4033   return isAlignrMask(Mask, VT, true);
4034 }
4035
4036 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4037 /// the two vector operands have swapped position.
4038 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4039                                      unsigned NumElems) {
4040   for (unsigned i = 0; i != NumElems; ++i) {
4041     int idx = Mask[i];
4042     if (idx < 0)
4043       continue;
4044     else if (idx < (int)NumElems)
4045       Mask[i] = idx + NumElems;
4046     else
4047       Mask[i] = idx - NumElems;
4048   }
4049 }
4050
4051 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4052 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4053 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4054 /// reverse of what x86 shuffles want.
4055 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4056
4057   unsigned NumElems = VT.getVectorNumElements();
4058   unsigned NumLanes = VT.getSizeInBits()/128;
4059   unsigned NumLaneElems = NumElems/NumLanes;
4060
4061   if (NumLaneElems != 2 && NumLaneElems != 4)
4062     return false;
4063
4064   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4065   bool symetricMaskRequired =
4066     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4067
4068   // VSHUFPSY divides the resulting vector into 4 chunks.
4069   // The sources are also splitted into 4 chunks, and each destination
4070   // chunk must come from a different source chunk.
4071   //
4072   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4073   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4074   //
4075   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4076   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4077   //
4078   // VSHUFPDY divides the resulting vector into 4 chunks.
4079   // The sources are also splitted into 4 chunks, and each destination
4080   // chunk must come from a different source chunk.
4081   //
4082   //  SRC1 =>      X3       X2       X1       X0
4083   //  SRC2 =>      Y3       Y2       Y1       Y0
4084   //
4085   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4086   //
4087   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4088   unsigned HalfLaneElems = NumLaneElems/2;
4089   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4090     for (unsigned i = 0; i != NumLaneElems; ++i) {
4091       int Idx = Mask[i+l];
4092       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4093       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4094         return false;
4095       // For VSHUFPSY, the mask of the second half must be the same as the
4096       // first but with the appropriate offsets. This works in the same way as
4097       // VPERMILPS works with masks.
4098       if (!symetricMaskRequired || Idx < 0)
4099         continue;
4100       if (MaskVal[i] < 0) {
4101         MaskVal[i] = Idx - l;
4102         continue;
4103       }
4104       if ((signed)(Idx - l) != MaskVal[i])
4105         return false;
4106     }
4107   }
4108
4109   return true;
4110 }
4111
4112 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4113 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4114 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4115   if (!VT.is128BitVector())
4116     return false;
4117
4118   unsigned NumElems = VT.getVectorNumElements();
4119
4120   if (NumElems != 4)
4121     return false;
4122
4123   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4124   return isUndefOrEqual(Mask[0], 6) &&
4125          isUndefOrEqual(Mask[1], 7) &&
4126          isUndefOrEqual(Mask[2], 2) &&
4127          isUndefOrEqual(Mask[3], 3);
4128 }
4129
4130 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4131 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4132 /// <2, 3, 2, 3>
4133 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4134   if (!VT.is128BitVector())
4135     return false;
4136
4137   unsigned NumElems = VT.getVectorNumElements();
4138
4139   if (NumElems != 4)
4140     return false;
4141
4142   return isUndefOrEqual(Mask[0], 2) &&
4143          isUndefOrEqual(Mask[1], 3) &&
4144          isUndefOrEqual(Mask[2], 2) &&
4145          isUndefOrEqual(Mask[3], 3);
4146 }
4147
4148 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4149 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4150 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4151   if (!VT.is128BitVector())
4152     return false;
4153
4154   unsigned NumElems = VT.getVectorNumElements();
4155
4156   if (NumElems != 2 && NumElems != 4)
4157     return false;
4158
4159   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4160     if (!isUndefOrEqual(Mask[i], i + NumElems))
4161       return false;
4162
4163   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4164     if (!isUndefOrEqual(Mask[i], i))
4165       return false;
4166
4167   return true;
4168 }
4169
4170 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4171 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4172 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4173   if (!VT.is128BitVector())
4174     return false;
4175
4176   unsigned NumElems = VT.getVectorNumElements();
4177
4178   if (NumElems != 2 && NumElems != 4)
4179     return false;
4180
4181   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4182     if (!isUndefOrEqual(Mask[i], i))
4183       return false;
4184
4185   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4186     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4187       return false;
4188
4189   return true;
4190 }
4191
4192 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4193 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4194 /// i. e: If all but one element come from the same vector.
4195 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4196   // TODO: Deal with AVX's VINSERTPS
4197   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4198     return false;
4199
4200   unsigned CorrectPosV1 = 0;
4201   unsigned CorrectPosV2 = 0;
4202   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4203     if (Mask[i] == -1) {
4204       ++CorrectPosV1;
4205       ++CorrectPosV2;
4206       continue;
4207     }
4208
4209     if (Mask[i] == i)
4210       ++CorrectPosV1;
4211     else if (Mask[i] == i + 4)
4212       ++CorrectPosV2;
4213   }
4214
4215   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4216     // We have 3 elements (undefs count as elements from any vector) from one
4217     // vector, and one from another.
4218     return true;
4219
4220   return false;
4221 }
4222
4223 //
4224 // Some special combinations that can be optimized.
4225 //
4226 static
4227 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4228                                SelectionDAG &DAG) {
4229   MVT VT = SVOp->getSimpleValueType(0);
4230   SDLoc dl(SVOp);
4231
4232   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4233     return SDValue();
4234
4235   ArrayRef<int> Mask = SVOp->getMask();
4236
4237   // These are the special masks that may be optimized.
4238   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4239   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4240   bool MatchEvenMask = true;
4241   bool MatchOddMask  = true;
4242   for (int i=0; i<8; ++i) {
4243     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4244       MatchEvenMask = false;
4245     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4246       MatchOddMask = false;
4247   }
4248
4249   if (!MatchEvenMask && !MatchOddMask)
4250     return SDValue();
4251
4252   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4253
4254   SDValue Op0 = SVOp->getOperand(0);
4255   SDValue Op1 = SVOp->getOperand(1);
4256
4257   if (MatchEvenMask) {
4258     // Shift the second operand right to 32 bits.
4259     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4260     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4261   } else {
4262     // Shift the first operand left to 32 bits.
4263     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4264     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4265   }
4266   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4267   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4268 }
4269
4270 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4271 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4272 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4273                          bool HasInt256, bool V2IsSplat = false) {
4274
4275   assert(VT.getSizeInBits() >= 128 &&
4276          "Unsupported vector type for unpckl");
4277
4278   unsigned NumElts = VT.getVectorNumElements();
4279   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4280       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4281     return false;
4282
4283   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4284          "Unsupported vector type for unpckh");
4285
4286   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4287   unsigned NumLanes = VT.getSizeInBits()/128;
4288   unsigned NumLaneElts = NumElts/NumLanes;
4289
4290   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4291     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4292       int BitI  = Mask[l+i];
4293       int BitI1 = Mask[l+i+1];
4294       if (!isUndefOrEqual(BitI, j))
4295         return false;
4296       if (V2IsSplat) {
4297         if (!isUndefOrEqual(BitI1, NumElts))
4298           return false;
4299       } else {
4300         if (!isUndefOrEqual(BitI1, j + NumElts))
4301           return false;
4302       }
4303     }
4304   }
4305
4306   return true;
4307 }
4308
4309 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4310 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4311 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4312                          bool HasInt256, bool V2IsSplat = false) {
4313   assert(VT.getSizeInBits() >= 128 &&
4314          "Unsupported vector type for unpckh");
4315
4316   unsigned NumElts = VT.getVectorNumElements();
4317   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4318       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4319     return false;
4320
4321   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4322          "Unsupported vector type for unpckh");
4323
4324   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4325   unsigned NumLanes = VT.getSizeInBits()/128;
4326   unsigned NumLaneElts = NumElts/NumLanes;
4327
4328   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4329     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4330       int BitI  = Mask[l+i];
4331       int BitI1 = Mask[l+i+1];
4332       if (!isUndefOrEqual(BitI, j))
4333         return false;
4334       if (V2IsSplat) {
4335         if (isUndefOrEqual(BitI1, NumElts))
4336           return false;
4337       } else {
4338         if (!isUndefOrEqual(BitI1, j+NumElts))
4339           return false;
4340       }
4341     }
4342   }
4343   return true;
4344 }
4345
4346 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4347 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4348 /// <0, 0, 1, 1>
4349 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4350   unsigned NumElts = VT.getVectorNumElements();
4351   bool Is256BitVec = VT.is256BitVector();
4352
4353   if (VT.is512BitVector())
4354     return false;
4355   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4356          "Unsupported vector type for unpckh");
4357
4358   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4359       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4360     return false;
4361
4362   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4363   // FIXME: Need a better way to get rid of this, there's no latency difference
4364   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4365   // the former later. We should also remove the "_undef" special mask.
4366   if (NumElts == 4 && Is256BitVec)
4367     return false;
4368
4369   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4370   // independently on 128-bit lanes.
4371   unsigned NumLanes = VT.getSizeInBits()/128;
4372   unsigned NumLaneElts = NumElts/NumLanes;
4373
4374   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4375     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4376       int BitI  = Mask[l+i];
4377       int BitI1 = Mask[l+i+1];
4378
4379       if (!isUndefOrEqual(BitI, j))
4380         return false;
4381       if (!isUndefOrEqual(BitI1, j))
4382         return false;
4383     }
4384   }
4385
4386   return true;
4387 }
4388
4389 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4390 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4391 /// <2, 2, 3, 3>
4392 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4393   unsigned NumElts = VT.getVectorNumElements();
4394
4395   if (VT.is512BitVector())
4396     return false;
4397
4398   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4399          "Unsupported vector type for unpckh");
4400
4401   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4402       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4403     return false;
4404
4405   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4406   // independently on 128-bit lanes.
4407   unsigned NumLanes = VT.getSizeInBits()/128;
4408   unsigned NumLaneElts = NumElts/NumLanes;
4409
4410   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4411     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4412       int BitI  = Mask[l+i];
4413       int BitI1 = Mask[l+i+1];
4414       if (!isUndefOrEqual(BitI, j))
4415         return false;
4416       if (!isUndefOrEqual(BitI1, j))
4417         return false;
4418     }
4419   }
4420   return true;
4421 }
4422
4423 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4424 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4425 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4426   if (!VT.is512BitVector())
4427     return false;
4428
4429   unsigned NumElts = VT.getVectorNumElements();
4430   unsigned HalfSize = NumElts/2;
4431   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4432     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4433       *Imm = 1;
4434       return true;
4435     }
4436   }
4437   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4438     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4439       *Imm = 0;
4440       return true;
4441     }
4442   }
4443   return false;
4444 }
4445
4446 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4447 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4448 /// MOVSD, and MOVD, i.e. setting the lowest element.
4449 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4450   if (VT.getVectorElementType().getSizeInBits() < 32)
4451     return false;
4452   if (!VT.is128BitVector())
4453     return false;
4454
4455   unsigned NumElts = VT.getVectorNumElements();
4456
4457   if (!isUndefOrEqual(Mask[0], NumElts))
4458     return false;
4459
4460   for (unsigned i = 1; i != NumElts; ++i)
4461     if (!isUndefOrEqual(Mask[i], i))
4462       return false;
4463
4464   return true;
4465 }
4466
4467 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4468 /// as permutations between 128-bit chunks or halves. As an example: this
4469 /// shuffle bellow:
4470 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4471 /// The first half comes from the second half of V1 and the second half from the
4472 /// the second half of V2.
4473 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4474   if (!HasFp256 || !VT.is256BitVector())
4475     return false;
4476
4477   // The shuffle result is divided into half A and half B. In total the two
4478   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4479   // B must come from C, D, E or F.
4480   unsigned HalfSize = VT.getVectorNumElements()/2;
4481   bool MatchA = false, MatchB = false;
4482
4483   // Check if A comes from one of C, D, E, F.
4484   for (unsigned Half = 0; Half != 4; ++Half) {
4485     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4486       MatchA = true;
4487       break;
4488     }
4489   }
4490
4491   // Check if B comes from one of C, D, E, F.
4492   for (unsigned Half = 0; Half != 4; ++Half) {
4493     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4494       MatchB = true;
4495       break;
4496     }
4497   }
4498
4499   return MatchA && MatchB;
4500 }
4501
4502 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4503 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4504 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4505   MVT VT = SVOp->getSimpleValueType(0);
4506
4507   unsigned HalfSize = VT.getVectorNumElements()/2;
4508
4509   unsigned FstHalf = 0, SndHalf = 0;
4510   for (unsigned i = 0; i < HalfSize; ++i) {
4511     if (SVOp->getMaskElt(i) > 0) {
4512       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4513       break;
4514     }
4515   }
4516   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4517     if (SVOp->getMaskElt(i) > 0) {
4518       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4519       break;
4520     }
4521   }
4522
4523   return (FstHalf | (SndHalf << 4));
4524 }
4525
4526 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4527 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4528   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4529   if (EltSize < 32)
4530     return false;
4531
4532   unsigned NumElts = VT.getVectorNumElements();
4533   Imm8 = 0;
4534   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4535     for (unsigned i = 0; i != NumElts; ++i) {
4536       if (Mask[i] < 0)
4537         continue;
4538       Imm8 |= Mask[i] << (i*2);
4539     }
4540     return true;
4541   }
4542
4543   unsigned LaneSize = 4;
4544   SmallVector<int, 4> MaskVal(LaneSize, -1);
4545
4546   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4547     for (unsigned i = 0; i != LaneSize; ++i) {
4548       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4549         return false;
4550       if (Mask[i+l] < 0)
4551         continue;
4552       if (MaskVal[i] < 0) {
4553         MaskVal[i] = Mask[i+l] - l;
4554         Imm8 |= MaskVal[i] << (i*2);
4555         continue;
4556       }
4557       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4558         return false;
4559     }
4560   }
4561   return true;
4562 }
4563
4564 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4565 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4566 /// Note that VPERMIL mask matching is different depending whether theunderlying
4567 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4568 /// to the same elements of the low, but to the higher half of the source.
4569 /// In VPERMILPD the two lanes could be shuffled independently of each other
4570 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4571 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4572   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4573   if (VT.getSizeInBits() < 256 || EltSize < 32)
4574     return false;
4575   bool symetricMaskRequired = (EltSize == 32);
4576   unsigned NumElts = VT.getVectorNumElements();
4577
4578   unsigned NumLanes = VT.getSizeInBits()/128;
4579   unsigned LaneSize = NumElts/NumLanes;
4580   // 2 or 4 elements in one lane
4581
4582   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4583   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4584     for (unsigned i = 0; i != LaneSize; ++i) {
4585       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4586         return false;
4587       if (symetricMaskRequired) {
4588         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4589           ExpectedMaskVal[i] = Mask[i+l] - l;
4590           continue;
4591         }
4592         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4593           return false;
4594       }
4595     }
4596   }
4597   return true;
4598 }
4599
4600 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4601 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4602 /// element of vector 2 and the other elements to come from vector 1 in order.
4603 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4604                                bool V2IsSplat = false, bool V2IsUndef = false) {
4605   if (!VT.is128BitVector())
4606     return false;
4607
4608   unsigned NumOps = VT.getVectorNumElements();
4609   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4610     return false;
4611
4612   if (!isUndefOrEqual(Mask[0], 0))
4613     return false;
4614
4615   for (unsigned i = 1; i != NumOps; ++i)
4616     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4617           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4618           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4619       return false;
4620
4621   return true;
4622 }
4623
4624 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4625 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4626 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4627 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4628                            const X86Subtarget *Subtarget) {
4629   if (!Subtarget->hasSSE3())
4630     return false;
4631
4632   unsigned NumElems = VT.getVectorNumElements();
4633
4634   if ((VT.is128BitVector() && NumElems != 4) ||
4635       (VT.is256BitVector() && NumElems != 8) ||
4636       (VT.is512BitVector() && NumElems != 16))
4637     return false;
4638
4639   // "i+1" is the value the indexed mask element must have
4640   for (unsigned i = 0; i != NumElems; i += 2)
4641     if (!isUndefOrEqual(Mask[i], i+1) ||
4642         !isUndefOrEqual(Mask[i+1], i+1))
4643       return false;
4644
4645   return true;
4646 }
4647
4648 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4649 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4650 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4651 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4652                            const X86Subtarget *Subtarget) {
4653   if (!Subtarget->hasSSE3())
4654     return false;
4655
4656   unsigned NumElems = VT.getVectorNumElements();
4657
4658   if ((VT.is128BitVector() && NumElems != 4) ||
4659       (VT.is256BitVector() && NumElems != 8) ||
4660       (VT.is512BitVector() && NumElems != 16))
4661     return false;
4662
4663   // "i" is the value the indexed mask element must have
4664   for (unsigned i = 0; i != NumElems; i += 2)
4665     if (!isUndefOrEqual(Mask[i], i) ||
4666         !isUndefOrEqual(Mask[i+1], i))
4667       return false;
4668
4669   return true;
4670 }
4671
4672 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4673 /// specifies a shuffle of elements that is suitable for input to 256-bit
4674 /// version of MOVDDUP.
4675 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4676   if (!HasFp256 || !VT.is256BitVector())
4677     return false;
4678
4679   unsigned NumElts = VT.getVectorNumElements();
4680   if (NumElts != 4)
4681     return false;
4682
4683   for (unsigned i = 0; i != NumElts/2; ++i)
4684     if (!isUndefOrEqual(Mask[i], 0))
4685       return false;
4686   for (unsigned i = NumElts/2; i != NumElts; ++i)
4687     if (!isUndefOrEqual(Mask[i], NumElts/2))
4688       return false;
4689   return true;
4690 }
4691
4692 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4693 /// specifies a shuffle of elements that is suitable for input to 128-bit
4694 /// version of MOVDDUP.
4695 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4696   if (!VT.is128BitVector())
4697     return false;
4698
4699   unsigned e = VT.getVectorNumElements() / 2;
4700   for (unsigned i = 0; i != e; ++i)
4701     if (!isUndefOrEqual(Mask[i], i))
4702       return false;
4703   for (unsigned i = 0; i != e; ++i)
4704     if (!isUndefOrEqual(Mask[e+i], i))
4705       return false;
4706   return true;
4707 }
4708
4709 /// isVEXTRACTIndex - Return true if the specified
4710 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4711 /// suitable for instruction that extract 128 or 256 bit vectors
4712 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4713   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4714   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4715     return false;
4716
4717   // The index should be aligned on a vecWidth-bit boundary.
4718   uint64_t Index =
4719     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4720
4721   MVT VT = N->getSimpleValueType(0);
4722   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4723   bool Result = (Index * ElSize) % vecWidth == 0;
4724
4725   return Result;
4726 }
4727
4728 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4729 /// operand specifies a subvector insert that is suitable for input to
4730 /// insertion of 128 or 256-bit subvectors
4731 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4732   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4733   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4734     return false;
4735   // The index should be aligned on a vecWidth-bit boundary.
4736   uint64_t Index =
4737     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4738
4739   MVT VT = N->getSimpleValueType(0);
4740   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4741   bool Result = (Index * ElSize) % vecWidth == 0;
4742
4743   return Result;
4744 }
4745
4746 bool X86::isVINSERT128Index(SDNode *N) {
4747   return isVINSERTIndex(N, 128);
4748 }
4749
4750 bool X86::isVINSERT256Index(SDNode *N) {
4751   return isVINSERTIndex(N, 256);
4752 }
4753
4754 bool X86::isVEXTRACT128Index(SDNode *N) {
4755   return isVEXTRACTIndex(N, 128);
4756 }
4757
4758 bool X86::isVEXTRACT256Index(SDNode *N) {
4759   return isVEXTRACTIndex(N, 256);
4760 }
4761
4762 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4763 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4764 /// Handles 128-bit and 256-bit.
4765 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4766   MVT VT = N->getSimpleValueType(0);
4767
4768   assert((VT.getSizeInBits() >= 128) &&
4769          "Unsupported vector type for PSHUF/SHUFP");
4770
4771   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4772   // independently on 128-bit lanes.
4773   unsigned NumElts = VT.getVectorNumElements();
4774   unsigned NumLanes = VT.getSizeInBits()/128;
4775   unsigned NumLaneElts = NumElts/NumLanes;
4776
4777   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4778          "Only supports 2, 4 or 8 elements per lane");
4779
4780   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4781   unsigned Mask = 0;
4782   for (unsigned i = 0; i != NumElts; ++i) {
4783     int Elt = N->getMaskElt(i);
4784     if (Elt < 0) continue;
4785     Elt &= NumLaneElts - 1;
4786     unsigned ShAmt = (i << Shift) % 8;
4787     Mask |= Elt << ShAmt;
4788   }
4789
4790   return Mask;
4791 }
4792
4793 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4794 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4795 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4796   MVT VT = N->getSimpleValueType(0);
4797
4798   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4799          "Unsupported vector type for PSHUFHW");
4800
4801   unsigned NumElts = VT.getVectorNumElements();
4802
4803   unsigned Mask = 0;
4804   for (unsigned l = 0; l != NumElts; l += 8) {
4805     // 8 nodes per lane, but we only care about the last 4.
4806     for (unsigned i = 0; i < 4; ++i) {
4807       int Elt = N->getMaskElt(l+i+4);
4808       if (Elt < 0) continue;
4809       Elt &= 0x3; // only 2-bits.
4810       Mask |= Elt << (i * 2);
4811     }
4812   }
4813
4814   return Mask;
4815 }
4816
4817 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4818 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4819 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4820   MVT VT = N->getSimpleValueType(0);
4821
4822   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4823          "Unsupported vector type for PSHUFHW");
4824
4825   unsigned NumElts = VT.getVectorNumElements();
4826
4827   unsigned Mask = 0;
4828   for (unsigned l = 0; l != NumElts; l += 8) {
4829     // 8 nodes per lane, but we only care about the first 4.
4830     for (unsigned i = 0; i < 4; ++i) {
4831       int Elt = N->getMaskElt(l+i);
4832       if (Elt < 0) continue;
4833       Elt &= 0x3; // only 2-bits
4834       Mask |= Elt << (i * 2);
4835     }
4836   }
4837
4838   return Mask;
4839 }
4840
4841 /// \brief Return the appropriate immediate to shuffle the specified
4842 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4843 /// VALIGN (if Interlane is true) instructions.
4844 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4845                                            bool InterLane) {
4846   MVT VT = SVOp->getSimpleValueType(0);
4847   unsigned EltSize = InterLane ? 1 :
4848     VT.getVectorElementType().getSizeInBits() >> 3;
4849
4850   unsigned NumElts = VT.getVectorNumElements();
4851   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4852   unsigned NumLaneElts = NumElts/NumLanes;
4853
4854   int Val = 0;
4855   unsigned i;
4856   for (i = 0; i != NumElts; ++i) {
4857     Val = SVOp->getMaskElt(i);
4858     if (Val >= 0)
4859       break;
4860   }
4861   if (Val >= (int)NumElts)
4862     Val -= NumElts - NumLaneElts;
4863
4864   assert(Val - i > 0 && "PALIGNR imm should be positive");
4865   return (Val - i) * EltSize;
4866 }
4867
4868 /// \brief Return the appropriate immediate to shuffle the specified
4869 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4870 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4871   return getShuffleAlignrImmediate(SVOp, false);
4872 }
4873
4874 /// \brief Return the appropriate immediate to shuffle the specified
4875 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4876 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4877   return getShuffleAlignrImmediate(SVOp, true);
4878 }
4879
4880
4881 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4882   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4883   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4884     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4885
4886   uint64_t Index =
4887     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4888
4889   MVT VecVT = N->getOperand(0).getSimpleValueType();
4890   MVT ElVT = VecVT.getVectorElementType();
4891
4892   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4893   return Index / NumElemsPerChunk;
4894 }
4895
4896 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4897   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4898   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4899     llvm_unreachable("Illegal insert subvector for VINSERT");
4900
4901   uint64_t Index =
4902     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4903
4904   MVT VecVT = N->getSimpleValueType(0);
4905   MVT ElVT = VecVT.getVectorElementType();
4906
4907   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4908   return Index / NumElemsPerChunk;
4909 }
4910
4911 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4912 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4913 /// and VINSERTI128 instructions.
4914 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4915   return getExtractVEXTRACTImmediate(N, 128);
4916 }
4917
4918 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4919 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4920 /// and VINSERTI64x4 instructions.
4921 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4922   return getExtractVEXTRACTImmediate(N, 256);
4923 }
4924
4925 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4926 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4927 /// and VINSERTI128 instructions.
4928 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4929   return getInsertVINSERTImmediate(N, 128);
4930 }
4931
4932 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4933 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4934 /// and VINSERTI64x4 instructions.
4935 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4936   return getInsertVINSERTImmediate(N, 256);
4937 }
4938
4939 /// isZero - Returns true if Elt is a constant integer zero
4940 static bool isZero(SDValue V) {
4941   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4942   return C && C->isNullValue();
4943 }
4944
4945 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4946 /// constant +0.0.
4947 bool X86::isZeroNode(SDValue Elt) {
4948   if (isZero(Elt))
4949     return true;
4950   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4951     return CFP->getValueAPF().isPosZero();
4952   return false;
4953 }
4954
4955 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4956 /// match movhlps. The lower half elements should come from upper half of
4957 /// V1 (and in order), and the upper half elements should come from the upper
4958 /// half of V2 (and in order).
4959 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4960   if (!VT.is128BitVector())
4961     return false;
4962   if (VT.getVectorNumElements() != 4)
4963     return false;
4964   for (unsigned i = 0, e = 2; i != e; ++i)
4965     if (!isUndefOrEqual(Mask[i], i+2))
4966       return false;
4967   for (unsigned i = 2; i != 4; ++i)
4968     if (!isUndefOrEqual(Mask[i], i+4))
4969       return false;
4970   return true;
4971 }
4972
4973 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4974 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4975 /// required.
4976 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4977   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4978     return false;
4979   N = N->getOperand(0).getNode();
4980   if (!ISD::isNON_EXTLoad(N))
4981     return false;
4982   if (LD)
4983     *LD = cast<LoadSDNode>(N);
4984   return true;
4985 }
4986
4987 // Test whether the given value is a vector value which will be legalized
4988 // into a load.
4989 static bool WillBeConstantPoolLoad(SDNode *N) {
4990   if (N->getOpcode() != ISD::BUILD_VECTOR)
4991     return false;
4992
4993   // Check for any non-constant elements.
4994   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4995     switch (N->getOperand(i).getNode()->getOpcode()) {
4996     case ISD::UNDEF:
4997     case ISD::ConstantFP:
4998     case ISD::Constant:
4999       break;
5000     default:
5001       return false;
5002     }
5003
5004   // Vectors of all-zeros and all-ones are materialized with special
5005   // instructions rather than being loaded.
5006   return !ISD::isBuildVectorAllZeros(N) &&
5007          !ISD::isBuildVectorAllOnes(N);
5008 }
5009
5010 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5011 /// match movlp{s|d}. The lower half elements should come from lower half of
5012 /// V1 (and in order), and the upper half elements should come from the upper
5013 /// half of V2 (and in order). And since V1 will become the source of the
5014 /// MOVLP, it must be either a vector load or a scalar load to vector.
5015 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5016                                ArrayRef<int> Mask, MVT VT) {
5017   if (!VT.is128BitVector())
5018     return false;
5019
5020   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5021     return false;
5022   // Is V2 is a vector load, don't do this transformation. We will try to use
5023   // load folding shufps op.
5024   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5025     return false;
5026
5027   unsigned NumElems = VT.getVectorNumElements();
5028
5029   if (NumElems != 2 && NumElems != 4)
5030     return false;
5031   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5032     if (!isUndefOrEqual(Mask[i], i))
5033       return false;
5034   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5035     if (!isUndefOrEqual(Mask[i], i+NumElems))
5036       return false;
5037   return true;
5038 }
5039
5040 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5041 /// to an zero vector.
5042 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5043 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5044   SDValue V1 = N->getOperand(0);
5045   SDValue V2 = N->getOperand(1);
5046   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5047   for (unsigned i = 0; i != NumElems; ++i) {
5048     int Idx = N->getMaskElt(i);
5049     if (Idx >= (int)NumElems) {
5050       unsigned Opc = V2.getOpcode();
5051       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5052         continue;
5053       if (Opc != ISD::BUILD_VECTOR ||
5054           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5055         return false;
5056     } else if (Idx >= 0) {
5057       unsigned Opc = V1.getOpcode();
5058       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5059         continue;
5060       if (Opc != ISD::BUILD_VECTOR ||
5061           !X86::isZeroNode(V1.getOperand(Idx)))
5062         return false;
5063     }
5064   }
5065   return true;
5066 }
5067
5068 /// getZeroVector - Returns a vector of specified type with all zero elements.
5069 ///
5070 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5071                              SelectionDAG &DAG, SDLoc dl) {
5072   assert(VT.isVector() && "Expected a vector type");
5073
5074   // Always build SSE zero vectors as <4 x i32> bitcasted
5075   // to their dest type. This ensures they get CSE'd.
5076   SDValue Vec;
5077   if (VT.is128BitVector()) {  // SSE
5078     if (Subtarget->hasSSE2()) {  // SSE2
5079       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5080       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5081     } else { // SSE1
5082       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5083       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5084     }
5085   } else if (VT.is256BitVector()) { // AVX
5086     if (Subtarget->hasInt256()) { // AVX2
5087       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5088       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5089       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5090     } else {
5091       // 256-bit logic and arithmetic instructions in AVX are all
5092       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5093       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5094       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5095       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5096     }
5097   } else if (VT.is512BitVector()) { // AVX-512
5098       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5099       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5100                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5101       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5102   } else if (VT.getScalarType() == MVT::i1) {
5103     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5104     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5105     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5106     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5107   } else
5108     llvm_unreachable("Unexpected vector type");
5109
5110   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5111 }
5112
5113 /// getOnesVector - Returns a vector of specified type with all bits set.
5114 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5115 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5116 /// Then bitcast to their original type, ensuring they get CSE'd.
5117 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5118                              SDLoc dl) {
5119   assert(VT.isVector() && "Expected a vector type");
5120
5121   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5122   SDValue Vec;
5123   if (VT.is256BitVector()) {
5124     if (HasInt256) { // AVX2
5125       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5126       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5127     } else { // AVX
5128       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5129       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5130     }
5131   } else if (VT.is128BitVector()) {
5132     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5133   } else
5134     llvm_unreachable("Unexpected vector type");
5135
5136   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5137 }
5138
5139 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5140 /// that point to V2 points to its first element.
5141 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5142   for (unsigned i = 0; i != NumElems; ++i) {
5143     if (Mask[i] > (int)NumElems) {
5144       Mask[i] = NumElems;
5145     }
5146   }
5147 }
5148
5149 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5150 /// operation of specified width.
5151 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5152                        SDValue V2) {
5153   unsigned NumElems = VT.getVectorNumElements();
5154   SmallVector<int, 8> Mask;
5155   Mask.push_back(NumElems);
5156   for (unsigned i = 1; i != NumElems; ++i)
5157     Mask.push_back(i);
5158   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5159 }
5160
5161 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5162 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5163                           SDValue V2) {
5164   unsigned NumElems = VT.getVectorNumElements();
5165   SmallVector<int, 8> Mask;
5166   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5167     Mask.push_back(i);
5168     Mask.push_back(i + NumElems);
5169   }
5170   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5171 }
5172
5173 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5174 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5175                           SDValue V2) {
5176   unsigned NumElems = VT.getVectorNumElements();
5177   SmallVector<int, 8> Mask;
5178   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5179     Mask.push_back(i + Half);
5180     Mask.push_back(i + NumElems + Half);
5181   }
5182   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5183 }
5184
5185 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5186 // a generic shuffle instruction because the target has no such instructions.
5187 // Generate shuffles which repeat i16 and i8 several times until they can be
5188 // represented by v4f32 and then be manipulated by target suported shuffles.
5189 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5190   MVT VT = V.getSimpleValueType();
5191   int NumElems = VT.getVectorNumElements();
5192   SDLoc dl(V);
5193
5194   while (NumElems > 4) {
5195     if (EltNo < NumElems/2) {
5196       V = getUnpackl(DAG, dl, VT, V, V);
5197     } else {
5198       V = getUnpackh(DAG, dl, VT, V, V);
5199       EltNo -= NumElems/2;
5200     }
5201     NumElems >>= 1;
5202   }
5203   return V;
5204 }
5205
5206 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5207 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5208   MVT VT = V.getSimpleValueType();
5209   SDLoc dl(V);
5210
5211   if (VT.is128BitVector()) {
5212     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5213     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5214     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5215                              &SplatMask[0]);
5216   } else if (VT.is256BitVector()) {
5217     // To use VPERMILPS to splat scalars, the second half of indicies must
5218     // refer to the higher part, which is a duplication of the lower one,
5219     // because VPERMILPS can only handle in-lane permutations.
5220     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5221                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5222
5223     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5224     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5225                              &SplatMask[0]);
5226   } else
5227     llvm_unreachable("Vector size not supported");
5228
5229   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5230 }
5231
5232 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5233 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5234   MVT SrcVT = SV->getSimpleValueType(0);
5235   SDValue V1 = SV->getOperand(0);
5236   SDLoc dl(SV);
5237
5238   int EltNo = SV->getSplatIndex();
5239   int NumElems = SrcVT.getVectorNumElements();
5240   bool Is256BitVec = SrcVT.is256BitVector();
5241
5242   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5243          "Unknown how to promote splat for type");
5244
5245   // Extract the 128-bit part containing the splat element and update
5246   // the splat element index when it refers to the higher register.
5247   if (Is256BitVec) {
5248     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5249     if (EltNo >= NumElems/2)
5250       EltNo -= NumElems/2;
5251   }
5252
5253   // All i16 and i8 vector types can't be used directly by a generic shuffle
5254   // instruction because the target has no such instruction. Generate shuffles
5255   // which repeat i16 and i8 several times until they fit in i32, and then can
5256   // be manipulated by target suported shuffles.
5257   MVT EltVT = SrcVT.getVectorElementType();
5258   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5259     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5260
5261   // Recreate the 256-bit vector and place the same 128-bit vector
5262   // into the low and high part. This is necessary because we want
5263   // to use VPERM* to shuffle the vectors
5264   if (Is256BitVec) {
5265     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5266   }
5267
5268   return getLegalSplat(DAG, V1, EltNo);
5269 }
5270
5271 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5272 /// vector of zero or undef vector.  This produces a shuffle where the low
5273 /// element of V2 is swizzled into the zero/undef vector, landing at element
5274 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5275 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5276                                            bool IsZero,
5277                                            const X86Subtarget *Subtarget,
5278                                            SelectionDAG &DAG) {
5279   MVT VT = V2.getSimpleValueType();
5280   SDValue V1 = IsZero
5281     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5282   unsigned NumElems = VT.getVectorNumElements();
5283   SmallVector<int, 16> MaskVec;
5284   for (unsigned i = 0; i != NumElems; ++i)
5285     // If this is the insertion idx, put the low elt of V2 here.
5286     MaskVec.push_back(i == Idx ? NumElems : i);
5287   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5288 }
5289
5290 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5291 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5292 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5293 /// shuffles which use a single input multiple times, and in those cases it will
5294 /// adjust the mask to only have indices within that single input.
5295 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5296                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5297   unsigned NumElems = VT.getVectorNumElements();
5298   SDValue ImmN;
5299
5300   IsUnary = false;
5301   bool IsFakeUnary = false;
5302   switch(N->getOpcode()) {
5303   case X86ISD::BLENDI:
5304     ImmN = N->getOperand(N->getNumOperands()-1);
5305     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5306     break;
5307   case X86ISD::SHUFP:
5308     ImmN = N->getOperand(N->getNumOperands()-1);
5309     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5310     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5311     break;
5312   case X86ISD::UNPCKH:
5313     DecodeUNPCKHMask(VT, Mask);
5314     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5315     break;
5316   case X86ISD::UNPCKL:
5317     DecodeUNPCKLMask(VT, Mask);
5318     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5319     break;
5320   case X86ISD::MOVHLPS:
5321     DecodeMOVHLPSMask(NumElems, Mask);
5322     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5323     break;
5324   case X86ISD::MOVLHPS:
5325     DecodeMOVLHPSMask(NumElems, Mask);
5326     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5327     break;
5328   case X86ISD::PALIGNR:
5329     ImmN = N->getOperand(N->getNumOperands()-1);
5330     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5331     break;
5332   case X86ISD::PSHUFD:
5333   case X86ISD::VPERMILPI:
5334     ImmN = N->getOperand(N->getNumOperands()-1);
5335     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5336     IsUnary = true;
5337     break;
5338   case X86ISD::PSHUFHW:
5339     ImmN = N->getOperand(N->getNumOperands()-1);
5340     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5341     IsUnary = true;
5342     break;
5343   case X86ISD::PSHUFLW:
5344     ImmN = N->getOperand(N->getNumOperands()-1);
5345     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5346     IsUnary = true;
5347     break;
5348   case X86ISD::PSHUFB: {
5349     IsUnary = true;
5350     SDValue MaskNode = N->getOperand(1);
5351     while (MaskNode->getOpcode() == ISD::BITCAST)
5352       MaskNode = MaskNode->getOperand(0);
5353
5354     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5355       // If we have a build-vector, then things are easy.
5356       EVT VT = MaskNode.getValueType();
5357       assert(VT.isVector() &&
5358              "Can't produce a non-vector with a build_vector!");
5359       if (!VT.isInteger())
5360         return false;
5361
5362       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5363
5364       SmallVector<uint64_t, 32> RawMask;
5365       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5366         SDValue Op = MaskNode->getOperand(i);
5367         if (Op->getOpcode() == ISD::UNDEF) {
5368           RawMask.push_back((uint64_t)SM_SentinelUndef);
5369           continue;
5370         }
5371         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5372         if (!CN)
5373           return false;
5374         APInt MaskElement = CN->getAPIntValue();
5375
5376         // We now have to decode the element which could be any integer size and
5377         // extract each byte of it.
5378         for (int j = 0; j < NumBytesPerElement; ++j) {
5379           // Note that this is x86 and so always little endian: the low byte is
5380           // the first byte of the mask.
5381           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5382           MaskElement = MaskElement.lshr(8);
5383         }
5384       }
5385       DecodePSHUFBMask(RawMask, Mask);
5386       break;
5387     }
5388
5389     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5390     if (!MaskLoad)
5391       return false;
5392
5393     SDValue Ptr = MaskLoad->getBasePtr();
5394     if (Ptr->getOpcode() == X86ISD::Wrapper)
5395       Ptr = Ptr->getOperand(0);
5396
5397     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5398     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5399       return false;
5400
5401     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5402       // FIXME: Support AVX-512 here.
5403       Type *Ty = C->getType();
5404       if (!Ty->isVectorTy() || (Ty->getVectorNumElements() != 16 &&
5405                                 Ty->getVectorNumElements() != 32))
5406         return false;
5407
5408       DecodePSHUFBMask(C, Mask);
5409       break;
5410     }
5411
5412     return false;
5413   }
5414   case X86ISD::VPERMI:
5415     ImmN = N->getOperand(N->getNumOperands()-1);
5416     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5417     IsUnary = true;
5418     break;
5419   case X86ISD::MOVSS:
5420   case X86ISD::MOVSD: {
5421     // The index 0 always comes from the first element of the second source,
5422     // this is why MOVSS and MOVSD are used in the first place. The other
5423     // elements come from the other positions of the first source vector
5424     Mask.push_back(NumElems);
5425     for (unsigned i = 1; i != NumElems; ++i) {
5426       Mask.push_back(i);
5427     }
5428     break;
5429   }
5430   case X86ISD::VPERM2X128:
5431     ImmN = N->getOperand(N->getNumOperands()-1);
5432     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5433     if (Mask.empty()) return false;
5434     break;
5435   case X86ISD::MOVSLDUP:
5436     DecodeMOVSLDUPMask(VT, Mask);
5437     break;
5438   case X86ISD::MOVSHDUP:
5439     DecodeMOVSHDUPMask(VT, Mask);
5440     break;
5441   case X86ISD::MOVDDUP:
5442   case X86ISD::MOVLHPD:
5443   case X86ISD::MOVLPD:
5444   case X86ISD::MOVLPS:
5445     // Not yet implemented
5446     return false;
5447   default: llvm_unreachable("unknown target shuffle node");
5448   }
5449
5450   // If we have a fake unary shuffle, the shuffle mask is spread across two
5451   // inputs that are actually the same node. Re-map the mask to always point
5452   // into the first input.
5453   if (IsFakeUnary)
5454     for (int &M : Mask)
5455       if (M >= (int)Mask.size())
5456         M -= Mask.size();
5457
5458   return true;
5459 }
5460
5461 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5462 /// element of the result of the vector shuffle.
5463 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5464                                    unsigned Depth) {
5465   if (Depth == 6)
5466     return SDValue();  // Limit search depth.
5467
5468   SDValue V = SDValue(N, 0);
5469   EVT VT = V.getValueType();
5470   unsigned Opcode = V.getOpcode();
5471
5472   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5473   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5474     int Elt = SV->getMaskElt(Index);
5475
5476     if (Elt < 0)
5477       return DAG.getUNDEF(VT.getVectorElementType());
5478
5479     unsigned NumElems = VT.getVectorNumElements();
5480     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5481                                          : SV->getOperand(1);
5482     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5483   }
5484
5485   // Recurse into target specific vector shuffles to find scalars.
5486   if (isTargetShuffle(Opcode)) {
5487     MVT ShufVT = V.getSimpleValueType();
5488     unsigned NumElems = ShufVT.getVectorNumElements();
5489     SmallVector<int, 16> ShuffleMask;
5490     bool IsUnary;
5491
5492     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5493       return SDValue();
5494
5495     int Elt = ShuffleMask[Index];
5496     if (Elt < 0)
5497       return DAG.getUNDEF(ShufVT.getVectorElementType());
5498
5499     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5500                                          : N->getOperand(1);
5501     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5502                                Depth+1);
5503   }
5504
5505   // Actual nodes that may contain scalar elements
5506   if (Opcode == ISD::BITCAST) {
5507     V = V.getOperand(0);
5508     EVT SrcVT = V.getValueType();
5509     unsigned NumElems = VT.getVectorNumElements();
5510
5511     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5512       return SDValue();
5513   }
5514
5515   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5516     return (Index == 0) ? V.getOperand(0)
5517                         : DAG.getUNDEF(VT.getVectorElementType());
5518
5519   if (V.getOpcode() == ISD::BUILD_VECTOR)
5520     return V.getOperand(Index);
5521
5522   return SDValue();
5523 }
5524
5525 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5526 /// shuffle operation which come from a consecutively from a zero. The
5527 /// search can start in two different directions, from left or right.
5528 /// We count undefs as zeros until PreferredNum is reached.
5529 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5530                                          unsigned NumElems, bool ZerosFromLeft,
5531                                          SelectionDAG &DAG,
5532                                          unsigned PreferredNum = -1U) {
5533   unsigned NumZeros = 0;
5534   for (unsigned i = 0; i != NumElems; ++i) {
5535     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5536     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5537     if (!Elt.getNode())
5538       break;
5539
5540     if (X86::isZeroNode(Elt))
5541       ++NumZeros;
5542     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5543       NumZeros = std::min(NumZeros + 1, PreferredNum);
5544     else
5545       break;
5546   }
5547
5548   return NumZeros;
5549 }
5550
5551 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5552 /// correspond consecutively to elements from one of the vector operands,
5553 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5554 static
5555 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5556                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5557                               unsigned NumElems, unsigned &OpNum) {
5558   bool SeenV1 = false;
5559   bool SeenV2 = false;
5560
5561   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5562     int Idx = SVOp->getMaskElt(i);
5563     // Ignore undef indicies
5564     if (Idx < 0)
5565       continue;
5566
5567     if (Idx < (int)NumElems)
5568       SeenV1 = true;
5569     else
5570       SeenV2 = true;
5571
5572     // Only accept consecutive elements from the same vector
5573     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5574       return false;
5575   }
5576
5577   OpNum = SeenV1 ? 0 : 1;
5578   return true;
5579 }
5580
5581 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5582 /// logical left shift of a vector.
5583 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5584                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5585   unsigned NumElems =
5586     SVOp->getSimpleValueType(0).getVectorNumElements();
5587   unsigned NumZeros = getNumOfConsecutiveZeros(
5588       SVOp, NumElems, false /* check zeros from right */, DAG,
5589       SVOp->getMaskElt(0));
5590   unsigned OpSrc;
5591
5592   if (!NumZeros)
5593     return false;
5594
5595   // Considering the elements in the mask that are not consecutive zeros,
5596   // check if they consecutively come from only one of the source vectors.
5597   //
5598   //               V1 = {X, A, B, C}     0
5599   //                         \  \  \    /
5600   //   vector_shuffle V1, V2 <1, 2, 3, X>
5601   //
5602   if (!isShuffleMaskConsecutive(SVOp,
5603             0,                   // Mask Start Index
5604             NumElems-NumZeros,   // Mask End Index(exclusive)
5605             NumZeros,            // Where to start looking in the src vector
5606             NumElems,            // Number of elements in vector
5607             OpSrc))              // Which source operand ?
5608     return false;
5609
5610   isLeft = false;
5611   ShAmt = NumZeros;
5612   ShVal = SVOp->getOperand(OpSrc);
5613   return true;
5614 }
5615
5616 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5617 /// logical left shift of a vector.
5618 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5619                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5620   unsigned NumElems =
5621     SVOp->getSimpleValueType(0).getVectorNumElements();
5622   unsigned NumZeros = getNumOfConsecutiveZeros(
5623       SVOp, NumElems, true /* check zeros from left */, DAG,
5624       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5625   unsigned OpSrc;
5626
5627   if (!NumZeros)
5628     return false;
5629
5630   // Considering the elements in the mask that are not consecutive zeros,
5631   // check if they consecutively come from only one of the source vectors.
5632   //
5633   //                           0    { A, B, X, X } = V2
5634   //                          / \    /  /
5635   //   vector_shuffle V1, V2 <X, X, 4, 5>
5636   //
5637   if (!isShuffleMaskConsecutive(SVOp,
5638             NumZeros,     // Mask Start Index
5639             NumElems,     // Mask End Index(exclusive)
5640             0,            // Where to start looking in the src vector
5641             NumElems,     // Number of elements in vector
5642             OpSrc))       // Which source operand ?
5643     return false;
5644
5645   isLeft = true;
5646   ShAmt = NumZeros;
5647   ShVal = SVOp->getOperand(OpSrc);
5648   return true;
5649 }
5650
5651 /// isVectorShift - Returns true if the shuffle can be implemented as a
5652 /// logical left or right shift of a vector.
5653 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5654                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5655   // Although the logic below support any bitwidth size, there are no
5656   // shift instructions which handle more than 128-bit vectors.
5657   if (!SVOp->getSimpleValueType(0).is128BitVector())
5658     return false;
5659
5660   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5661       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5662     return true;
5663
5664   return false;
5665 }
5666
5667 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5668 ///
5669 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5670                                        unsigned NumNonZero, unsigned NumZero,
5671                                        SelectionDAG &DAG,
5672                                        const X86Subtarget* Subtarget,
5673                                        const TargetLowering &TLI) {
5674   if (NumNonZero > 8)
5675     return SDValue();
5676
5677   SDLoc dl(Op);
5678   SDValue V;
5679   bool First = true;
5680   for (unsigned i = 0; i < 16; ++i) {
5681     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5682     if (ThisIsNonZero && First) {
5683       if (NumZero)
5684         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5685       else
5686         V = DAG.getUNDEF(MVT::v8i16);
5687       First = false;
5688     }
5689
5690     if ((i & 1) != 0) {
5691       SDValue ThisElt, LastElt;
5692       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5693       if (LastIsNonZero) {
5694         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5695                               MVT::i16, Op.getOperand(i-1));
5696       }
5697       if (ThisIsNonZero) {
5698         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5699         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5700                               ThisElt, DAG.getConstant(8, MVT::i8));
5701         if (LastIsNonZero)
5702           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5703       } else
5704         ThisElt = LastElt;
5705
5706       if (ThisElt.getNode())
5707         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5708                         DAG.getIntPtrConstant(i/2));
5709     }
5710   }
5711
5712   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5713 }
5714
5715 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5716 ///
5717 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5718                                      unsigned NumNonZero, unsigned NumZero,
5719                                      SelectionDAG &DAG,
5720                                      const X86Subtarget* Subtarget,
5721                                      const TargetLowering &TLI) {
5722   if (NumNonZero > 4)
5723     return SDValue();
5724
5725   SDLoc dl(Op);
5726   SDValue V;
5727   bool First = true;
5728   for (unsigned i = 0; i < 8; ++i) {
5729     bool isNonZero = (NonZeros & (1 << i)) != 0;
5730     if (isNonZero) {
5731       if (First) {
5732         if (NumZero)
5733           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5734         else
5735           V = DAG.getUNDEF(MVT::v8i16);
5736         First = false;
5737       }
5738       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5739                       MVT::v8i16, V, Op.getOperand(i),
5740                       DAG.getIntPtrConstant(i));
5741     }
5742   }
5743
5744   return V;
5745 }
5746
5747 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5748 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5749                                      unsigned NonZeros, unsigned NumNonZero,
5750                                      unsigned NumZero, SelectionDAG &DAG,
5751                                      const X86Subtarget *Subtarget,
5752                                      const TargetLowering &TLI) {
5753   // We know there's at least one non-zero element
5754   unsigned FirstNonZeroIdx = 0;
5755   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5756   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5757          X86::isZeroNode(FirstNonZero)) {
5758     ++FirstNonZeroIdx;
5759     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5760   }
5761
5762   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5763       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5764     return SDValue();
5765
5766   SDValue V = FirstNonZero.getOperand(0);
5767   MVT VVT = V.getSimpleValueType();
5768   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5769     return SDValue();
5770
5771   unsigned FirstNonZeroDst =
5772       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5773   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5774   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5775   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5776
5777   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5778     SDValue Elem = Op.getOperand(Idx);
5779     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5780       continue;
5781
5782     // TODO: What else can be here? Deal with it.
5783     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5784       return SDValue();
5785
5786     // TODO: Some optimizations are still possible here
5787     // ex: Getting one element from a vector, and the rest from another.
5788     if (Elem.getOperand(0) != V)
5789       return SDValue();
5790
5791     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5792     if (Dst == Idx)
5793       ++CorrectIdx;
5794     else if (IncorrectIdx == -1U) {
5795       IncorrectIdx = Idx;
5796       IncorrectDst = Dst;
5797     } else
5798       // There was already one element with an incorrect index.
5799       // We can't optimize this case to an insertps.
5800       return SDValue();
5801   }
5802
5803   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5804     SDLoc dl(Op);
5805     EVT VT = Op.getSimpleValueType();
5806     unsigned ElementMoveMask = 0;
5807     if (IncorrectIdx == -1U)
5808       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5809     else
5810       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5811
5812     SDValue InsertpsMask =
5813         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5814     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5815   }
5816
5817   return SDValue();
5818 }
5819
5820 /// getVShift - Return a vector logical shift node.
5821 ///
5822 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5823                          unsigned NumBits, SelectionDAG &DAG,
5824                          const TargetLowering &TLI, SDLoc dl) {
5825   assert(VT.is128BitVector() && "Unknown type for VShift");
5826   EVT ShVT = MVT::v2i64;
5827   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5828   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5829   return DAG.getNode(ISD::BITCAST, dl, VT,
5830                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5831                              DAG.getConstant(NumBits,
5832                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5833 }
5834
5835 static SDValue
5836 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5837
5838   // Check if the scalar load can be widened into a vector load. And if
5839   // the address is "base + cst" see if the cst can be "absorbed" into
5840   // the shuffle mask.
5841   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5842     SDValue Ptr = LD->getBasePtr();
5843     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5844       return SDValue();
5845     EVT PVT = LD->getValueType(0);
5846     if (PVT != MVT::i32 && PVT != MVT::f32)
5847       return SDValue();
5848
5849     int FI = -1;
5850     int64_t Offset = 0;
5851     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5852       FI = FINode->getIndex();
5853       Offset = 0;
5854     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5855                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5856       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5857       Offset = Ptr.getConstantOperandVal(1);
5858       Ptr = Ptr.getOperand(0);
5859     } else {
5860       return SDValue();
5861     }
5862
5863     // FIXME: 256-bit vector instructions don't require a strict alignment,
5864     // improve this code to support it better.
5865     unsigned RequiredAlign = VT.getSizeInBits()/8;
5866     SDValue Chain = LD->getChain();
5867     // Make sure the stack object alignment is at least 16 or 32.
5868     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5869     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5870       if (MFI->isFixedObjectIndex(FI)) {
5871         // Can't change the alignment. FIXME: It's possible to compute
5872         // the exact stack offset and reference FI + adjust offset instead.
5873         // If someone *really* cares about this. That's the way to implement it.
5874         return SDValue();
5875       } else {
5876         MFI->setObjectAlignment(FI, RequiredAlign);
5877       }
5878     }
5879
5880     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5881     // Ptr + (Offset & ~15).
5882     if (Offset < 0)
5883       return SDValue();
5884     if ((Offset % RequiredAlign) & 3)
5885       return SDValue();
5886     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5887     if (StartOffset)
5888       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5889                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5890
5891     int EltNo = (Offset - StartOffset) >> 2;
5892     unsigned NumElems = VT.getVectorNumElements();
5893
5894     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5895     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5896                              LD->getPointerInfo().getWithOffset(StartOffset),
5897                              false, false, false, 0);
5898
5899     SmallVector<int, 8> Mask;
5900     for (unsigned i = 0; i != NumElems; ++i)
5901       Mask.push_back(EltNo);
5902
5903     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5904   }
5905
5906   return SDValue();
5907 }
5908
5909 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5910 /// vector of type 'VT', see if the elements can be replaced by a single large
5911 /// load which has the same value as a build_vector whose operands are 'elts'.
5912 ///
5913 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5914 ///
5915 /// FIXME: we'd also like to handle the case where the last elements are zero
5916 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5917 /// There's even a handy isZeroNode for that purpose.
5918 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5919                                         SDLoc &DL, SelectionDAG &DAG,
5920                                         bool isAfterLegalize) {
5921   EVT EltVT = VT.getVectorElementType();
5922   unsigned NumElems = Elts.size();
5923
5924   LoadSDNode *LDBase = nullptr;
5925   unsigned LastLoadedElt = -1U;
5926
5927   // For each element in the initializer, see if we've found a load or an undef.
5928   // If we don't find an initial load element, or later load elements are
5929   // non-consecutive, bail out.
5930   for (unsigned i = 0; i < NumElems; ++i) {
5931     SDValue Elt = Elts[i];
5932
5933     if (!Elt.getNode() ||
5934         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5935       return SDValue();
5936     if (!LDBase) {
5937       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5938         return SDValue();
5939       LDBase = cast<LoadSDNode>(Elt.getNode());
5940       LastLoadedElt = i;
5941       continue;
5942     }
5943     if (Elt.getOpcode() == ISD::UNDEF)
5944       continue;
5945
5946     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5947     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5948       return SDValue();
5949     LastLoadedElt = i;
5950   }
5951
5952   // If we have found an entire vector of loads and undefs, then return a large
5953   // load of the entire vector width starting at the base pointer.  If we found
5954   // consecutive loads for the low half, generate a vzext_load node.
5955   if (LastLoadedElt == NumElems - 1) {
5956
5957     if (isAfterLegalize &&
5958         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5959       return SDValue();
5960
5961     SDValue NewLd = SDValue();
5962
5963     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5964       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5965                           LDBase->getPointerInfo(),
5966                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5967                           LDBase->isInvariant(), 0);
5968     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5969                         LDBase->getPointerInfo(),
5970                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5971                         LDBase->isInvariant(), LDBase->getAlignment());
5972
5973     if (LDBase->hasAnyUseOfValue(1)) {
5974       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5975                                      SDValue(LDBase, 1),
5976                                      SDValue(NewLd.getNode(), 1));
5977       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5978       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5979                              SDValue(NewLd.getNode(), 1));
5980     }
5981
5982     return NewLd;
5983   }
5984   if (NumElems == 4 && LastLoadedElt == 1 &&
5985       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5986     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5987     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5988     SDValue ResNode =
5989         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5990                                 LDBase->getPointerInfo(),
5991                                 LDBase->getAlignment(),
5992                                 false/*isVolatile*/, true/*ReadMem*/,
5993                                 false/*WriteMem*/);
5994
5995     // Make sure the newly-created LOAD is in the same position as LDBase in
5996     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5997     // update uses of LDBase's output chain to use the TokenFactor.
5998     if (LDBase->hasAnyUseOfValue(1)) {
5999       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6000                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
6001       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6002       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6003                              SDValue(ResNode.getNode(), 1));
6004     }
6005
6006     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
6007   }
6008   return SDValue();
6009 }
6010
6011 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6012 /// to generate a splat value for the following cases:
6013 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6014 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6015 /// a scalar load, or a constant.
6016 /// The VBROADCAST node is returned when a pattern is found,
6017 /// or SDValue() otherwise.
6018 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6019                                     SelectionDAG &DAG) {
6020   // VBROADCAST requires AVX.
6021   // TODO: Splats could be generated for non-AVX CPUs using SSE
6022   // instructions, but there's less potential gain for only 128-bit vectors.
6023   if (!Subtarget->hasAVX())
6024     return SDValue();
6025
6026   MVT VT = Op.getSimpleValueType();
6027   SDLoc dl(Op);
6028
6029   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6030          "Unsupported vector type for broadcast.");
6031
6032   SDValue Ld;
6033   bool ConstSplatVal;
6034
6035   switch (Op.getOpcode()) {
6036     default:
6037       // Unknown pattern found.
6038       return SDValue();
6039
6040     case ISD::BUILD_VECTOR: {
6041       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6042       BitVector UndefElements;
6043       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6044
6045       // We need a splat of a single value to use broadcast, and it doesn't
6046       // make any sense if the value is only in one element of the vector.
6047       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6048         return SDValue();
6049
6050       Ld = Splat;
6051       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6052                        Ld.getOpcode() == ISD::ConstantFP);
6053
6054       // Make sure that all of the users of a non-constant load are from the
6055       // BUILD_VECTOR node.
6056       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6057         return SDValue();
6058       break;
6059     }
6060
6061     case ISD::VECTOR_SHUFFLE: {
6062       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6063
6064       // Shuffles must have a splat mask where the first element is
6065       // broadcasted.
6066       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6067         return SDValue();
6068
6069       SDValue Sc = Op.getOperand(0);
6070       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6071           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6072
6073         if (!Subtarget->hasInt256())
6074           return SDValue();
6075
6076         // Use the register form of the broadcast instruction available on AVX2.
6077         if (VT.getSizeInBits() >= 256)
6078           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6079         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6080       }
6081
6082       Ld = Sc.getOperand(0);
6083       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6084                        Ld.getOpcode() == ISD::ConstantFP);
6085
6086       // The scalar_to_vector node and the suspected
6087       // load node must have exactly one user.
6088       // Constants may have multiple users.
6089
6090       // AVX-512 has register version of the broadcast
6091       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6092         Ld.getValueType().getSizeInBits() >= 32;
6093       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6094           !hasRegVer))
6095         return SDValue();
6096       break;
6097     }
6098   }
6099
6100   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6101   bool IsGE256 = (VT.getSizeInBits() >= 256);
6102
6103   // When optimizing for size, generate up to 5 extra bytes for a broadcast
6104   // instruction to save 8 or more bytes of constant pool data.
6105   // TODO: If multiple splats are generated to load the same constant,
6106   // it may be detrimental to overall size. There needs to be a way to detect
6107   // that condition to know if this is truly a size win.
6108   const Function *F = DAG.getMachineFunction().getFunction();
6109   bool OptForSize = F->getAttributes().
6110     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6111
6112   // Handle broadcasting a single constant scalar from the constant pool
6113   // into a vector.
6114   // On Sandybridge (no AVX2), it is still better to load a constant vector
6115   // from the constant pool and not to broadcast it from a scalar.
6116   // But override that restriction when optimizing for size.
6117   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
6118   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
6119     EVT CVT = Ld.getValueType();
6120     assert(!CVT.isVector() && "Must not broadcast a vector type");
6121
6122     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
6123     // For size optimization, also splat v2f64 and v2i64, and for size opt
6124     // with AVX2, also splat i8 and i16.
6125     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
6126     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6127         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
6128       const Constant *C = nullptr;
6129       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6130         C = CI->getConstantIntValue();
6131       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6132         C = CF->getConstantFPValue();
6133
6134       assert(C && "Invalid constant type");
6135
6136       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6137       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6138       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6139       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6140                        MachinePointerInfo::getConstantPool(),
6141                        false, false, false, Alignment);
6142
6143       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6144     }
6145   }
6146
6147   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6148
6149   // Handle AVX2 in-register broadcasts.
6150   if (!IsLoad && Subtarget->hasInt256() &&
6151       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6152     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6153
6154   // The scalar source must be a normal load.
6155   if (!IsLoad)
6156     return SDValue();
6157
6158   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6159     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6160
6161   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6162   // double since there is no vbroadcastsd xmm
6163   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6164     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6165       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6166   }
6167
6168   // Unsupported broadcast.
6169   return SDValue();
6170 }
6171
6172 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6173 /// underlying vector and index.
6174 ///
6175 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6176 /// index.
6177 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6178                                          SDValue ExtIdx) {
6179   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6180   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6181     return Idx;
6182
6183   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6184   // lowered this:
6185   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6186   // to:
6187   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6188   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6189   //                           undef)
6190   //                       Constant<0>)
6191   // In this case the vector is the extract_subvector expression and the index
6192   // is 2, as specified by the shuffle.
6193   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6194   SDValue ShuffleVec = SVOp->getOperand(0);
6195   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6196   assert(ShuffleVecVT.getVectorElementType() ==
6197          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6198
6199   int ShuffleIdx = SVOp->getMaskElt(Idx);
6200   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6201     ExtractedFromVec = ShuffleVec;
6202     return ShuffleIdx;
6203   }
6204   return Idx;
6205 }
6206
6207 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6208   MVT VT = Op.getSimpleValueType();
6209
6210   // Skip if insert_vec_elt is not supported.
6211   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6212   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6213     return SDValue();
6214
6215   SDLoc DL(Op);
6216   unsigned NumElems = Op.getNumOperands();
6217
6218   SDValue VecIn1;
6219   SDValue VecIn2;
6220   SmallVector<unsigned, 4> InsertIndices;
6221   SmallVector<int, 8> Mask(NumElems, -1);
6222
6223   for (unsigned i = 0; i != NumElems; ++i) {
6224     unsigned Opc = Op.getOperand(i).getOpcode();
6225
6226     if (Opc == ISD::UNDEF)
6227       continue;
6228
6229     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6230       // Quit if more than 1 elements need inserting.
6231       if (InsertIndices.size() > 1)
6232         return SDValue();
6233
6234       InsertIndices.push_back(i);
6235       continue;
6236     }
6237
6238     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6239     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6240     // Quit if non-constant index.
6241     if (!isa<ConstantSDNode>(ExtIdx))
6242       return SDValue();
6243     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6244
6245     // Quit if extracted from vector of different type.
6246     if (ExtractedFromVec.getValueType() != VT)
6247       return SDValue();
6248
6249     if (!VecIn1.getNode())
6250       VecIn1 = ExtractedFromVec;
6251     else if (VecIn1 != ExtractedFromVec) {
6252       if (!VecIn2.getNode())
6253         VecIn2 = ExtractedFromVec;
6254       else if (VecIn2 != ExtractedFromVec)
6255         // Quit if more than 2 vectors to shuffle
6256         return SDValue();
6257     }
6258
6259     if (ExtractedFromVec == VecIn1)
6260       Mask[i] = Idx;
6261     else if (ExtractedFromVec == VecIn2)
6262       Mask[i] = Idx + NumElems;
6263   }
6264
6265   if (!VecIn1.getNode())
6266     return SDValue();
6267
6268   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6269   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6270   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6271     unsigned Idx = InsertIndices[i];
6272     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6273                      DAG.getIntPtrConstant(Idx));
6274   }
6275
6276   return NV;
6277 }
6278
6279 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6280 SDValue
6281 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6282
6283   MVT VT = Op.getSimpleValueType();
6284   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6285          "Unexpected type in LowerBUILD_VECTORvXi1!");
6286
6287   SDLoc dl(Op);
6288   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6289     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6290     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6291     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6292   }
6293
6294   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6295     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6296     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6297     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6298   }
6299
6300   bool AllContants = true;
6301   uint64_t Immediate = 0;
6302   int NonConstIdx = -1;
6303   bool IsSplat = true;
6304   unsigned NumNonConsts = 0;
6305   unsigned NumConsts = 0;
6306   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6307     SDValue In = Op.getOperand(idx);
6308     if (In.getOpcode() == ISD::UNDEF)
6309       continue;
6310     if (!isa<ConstantSDNode>(In)) {
6311       AllContants = false;
6312       NonConstIdx = idx;
6313       NumNonConsts++;
6314     }
6315     else {
6316       NumConsts++;
6317       if (cast<ConstantSDNode>(In)->getZExtValue())
6318       Immediate |= (1ULL << idx);
6319     }
6320     if (In != Op.getOperand(0))
6321       IsSplat = false;
6322   }
6323
6324   if (AllContants) {
6325     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6326       DAG.getConstant(Immediate, MVT::i16));
6327     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6328                        DAG.getIntPtrConstant(0));
6329   }
6330
6331   if (NumNonConsts == 1 && NonConstIdx != 0) {
6332     SDValue DstVec;
6333     if (NumConsts) {
6334       SDValue VecAsImm = DAG.getConstant(Immediate,
6335                                          MVT::getIntegerVT(VT.getSizeInBits()));
6336       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6337     }
6338     else 
6339       DstVec = DAG.getUNDEF(VT);
6340     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6341                        Op.getOperand(NonConstIdx),
6342                        DAG.getIntPtrConstant(NonConstIdx));
6343   }
6344   if (!IsSplat && (NonConstIdx != 0))
6345     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6346   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6347   SDValue Select;
6348   if (IsSplat)
6349     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6350                           DAG.getConstant(-1, SelectVT),
6351                           DAG.getConstant(0, SelectVT));
6352   else
6353     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6354                          DAG.getConstant((Immediate | 1), SelectVT),
6355                          DAG.getConstant(Immediate, SelectVT));
6356   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6357 }
6358
6359 /// \brief Return true if \p N implements a horizontal binop and return the
6360 /// operands for the horizontal binop into V0 and V1.
6361 /// 
6362 /// This is a helper function of PerformBUILD_VECTORCombine.
6363 /// This function checks that the build_vector \p N in input implements a
6364 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6365 /// operation to match.
6366 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6367 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6368 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6369 /// arithmetic sub.
6370 ///
6371 /// This function only analyzes elements of \p N whose indices are
6372 /// in range [BaseIdx, LastIdx).
6373 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6374                               SelectionDAG &DAG,
6375                               unsigned BaseIdx, unsigned LastIdx,
6376                               SDValue &V0, SDValue &V1) {
6377   EVT VT = N->getValueType(0);
6378
6379   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6380   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6381          "Invalid Vector in input!");
6382   
6383   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6384   bool CanFold = true;
6385   unsigned ExpectedVExtractIdx = BaseIdx;
6386   unsigned NumElts = LastIdx - BaseIdx;
6387   V0 = DAG.getUNDEF(VT);
6388   V1 = DAG.getUNDEF(VT);
6389
6390   // Check if N implements a horizontal binop.
6391   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6392     SDValue Op = N->getOperand(i + BaseIdx);
6393
6394     // Skip UNDEFs.
6395     if (Op->getOpcode() == ISD::UNDEF) {
6396       // Update the expected vector extract index.
6397       if (i * 2 == NumElts)
6398         ExpectedVExtractIdx = BaseIdx;
6399       ExpectedVExtractIdx += 2;
6400       continue;
6401     }
6402
6403     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6404
6405     if (!CanFold)
6406       break;
6407
6408     SDValue Op0 = Op.getOperand(0);
6409     SDValue Op1 = Op.getOperand(1);
6410
6411     // Try to match the following pattern:
6412     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6413     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6414         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6415         Op0.getOperand(0) == Op1.getOperand(0) &&
6416         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6417         isa<ConstantSDNode>(Op1.getOperand(1)));
6418     if (!CanFold)
6419       break;
6420
6421     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6422     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6423
6424     if (i * 2 < NumElts) {
6425       if (V0.getOpcode() == ISD::UNDEF)
6426         V0 = Op0.getOperand(0);
6427     } else {
6428       if (V1.getOpcode() == ISD::UNDEF)
6429         V1 = Op0.getOperand(0);
6430       if (i * 2 == NumElts)
6431         ExpectedVExtractIdx = BaseIdx;
6432     }
6433
6434     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6435     if (I0 == ExpectedVExtractIdx)
6436       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6437     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6438       // Try to match the following dag sequence:
6439       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6440       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6441     } else
6442       CanFold = false;
6443
6444     ExpectedVExtractIdx += 2;
6445   }
6446
6447   return CanFold;
6448 }
6449
6450 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6451 /// a concat_vector. 
6452 ///
6453 /// This is a helper function of PerformBUILD_VECTORCombine.
6454 /// This function expects two 256-bit vectors called V0 and V1.
6455 /// At first, each vector is split into two separate 128-bit vectors.
6456 /// Then, the resulting 128-bit vectors are used to implement two
6457 /// horizontal binary operations. 
6458 ///
6459 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6460 ///
6461 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6462 /// the two new horizontal binop.
6463 /// When Mode is set, the first horizontal binop dag node would take as input
6464 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6465 /// horizontal binop dag node would take as input the lower 128-bit of V1
6466 /// and the upper 128-bit of V1.
6467 ///   Example:
6468 ///     HADD V0_LO, V0_HI
6469 ///     HADD V1_LO, V1_HI
6470 ///
6471 /// Otherwise, the first horizontal binop dag node takes as input the lower
6472 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6473 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6474 ///   Example:
6475 ///     HADD V0_LO, V1_LO
6476 ///     HADD V0_HI, V1_HI
6477 ///
6478 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6479 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6480 /// the upper 128-bits of the result.
6481 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6482                                      SDLoc DL, SelectionDAG &DAG,
6483                                      unsigned X86Opcode, bool Mode,
6484                                      bool isUndefLO, bool isUndefHI) {
6485   EVT VT = V0.getValueType();
6486   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6487          "Invalid nodes in input!");
6488
6489   unsigned NumElts = VT.getVectorNumElements();
6490   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6491   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6492   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6493   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6494   EVT NewVT = V0_LO.getValueType();
6495
6496   SDValue LO = DAG.getUNDEF(NewVT);
6497   SDValue HI = DAG.getUNDEF(NewVT);
6498
6499   if (Mode) {
6500     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6501     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6502       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6503     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6504       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6505   } else {
6506     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6507     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6508                        V1_LO->getOpcode() != ISD::UNDEF))
6509       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6510
6511     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6512                        V1_HI->getOpcode() != ISD::UNDEF))
6513       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6514   }
6515
6516   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6517 }
6518
6519 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6520 /// sequence of 'vadd + vsub + blendi'.
6521 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6522                            const X86Subtarget *Subtarget) {
6523   SDLoc DL(BV);
6524   EVT VT = BV->getValueType(0);
6525   unsigned NumElts = VT.getVectorNumElements();
6526   SDValue InVec0 = DAG.getUNDEF(VT);
6527   SDValue InVec1 = DAG.getUNDEF(VT);
6528
6529   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6530           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6531
6532   // Odd-numbered elements in the input build vector are obtained from
6533   // adding two integer/float elements.
6534   // Even-numbered elements in the input build vector are obtained from
6535   // subtracting two integer/float elements.
6536   unsigned ExpectedOpcode = ISD::FSUB;
6537   unsigned NextExpectedOpcode = ISD::FADD;
6538   bool AddFound = false;
6539   bool SubFound = false;
6540
6541   for (unsigned i = 0, e = NumElts; i != e; i++) {
6542     SDValue Op = BV->getOperand(i);
6543
6544     // Skip 'undef' values.
6545     unsigned Opcode = Op.getOpcode();
6546     if (Opcode == ISD::UNDEF) {
6547       std::swap(ExpectedOpcode, NextExpectedOpcode);
6548       continue;
6549     }
6550
6551     // Early exit if we found an unexpected opcode.
6552     if (Opcode != ExpectedOpcode)
6553       return SDValue();
6554
6555     SDValue Op0 = Op.getOperand(0);
6556     SDValue Op1 = Op.getOperand(1);
6557
6558     // Try to match the following pattern:
6559     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6560     // Early exit if we cannot match that sequence.
6561     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6562         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6563         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6564         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6565         Op0.getOperand(1) != Op1.getOperand(1))
6566       return SDValue();
6567
6568     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6569     if (I0 != i)
6570       return SDValue();
6571
6572     // We found a valid add/sub node. Update the information accordingly.
6573     if (i & 1)
6574       AddFound = true;
6575     else
6576       SubFound = true;
6577
6578     // Update InVec0 and InVec1.
6579     if (InVec0.getOpcode() == ISD::UNDEF)
6580       InVec0 = Op0.getOperand(0);
6581     if (InVec1.getOpcode() == ISD::UNDEF)
6582       InVec1 = Op1.getOperand(0);
6583
6584     // Make sure that operands in input to each add/sub node always
6585     // come from a same pair of vectors.
6586     if (InVec0 != Op0.getOperand(0)) {
6587       if (ExpectedOpcode == ISD::FSUB)
6588         return SDValue();
6589
6590       // FADD is commutable. Try to commute the operands
6591       // and then test again.
6592       std::swap(Op0, Op1);
6593       if (InVec0 != Op0.getOperand(0))
6594         return SDValue();
6595     }
6596
6597     if (InVec1 != Op1.getOperand(0))
6598       return SDValue();
6599
6600     // Update the pair of expected opcodes.
6601     std::swap(ExpectedOpcode, NextExpectedOpcode);
6602   }
6603
6604   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6605   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6606       InVec1.getOpcode() != ISD::UNDEF)
6607     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6608
6609   return SDValue();
6610 }
6611
6612 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6613                                           const X86Subtarget *Subtarget) {
6614   SDLoc DL(N);
6615   EVT VT = N->getValueType(0);
6616   unsigned NumElts = VT.getVectorNumElements();
6617   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6618   SDValue InVec0, InVec1;
6619
6620   // Try to match an ADDSUB.
6621   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6622       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6623     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6624     if (Value.getNode())
6625       return Value;
6626   }
6627
6628   // Try to match horizontal ADD/SUB.
6629   unsigned NumUndefsLO = 0;
6630   unsigned NumUndefsHI = 0;
6631   unsigned Half = NumElts/2;
6632
6633   // Count the number of UNDEF operands in the build_vector in input.
6634   for (unsigned i = 0, e = Half; i != e; ++i)
6635     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6636       NumUndefsLO++;
6637
6638   for (unsigned i = Half, e = NumElts; i != e; ++i)
6639     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6640       NumUndefsHI++;
6641
6642   // Early exit if this is either a build_vector of all UNDEFs or all the
6643   // operands but one are UNDEF.
6644   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6645     return SDValue();
6646
6647   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6648     // Try to match an SSE3 float HADD/HSUB.
6649     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6650       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6651     
6652     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6653       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6654   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6655     // Try to match an SSSE3 integer HADD/HSUB.
6656     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6657       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6658     
6659     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6660       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6661   }
6662   
6663   if (!Subtarget->hasAVX())
6664     return SDValue();
6665
6666   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6667     // Try to match an AVX horizontal add/sub of packed single/double
6668     // precision floating point values from 256-bit vectors.
6669     SDValue InVec2, InVec3;
6670     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6671         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6672         ((InVec0.getOpcode() == ISD::UNDEF ||
6673           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6674         ((InVec1.getOpcode() == ISD::UNDEF ||
6675           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6676       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6677
6678     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6679         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6680         ((InVec0.getOpcode() == ISD::UNDEF ||
6681           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6682         ((InVec1.getOpcode() == ISD::UNDEF ||
6683           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6684       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6685   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6686     // Try to match an AVX2 horizontal add/sub of signed integers.
6687     SDValue InVec2, InVec3;
6688     unsigned X86Opcode;
6689     bool CanFold = true;
6690
6691     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6692         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6693         ((InVec0.getOpcode() == ISD::UNDEF ||
6694           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6695         ((InVec1.getOpcode() == ISD::UNDEF ||
6696           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6697       X86Opcode = X86ISD::HADD;
6698     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6699         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6700         ((InVec0.getOpcode() == ISD::UNDEF ||
6701           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6702         ((InVec1.getOpcode() == ISD::UNDEF ||
6703           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6704       X86Opcode = X86ISD::HSUB;
6705     else
6706       CanFold = false;
6707
6708     if (CanFold) {
6709       // Fold this build_vector into a single horizontal add/sub.
6710       // Do this only if the target has AVX2.
6711       if (Subtarget->hasAVX2())
6712         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6713  
6714       // Do not try to expand this build_vector into a pair of horizontal
6715       // add/sub if we can emit a pair of scalar add/sub.
6716       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6717         return SDValue();
6718
6719       // Convert this build_vector into a pair of horizontal binop followed by
6720       // a concat vector.
6721       bool isUndefLO = NumUndefsLO == Half;
6722       bool isUndefHI = NumUndefsHI == Half;
6723       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6724                                    isUndefLO, isUndefHI);
6725     }
6726   }
6727
6728   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6729        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6730     unsigned X86Opcode;
6731     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6732       X86Opcode = X86ISD::HADD;
6733     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6734       X86Opcode = X86ISD::HSUB;
6735     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6736       X86Opcode = X86ISD::FHADD;
6737     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6738       X86Opcode = X86ISD::FHSUB;
6739     else
6740       return SDValue();
6741
6742     // Don't try to expand this build_vector into a pair of horizontal add/sub
6743     // if we can simply emit a pair of scalar add/sub.
6744     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6745       return SDValue();
6746
6747     // Convert this build_vector into two horizontal add/sub followed by
6748     // a concat vector.
6749     bool isUndefLO = NumUndefsLO == Half;
6750     bool isUndefHI = NumUndefsHI == Half;
6751     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6752                                  isUndefLO, isUndefHI);
6753   }
6754
6755   return SDValue();
6756 }
6757
6758 SDValue
6759 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6760   SDLoc dl(Op);
6761
6762   MVT VT = Op.getSimpleValueType();
6763   MVT ExtVT = VT.getVectorElementType();
6764   unsigned NumElems = Op.getNumOperands();
6765
6766   // Generate vectors for predicate vectors.
6767   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6768     return LowerBUILD_VECTORvXi1(Op, DAG);
6769
6770   // Vectors containing all zeros can be matched by pxor and xorps later
6771   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6772     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6773     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6774     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6775       return Op;
6776
6777     return getZeroVector(VT, Subtarget, DAG, dl);
6778   }
6779
6780   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6781   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6782   // vpcmpeqd on 256-bit vectors.
6783   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6784     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6785       return Op;
6786
6787     if (!VT.is512BitVector())
6788       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6789   }
6790
6791   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6792   if (Broadcast.getNode())
6793     return Broadcast;
6794
6795   unsigned EVTBits = ExtVT.getSizeInBits();
6796
6797   unsigned NumZero  = 0;
6798   unsigned NumNonZero = 0;
6799   unsigned NonZeros = 0;
6800   bool IsAllConstants = true;
6801   SmallSet<SDValue, 8> Values;
6802   for (unsigned i = 0; i < NumElems; ++i) {
6803     SDValue Elt = Op.getOperand(i);
6804     if (Elt.getOpcode() == ISD::UNDEF)
6805       continue;
6806     Values.insert(Elt);
6807     if (Elt.getOpcode() != ISD::Constant &&
6808         Elt.getOpcode() != ISD::ConstantFP)
6809       IsAllConstants = false;
6810     if (X86::isZeroNode(Elt))
6811       NumZero++;
6812     else {
6813       NonZeros |= (1 << i);
6814       NumNonZero++;
6815     }
6816   }
6817
6818   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6819   if (NumNonZero == 0)
6820     return DAG.getUNDEF(VT);
6821
6822   // Special case for single non-zero, non-undef, element.
6823   if (NumNonZero == 1) {
6824     unsigned Idx = countTrailingZeros(NonZeros);
6825     SDValue Item = Op.getOperand(Idx);
6826
6827     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6828     // the value are obviously zero, truncate the value to i32 and do the
6829     // insertion that way.  Only do this if the value is non-constant or if the
6830     // value is a constant being inserted into element 0.  It is cheaper to do
6831     // a constant pool load than it is to do a movd + shuffle.
6832     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6833         (!IsAllConstants || Idx == 0)) {
6834       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6835         // Handle SSE only.
6836         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6837         EVT VecVT = MVT::v4i32;
6838         unsigned VecElts = 4;
6839
6840         // Truncate the value (which may itself be a constant) to i32, and
6841         // convert it to a vector with movd (S2V+shuffle to zero extend).
6842         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6843         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6844
6845         // If using the new shuffle lowering, just directly insert this.
6846         if (ExperimentalVectorShuffleLowering)
6847           return DAG.getNode(
6848               ISD::BITCAST, dl, VT,
6849               getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6850
6851         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6852
6853         // Now we have our 32-bit value zero extended in the low element of
6854         // a vector.  If Idx != 0, swizzle it into place.
6855         if (Idx != 0) {
6856           SmallVector<int, 4> Mask;
6857           Mask.push_back(Idx);
6858           for (unsigned i = 1; i != VecElts; ++i)
6859             Mask.push_back(i);
6860           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6861                                       &Mask[0]);
6862         }
6863         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6864       }
6865     }
6866
6867     // If we have a constant or non-constant insertion into the low element of
6868     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6869     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6870     // depending on what the source datatype is.
6871     if (Idx == 0) {
6872       if (NumZero == 0)
6873         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6874
6875       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6876           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6877         if (VT.is256BitVector() || VT.is512BitVector()) {
6878           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6879           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6880                              Item, DAG.getIntPtrConstant(0));
6881         }
6882         assert(VT.is128BitVector() && "Expected an SSE value type!");
6883         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6884         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6885         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6886       }
6887
6888       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6889         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6890         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6891         if (VT.is256BitVector()) {
6892           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6893           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6894         } else {
6895           assert(VT.is128BitVector() && "Expected an SSE value type!");
6896           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6897         }
6898         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6899       }
6900     }
6901
6902     // Is it a vector logical left shift?
6903     if (NumElems == 2 && Idx == 1 &&
6904         X86::isZeroNode(Op.getOperand(0)) &&
6905         !X86::isZeroNode(Op.getOperand(1))) {
6906       unsigned NumBits = VT.getSizeInBits();
6907       return getVShift(true, VT,
6908                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6909                                    VT, Op.getOperand(1)),
6910                        NumBits/2, DAG, *this, dl);
6911     }
6912
6913     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6914       return SDValue();
6915
6916     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6917     // is a non-constant being inserted into an element other than the low one,
6918     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6919     // movd/movss) to move this into the low element, then shuffle it into
6920     // place.
6921     if (EVTBits == 32) {
6922       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6923
6924       // If using the new shuffle lowering, just directly insert this.
6925       if (ExperimentalVectorShuffleLowering)
6926         return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6927
6928       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6929       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6930       SmallVector<int, 8> MaskVec;
6931       for (unsigned i = 0; i != NumElems; ++i)
6932         MaskVec.push_back(i == Idx ? 0 : 1);
6933       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6934     }
6935   }
6936
6937   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6938   if (Values.size() == 1) {
6939     if (EVTBits == 32) {
6940       // Instead of a shuffle like this:
6941       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6942       // Check if it's possible to issue this instead.
6943       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6944       unsigned Idx = countTrailingZeros(NonZeros);
6945       SDValue Item = Op.getOperand(Idx);
6946       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6947         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6948     }
6949     return SDValue();
6950   }
6951
6952   // A vector full of immediates; various special cases are already
6953   // handled, so this is best done with a single constant-pool load.
6954   if (IsAllConstants)
6955     return SDValue();
6956
6957   // For AVX-length vectors, build the individual 128-bit pieces and use
6958   // shuffles to put them in place.
6959   if (VT.is256BitVector() || VT.is512BitVector()) {
6960     SmallVector<SDValue, 64> V;
6961     for (unsigned i = 0; i != NumElems; ++i)
6962       V.push_back(Op.getOperand(i));
6963
6964     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6965
6966     // Build both the lower and upper subvector.
6967     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6968                                 makeArrayRef(&V[0], NumElems/2));
6969     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6970                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6971
6972     // Recreate the wider vector with the lower and upper part.
6973     if (VT.is256BitVector())
6974       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6975     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6976   }
6977
6978   // Let legalizer expand 2-wide build_vectors.
6979   if (EVTBits == 64) {
6980     if (NumNonZero == 1) {
6981       // One half is zero or undef.
6982       unsigned Idx = countTrailingZeros(NonZeros);
6983       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6984                                  Op.getOperand(Idx));
6985       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6986     }
6987     return SDValue();
6988   }
6989
6990   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6991   if (EVTBits == 8 && NumElems == 16) {
6992     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6993                                         Subtarget, *this);
6994     if (V.getNode()) return V;
6995   }
6996
6997   if (EVTBits == 16 && NumElems == 8) {
6998     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6999                                       Subtarget, *this);
7000     if (V.getNode()) return V;
7001   }
7002
7003   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
7004   if (EVTBits == 32 && NumElems == 4) {
7005     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
7006                                       NumZero, DAG, Subtarget, *this);
7007     if (V.getNode())
7008       return V;
7009   }
7010
7011   // If element VT is == 32 bits, turn it into a number of shuffles.
7012   SmallVector<SDValue, 8> V(NumElems);
7013   if (NumElems == 4 && NumZero > 0) {
7014     for (unsigned i = 0; i < 4; ++i) {
7015       bool isZero = !(NonZeros & (1 << i));
7016       if (isZero)
7017         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7018       else
7019         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7020     }
7021
7022     for (unsigned i = 0; i < 2; ++i) {
7023       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7024         default: break;
7025         case 0:
7026           V[i] = V[i*2];  // Must be a zero vector.
7027           break;
7028         case 1:
7029           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7030           break;
7031         case 2:
7032           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7033           break;
7034         case 3:
7035           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7036           break;
7037       }
7038     }
7039
7040     bool Reverse1 = (NonZeros & 0x3) == 2;
7041     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7042     int MaskVec[] = {
7043       Reverse1 ? 1 : 0,
7044       Reverse1 ? 0 : 1,
7045       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7046       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7047     };
7048     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7049   }
7050
7051   if (Values.size() > 1 && VT.is128BitVector()) {
7052     // Check for a build vector of consecutive loads.
7053     for (unsigned i = 0; i < NumElems; ++i)
7054       V[i] = Op.getOperand(i);
7055
7056     // Check for elements which are consecutive loads.
7057     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7058     if (LD.getNode())
7059       return LD;
7060
7061     // Check for a build vector from mostly shuffle plus few inserting.
7062     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7063     if (Sh.getNode())
7064       return Sh;
7065
7066     // For SSE 4.1, use insertps to put the high elements into the low element.
7067     if (getSubtarget()->hasSSE41()) {
7068       SDValue Result;
7069       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7070         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7071       else
7072         Result = DAG.getUNDEF(VT);
7073
7074       for (unsigned i = 1; i < NumElems; ++i) {
7075         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7076         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7077                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7078       }
7079       return Result;
7080     }
7081
7082     // Otherwise, expand into a number of unpckl*, start by extending each of
7083     // our (non-undef) elements to the full vector width with the element in the
7084     // bottom slot of the vector (which generates no code for SSE).
7085     for (unsigned i = 0; i < NumElems; ++i) {
7086       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7087         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7088       else
7089         V[i] = DAG.getUNDEF(VT);
7090     }
7091
7092     // Next, we iteratively mix elements, e.g. for v4f32:
7093     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7094     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7095     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7096     unsigned EltStride = NumElems >> 1;
7097     while (EltStride != 0) {
7098       for (unsigned i = 0; i < EltStride; ++i) {
7099         // If V[i+EltStride] is undef and this is the first round of mixing,
7100         // then it is safe to just drop this shuffle: V[i] is already in the
7101         // right place, the one element (since it's the first round) being
7102         // inserted as undef can be dropped.  This isn't safe for successive
7103         // rounds because they will permute elements within both vectors.
7104         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7105             EltStride == NumElems/2)
7106           continue;
7107
7108         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7109       }
7110       EltStride >>= 1;
7111     }
7112     return V[0];
7113   }
7114   return SDValue();
7115 }
7116
7117 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7118 // to create 256-bit vectors from two other 128-bit ones.
7119 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7120   SDLoc dl(Op);
7121   MVT ResVT = Op.getSimpleValueType();
7122
7123   assert((ResVT.is256BitVector() ||
7124           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7125
7126   SDValue V1 = Op.getOperand(0);
7127   SDValue V2 = Op.getOperand(1);
7128   unsigned NumElems = ResVT.getVectorNumElements();
7129   if(ResVT.is256BitVector())
7130     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7131
7132   if (Op.getNumOperands() == 4) {
7133     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7134                                 ResVT.getVectorNumElements()/2);
7135     SDValue V3 = Op.getOperand(2);
7136     SDValue V4 = Op.getOperand(3);
7137     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7138       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7139   }
7140   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7141 }
7142
7143 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7144   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7145   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7146          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7147           Op.getNumOperands() == 4)));
7148
7149   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7150   // from two other 128-bit ones.
7151
7152   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7153   return LowerAVXCONCAT_VECTORS(Op, DAG);
7154 }
7155
7156
7157 //===----------------------------------------------------------------------===//
7158 // Vector shuffle lowering
7159 //
7160 // This is an experimental code path for lowering vector shuffles on x86. It is
7161 // designed to handle arbitrary vector shuffles and blends, gracefully
7162 // degrading performance as necessary. It works hard to recognize idiomatic
7163 // shuffles and lower them to optimal instruction patterns without leaving
7164 // a framework that allows reasonably efficient handling of all vector shuffle
7165 // patterns.
7166 //===----------------------------------------------------------------------===//
7167
7168 /// \brief Tiny helper function to identify a no-op mask.
7169 ///
7170 /// This is a somewhat boring predicate function. It checks whether the mask
7171 /// array input, which is assumed to be a single-input shuffle mask of the kind
7172 /// used by the X86 shuffle instructions (not a fully general
7173 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7174 /// in-place shuffle are 'no-op's.
7175 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7176   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7177     if (Mask[i] != -1 && Mask[i] != i)
7178       return false;
7179   return true;
7180 }
7181
7182 /// \brief Helper function to classify a mask as a single-input mask.
7183 ///
7184 /// This isn't a generic single-input test because in the vector shuffle
7185 /// lowering we canonicalize single inputs to be the first input operand. This
7186 /// means we can more quickly test for a single input by only checking whether
7187 /// an input from the second operand exists. We also assume that the size of
7188 /// mask corresponds to the size of the input vectors which isn't true in the
7189 /// fully general case.
7190 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7191   for (int M : Mask)
7192     if (M >= (int)Mask.size())
7193       return false;
7194   return true;
7195 }
7196
7197 /// \brief Test whether there are elements crossing 128-bit lanes in this
7198 /// shuffle mask.
7199 ///
7200 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
7201 /// and we routinely test for these.
7202 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
7203   int LaneSize = 128 / VT.getScalarSizeInBits();
7204   int Size = Mask.size();
7205   for (int i = 0; i < Size; ++i)
7206     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
7207       return true;
7208   return false;
7209 }
7210
7211 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
7212 ///
7213 /// This checks a shuffle mask to see if it is performing the same
7214 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
7215 /// that it is also not lane-crossing. It may however involve a blend from the
7216 /// same lane of a second vector.
7217 ///
7218 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
7219 /// non-trivial to compute in the face of undef lanes. The representation is
7220 /// *not* suitable for use with existing 128-bit shuffles as it will contain
7221 /// entries from both V1 and V2 inputs to the wider mask.
7222 static bool
7223 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
7224                                 SmallVectorImpl<int> &RepeatedMask) {
7225   int LaneSize = 128 / VT.getScalarSizeInBits();
7226   RepeatedMask.resize(LaneSize, -1);
7227   int Size = Mask.size();
7228   for (int i = 0; i < Size; ++i) {
7229     if (Mask[i] < 0)
7230       continue;
7231     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
7232       // This entry crosses lanes, so there is no way to model this shuffle.
7233       return false;
7234
7235     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
7236     if (RepeatedMask[i % LaneSize] == -1)
7237       // This is the first non-undef entry in this slot of a 128-bit lane.
7238       RepeatedMask[i % LaneSize] =
7239           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
7240     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
7241       // Found a mismatch with the repeated mask.
7242       return false;
7243   }
7244   return true;
7245 }
7246
7247 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7248 // 2013 will allow us to use it as a non-type template parameter.
7249 namespace {
7250
7251 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7252 ///
7253 /// See its documentation for details.
7254 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7255   if (Mask.size() != Args.size())
7256     return false;
7257   for (int i = 0, e = Mask.size(); i < e; ++i) {
7258     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7259     if (Mask[i] != -1 && Mask[i] != *Args[i])
7260       return false;
7261   }
7262   return true;
7263 }
7264
7265 } // namespace
7266
7267 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7268 /// arguments.
7269 ///
7270 /// This is a fast way to test a shuffle mask against a fixed pattern:
7271 ///
7272 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7273 ///
7274 /// It returns true if the mask is exactly as wide as the argument list, and
7275 /// each element of the mask is either -1 (signifying undef) or the value given
7276 /// in the argument.
7277 static const VariadicFunction1<
7278     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7279
7280 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7281 ///
7282 /// This helper function produces an 8-bit shuffle immediate corresponding to
7283 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7284 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7285 /// example.
7286 ///
7287 /// NB: We rely heavily on "undef" masks preserving the input lane.
7288 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7289                                           SelectionDAG &DAG) {
7290   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7291   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7292   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7293   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7294   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7295
7296   unsigned Imm = 0;
7297   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7298   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7299   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7300   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7301   return DAG.getConstant(Imm, MVT::i8);
7302 }
7303
7304 /// \brief Try to emit a blend instruction for a shuffle.
7305 ///
7306 /// This doesn't do any checks for the availability of instructions for blending
7307 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7308 /// be matched in the backend with the type given. What it does check for is
7309 /// that the shuffle mask is in fact a blend.
7310 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7311                                          SDValue V2, ArrayRef<int> Mask,
7312                                          const X86Subtarget *Subtarget,
7313                                          SelectionDAG &DAG) {
7314
7315   unsigned BlendMask = 0;
7316   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7317     if (Mask[i] >= Size) {
7318       if (Mask[i] != i + Size)
7319         return SDValue(); // Shuffled V2 input!
7320       BlendMask |= 1u << i;
7321       continue;
7322     }
7323     if (Mask[i] >= 0 && Mask[i] != i)
7324       return SDValue(); // Shuffled V1 input!
7325   }
7326   switch (VT.SimpleTy) {
7327   case MVT::v2f64:
7328   case MVT::v4f32:
7329   case MVT::v4f64:
7330   case MVT::v8f32:
7331     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7332                        DAG.getConstant(BlendMask, MVT::i8));
7333
7334   case MVT::v4i64:
7335   case MVT::v8i32:
7336     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7337     // FALLTHROUGH
7338   case MVT::v2i64:
7339   case MVT::v4i32:
7340     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7341     // that instruction.
7342     if (Subtarget->hasAVX2()) {
7343       // Scale the blend by the number of 32-bit dwords per element.
7344       int Scale =  VT.getScalarSizeInBits() / 32;
7345       BlendMask = 0;
7346       for (int i = 0, Size = Mask.size(); i < Size; ++i)
7347         if (Mask[i] >= Size)
7348           for (int j = 0; j < Scale; ++j)
7349             BlendMask |= 1u << (i * Scale + j);
7350
7351       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7352       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
7353       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
7354       return DAG.getNode(ISD::BITCAST, DL, VT,
7355                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7356                                      DAG.getConstant(BlendMask, MVT::i8)));
7357     }
7358     // FALLTHROUGH
7359   case MVT::v8i16: {
7360     // For integer shuffles we need to expand the mask and cast the inputs to
7361     // v8i16s prior to blending.
7362     int Scale = 8 / VT.getVectorNumElements();
7363     BlendMask = 0;
7364     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7365       if (Mask[i] >= Size)
7366         for (int j = 0; j < Scale; ++j)
7367           BlendMask |= 1u << (i * Scale + j);
7368
7369     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
7370     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
7371     return DAG.getNode(ISD::BITCAST, DL, VT,
7372                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7373                                    DAG.getConstant(BlendMask, MVT::i8)));
7374   }
7375
7376   case MVT::v16i16: {
7377     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7378     SmallVector<int, 8> RepeatedMask;
7379     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7380       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7381       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7382       BlendMask = 0;
7383       for (int i = 0; i < 8; ++i)
7384         if (RepeatedMask[i] >= 16)
7385           BlendMask |= 1u << i;
7386       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7387                          DAG.getConstant(BlendMask, MVT::i8));
7388     }
7389   }
7390     // FALLTHROUGH
7391   case MVT::v32i8: {
7392     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7393     // Scale the blend by the number of bytes per element.
7394     int Scale =  VT.getScalarSizeInBits() / 8;
7395     assert(Mask.size() * Scale == 32 && "Not a 256-bit vector!");
7396
7397     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7398     // mix of LLVM's code generator and the x86 backend. We tell the code
7399     // generator that boolean values in the elements of an x86 vector register
7400     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7401     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7402     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7403     // of the element (the remaining are ignored) and 0 in that high bit would
7404     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7405     // the LLVM model for boolean values in vector elements gets the relevant
7406     // bit set, it is set backwards and over constrained relative to x86's
7407     // actual model.
7408     SDValue VSELECTMask[32];
7409     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7410       for (int j = 0; j < Scale; ++j)
7411         VSELECTMask[Scale * i + j] =
7412             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7413                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8);
7414
7415     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1);
7416     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V2);
7417     return DAG.getNode(
7418         ISD::BITCAST, DL, VT,
7419         DAG.getNode(ISD::VSELECT, DL, MVT::v32i8,
7420                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, VSELECTMask),
7421                     V1, V2));
7422   }
7423
7424   default:
7425     llvm_unreachable("Not a supported integer vector type!");
7426   }
7427 }
7428
7429 /// \brief Generic routine to lower a shuffle and blend as a decomposed set of
7430 /// unblended shuffles followed by an unshuffled blend.
7431 ///
7432 /// This matches the extremely common pattern for handling combined
7433 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7434 /// operations.
7435 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7436                                                           SDValue V1,
7437                                                           SDValue V2,
7438                                                           ArrayRef<int> Mask,
7439                                                           SelectionDAG &DAG) {
7440   // Shuffle the input elements into the desired positions in V1 and V2 and
7441   // blend them together.
7442   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7443   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7444   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7445   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7446     if (Mask[i] >= 0 && Mask[i] < Size) {
7447       V1Mask[i] = Mask[i];
7448       BlendMask[i] = i;
7449     } else if (Mask[i] >= Size) {
7450       V2Mask[i] = Mask[i] - Size;
7451       BlendMask[i] = i + Size;
7452     }
7453
7454   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7455   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7456   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7457 }
7458
7459 /// \brief Try to lower a vector shuffle as a byte rotation.
7460 ///
7461 /// We have a generic PALIGNR instruction in x86 that will do an arbitrary
7462 /// byte-rotation of the concatenation of two vectors. This routine will
7463 /// try to generically lower a vector shuffle through such an instruction. It
7464 /// does not check for the availability of PALIGNR-based lowerings, only the
7465 /// applicability of this strategy to the given mask. This matches shuffle
7466 /// vectors that look like:
7467 /// 
7468 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7469 /// 
7470 /// Essentially it concatenates V1 and V2, shifts right by some number of
7471 /// elements, and takes the low elements as the result. Note that while this is
7472 /// specified as a *right shift* because x86 is little-endian, it is a *left
7473 /// rotate* of the vector lanes.
7474 ///
7475 /// Note that this only handles 128-bit vector widths currently.
7476 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7477                                               SDValue V2,
7478                                               ArrayRef<int> Mask,
7479                                               SelectionDAG &DAG) {
7480   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7481
7482   // We need to detect various ways of spelling a rotation:
7483   //   [11, 12, 13, 14, 15,  0,  1,  2]
7484   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7485   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7486   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7487   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7488   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7489   int Rotation = 0;
7490   SDValue Lo, Hi;
7491   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7492     if (Mask[i] == -1)
7493       continue;
7494     assert(Mask[i] >= 0 && "Only -1 is a valid negative mask element!");
7495
7496     // Based on the mod-Size value of this mask element determine where
7497     // a rotated vector would have started.
7498     int StartIdx = i - (Mask[i] % Size);
7499     if (StartIdx == 0)
7500       // The identity rotation isn't interesting, stop.
7501       return SDValue();
7502
7503     // If we found the tail of a vector the rotation must be the missing
7504     // front. If we found the head of a vector, it must be how much of the head.
7505     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
7506
7507     if (Rotation == 0)
7508       Rotation = CandidateRotation;
7509     else if (Rotation != CandidateRotation)
7510       // The rotations don't match, so we can't match this mask.
7511       return SDValue();
7512
7513     // Compute which value this mask is pointing at.
7514     SDValue MaskV = Mask[i] < Size ? V1 : V2;
7515
7516     // Compute which of the two target values this index should be assigned to.
7517     // This reflects whether the high elements are remaining or the low elements
7518     // are remaining.
7519     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7520
7521     // Either set up this value if we've not encountered it before, or check
7522     // that it remains consistent.
7523     if (!TargetV)
7524       TargetV = MaskV;
7525     else if (TargetV != MaskV)
7526       // This may be a rotation, but it pulls from the inputs in some
7527       // unsupported interleaving.
7528       return SDValue();
7529   }
7530
7531   // Check that we successfully analyzed the mask, and normalize the results.
7532   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7533   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7534   if (!Lo)
7535     Lo = Hi;
7536   else if (!Hi)
7537     Hi = Lo;
7538
7539   // Cast the inputs to v16i8 to match PALIGNR.
7540   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Lo);
7541   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Hi);
7542
7543   assert(VT.getSizeInBits() == 128 &&
7544          "Rotate-based lowering only supports 128-bit lowering!");
7545   assert(Mask.size() <= 16 &&
7546          "Can shuffle at most 16 bytes in a 128-bit vector!");
7547   // The actual rotate instruction rotates bytes, so we need to scale the
7548   // rotation based on how many bytes are in the vector.
7549   int Scale = 16 / Mask.size();
7550
7551   return DAG.getNode(ISD::BITCAST, DL, VT,
7552                      DAG.getNode(X86ISD::PALIGNR, DL, MVT::v16i8, Hi, Lo,
7553                                  DAG.getConstant(Rotation * Scale, MVT::i8)));
7554 }
7555
7556 /// \brief Compute whether each element of a shuffle is zeroable.
7557 ///
7558 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7559 /// Either it is an undef element in the shuffle mask, the element of the input
7560 /// referenced is undef, or the element of the input referenced is known to be
7561 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7562 /// as many lanes with this technique as possible to simplify the remaining
7563 /// shuffle.
7564 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
7565                                                      SDValue V1, SDValue V2) {
7566   SmallBitVector Zeroable(Mask.size(), false);
7567
7568   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7569   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7570
7571   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7572     int M = Mask[i];
7573     // Handle the easy cases.
7574     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7575       Zeroable[i] = true;
7576       continue;
7577     }
7578
7579     // If this is an index into a build_vector node, dig out the input value and
7580     // use it.
7581     SDValue V = M < Size ? V1 : V2;
7582     if (V.getOpcode() != ISD::BUILD_VECTOR)
7583       continue;
7584
7585     SDValue Input = V.getOperand(M % Size);
7586     // The UNDEF opcode check really should be dead code here, but not quite
7587     // worth asserting on (it isn't invalid, just unexpected).
7588     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
7589       Zeroable[i] = true;
7590   }
7591
7592   return Zeroable;
7593 }
7594
7595 /// \brief Lower a vector shuffle as a zero or any extension.
7596 ///
7597 /// Given a specific number of elements, element bit width, and extension
7598 /// stride, produce either a zero or any extension based on the available
7599 /// features of the subtarget.
7600 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7601     SDLoc DL, MVT VT, int NumElements, int Scale, bool AnyExt, SDValue InputV,
7602     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7603   assert(Scale > 1 && "Need a scale to extend.");
7604   int EltBits = VT.getSizeInBits() / NumElements;
7605   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7606          "Only 8, 16, and 32 bit elements can be extended.");
7607   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7608
7609   // Found a valid zext mask! Try various lowering strategies based on the
7610   // input type and available ISA extensions.
7611   if (Subtarget->hasSSE41()) {
7612     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7613     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7614                                  NumElements / Scale);
7615     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7616     return DAG.getNode(ISD::BITCAST, DL, VT,
7617                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7618   }
7619
7620   // For any extends we can cheat for larger element sizes and use shuffle
7621   // instructions that can fold with a load and/or copy.
7622   if (AnyExt && EltBits == 32) {
7623     int PSHUFDMask[4] = {0, -1, 1, -1};
7624     return DAG.getNode(
7625         ISD::BITCAST, DL, VT,
7626         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7627                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7628                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7629   }
7630   if (AnyExt && EltBits == 16 && Scale > 2) {
7631     int PSHUFDMask[4] = {0, -1, 0, -1};
7632     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7633                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7634                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
7635     int PSHUFHWMask[4] = {1, -1, -1, -1};
7636     return DAG.getNode(
7637         ISD::BITCAST, DL, VT,
7638         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7639                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
7640                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
7641   }
7642
7643   // If this would require more than 2 unpack instructions to expand, use
7644   // pshufb when available. We can only use more than 2 unpack instructions
7645   // when zero extending i8 elements which also makes it easier to use pshufb.
7646   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7647     assert(NumElements == 16 && "Unexpected byte vector width!");
7648     SDValue PSHUFBMask[16];
7649     for (int i = 0; i < 16; ++i)
7650       PSHUFBMask[i] =
7651           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
7652     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
7653     return DAG.getNode(ISD::BITCAST, DL, VT,
7654                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7655                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
7656                                                MVT::v16i8, PSHUFBMask)));
7657   }
7658
7659   // Otherwise emit a sequence of unpacks.
7660   do {
7661     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7662     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7663                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7664     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7665     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7666     Scale /= 2;
7667     EltBits *= 2;
7668     NumElements /= 2;
7669   } while (Scale > 1);
7670   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
7671 }
7672
7673 /// \brief Try to lower a vector shuffle as a zero extension on any micrarch.
7674 ///
7675 /// This routine will try to do everything in its power to cleverly lower
7676 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7677 /// check for the profitability of this lowering,  it tries to aggressively
7678 /// match this pattern. It will use all of the micro-architectural details it
7679 /// can to emit an efficient lowering. It handles both blends with all-zero
7680 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7681 /// masking out later).
7682 ///
7683 /// The reason we have dedicated lowering for zext-style shuffles is that they
7684 /// are both incredibly common and often quite performance sensitive.
7685 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7686     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7687     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7688   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7689
7690   int Bits = VT.getSizeInBits();
7691   int NumElements = Mask.size();
7692
7693   // Define a helper function to check a particular ext-scale and lower to it if
7694   // valid.
7695   auto Lower = [&](int Scale) -> SDValue {
7696     SDValue InputV;
7697     bool AnyExt = true;
7698     for (int i = 0; i < NumElements; ++i) {
7699       if (Mask[i] == -1)
7700         continue; // Valid anywhere but doesn't tell us anything.
7701       if (i % Scale != 0) {
7702         // Each of the extend elements needs to be zeroable.
7703         if (!Zeroable[i])
7704           return SDValue();
7705
7706         // We no lorger are in the anyext case.
7707         AnyExt = false;
7708         continue;
7709       }
7710
7711       // Each of the base elements needs to be consecutive indices into the
7712       // same input vector.
7713       SDValue V = Mask[i] < NumElements ? V1 : V2;
7714       if (!InputV)
7715         InputV = V;
7716       else if (InputV != V)
7717         return SDValue(); // Flip-flopping inputs.
7718
7719       if (Mask[i] % NumElements != i / Scale)
7720         return SDValue(); // Non-consecutive strided elemenst.
7721     }
7722
7723     // If we fail to find an input, we have a zero-shuffle which should always
7724     // have already been handled.
7725     // FIXME: Maybe handle this here in case during blending we end up with one?
7726     if (!InputV)
7727       return SDValue();
7728
7729     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7730         DL, VT, NumElements, Scale, AnyExt, InputV, Subtarget, DAG);
7731   };
7732
7733   // The widest scale possible for extending is to a 64-bit integer.
7734   assert(Bits % 64 == 0 &&
7735          "The number of bits in a vector must be divisible by 64 on x86!");
7736   int NumExtElements = Bits / 64;
7737
7738   // Each iteration, try extending the elements half as much, but into twice as
7739   // many elements.
7740   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7741     assert(NumElements % NumExtElements == 0 &&
7742            "The input vector size must be divisble by the extended size.");
7743     if (SDValue V = Lower(NumElements / NumExtElements))
7744       return V;
7745   }
7746
7747   // No viable ext lowering found.
7748   return SDValue();
7749 }
7750
7751 /// \brief Try to get a scalar value for a specific element of a vector.
7752 ///
7753 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7754 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7755                                               SelectionDAG &DAG) {
7756   MVT VT = V.getSimpleValueType();
7757   MVT EltVT = VT.getVectorElementType();
7758   while (V.getOpcode() == ISD::BITCAST)
7759     V = V.getOperand(0);
7760   // If the bitcasts shift the element size, we can't extract an equivalent
7761   // element from it.
7762   MVT NewVT = V.getSimpleValueType();
7763   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7764     return SDValue();
7765
7766   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7767       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
7768     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
7769
7770   return SDValue();
7771 }
7772
7773 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7774 ///
7775 /// This is particularly important because the set of instructions varies
7776 /// significantly based on whether the operand is a load or not.
7777 static bool isShuffleFoldableLoad(SDValue V) {
7778   while (V.getOpcode() == ISD::BITCAST)
7779     V = V.getOperand(0);
7780
7781   return ISD::isNON_EXTLoad(V.getNode());
7782 }
7783
7784 /// \brief Try to lower insertion of a single element into a zero vector.
7785 ///
7786 /// This is a common pattern that we have especially efficient patterns to lower
7787 /// across all subtarget feature sets.
7788 static SDValue lowerVectorShuffleAsElementInsertion(
7789     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7790     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7791   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7792   MVT ExtVT = VT;
7793   MVT EltVT = VT.getVectorElementType();
7794
7795   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7796                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7797                 Mask.begin();
7798   bool IsV1Zeroable = true;
7799   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7800     if (i != V2Index && !Zeroable[i]) {
7801       IsV1Zeroable = false;
7802       break;
7803     }
7804
7805   // Check for a single input from a SCALAR_TO_VECTOR node.
7806   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7807   // all the smarts here sunk into that routine. However, the current
7808   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7809   // vector shuffle lowering is dead.
7810   if (SDValue V2S = getScalarValueForVectorElement(
7811           V2, Mask[V2Index] - Mask.size(), DAG)) {
7812     // We need to zext the scalar if it is smaller than an i32.
7813     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7814     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7815       // Using zext to expand a narrow element won't work for non-zero
7816       // insertions.
7817       if (!IsV1Zeroable)
7818         return SDValue();
7819
7820       // Zero-extend directly to i32.
7821       ExtVT = MVT::v4i32;
7822       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7823     }
7824     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7825   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7826              EltVT == MVT::i16) {
7827     // Either not inserting from the low element of the input or the input
7828     // element size is too small to use VZEXT_MOVL to clear the high bits.
7829     return SDValue();
7830   }
7831
7832   if (!IsV1Zeroable) {
7833     // If V1 can't be treated as a zero vector we have fewer options to lower
7834     // this. We can't support integer vectors or non-zero targets cheaply, and
7835     // the V1 elements can't be permuted in any way.
7836     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7837     if (!VT.isFloatingPoint() || V2Index != 0)
7838       return SDValue();
7839     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7840     V1Mask[V2Index] = -1;
7841     if (!isNoopShuffleMask(V1Mask))
7842       return SDValue();
7843     // This is essentially a special case blend operation, but if we have
7844     // general purpose blend operations, they are always faster. Bail and let
7845     // the rest of the lowering handle these as blends.
7846     if (Subtarget->hasSSE41())
7847       return SDValue();
7848
7849     // Otherwise, use MOVSD or MOVSS.
7850     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7851            "Only two types of floating point element types to handle!");
7852     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7853                        ExtVT, V1, V2);
7854   }
7855
7856   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7857   if (ExtVT != VT)
7858     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7859
7860   if (V2Index != 0) {
7861     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7862     // the desired position. Otherwise it is more efficient to do a vector
7863     // shift left. We know that we can do a vector shift left because all
7864     // the inputs are zero.
7865     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7866       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7867       V2Shuffle[V2Index] = 0;
7868       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7869     } else {
7870       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7871       V2 = DAG.getNode(
7872           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7873           DAG.getConstant(
7874               V2Index * EltVT.getSizeInBits(),
7875               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7876       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7877     }
7878   }
7879   return V2;
7880 }
7881
7882 /// \brief Try to lower broadcast of a single element.
7883 ///
7884 /// For convenience, this code also bundles all of the subtarget feature set
7885 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7886 /// a convenient way to factor it out.
7887 static SDValue lowerVectorShuffleAsBroadcast(MVT VT, SDLoc DL, SDValue V,
7888                                              ArrayRef<int> Mask,
7889                                              const X86Subtarget *Subtarget,
7890                                              SelectionDAG &DAG) {
7891   if (!Subtarget->hasAVX())
7892     return SDValue();
7893   if (VT.isInteger() && !Subtarget->hasAVX2())
7894     return SDValue();
7895
7896   // Check that the mask is a broadcast.
7897   int BroadcastIdx = -1;
7898   for (int M : Mask)
7899     if (M >= 0 && BroadcastIdx == -1)
7900       BroadcastIdx = M;
7901     else if (M >= 0 && M != BroadcastIdx)
7902       return SDValue();
7903
7904   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7905                                             "a sorted mask where the broadcast "
7906                                             "comes from V1.");
7907
7908   // Go up the chain of (vector) values to try and find a scalar load that
7909   // we can combine with the broadcast.
7910   for (;;) {
7911     switch (V.getOpcode()) {
7912     case ISD::CONCAT_VECTORS: {
7913       int OperandSize = Mask.size() / V.getNumOperands();
7914       V = V.getOperand(BroadcastIdx / OperandSize);
7915       BroadcastIdx %= OperandSize;
7916       continue;
7917     }
7918
7919     case ISD::INSERT_SUBVECTOR: {
7920       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7921       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7922       if (!ConstantIdx)
7923         break;
7924
7925       int BeginIdx = (int)ConstantIdx->getZExtValue();
7926       int EndIdx =
7927           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7928       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7929         BroadcastIdx -= BeginIdx;
7930         V = VInner;
7931       } else {
7932         V = VOuter;
7933       }
7934       continue;
7935     }
7936     }
7937     break;
7938   }
7939
7940   // Check if this is a broadcast of a scalar. We special case lowering
7941   // for scalars so that we can more effectively fold with loads.
7942   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7943       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7944     V = V.getOperand(BroadcastIdx);
7945
7946     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
7947     // AVX2.
7948     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7949       return SDValue();
7950   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7951     // We can't broadcast from a vector register w/o AVX2, and we can only
7952     // broadcast from the zero-element of a vector register.
7953     return SDValue();
7954   }
7955
7956   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7957 }
7958
7959 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7960 ///
7961 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7962 /// support for floating point shuffles but not integer shuffles. These
7963 /// instructions will incur a domain crossing penalty on some chips though so
7964 /// it is better to avoid lowering through this for integer vectors where
7965 /// possible.
7966 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7967                                        const X86Subtarget *Subtarget,
7968                                        SelectionDAG &DAG) {
7969   SDLoc DL(Op);
7970   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7971   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7972   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7973   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7974   ArrayRef<int> Mask = SVOp->getMask();
7975   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7976
7977   if (isSingleInputShuffleMask(Mask)) {
7978     // Straight shuffle of a single input vector. Simulate this by using the
7979     // single input as both of the "inputs" to this instruction..
7980     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7981
7982     if (Subtarget->hasAVX()) {
7983       // If we have AVX, we can use VPERMILPS which will allow folding a load
7984       // into the shuffle.
7985       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7986                          DAG.getConstant(SHUFPDMask, MVT::i8));
7987     }
7988
7989     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7990                        DAG.getConstant(SHUFPDMask, MVT::i8));
7991   }
7992   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7993   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7994
7995   // Use dedicated unpack instructions for masks that match their pattern.
7996   if (isShuffleEquivalent(Mask, 0, 2))
7997     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7998   if (isShuffleEquivalent(Mask, 1, 3))
7999     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8000
8001   // If we have a single input, insert that into V1 if we can do so cheaply.
8002   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8003     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8004             MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
8005       return Insertion;
8006     // Try inverting the insertion since for v2 masks it is easy to do and we
8007     // can't reliably sort the mask one way or the other.
8008     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8009                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8010     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8011             MVT::v2f64, DL, V2, V1, InverseMask, Subtarget, DAG))
8012       return Insertion;
8013   }
8014
8015   // Try to use one of the special instruction patterns to handle two common
8016   // blend patterns if a zero-blend above didn't work.
8017   if (isShuffleEquivalent(Mask, 0, 3) || isShuffleEquivalent(Mask, 1, 3))
8018     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8019       // We can either use a special instruction to load over the low double or
8020       // to move just the low double.
8021       return DAG.getNode(
8022           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8023           DL, MVT::v2f64, V2,
8024           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8025
8026   if (Subtarget->hasSSE41())
8027     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8028                                                   Subtarget, DAG))
8029       return Blend;
8030
8031   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8032   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
8033                      DAG.getConstant(SHUFPDMask, MVT::i8));
8034 }
8035
8036 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8037 ///
8038 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8039 /// the integer unit to minimize domain crossing penalties. However, for blends
8040 /// it falls back to the floating point shuffle operation with appropriate bit
8041 /// casting.
8042 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8043                                        const X86Subtarget *Subtarget,
8044                                        SelectionDAG &DAG) {
8045   SDLoc DL(Op);
8046   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8047   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8048   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8049   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8050   ArrayRef<int> Mask = SVOp->getMask();
8051   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8052
8053   if (isSingleInputShuffleMask(Mask)) {
8054     // Check for being able to broadcast a single element.
8055     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v2i64, DL, V1,
8056                                                           Mask, Subtarget, DAG))
8057       return Broadcast;
8058
8059     // Straight shuffle of a single input vector. For everything from SSE2
8060     // onward this has a single fast instruction with no scary immediates.
8061     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8062     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
8063     int WidenedMask[4] = {
8064         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8065         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8066     return DAG.getNode(
8067         ISD::BITCAST, DL, MVT::v2i64,
8068         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
8069                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
8070   }
8071
8072   // If we have a single input from V2 insert that into V1 if we can do so
8073   // cheaply.
8074   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8075     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8076             MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
8077       return Insertion;
8078     // Try inverting the insertion since for v2 masks it is easy to do and we
8079     // can't reliably sort the mask one way or the other.
8080     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8081                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8082     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8083             MVT::v2i64, DL, V2, V1, InverseMask, Subtarget, DAG))
8084       return Insertion;
8085   }
8086
8087   // Use dedicated unpack instructions for masks that match their pattern.
8088   if (isShuffleEquivalent(Mask, 0, 2))
8089     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8090   if (isShuffleEquivalent(Mask, 1, 3))
8091     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8092
8093   if (Subtarget->hasSSE41())
8094     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8095                                                   Subtarget, DAG))
8096       return Blend;
8097
8098   // Try to use rotation instructions if available.
8099   if (Subtarget->hasSSSE3())
8100     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8101             DL, MVT::v2i64, V1, V2, Mask, DAG))
8102       return Rotate;
8103
8104   // We implement this with SHUFPD which is pretty lame because it will likely
8105   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8106   // However, all the alternatives are still more cycles and newer chips don't
8107   // have this problem. It would be really nice if x86 had better shuffles here.
8108   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
8109   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
8110   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
8111                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8112 }
8113
8114 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8115 ///
8116 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8117 /// It makes no assumptions about whether this is the *best* lowering, it simply
8118 /// uses it.
8119 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8120                                             ArrayRef<int> Mask, SDValue V1,
8121                                             SDValue V2, SelectionDAG &DAG) {
8122   SDValue LowV = V1, HighV = V2;
8123   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8124
8125   int NumV2Elements =
8126       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8127
8128   if (NumV2Elements == 1) {
8129     int V2Index =
8130         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8131         Mask.begin();
8132
8133     // Compute the index adjacent to V2Index and in the same half by toggling
8134     // the low bit.
8135     int V2AdjIndex = V2Index ^ 1;
8136
8137     if (Mask[V2AdjIndex] == -1) {
8138       // Handles all the cases where we have a single V2 element and an undef.
8139       // This will only ever happen in the high lanes because we commute the
8140       // vector otherwise.
8141       if (V2Index < 2)
8142         std::swap(LowV, HighV);
8143       NewMask[V2Index] -= 4;
8144     } else {
8145       // Handle the case where the V2 element ends up adjacent to a V1 element.
8146       // To make this work, blend them together as the first step.
8147       int V1Index = V2AdjIndex;
8148       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8149       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8150                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8151
8152       // Now proceed to reconstruct the final blend as we have the necessary
8153       // high or low half formed.
8154       if (V2Index < 2) {
8155         LowV = V2;
8156         HighV = V1;
8157       } else {
8158         HighV = V2;
8159       }
8160       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8161       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8162     }
8163   } else if (NumV2Elements == 2) {
8164     if (Mask[0] < 4 && Mask[1] < 4) {
8165       // Handle the easy case where we have V1 in the low lanes and V2 in the
8166       // high lanes.
8167       NewMask[2] -= 4;
8168       NewMask[3] -= 4;
8169     } else if (Mask[2] < 4 && Mask[3] < 4) {
8170       // We also handle the reversed case because this utility may get called
8171       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8172       // arrange things in the right direction.
8173       NewMask[0] -= 4;
8174       NewMask[1] -= 4;
8175       HighV = V1;
8176       LowV = V2;
8177     } else {
8178       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8179       // trying to place elements directly, just blend them and set up the final
8180       // shuffle to place them.
8181
8182       // The first two blend mask elements are for V1, the second two are for
8183       // V2.
8184       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8185                           Mask[2] < 4 ? Mask[2] : Mask[3],
8186                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8187                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8188       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8189                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8190
8191       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8192       // a blend.
8193       LowV = HighV = V1;
8194       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8195       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8196       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8197       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8198     }
8199   }
8200   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8201                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
8202 }
8203
8204 /// \brief Lower 4-lane 32-bit floating point shuffles.
8205 ///
8206 /// Uses instructions exclusively from the floating point unit to minimize
8207 /// domain crossing penalties, as these are sufficient to implement all v4f32
8208 /// shuffles.
8209 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8210                                        const X86Subtarget *Subtarget,
8211                                        SelectionDAG &DAG) {
8212   SDLoc DL(Op);
8213   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8214   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8215   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8216   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8217   ArrayRef<int> Mask = SVOp->getMask();
8218   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8219
8220   int NumV2Elements =
8221       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8222
8223   if (NumV2Elements == 0) {
8224     // Check for being able to broadcast a single element.
8225     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f32, DL, V1,
8226                                                           Mask, Subtarget, DAG))
8227       return Broadcast;
8228
8229     if (Subtarget->hasAVX()) {
8230       // If we have AVX, we can use VPERMILPS which will allow folding a load
8231       // into the shuffle.
8232       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8233                          getV4X86ShuffleImm8ForMask(Mask, DAG));
8234     }
8235
8236     // Otherwise, use a straight shuffle of a single input vector. We pass the
8237     // input vector to both operands to simulate this with a SHUFPS.
8238     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8239                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8240   }
8241
8242   // Use dedicated unpack instructions for masks that match their pattern.
8243   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8244     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8245   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8246     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8247
8248   // There are special ways we can lower some single-element blends. However, we
8249   // have custom ways we can lower more complex single-element blends below that
8250   // we defer to if both this and BLENDPS fail to match, so restrict this to
8251   // when the V2 input is targeting element 0 of the mask -- that is the fast
8252   // case here.
8253   if (NumV2Elements == 1 && Mask[0] >= 4)
8254     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
8255                                                          Mask, Subtarget, DAG))
8256       return V;
8257
8258   if (Subtarget->hasSSE41())
8259     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8260                                                   Subtarget, DAG))
8261       return Blend;
8262
8263   // Check for whether we can use INSERTPS to perform the blend. We only use
8264   // INSERTPS when the V1 elements are already in the correct locations
8265   // because otherwise we can just always use two SHUFPS instructions which
8266   // are much smaller to encode than a SHUFPS and an INSERTPS.
8267   if (NumV2Elements == 1 && Subtarget->hasSSE41()) {
8268     int V2Index =
8269         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8270         Mask.begin();
8271
8272     // When using INSERTPS we can zero any lane of the destination. Collect
8273     // the zero inputs into a mask and drop them from the lanes of V1 which
8274     // actually need to be present as inputs to the INSERTPS.
8275     SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8276
8277     // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
8278     bool InsertNeedsShuffle = false;
8279     unsigned ZMask = 0;
8280     for (int i = 0; i < 4; ++i)
8281       if (i != V2Index) {
8282         if (Zeroable[i]) {
8283           ZMask |= 1 << i;
8284         } else if (Mask[i] != i) {
8285           InsertNeedsShuffle = true;
8286           break;
8287         }
8288       }
8289
8290     // We don't want to use INSERTPS or other insertion techniques if it will
8291     // require shuffling anyways.
8292     if (!InsertNeedsShuffle) {
8293       // If all of V1 is zeroable, replace it with undef.
8294       if ((ZMask | 1 << V2Index) == 0xF)
8295         V1 = DAG.getUNDEF(MVT::v4f32);
8296
8297       unsigned InsertPSMask = (Mask[V2Index] - 4) << 6 | V2Index << 4 | ZMask;
8298       assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8299
8300       // Insert the V2 element into the desired position.
8301       return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8302                          DAG.getConstant(InsertPSMask, MVT::i8));
8303     }
8304   }
8305
8306   // Otherwise fall back to a SHUFPS lowering strategy.
8307   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8308 }
8309
8310 /// \brief Lower 4-lane i32 vector shuffles.
8311 ///
8312 /// We try to handle these with integer-domain shuffles where we can, but for
8313 /// blends we use the floating point domain blend instructions.
8314 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8315                                        const X86Subtarget *Subtarget,
8316                                        SelectionDAG &DAG) {
8317   SDLoc DL(Op);
8318   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8319   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8320   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8321   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8322   ArrayRef<int> Mask = SVOp->getMask();
8323   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8324
8325   // Whenever we can lower this as a zext, that instruction is strictly faster
8326   // than any alternative. It also allows us to fold memory operands into the
8327   // shuffle in many cases.
8328   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8329                                                          Mask, Subtarget, DAG))
8330     return ZExt;
8331
8332   int NumV2Elements =
8333       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8334
8335   if (NumV2Elements == 0) {
8336     // Check for being able to broadcast a single element.
8337     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i32, DL, V1,
8338                                                           Mask, Subtarget, DAG))
8339       return Broadcast;
8340
8341     // Straight shuffle of a single input vector. For everything from SSE2
8342     // onward this has a single fast instruction with no scary immediates.
8343     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8344     // but we aren't actually going to use the UNPCK instruction because doing
8345     // so prevents folding a load into this instruction or making a copy.
8346     const int UnpackLoMask[] = {0, 0, 1, 1};
8347     const int UnpackHiMask[] = {2, 2, 3, 3};
8348     if (isShuffleEquivalent(Mask, 0, 0, 1, 1))
8349       Mask = UnpackLoMask;
8350     else if (isShuffleEquivalent(Mask, 2, 2, 3, 3))
8351       Mask = UnpackHiMask;
8352
8353     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8354                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8355   }
8356
8357   // There are special ways we can lower some single-element blends.
8358   if (NumV2Elements == 1)
8359     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
8360                                                          Mask, Subtarget, DAG))
8361       return V;
8362
8363   // Use dedicated unpack instructions for masks that match their pattern.
8364   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8365     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8366   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8367     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8368
8369   if (Subtarget->hasSSE41())
8370     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8371                                                   Subtarget, DAG))
8372       return Blend;
8373
8374   // Try to use rotation instructions if available.
8375   if (Subtarget->hasSSSE3())
8376     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8377             DL, MVT::v4i32, V1, V2, Mask, DAG))
8378       return Rotate;
8379
8380   // We implement this with SHUFPS because it can blend from two vectors.
8381   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8382   // up the inputs, bypassing domain shift penalties that we would encur if we
8383   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8384   // relevant.
8385   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
8386                      DAG.getVectorShuffle(
8387                          MVT::v4f32, DL,
8388                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
8389                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
8390 }
8391
8392 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8393 /// shuffle lowering, and the most complex part.
8394 ///
8395 /// The lowering strategy is to try to form pairs of input lanes which are
8396 /// targeted at the same half of the final vector, and then use a dword shuffle
8397 /// to place them onto the right half, and finally unpack the paired lanes into
8398 /// their final position.
8399 ///
8400 /// The exact breakdown of how to form these dword pairs and align them on the
8401 /// correct sides is really tricky. See the comments within the function for
8402 /// more of the details.
8403 static SDValue lowerV8I16SingleInputVectorShuffle(
8404     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
8405     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8406   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8407   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8408   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8409
8410   SmallVector<int, 4> LoInputs;
8411   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8412                [](int M) { return M >= 0; });
8413   std::sort(LoInputs.begin(), LoInputs.end());
8414   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8415   SmallVector<int, 4> HiInputs;
8416   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8417                [](int M) { return M >= 0; });
8418   std::sort(HiInputs.begin(), HiInputs.end());
8419   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8420   int NumLToL =
8421       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8422   int NumHToL = LoInputs.size() - NumLToL;
8423   int NumLToH =
8424       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8425   int NumHToH = HiInputs.size() - NumLToH;
8426   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8427   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8428   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8429   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8430
8431   // Check for being able to broadcast a single element.
8432   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i16, DL, V,
8433                                                         Mask, Subtarget, DAG))
8434     return Broadcast;
8435
8436   // Use dedicated unpack instructions for masks that match their pattern.
8437   if (isShuffleEquivalent(Mask, 0, 0, 1, 1, 2, 2, 3, 3))
8438     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
8439   if (isShuffleEquivalent(Mask, 4, 4, 5, 5, 6, 6, 7, 7))
8440     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
8441
8442   // Try to use rotation instructions if available.
8443   if (Subtarget->hasSSSE3())
8444     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8445             DL, MVT::v8i16, V, V, Mask, DAG))
8446       return Rotate;
8447
8448   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8449   // such inputs we can swap two of the dwords across the half mark and end up
8450   // with <=2 inputs to each half in each half. Once there, we can fall through
8451   // to the generic code below. For example:
8452   //
8453   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8454   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8455   //
8456   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8457   // and an existing 2-into-2 on the other half. In this case we may have to
8458   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8459   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8460   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8461   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8462   // half than the one we target for fixing) will be fixed when we re-enter this
8463   // path. We will also combine away any sequence of PSHUFD instructions that
8464   // result into a single instruction. Here is an example of the tricky case:
8465   //
8466   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8467   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8468   //
8469   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8470   //
8471   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8472   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8473   //
8474   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8475   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8476   //
8477   // The result is fine to be handled by the generic logic.
8478   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8479                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8480                           int AOffset, int BOffset) {
8481     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8482            "Must call this with A having 3 or 1 inputs from the A half.");
8483     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8484            "Must call this with B having 1 or 3 inputs from the B half.");
8485     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8486            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8487
8488     // Compute the index of dword with only one word among the three inputs in
8489     // a half by taking the sum of the half with three inputs and subtracting
8490     // the sum of the actual three inputs. The difference is the remaining
8491     // slot.
8492     int ADWord, BDWord;
8493     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8494     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8495     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8496     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8497     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8498     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8499     int TripleNonInputIdx =
8500         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8501     TripleDWord = TripleNonInputIdx / 2;
8502
8503     // We use xor with one to compute the adjacent DWord to whichever one the
8504     // OneInput is in.
8505     OneInputDWord = (OneInput / 2) ^ 1;
8506
8507     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8508     // and BToA inputs. If there is also such a problem with the BToB and AToB
8509     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8510     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8511     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8512     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8513       // Compute how many inputs will be flipped by swapping these DWords. We
8514       // need
8515       // to balance this to ensure we don't form a 3-1 shuffle in the other
8516       // half.
8517       int NumFlippedAToBInputs =
8518           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8519           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8520       int NumFlippedBToBInputs =
8521           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8522           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8523       if ((NumFlippedAToBInputs == 1 &&
8524            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8525           (NumFlippedBToBInputs == 1 &&
8526            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8527         // We choose whether to fix the A half or B half based on whether that
8528         // half has zero flipped inputs. At zero, we may not be able to fix it
8529         // with that half. We also bias towards fixing the B half because that
8530         // will more commonly be the high half, and we have to bias one way.
8531         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8532                                                        ArrayRef<int> Inputs) {
8533           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8534           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8535                                          PinnedIdx ^ 1) != Inputs.end();
8536           // Determine whether the free index is in the flipped dword or the
8537           // unflipped dword based on where the pinned index is. We use this bit
8538           // in an xor to conditionally select the adjacent dword.
8539           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8540           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8541                                              FixFreeIdx) != Inputs.end();
8542           if (IsFixIdxInput == IsFixFreeIdxInput)
8543             FixFreeIdx += 1;
8544           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8545                                         FixFreeIdx) != Inputs.end();
8546           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8547                  "We need to be changing the number of flipped inputs!");
8548           int PSHUFHalfMask[] = {0, 1, 2, 3};
8549           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8550           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8551                           MVT::v8i16, V,
8552                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
8553
8554           for (int &M : Mask)
8555             if (M != -1 && M == FixIdx)
8556               M = FixFreeIdx;
8557             else if (M != -1 && M == FixFreeIdx)
8558               M = FixIdx;
8559         };
8560         if (NumFlippedBToBInputs != 0) {
8561           int BPinnedIdx =
8562               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8563           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8564         } else {
8565           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8566           int APinnedIdx =
8567               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8568           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8569         }
8570       }
8571     }
8572
8573     int PSHUFDMask[] = {0, 1, 2, 3};
8574     PSHUFDMask[ADWord] = BDWord;
8575     PSHUFDMask[BDWord] = ADWord;
8576     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8577                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8578                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8579                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8580
8581     // Adjust the mask to match the new locations of A and B.
8582     for (int &M : Mask)
8583       if (M != -1 && M/2 == ADWord)
8584         M = 2 * BDWord + M % 2;
8585       else if (M != -1 && M/2 == BDWord)
8586         M = 2 * ADWord + M % 2;
8587
8588     // Recurse back into this routine to re-compute state now that this isn't
8589     // a 3 and 1 problem.
8590     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8591                                 Mask);
8592   };
8593   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8594     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8595   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8596     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8597
8598   // At this point there are at most two inputs to the low and high halves from
8599   // each half. That means the inputs can always be grouped into dwords and
8600   // those dwords can then be moved to the correct half with a dword shuffle.
8601   // We use at most one low and one high word shuffle to collect these paired
8602   // inputs into dwords, and finally a dword shuffle to place them.
8603   int PSHUFLMask[4] = {-1, -1, -1, -1};
8604   int PSHUFHMask[4] = {-1, -1, -1, -1};
8605   int PSHUFDMask[4] = {-1, -1, -1, -1};
8606
8607   // First fix the masks for all the inputs that are staying in their
8608   // original halves. This will then dictate the targets of the cross-half
8609   // shuffles.
8610   auto fixInPlaceInputs =
8611       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8612                     MutableArrayRef<int> SourceHalfMask,
8613                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8614     if (InPlaceInputs.empty())
8615       return;
8616     if (InPlaceInputs.size() == 1) {
8617       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8618           InPlaceInputs[0] - HalfOffset;
8619       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8620       return;
8621     }
8622     if (IncomingInputs.empty()) {
8623       // Just fix all of the in place inputs.
8624       for (int Input : InPlaceInputs) {
8625         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8626         PSHUFDMask[Input / 2] = Input / 2;
8627       }
8628       return;
8629     }
8630
8631     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8632     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8633         InPlaceInputs[0] - HalfOffset;
8634     // Put the second input next to the first so that they are packed into
8635     // a dword. We find the adjacent index by toggling the low bit.
8636     int AdjIndex = InPlaceInputs[0] ^ 1;
8637     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8638     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8639     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8640   };
8641   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8642   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8643
8644   // Now gather the cross-half inputs and place them into a free dword of
8645   // their target half.
8646   // FIXME: This operation could almost certainly be simplified dramatically to
8647   // look more like the 3-1 fixing operation.
8648   auto moveInputsToRightHalf = [&PSHUFDMask](
8649       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8650       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8651       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8652       int DestOffset) {
8653     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8654       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8655     };
8656     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8657                                                int Word) {
8658       int LowWord = Word & ~1;
8659       int HighWord = Word | 1;
8660       return isWordClobbered(SourceHalfMask, LowWord) ||
8661              isWordClobbered(SourceHalfMask, HighWord);
8662     };
8663
8664     if (IncomingInputs.empty())
8665       return;
8666
8667     if (ExistingInputs.empty()) {
8668       // Map any dwords with inputs from them into the right half.
8669       for (int Input : IncomingInputs) {
8670         // If the source half mask maps over the inputs, turn those into
8671         // swaps and use the swapped lane.
8672         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8673           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8674             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8675                 Input - SourceOffset;
8676             // We have to swap the uses in our half mask in one sweep.
8677             for (int &M : HalfMask)
8678               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8679                 M = Input;
8680               else if (M == Input)
8681                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8682           } else {
8683             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8684                        Input - SourceOffset &&
8685                    "Previous placement doesn't match!");
8686           }
8687           // Note that this correctly re-maps both when we do a swap and when
8688           // we observe the other side of the swap above. We rely on that to
8689           // avoid swapping the members of the input list directly.
8690           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8691         }
8692
8693         // Map the input's dword into the correct half.
8694         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8695           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8696         else
8697           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8698                      Input / 2 &&
8699                  "Previous placement doesn't match!");
8700       }
8701
8702       // And just directly shift any other-half mask elements to be same-half
8703       // as we will have mirrored the dword containing the element into the
8704       // same position within that half.
8705       for (int &M : HalfMask)
8706         if (M >= SourceOffset && M < SourceOffset + 4) {
8707           M = M - SourceOffset + DestOffset;
8708           assert(M >= 0 && "This should never wrap below zero!");
8709         }
8710       return;
8711     }
8712
8713     // Ensure we have the input in a viable dword of its current half. This
8714     // is particularly tricky because the original position may be clobbered
8715     // by inputs being moved and *staying* in that half.
8716     if (IncomingInputs.size() == 1) {
8717       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8718         int InputFixed = std::find(std::begin(SourceHalfMask),
8719                                    std::end(SourceHalfMask), -1) -
8720                          std::begin(SourceHalfMask) + SourceOffset;
8721         SourceHalfMask[InputFixed - SourceOffset] =
8722             IncomingInputs[0] - SourceOffset;
8723         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8724                      InputFixed);
8725         IncomingInputs[0] = InputFixed;
8726       }
8727     } else if (IncomingInputs.size() == 2) {
8728       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8729           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8730         // We have two non-adjacent or clobbered inputs we need to extract from
8731         // the source half. To do this, we need to map them into some adjacent
8732         // dword slot in the source mask.
8733         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8734                               IncomingInputs[1] - SourceOffset};
8735
8736         // If there is a free slot in the source half mask adjacent to one of
8737         // the inputs, place the other input in it. We use (Index XOR 1) to
8738         // compute an adjacent index.
8739         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8740             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8741           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8742           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8743           InputsFixed[1] = InputsFixed[0] ^ 1;
8744         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8745                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8746           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8747           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8748           InputsFixed[0] = InputsFixed[1] ^ 1;
8749         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8750                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8751           // The two inputs are in the same DWord but it is clobbered and the
8752           // adjacent DWord isn't used at all. Move both inputs to the free
8753           // slot.
8754           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8755           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8756           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8757           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8758         } else {
8759           // The only way we hit this point is if there is no clobbering
8760           // (because there are no off-half inputs to this half) and there is no
8761           // free slot adjacent to one of the inputs. In this case, we have to
8762           // swap an input with a non-input.
8763           for (int i = 0; i < 4; ++i)
8764             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8765                    "We can't handle any clobbers here!");
8766           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8767                  "Cannot have adjacent inputs here!");
8768
8769           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8770           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8771
8772           // We also have to update the final source mask in this case because
8773           // it may need to undo the above swap.
8774           for (int &M : FinalSourceHalfMask)
8775             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8776               M = InputsFixed[1] + SourceOffset;
8777             else if (M == InputsFixed[1] + SourceOffset)
8778               M = (InputsFixed[0] ^ 1) + SourceOffset;
8779
8780           InputsFixed[1] = InputsFixed[0] ^ 1;
8781         }
8782
8783         // Point everything at the fixed inputs.
8784         for (int &M : HalfMask)
8785           if (M == IncomingInputs[0])
8786             M = InputsFixed[0] + SourceOffset;
8787           else if (M == IncomingInputs[1])
8788             M = InputsFixed[1] + SourceOffset;
8789
8790         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8791         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8792       }
8793     } else {
8794       llvm_unreachable("Unhandled input size!");
8795     }
8796
8797     // Now hoist the DWord down to the right half.
8798     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8799     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8800     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8801     for (int &M : HalfMask)
8802       for (int Input : IncomingInputs)
8803         if (M == Input)
8804           M = FreeDWord * 2 + Input % 2;
8805   };
8806   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8807                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8808   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8809                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8810
8811   // Now enact all the shuffles we've computed to move the inputs into their
8812   // target half.
8813   if (!isNoopShuffleMask(PSHUFLMask))
8814     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8815                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8816   if (!isNoopShuffleMask(PSHUFHMask))
8817     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8818                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8819   if (!isNoopShuffleMask(PSHUFDMask))
8820     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8821                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8822                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8823                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8824
8825   // At this point, each half should contain all its inputs, and we can then
8826   // just shuffle them into their final position.
8827   assert(std::count_if(LoMask.begin(), LoMask.end(),
8828                        [](int M) { return M >= 4; }) == 0 &&
8829          "Failed to lift all the high half inputs to the low mask!");
8830   assert(std::count_if(HiMask.begin(), HiMask.end(),
8831                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8832          "Failed to lift all the low half inputs to the high mask!");
8833
8834   // Do a half shuffle for the low mask.
8835   if (!isNoopShuffleMask(LoMask))
8836     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8837                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8838
8839   // Do a half shuffle with the high mask after shifting its values down.
8840   for (int &M : HiMask)
8841     if (M >= 0)
8842       M -= 4;
8843   if (!isNoopShuffleMask(HiMask))
8844     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8845                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8846
8847   return V;
8848 }
8849
8850 /// \brief Detect whether the mask pattern should be lowered through
8851 /// interleaving.
8852 ///
8853 /// This essentially tests whether viewing the mask as an interleaving of two
8854 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
8855 /// lowering it through interleaving is a significantly better strategy.
8856 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
8857   int NumEvenInputs[2] = {0, 0};
8858   int NumOddInputs[2] = {0, 0};
8859   int NumLoInputs[2] = {0, 0};
8860   int NumHiInputs[2] = {0, 0};
8861   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
8862     if (Mask[i] < 0)
8863       continue;
8864
8865     int InputIdx = Mask[i] >= Size;
8866
8867     if (i < Size / 2)
8868       ++NumLoInputs[InputIdx];
8869     else
8870       ++NumHiInputs[InputIdx];
8871
8872     if ((i % 2) == 0)
8873       ++NumEvenInputs[InputIdx];
8874     else
8875       ++NumOddInputs[InputIdx];
8876   }
8877
8878   // The minimum number of cross-input results for both the interleaved and
8879   // split cases. If interleaving results in fewer cross-input results, return
8880   // true.
8881   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
8882                                     NumEvenInputs[0] + NumOddInputs[1]);
8883   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
8884                               NumLoInputs[0] + NumHiInputs[1]);
8885   return InterleavedCrosses < SplitCrosses;
8886 }
8887
8888 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
8889 ///
8890 /// This strategy only works when the inputs from each vector fit into a single
8891 /// half of that vector, and generally there are not so many inputs as to leave
8892 /// the in-place shuffles required highly constrained (and thus expensive). It
8893 /// shifts all the inputs into a single side of both input vectors and then
8894 /// uses an unpack to interleave these inputs in a single vector. At that
8895 /// point, we will fall back on the generic single input shuffle lowering.
8896 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
8897                                                  SDValue V2,
8898                                                  MutableArrayRef<int> Mask,
8899                                                  const X86Subtarget *Subtarget,
8900                                                  SelectionDAG &DAG) {
8901   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8902   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8903   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
8904   for (int i = 0; i < 8; ++i)
8905     if (Mask[i] >= 0 && Mask[i] < 4)
8906       LoV1Inputs.push_back(i);
8907     else if (Mask[i] >= 4 && Mask[i] < 8)
8908       HiV1Inputs.push_back(i);
8909     else if (Mask[i] >= 8 && Mask[i] < 12)
8910       LoV2Inputs.push_back(i);
8911     else if (Mask[i] >= 12)
8912       HiV2Inputs.push_back(i);
8913
8914   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
8915   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
8916   (void)NumV1Inputs;
8917   (void)NumV2Inputs;
8918   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
8919   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
8920   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
8921
8922   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
8923                      HiV1Inputs.size() + HiV2Inputs.size();
8924
8925   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
8926                               ArrayRef<int> HiInputs, bool MoveToLo,
8927                               int MaskOffset) {
8928     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
8929     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
8930     if (BadInputs.empty())
8931       return V;
8932
8933     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8934     int MoveOffset = MoveToLo ? 0 : 4;
8935
8936     if (GoodInputs.empty()) {
8937       for (int BadInput : BadInputs) {
8938         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
8939         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
8940       }
8941     } else {
8942       if (GoodInputs.size() == 2) {
8943         // If the low inputs are spread across two dwords, pack them into
8944         // a single dword.
8945         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
8946         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
8947         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
8948         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
8949       } else {
8950         // Otherwise pin the good inputs.
8951         for (int GoodInput : GoodInputs)
8952           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
8953       }
8954
8955       if (BadInputs.size() == 2) {
8956         // If we have two bad inputs then there may be either one or two good
8957         // inputs fixed in place. Find a fixed input, and then find the *other*
8958         // two adjacent indices by using modular arithmetic.
8959         int GoodMaskIdx =
8960             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
8961                          [](int M) { return M >= 0; }) -
8962             std::begin(MoveMask);
8963         int MoveMaskIdx =
8964             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
8965         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
8966         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
8967         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8968         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
8969         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8970         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
8971       } else {
8972         assert(BadInputs.size() == 1 && "All sizes handled");
8973         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
8974                                     std::end(MoveMask), -1) -
8975                           std::begin(MoveMask);
8976         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8977         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8978       }
8979     }
8980
8981     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8982                                 MoveMask);
8983   };
8984   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
8985                         /*MaskOffset*/ 0);
8986   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
8987                         /*MaskOffset*/ 8);
8988
8989   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
8990   // cross-half traffic in the final shuffle.
8991
8992   // Munge the mask to be a single-input mask after the unpack merges the
8993   // results.
8994   for (int &M : Mask)
8995     if (M != -1)
8996       M = 2 * (M % 4) + (M / 8);
8997
8998   return DAG.getVectorShuffle(
8999       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
9000                                   DL, MVT::v8i16, V1, V2),
9001       DAG.getUNDEF(MVT::v8i16), Mask);
9002 }
9003
9004 /// \brief Generic lowering of 8-lane i16 shuffles.
9005 ///
9006 /// This handles both single-input shuffles and combined shuffle/blends with
9007 /// two inputs. The single input shuffles are immediately delegated to
9008 /// a dedicated lowering routine.
9009 ///
9010 /// The blends are lowered in one of three fundamental ways. If there are few
9011 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9012 /// of the input is significantly cheaper when lowered as an interleaving of
9013 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9014 /// halves of the inputs separately (making them have relatively few inputs)
9015 /// and then concatenate them.
9016 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9017                                        const X86Subtarget *Subtarget,
9018                                        SelectionDAG &DAG) {
9019   SDLoc DL(Op);
9020   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9021   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9022   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9023   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9024   ArrayRef<int> OrigMask = SVOp->getMask();
9025   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9026                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9027   MutableArrayRef<int> Mask(MaskStorage);
9028
9029   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9030
9031   // Whenever we can lower this as a zext, that instruction is strictly faster
9032   // than any alternative.
9033   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9034           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9035     return ZExt;
9036
9037   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9038   auto isV2 = [](int M) { return M >= 8; };
9039
9040   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
9041   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9042
9043   if (NumV2Inputs == 0)
9044     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
9045
9046   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
9047                             "to be V1-input shuffles.");
9048
9049   // There are special ways we can lower some single-element blends.
9050   if (NumV2Inputs == 1)
9051     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
9052                                                          Mask, Subtarget, DAG))
9053       return V;
9054
9055   // Use dedicated unpack instructions for masks that match their pattern.
9056   if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 2, 10, 3, 11))
9057     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9058   if (isShuffleEquivalent(Mask, 4, 12, 5, 13, 6, 14, 7, 15))
9059     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9060
9061   if (Subtarget->hasSSE41())
9062     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9063                                                   Subtarget, DAG))
9064       return Blend;
9065
9066   // Try to use rotation instructions if available.
9067   if (Subtarget->hasSSSE3())
9068     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9069             DL, MVT::v8i16, V1, V2, Mask, DAG))
9070       return Rotate;
9071
9072   if (NumV1Inputs + NumV2Inputs <= 4)
9073     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
9074
9075   // Check whether an interleaving lowering is likely to be more efficient.
9076   // This isn't perfect but it is a strong heuristic that tends to work well on
9077   // the kinds of shuffles that show up in practice.
9078   //
9079   // FIXME: Handle 1x, 2x, and 4x interleaving.
9080   if (shouldLowerAsInterleaving(Mask)) {
9081     // FIXME: Figure out whether we should pack these into the low or high
9082     // halves.
9083
9084     int EMask[8], OMask[8];
9085     for (int i = 0; i < 4; ++i) {
9086       EMask[i] = Mask[2*i];
9087       OMask[i] = Mask[2*i + 1];
9088       EMask[i + 4] = -1;
9089       OMask[i + 4] = -1;
9090     }
9091
9092     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
9093     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
9094
9095     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
9096   }
9097
9098   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9099   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9100
9101   for (int i = 0; i < 4; ++i) {
9102     LoBlendMask[i] = Mask[i];
9103     HiBlendMask[i] = Mask[i + 4];
9104   }
9105
9106   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9107   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9108   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
9109   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
9110
9111   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9112                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
9113 }
9114
9115 /// \brief Check whether a compaction lowering can be done by dropping even
9116 /// elements and compute how many times even elements must be dropped.
9117 ///
9118 /// This handles shuffles which take every Nth element where N is a power of
9119 /// two. Example shuffle masks:
9120 ///
9121 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9122 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9123 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9124 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9125 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9126 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9127 ///
9128 /// Any of these lanes can of course be undef.
9129 ///
9130 /// This routine only supports N <= 3.
9131 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9132 /// for larger N.
9133 ///
9134 /// \returns N above, or the number of times even elements must be dropped if
9135 /// there is such a number. Otherwise returns zero.
9136 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9137   // Figure out whether we're looping over two inputs or just one.
9138   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9139
9140   // The modulus for the shuffle vector entries is based on whether this is
9141   // a single input or not.
9142   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9143   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9144          "We should only be called with masks with a power-of-2 size!");
9145
9146   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9147
9148   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9149   // and 2^3 simultaneously. This is because we may have ambiguity with
9150   // partially undef inputs.
9151   bool ViableForN[3] = {true, true, true};
9152
9153   for (int i = 0, e = Mask.size(); i < e; ++i) {
9154     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9155     // want.
9156     if (Mask[i] == -1)
9157       continue;
9158
9159     bool IsAnyViable = false;
9160     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9161       if (ViableForN[j]) {
9162         uint64_t N = j + 1;
9163
9164         // The shuffle mask must be equal to (i * 2^N) % M.
9165         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9166           IsAnyViable = true;
9167         else
9168           ViableForN[j] = false;
9169       }
9170     // Early exit if we exhaust the possible powers of two.
9171     if (!IsAnyViable)
9172       break;
9173   }
9174
9175   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9176     if (ViableForN[j])
9177       return j + 1;
9178
9179   // Return 0 as there is no viable power of two.
9180   return 0;
9181 }
9182
9183 /// \brief Generic lowering of v16i8 shuffles.
9184 ///
9185 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9186 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9187 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9188 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9189 /// back together.
9190 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9191                                        const X86Subtarget *Subtarget,
9192                                        SelectionDAG &DAG) {
9193   SDLoc DL(Op);
9194   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9195   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9196   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9197   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9198   ArrayRef<int> OrigMask = SVOp->getMask();
9199   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9200
9201   // Try to use rotation instructions if available.
9202   if (Subtarget->hasSSSE3())
9203     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9204             DL, MVT::v16i8, V1, V2, OrigMask, DAG))
9205       return Rotate;
9206
9207   // Try to use a zext lowering.
9208   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9209           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9210     return ZExt;
9211
9212   int MaskStorage[16] = {
9213       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
9214       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
9215       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
9216       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
9217   MutableArrayRef<int> Mask(MaskStorage);
9218   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
9219   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
9220
9221   int NumV2Elements =
9222       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9223
9224   // For single-input shuffles, there are some nicer lowering tricks we can use.
9225   if (NumV2Elements == 0) {
9226     // Check for being able to broadcast a single element.
9227     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i8, DL, V1,
9228                                                           Mask, Subtarget, DAG))
9229       return Broadcast;
9230
9231     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9232     // Notably, this handles splat and partial-splat shuffles more efficiently.
9233     // However, it only makes sense if the pre-duplication shuffle simplifies
9234     // things significantly. Currently, this means we need to be able to
9235     // express the pre-duplication shuffle as an i16 shuffle.
9236     //
9237     // FIXME: We should check for other patterns which can be widened into an
9238     // i16 shuffle as well.
9239     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9240       for (int i = 0; i < 16; i += 2)
9241         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9242           return false;
9243
9244       return true;
9245     };
9246     auto tryToWidenViaDuplication = [&]() -> SDValue {
9247       if (!canWidenViaDuplication(Mask))
9248         return SDValue();
9249       SmallVector<int, 4> LoInputs;
9250       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9251                    [](int M) { return M >= 0 && M < 8; });
9252       std::sort(LoInputs.begin(), LoInputs.end());
9253       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9254                      LoInputs.end());
9255       SmallVector<int, 4> HiInputs;
9256       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9257                    [](int M) { return M >= 8; });
9258       std::sort(HiInputs.begin(), HiInputs.end());
9259       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9260                      HiInputs.end());
9261
9262       bool TargetLo = LoInputs.size() >= HiInputs.size();
9263       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9264       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9265
9266       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9267       SmallDenseMap<int, int, 8> LaneMap;
9268       for (int I : InPlaceInputs) {
9269         PreDupI16Shuffle[I/2] = I/2;
9270         LaneMap[I] = I;
9271       }
9272       int j = TargetLo ? 0 : 4, je = j + 4;
9273       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9274         // Check if j is already a shuffle of this input. This happens when
9275         // there are two adjacent bytes after we move the low one.
9276         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9277           // If we haven't yet mapped the input, search for a slot into which
9278           // we can map it.
9279           while (j < je && PreDupI16Shuffle[j] != -1)
9280             ++j;
9281
9282           if (j == je)
9283             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9284             return SDValue();
9285
9286           // Map this input with the i16 shuffle.
9287           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9288         }
9289
9290         // Update the lane map based on the mapping we ended up with.
9291         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9292       }
9293       V1 = DAG.getNode(
9294           ISD::BITCAST, DL, MVT::v16i8,
9295           DAG.getVectorShuffle(MVT::v8i16, DL,
9296                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9297                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9298
9299       // Unpack the bytes to form the i16s that will be shuffled into place.
9300       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9301                        MVT::v16i8, V1, V1);
9302
9303       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9304       for (int i = 0; i < 16; ++i)
9305         if (Mask[i] != -1) {
9306           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9307           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9308           if (PostDupI16Shuffle[i / 2] == -1)
9309             PostDupI16Shuffle[i / 2] = MappedMask;
9310           else
9311             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9312                    "Conflicting entrties in the original shuffle!");
9313         }
9314       return DAG.getNode(
9315           ISD::BITCAST, DL, MVT::v16i8,
9316           DAG.getVectorShuffle(MVT::v8i16, DL,
9317                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9318                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9319     };
9320     if (SDValue V = tryToWidenViaDuplication())
9321       return V;
9322   }
9323
9324   // Check whether an interleaving lowering is likely to be more efficient.
9325   // This isn't perfect but it is a strong heuristic that tends to work well on
9326   // the kinds of shuffles that show up in practice.
9327   //
9328   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
9329   if (shouldLowerAsInterleaving(Mask)) {
9330     int NumLoHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9331       return (M >= 0 && M < 8) || (M >= 16 && M < 24);
9332     });
9333     int NumHiHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9334       return (M >= 8 && M < 16) || M >= 24;
9335     });
9336     int EMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9337                      -1, -1, -1, -1, -1, -1, -1, -1};
9338     int OMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9339                      -1, -1, -1, -1, -1, -1, -1, -1};
9340     bool UnpackLo = NumLoHalf >= NumHiHalf;
9341     MutableArrayRef<int> TargetEMask(UnpackLo ? EMask : EMask + 8, 8);
9342     MutableArrayRef<int> TargetOMask(UnpackLo ? OMask : OMask + 8, 8);
9343     for (int i = 0; i < 8; ++i) {
9344       TargetEMask[i] = Mask[2 * i];
9345       TargetOMask[i] = Mask[2 * i + 1];
9346     }
9347
9348     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
9349     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
9350
9351     return DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9352                        MVT::v16i8, Evens, Odds);
9353   }
9354
9355   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9356   // with PSHUFB. It is important to do this before we attempt to generate any
9357   // blends but after all of the single-input lowerings. If the single input
9358   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9359   // want to preserve that and we can DAG combine any longer sequences into
9360   // a PSHUFB in the end. But once we start blending from multiple inputs,
9361   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9362   // and there are *very* few patterns that would actually be faster than the
9363   // PSHUFB approach because of its ability to zero lanes.
9364   //
9365   // FIXME: The only exceptions to the above are blends which are exact
9366   // interleavings with direct instructions supporting them. We currently don't
9367   // handle those well here.
9368   if (Subtarget->hasSSSE3()) {
9369     SDValue V1Mask[16];
9370     SDValue V2Mask[16];
9371     for (int i = 0; i < 16; ++i)
9372       if (Mask[i] == -1) {
9373         V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9374       } else {
9375         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
9376         V2Mask[i] =
9377             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
9378       }
9379     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
9380                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9381     if (isSingleInputShuffleMask(Mask))
9382       return V1; // Single inputs are easy.
9383
9384     // Otherwise, blend the two.
9385     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
9386                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9387     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9388   }
9389
9390   // There are special ways we can lower some single-element blends.
9391   if (NumV2Elements == 1)
9392     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
9393                                                          Mask, Subtarget, DAG))
9394       return V;
9395
9396   // Check whether a compaction lowering can be done. This handles shuffles
9397   // which take every Nth element for some even N. See the helper function for
9398   // details.
9399   //
9400   // We special case these as they can be particularly efficiently handled with
9401   // the PACKUSB instruction on x86 and they show up in common patterns of
9402   // rearranging bytes to truncate wide elements.
9403   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9404     // NumEvenDrops is the power of two stride of the elements. Another way of
9405     // thinking about it is that we need to drop the even elements this many
9406     // times to get the original input.
9407     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9408
9409     // First we need to zero all the dropped bytes.
9410     assert(NumEvenDrops <= 3 &&
9411            "No support for dropping even elements more than 3 times.");
9412     // We use the mask type to pick which bytes are preserved based on how many
9413     // elements are dropped.
9414     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9415     SDValue ByteClearMask =
9416         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
9417                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
9418     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9419     if (!IsSingleInput)
9420       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9421
9422     // Now pack things back together.
9423     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
9424     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
9425     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9426     for (int i = 1; i < NumEvenDrops; ++i) {
9427       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
9428       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9429     }
9430
9431     return Result;
9432   }
9433
9434   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9435   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9436   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9437   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9438
9439   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
9440                             MutableArrayRef<int> V1HalfBlendMask,
9441                             MutableArrayRef<int> V2HalfBlendMask) {
9442     for (int i = 0; i < 8; ++i)
9443       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
9444         V1HalfBlendMask[i] = HalfMask[i];
9445         HalfMask[i] = i;
9446       } else if (HalfMask[i] >= 16) {
9447         V2HalfBlendMask[i] = HalfMask[i] - 16;
9448         HalfMask[i] = i + 8;
9449       }
9450   };
9451   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
9452   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
9453
9454   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9455
9456   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
9457                              MutableArrayRef<int> HiBlendMask) {
9458     SDValue V1, V2;
9459     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9460     // them out and avoid using UNPCK{L,H} to extract the elements of V as
9461     // i16s.
9462     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
9463                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
9464         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
9465                      [](int M) { return M >= 0 && M % 2 == 1; })) {
9466       // Use a mask to drop the high bytes.
9467       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
9468       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
9469                        DAG.getConstant(0x00FF, MVT::v8i16));
9470
9471       // This will be a single vector shuffle instead of a blend so nuke V2.
9472       V2 = DAG.getUNDEF(MVT::v8i16);
9473
9474       // Squash the masks to point directly into V1.
9475       for (int &M : LoBlendMask)
9476         if (M >= 0)
9477           M /= 2;
9478       for (int &M : HiBlendMask)
9479         if (M >= 0)
9480           M /= 2;
9481     } else {
9482       // Otherwise just unpack the low half of V into V1 and the high half into
9483       // V2 so that we can blend them as i16s.
9484       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9485                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9486       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9487                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9488     }
9489
9490     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9491     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9492     return std::make_pair(BlendedLo, BlendedHi);
9493   };
9494   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
9495   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
9496   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
9497
9498   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
9499   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
9500
9501   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9502 }
9503
9504 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9505 ///
9506 /// This routine breaks down the specific type of 128-bit shuffle and
9507 /// dispatches to the lowering routines accordingly.
9508 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9509                                         MVT VT, const X86Subtarget *Subtarget,
9510                                         SelectionDAG &DAG) {
9511   switch (VT.SimpleTy) {
9512   case MVT::v2i64:
9513     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9514   case MVT::v2f64:
9515     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9516   case MVT::v4i32:
9517     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9518   case MVT::v4f32:
9519     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9520   case MVT::v8i16:
9521     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9522   case MVT::v16i8:
9523     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9524
9525   default:
9526     llvm_unreachable("Unimplemented!");
9527   }
9528 }
9529
9530 /// \brief Helper function to test whether a shuffle mask could be
9531 /// simplified by widening the elements being shuffled.
9532 ///
9533 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9534 /// leaves it in an unspecified state.
9535 ///
9536 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9537 /// shuffle masks. The latter have the special property of a '-2' representing
9538 /// a zero-ed lane of a vector.
9539 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9540                                     SmallVectorImpl<int> &WidenedMask) {
9541   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9542     // If both elements are undef, its trivial.
9543     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9544       WidenedMask.push_back(SM_SentinelUndef);
9545       continue;
9546     }
9547
9548     // Check for an undef mask and a mask value properly aligned to fit with
9549     // a pair of values. If we find such a case, use the non-undef mask's value.
9550     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9551       WidenedMask.push_back(Mask[i + 1] / 2);
9552       continue;
9553     }
9554     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9555       WidenedMask.push_back(Mask[i] / 2);
9556       continue;
9557     }
9558
9559     // When zeroing, we need to spread the zeroing across both lanes to widen.
9560     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9561       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9562           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9563         WidenedMask.push_back(SM_SentinelZero);
9564         continue;
9565       }
9566       return false;
9567     }
9568
9569     // Finally check if the two mask values are adjacent and aligned with
9570     // a pair.
9571     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9572       WidenedMask.push_back(Mask[i] / 2);
9573       continue;
9574     }
9575
9576     // Otherwise we can't safely widen the elements used in this shuffle.
9577     return false;
9578   }
9579   assert(WidenedMask.size() == Mask.size() / 2 &&
9580          "Incorrect size of mask after widening the elements!");
9581
9582   return true;
9583 }
9584
9585 /// \brief Generic routine to split ector shuffle into half-sized shuffles.
9586 ///
9587 /// This routine just extracts two subvectors, shuffles them independently, and
9588 /// then concatenates them back together. This should work effectively with all
9589 /// AVX vector shuffle types.
9590 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9591                                           SDValue V2, ArrayRef<int> Mask,
9592                                           SelectionDAG &DAG) {
9593   assert(VT.getSizeInBits() >= 256 &&
9594          "Only for 256-bit or wider vector shuffles!");
9595   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9596   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9597
9598   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9599   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9600
9601   int NumElements = VT.getVectorNumElements();
9602   int SplitNumElements = NumElements / 2;
9603   MVT ScalarVT = VT.getScalarType();
9604   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9605
9606   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9607                              DAG.getIntPtrConstant(0));
9608   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9609                              DAG.getIntPtrConstant(SplitNumElements));
9610   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9611                              DAG.getIntPtrConstant(0));
9612   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9613                              DAG.getIntPtrConstant(SplitNumElements));
9614
9615   // Now create two 4-way blends of these half-width vectors.
9616   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9617     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9618     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9619     for (int i = 0; i < SplitNumElements; ++i) {
9620       int M = HalfMask[i];
9621       if (M >= NumElements) {
9622         if (M >= NumElements + SplitNumElements)
9623           UseHiV2 = true;
9624         else
9625           UseLoV2 = true;
9626         V2BlendMask.push_back(M - NumElements);
9627         V1BlendMask.push_back(-1);
9628         BlendMask.push_back(SplitNumElements + i);
9629       } else if (M >= 0) {
9630         if (M >= SplitNumElements)
9631           UseHiV1 = true;
9632         else
9633           UseLoV1 = true;
9634         V2BlendMask.push_back(-1);
9635         V1BlendMask.push_back(M);
9636         BlendMask.push_back(i);
9637       } else {
9638         V2BlendMask.push_back(-1);
9639         V1BlendMask.push_back(-1);
9640         BlendMask.push_back(-1);
9641       }
9642     }
9643
9644     // Because the lowering happens after all combining takes place, we need to
9645     // manually combine these blend masks as much as possible so that we create
9646     // a minimal number of high-level vector shuffle nodes.
9647
9648     // First try just blending the halves of V1 or V2.
9649     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9650       return DAG.getUNDEF(SplitVT);
9651     if (!UseLoV2 && !UseHiV2)
9652       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9653     if (!UseLoV1 && !UseHiV1)
9654       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9655
9656     SDValue V1Blend, V2Blend;
9657     if (UseLoV1 && UseHiV1) {
9658       V1Blend =
9659         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9660     } else {
9661       // We only use half of V1 so map the usage down into the final blend mask.
9662       V1Blend = UseLoV1 ? LoV1 : HiV1;
9663       for (int i = 0; i < SplitNumElements; ++i)
9664         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9665           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9666     }
9667     if (UseLoV2 && UseHiV2) {
9668       V2Blend =
9669         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9670     } else {
9671       // We only use half of V2 so map the usage down into the final blend mask.
9672       V2Blend = UseLoV2 ? LoV2 : HiV2;
9673       for (int i = 0; i < SplitNumElements; ++i)
9674         if (BlendMask[i] >= SplitNumElements)
9675           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9676     }
9677     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9678   };
9679   SDValue Lo = HalfBlend(LoMask);
9680   SDValue Hi = HalfBlend(HiMask);
9681   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9682 }
9683
9684 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9685 /// a permutation and blend of those lanes.
9686 ///
9687 /// This essentially blends the out-of-lane inputs to each lane into the lane
9688 /// from a permuted copy of the vector. This lowering strategy results in four
9689 /// instructions in the worst case for a single-input cross lane shuffle which
9690 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9691 /// of. Special cases for each particular shuffle pattern should be handled
9692 /// prior to trying this lowering.
9693 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9694                                                        SDValue V1, SDValue V2,
9695                                                        ArrayRef<int> Mask,
9696                                                        SelectionDAG &DAG) {
9697   // FIXME: This should probably be generalized for 512-bit vectors as well.
9698   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9699   int LaneSize = Mask.size() / 2;
9700
9701   // If there are only inputs from one 128-bit lane, splitting will in fact be
9702   // less expensive. The flags track wether the given lane contains an element
9703   // that crosses to another lane.
9704   bool LaneCrossing[2] = {false, false};
9705   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9706     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9707       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9708   if (!LaneCrossing[0] || !LaneCrossing[1])
9709     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9710
9711   if (isSingleInputShuffleMask(Mask)) {
9712     SmallVector<int, 32> FlippedBlendMask;
9713     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9714       FlippedBlendMask.push_back(
9715           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9716                                   ? Mask[i]
9717                                   : Mask[i] % LaneSize +
9718                                         (i / LaneSize) * LaneSize + Size));
9719
9720     // Flip the vector, and blend the results which should now be in-lane. The
9721     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9722     // 5 for the high source. The value 3 selects the high half of source 2 and
9723     // the value 2 selects the low half of source 2. We only use source 2 to
9724     // allow folding it into a memory operand.
9725     unsigned PERMMask = 3 | 2 << 4;
9726     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9727                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9728     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9729   }
9730
9731   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9732   // will be handled by the above logic and a blend of the results, much like
9733   // other patterns in AVX.
9734   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9735 }
9736
9737 /// \brief Handle lowering 2-lane 128-bit shuffles.
9738 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9739                                         SDValue V2, ArrayRef<int> Mask,
9740                                         const X86Subtarget *Subtarget,
9741                                         SelectionDAG &DAG) {
9742   // Blends are faster and handle all the non-lane-crossing cases.
9743   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9744                                                 Subtarget, DAG))
9745     return Blend;
9746
9747   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9748                                VT.getVectorNumElements() / 2);
9749   // Check for patterns which can be matched with a single insert of a 128-bit
9750   // subvector.
9751   if (isShuffleEquivalent(Mask, 0, 1, 0, 1) ||
9752       isShuffleEquivalent(Mask, 0, 1, 4, 5)) {
9753     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9754                               DAG.getIntPtrConstant(0));
9755     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9756                               Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
9757     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9758   }
9759   if (isShuffleEquivalent(Mask, 0, 1, 6, 7)) {
9760     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9761                               DAG.getIntPtrConstant(0));
9762     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9763                               DAG.getIntPtrConstant(2));
9764     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9765   }
9766
9767   // Otherwise form a 128-bit permutation.
9768   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9769   unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
9770   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9771                      DAG.getConstant(PermMask, MVT::i8));
9772 }
9773
9774 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9775 ///
9776 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9777 /// isn't available.
9778 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9779                                        const X86Subtarget *Subtarget,
9780                                        SelectionDAG &DAG) {
9781   SDLoc DL(Op);
9782   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9783   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9784   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9785   ArrayRef<int> Mask = SVOp->getMask();
9786   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9787
9788   SmallVector<int, 4> WidenedMask;
9789   if (canWidenShuffleElements(Mask, WidenedMask))
9790     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9791                                     DAG);
9792
9793   if (isSingleInputShuffleMask(Mask)) {
9794     // Check for being able to broadcast a single element.
9795     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f64, DL, V1,
9796                                                           Mask, Subtarget, DAG))
9797       return Broadcast;
9798
9799     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9800       // Non-half-crossing single input shuffles can be lowerid with an
9801       // interleaved permutation.
9802       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9803                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9804       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9805                          DAG.getConstant(VPERMILPMask, MVT::i8));
9806     }
9807
9808     // With AVX2 we have direct support for this permutation.
9809     if (Subtarget->hasAVX2())
9810       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9811                          getV4X86ShuffleImm8ForMask(Mask, DAG));
9812
9813     // Otherwise, fall back.
9814     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9815                                                    DAG);
9816   }
9817
9818   // X86 has dedicated unpack instructions that can handle specific blend
9819   // operations: UNPCKH and UNPCKL.
9820   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
9821     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9822   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
9823     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9824
9825   // If we have a single input to the zero element, insert that into V1 if we
9826   // can do so cheaply.
9827   int NumV2Elements =
9828       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9829   if (NumV2Elements == 1 && Mask[0] >= 4)
9830     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9831             MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
9832       return Insertion;
9833
9834   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9835                                                 Subtarget, DAG))
9836     return Blend;
9837
9838   // Check if the blend happens to exactly fit that of SHUFPD.
9839   if ((Mask[0] == -1 || Mask[0] < 2) &&
9840       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9841       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9842       (Mask[3] == -1 || Mask[3] >= 6)) {
9843     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9844                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9845     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9846                        DAG.getConstant(SHUFPDMask, MVT::i8));
9847   }
9848   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9849       (Mask[1] == -1 || Mask[1] < 2) &&
9850       (Mask[2] == -1 || Mask[2] >= 6) &&
9851       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9852     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9853                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9854     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9855                        DAG.getConstant(SHUFPDMask, MVT::i8));
9856   }
9857
9858   // Otherwise fall back on generic blend lowering.
9859   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9860                                                     Mask, DAG);
9861 }
9862
9863 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9864 ///
9865 /// This routine is only called when we have AVX2 and thus a reasonable
9866 /// instruction set for v4i64 shuffling..
9867 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9868                                        const X86Subtarget *Subtarget,
9869                                        SelectionDAG &DAG) {
9870   SDLoc DL(Op);
9871   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9872   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9873   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9874   ArrayRef<int> Mask = SVOp->getMask();
9875   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9876   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9877
9878   SmallVector<int, 4> WidenedMask;
9879   if (canWidenShuffleElements(Mask, WidenedMask))
9880     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9881                                     DAG);
9882
9883   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9884                                                 Subtarget, DAG))
9885     return Blend;
9886
9887   // Check for being able to broadcast a single element.
9888   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i64, DL, V1,
9889                                                         Mask, Subtarget, DAG))
9890     return Broadcast;
9891
9892   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9893   // use lower latency instructions that will operate on both 128-bit lanes.
9894   SmallVector<int, 2> RepeatedMask;
9895   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9896     if (isSingleInputShuffleMask(Mask)) {
9897       int PSHUFDMask[] = {-1, -1, -1, -1};
9898       for (int i = 0; i < 2; ++i)
9899         if (RepeatedMask[i] >= 0) {
9900           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9901           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9902         }
9903       return DAG.getNode(
9904           ISD::BITCAST, DL, MVT::v4i64,
9905           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9906                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9907                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9908     }
9909
9910     // Use dedicated unpack instructions for masks that match their pattern.
9911     if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
9912       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9913     if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
9914       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9915   }
9916
9917   // AVX2 provides a direct instruction for permuting a single input across
9918   // lanes.
9919   if (isSingleInputShuffleMask(Mask))
9920     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9921                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9922
9923   // Otherwise fall back on generic blend lowering.
9924   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9925                                                     Mask, DAG);
9926 }
9927
9928 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9929 ///
9930 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9931 /// isn't available.
9932 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9933                                        const X86Subtarget *Subtarget,
9934                                        SelectionDAG &DAG) {
9935   SDLoc DL(Op);
9936   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9937   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9938   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9939   ArrayRef<int> Mask = SVOp->getMask();
9940   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9941
9942   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9943                                                 Subtarget, DAG))
9944     return Blend;
9945
9946   // Check for being able to broadcast a single element.
9947   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8f32, DL, V1,
9948                                                         Mask, Subtarget, DAG))
9949     return Broadcast;
9950
9951   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9952   // options to efficiently lower the shuffle.
9953   SmallVector<int, 4> RepeatedMask;
9954   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9955     assert(RepeatedMask.size() == 4 &&
9956            "Repeated masks must be half the mask width!");
9957     if (isSingleInputShuffleMask(Mask))
9958       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9959                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9960
9961     // Use dedicated unpack instructions for masks that match their pattern.
9962     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
9963       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9964     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
9965       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9966
9967     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9968     // have already handled any direct blends. We also need to squash the
9969     // repeated mask into a simulated v4f32 mask.
9970     for (int i = 0; i < 4; ++i)
9971       if (RepeatedMask[i] >= 8)
9972         RepeatedMask[i] -= 4;
9973     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9974   }
9975
9976   // If we have a single input shuffle with different shuffle patterns in the
9977   // two 128-bit lanes use the variable mask to VPERMILPS.
9978   if (isSingleInputShuffleMask(Mask)) {
9979     SDValue VPermMask[8];
9980     for (int i = 0; i < 8; ++i)
9981       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9982                                  : DAG.getConstant(Mask[i], MVT::i32);
9983     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9984       return DAG.getNode(
9985           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9986           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9987
9988     if (Subtarget->hasAVX2())
9989       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9990                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9991                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9992                                                  MVT::v8i32, VPermMask)),
9993                          V1);
9994
9995     // Otherwise, fall back.
9996     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9997                                                    DAG);
9998   }
9999
10000   // Otherwise fall back on generic blend lowering.
10001   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10002                                                     Mask, DAG);
10003 }
10004
10005 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10006 ///
10007 /// This routine is only called when we have AVX2 and thus a reasonable
10008 /// instruction set for v8i32 shuffling..
10009 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10010                                        const X86Subtarget *Subtarget,
10011                                        SelectionDAG &DAG) {
10012   SDLoc DL(Op);
10013   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10014   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10015   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10016   ArrayRef<int> Mask = SVOp->getMask();
10017   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10018   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10019
10020   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10021                                                 Subtarget, DAG))
10022     return Blend;
10023
10024   // Check for being able to broadcast a single element.
10025   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i32, DL, V1,
10026                                                         Mask, Subtarget, DAG))
10027     return Broadcast;
10028
10029   // If the shuffle mask is repeated in each 128-bit lane we can use more
10030   // efficient instructions that mirror the shuffles across the two 128-bit
10031   // lanes.
10032   SmallVector<int, 4> RepeatedMask;
10033   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10034     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10035     if (isSingleInputShuffleMask(Mask))
10036       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10037                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10038
10039     // Use dedicated unpack instructions for masks that match their pattern.
10040     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10041       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10042     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10043       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10044   }
10045
10046   // If the shuffle patterns aren't repeated but it is a single input, directly
10047   // generate a cross-lane VPERMD instruction.
10048   if (isSingleInputShuffleMask(Mask)) {
10049     SDValue VPermMask[8];
10050     for (int i = 0; i < 8; ++i)
10051       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10052                                  : DAG.getConstant(Mask[i], MVT::i32);
10053     return DAG.getNode(
10054         X86ISD::VPERMV, DL, MVT::v8i32,
10055         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10056   }
10057
10058   // Otherwise fall back on generic blend lowering.
10059   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10060                                                     Mask, DAG);
10061 }
10062
10063 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10064 ///
10065 /// This routine is only called when we have AVX2 and thus a reasonable
10066 /// instruction set for v16i16 shuffling..
10067 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10068                                         const X86Subtarget *Subtarget,
10069                                         SelectionDAG &DAG) {
10070   SDLoc DL(Op);
10071   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10072   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10073   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10074   ArrayRef<int> Mask = SVOp->getMask();
10075   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10076   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10077
10078   // Check for being able to broadcast a single element.
10079   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i16, DL, V1,
10080                                                         Mask, Subtarget, DAG))
10081     return Broadcast;
10082
10083   // There are no generalized cross-lane shuffle operations available on i16
10084   // element types.
10085   if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10086     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10087                                                    Mask, DAG);
10088
10089   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10090                                                 Subtarget, DAG))
10091     return Blend;
10092
10093   // Use dedicated unpack instructions for masks that match their pattern.
10094   if (isShuffleEquivalent(Mask,
10095                           // First 128-bit lane:
10096                           0, 16, 1, 17, 2, 18, 3, 19,
10097                           // Second 128-bit lane:
10098                           8, 24, 9, 25, 10, 26, 11, 27))
10099     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10100   if (isShuffleEquivalent(Mask,
10101                           // First 128-bit lane:
10102                           4, 20, 5, 21, 6, 22, 7, 23,
10103                           // Second 128-bit lane:
10104                           12, 28, 13, 29, 14, 30, 15, 31))
10105     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10106
10107   if (isSingleInputShuffleMask(Mask)) {
10108     SDValue PSHUFBMask[32];
10109     for (int i = 0; i < 16; ++i) {
10110       if (Mask[i] == -1) {
10111         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10112         continue;
10113       }
10114
10115       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10116       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10117       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
10118       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
10119     }
10120     return DAG.getNode(
10121         ISD::BITCAST, DL, MVT::v16i16,
10122         DAG.getNode(
10123             X86ISD::PSHUFB, DL, MVT::v32i8,
10124             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
10125             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
10126   }
10127
10128   // Otherwise fall back on generic blend lowering.
10129   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i16, V1, V2,
10130                                                     Mask, DAG);
10131 }
10132
10133 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10134 ///
10135 /// This routine is only called when we have AVX2 and thus a reasonable
10136 /// instruction set for v32i8 shuffling..
10137 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10138                                        const X86Subtarget *Subtarget,
10139                                        SelectionDAG &DAG) {
10140   SDLoc DL(Op);
10141   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10142   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10143   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10144   ArrayRef<int> Mask = SVOp->getMask();
10145   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10146   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10147
10148   // Check for being able to broadcast a single element.
10149   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v32i8, DL, V1,
10150                                                         Mask, Subtarget, DAG))
10151     return Broadcast;
10152
10153   // There are no generalized cross-lane shuffle operations available on i8
10154   // element types.
10155   if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10156     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10157                                                    Mask, DAG);
10158
10159   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10160                                                 Subtarget, DAG))
10161     return Blend;
10162
10163   // Use dedicated unpack instructions for masks that match their pattern.
10164   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10165   // 256-bit lanes.
10166   if (isShuffleEquivalent(
10167           Mask,
10168           // First 128-bit lane:
10169           0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10170           // Second 128-bit lane:
10171           16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55))
10172     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10173   if (isShuffleEquivalent(
10174           Mask,
10175           // First 128-bit lane:
10176           8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10177           // Second 128-bit lane:
10178           24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63))
10179     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10180
10181   if (isSingleInputShuffleMask(Mask)) {
10182     SDValue PSHUFBMask[32];
10183     for (int i = 0; i < 32; ++i)
10184       PSHUFBMask[i] =
10185           Mask[i] < 0
10186               ? DAG.getUNDEF(MVT::i8)
10187               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
10188
10189     return DAG.getNode(
10190         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10191         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10192   }
10193
10194   // Otherwise fall back on generic blend lowering.
10195   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v32i8, V1, V2,
10196                                                     Mask, DAG);
10197 }
10198
10199 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10200 ///
10201 /// This routine either breaks down the specific type of a 256-bit x86 vector
10202 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10203 /// together based on the available instructions.
10204 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10205                                         MVT VT, const X86Subtarget *Subtarget,
10206                                         SelectionDAG &DAG) {
10207   SDLoc DL(Op);
10208   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10209   ArrayRef<int> Mask = SVOp->getMask();
10210
10211   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10212   // check for those subtargets here and avoid much of the subtarget querying in
10213   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10214   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10215   // floating point types there eventually, just immediately cast everything to
10216   // a float and operate entirely in that domain.
10217   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10218     int ElementBits = VT.getScalarSizeInBits();
10219     if (ElementBits < 32)
10220       // No floating point type available, decompose into 128-bit vectors.
10221       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10222
10223     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10224                                 VT.getVectorNumElements());
10225     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10226     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10227     return DAG.getNode(ISD::BITCAST, DL, VT,
10228                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10229   }
10230
10231   switch (VT.SimpleTy) {
10232   case MVT::v4f64:
10233     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10234   case MVT::v4i64:
10235     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10236   case MVT::v8f32:
10237     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10238   case MVT::v8i32:
10239     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10240   case MVT::v16i16:
10241     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10242   case MVT::v32i8:
10243     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10244
10245   default:
10246     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10247   }
10248 }
10249
10250 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10251 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10252                                        const X86Subtarget *Subtarget,
10253                                        SelectionDAG &DAG) {
10254   SDLoc DL(Op);
10255   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10256   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10257   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10258   ArrayRef<int> Mask = SVOp->getMask();
10259   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10260
10261   // FIXME: Implement direct support for this type!
10262   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10263 }
10264
10265 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10266 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10267                                        const X86Subtarget *Subtarget,
10268                                        SelectionDAG &DAG) {
10269   SDLoc DL(Op);
10270   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10271   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10272   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10273   ArrayRef<int> Mask = SVOp->getMask();
10274   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10275
10276   // FIXME: Implement direct support for this type!
10277   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10278 }
10279
10280 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10281 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10282                                        const X86Subtarget *Subtarget,
10283                                        SelectionDAG &DAG) {
10284   SDLoc DL(Op);
10285   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10286   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10287   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10288   ArrayRef<int> Mask = SVOp->getMask();
10289   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10290
10291   // FIXME: Implement direct support for this type!
10292   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10293 }
10294
10295 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10296 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10297                                        const X86Subtarget *Subtarget,
10298                                        SelectionDAG &DAG) {
10299   SDLoc DL(Op);
10300   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10301   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10302   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10303   ArrayRef<int> Mask = SVOp->getMask();
10304   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10305
10306   // FIXME: Implement direct support for this type!
10307   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10308 }
10309
10310 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10311 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10312                                         const X86Subtarget *Subtarget,
10313                                         SelectionDAG &DAG) {
10314   SDLoc DL(Op);
10315   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10316   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10317   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10318   ArrayRef<int> Mask = SVOp->getMask();
10319   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10320   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10321
10322   // FIXME: Implement direct support for this type!
10323   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10324 }
10325
10326 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10327 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10328                                        const X86Subtarget *Subtarget,
10329                                        SelectionDAG &DAG) {
10330   SDLoc DL(Op);
10331   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10332   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10333   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10334   ArrayRef<int> Mask = SVOp->getMask();
10335   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10336   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10337
10338   // FIXME: Implement direct support for this type!
10339   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10340 }
10341
10342 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10343 ///
10344 /// This routine either breaks down the specific type of a 512-bit x86 vector
10345 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10346 /// together based on the available instructions.
10347 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10348                                         MVT VT, const X86Subtarget *Subtarget,
10349                                         SelectionDAG &DAG) {
10350   SDLoc DL(Op);
10351   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10352   ArrayRef<int> Mask = SVOp->getMask();
10353   assert(Subtarget->hasAVX512() &&
10354          "Cannot lower 512-bit vectors w/ basic ISA!");
10355
10356   // Check for being able to broadcast a single element.
10357   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(VT.SimpleTy, DL, V1,
10358                                                         Mask, Subtarget, DAG))
10359     return Broadcast;
10360
10361   // Dispatch to each element type for lowering. If we don't have supprot for
10362   // specific element type shuffles at 512 bits, immediately split them and
10363   // lower them. Each lowering routine of a given type is allowed to assume that
10364   // the requisite ISA extensions for that element type are available.
10365   switch (VT.SimpleTy) {
10366   case MVT::v8f64:
10367     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10368   case MVT::v16f32:
10369     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10370   case MVT::v8i64:
10371     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10372   case MVT::v16i32:
10373     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10374   case MVT::v32i16:
10375     if (Subtarget->hasBWI())
10376       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10377     break;
10378   case MVT::v64i8:
10379     if (Subtarget->hasBWI())
10380       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10381     break;
10382
10383   default:
10384     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10385   }
10386
10387   // Otherwise fall back on splitting.
10388   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10389 }
10390
10391 /// \brief Top-level lowering for x86 vector shuffles.
10392 ///
10393 /// This handles decomposition, canonicalization, and lowering of all x86
10394 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10395 /// above in helper routines. The canonicalization attempts to widen shuffles
10396 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10397 /// s.t. only one of the two inputs needs to be tested, etc.
10398 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10399                                   SelectionDAG &DAG) {
10400   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10401   ArrayRef<int> Mask = SVOp->getMask();
10402   SDValue V1 = Op.getOperand(0);
10403   SDValue V2 = Op.getOperand(1);
10404   MVT VT = Op.getSimpleValueType();
10405   int NumElements = VT.getVectorNumElements();
10406   SDLoc dl(Op);
10407
10408   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10409
10410   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10411   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10412   if (V1IsUndef && V2IsUndef)
10413     return DAG.getUNDEF(VT);
10414
10415   // When we create a shuffle node we put the UNDEF node to second operand,
10416   // but in some cases the first operand may be transformed to UNDEF.
10417   // In this case we should just commute the node.
10418   if (V1IsUndef)
10419     return DAG.getCommutedVectorShuffle(*SVOp);
10420
10421   // Check for non-undef masks pointing at an undef vector and make the masks
10422   // undef as well. This makes it easier to match the shuffle based solely on
10423   // the mask.
10424   if (V2IsUndef)
10425     for (int M : Mask)
10426       if (M >= NumElements) {
10427         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10428         for (int &M : NewMask)
10429           if (M >= NumElements)
10430             M = -1;
10431         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10432       }
10433
10434   // Try to collapse shuffles into using a vector type with fewer elements but
10435   // wider element types. We cap this to not form integers or floating point
10436   // elements wider than 64 bits, but it might be interesting to form i128
10437   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10438   SmallVector<int, 16> WidenedMask;
10439   if (VT.getScalarSizeInBits() < 64 &&
10440       canWidenShuffleElements(Mask, WidenedMask)) {
10441     MVT NewEltVT = VT.isFloatingPoint()
10442                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10443                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10444     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10445     // Make sure that the new vector type is legal. For example, v2f64 isn't
10446     // legal on SSE1.
10447     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10448       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10449       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10450       return DAG.getNode(ISD::BITCAST, dl, VT,
10451                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10452     }
10453   }
10454
10455   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10456   for (int M : SVOp->getMask())
10457     if (M < 0)
10458       ++NumUndefElements;
10459     else if (M < NumElements)
10460       ++NumV1Elements;
10461     else
10462       ++NumV2Elements;
10463
10464   // Commute the shuffle as needed such that more elements come from V1 than
10465   // V2. This allows us to match the shuffle pattern strictly on how many
10466   // elements come from V1 without handling the symmetric cases.
10467   if (NumV2Elements > NumV1Elements)
10468     return DAG.getCommutedVectorShuffle(*SVOp);
10469
10470   // When the number of V1 and V2 elements are the same, try to minimize the
10471   // number of uses of V2 in the low half of the vector. When that is tied,
10472   // ensure that the sum of indices for V1 is equal to or lower than the sum
10473   // indices for V2.
10474   if (NumV1Elements == NumV2Elements) {
10475     int LowV1Elements = 0, LowV2Elements = 0;
10476     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10477       if (M >= NumElements)
10478         ++LowV2Elements;
10479       else if (M >= 0)
10480         ++LowV1Elements;
10481     if (LowV2Elements > LowV1Elements) {
10482       return DAG.getCommutedVectorShuffle(*SVOp);
10483     } else if (LowV2Elements == LowV1Elements) {
10484       int SumV1Indices = 0, SumV2Indices = 0;
10485       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10486         if (SVOp->getMask()[i] >= NumElements)
10487           SumV2Indices += i;
10488         else if (SVOp->getMask()[i] >= 0)
10489           SumV1Indices += i;
10490       if (SumV2Indices < SumV1Indices)
10491         return DAG.getCommutedVectorShuffle(*SVOp);
10492     }
10493   }
10494
10495   // For each vector width, delegate to a specialized lowering routine.
10496   if (VT.getSizeInBits() == 128)
10497     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10498
10499   if (VT.getSizeInBits() == 256)
10500     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10501
10502   // Force AVX-512 vectors to be scalarized for now.
10503   // FIXME: Implement AVX-512 support!
10504   if (VT.getSizeInBits() == 512)
10505     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10506
10507   llvm_unreachable("Unimplemented!");
10508 }
10509
10510
10511 //===----------------------------------------------------------------------===//
10512 // Legacy vector shuffle lowering
10513 //
10514 // This code is the legacy code handling vector shuffles until the above
10515 // replaces its functionality and performance.
10516 //===----------------------------------------------------------------------===//
10517
10518 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
10519                         bool hasInt256, unsigned *MaskOut = nullptr) {
10520   MVT EltVT = VT.getVectorElementType();
10521
10522   // There is no blend with immediate in AVX-512.
10523   if (VT.is512BitVector())
10524     return false;
10525
10526   if (!hasSSE41 || EltVT == MVT::i8)
10527     return false;
10528   if (!hasInt256 && VT == MVT::v16i16)
10529     return false;
10530
10531   unsigned MaskValue = 0;
10532   unsigned NumElems = VT.getVectorNumElements();
10533   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10534   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10535   unsigned NumElemsInLane = NumElems / NumLanes;
10536
10537   // Blend for v16i16 should be symetric for the both lanes.
10538   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10539
10540     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
10541     int EltIdx = MaskVals[i];
10542
10543     if ((EltIdx < 0 || EltIdx == (int)i) &&
10544         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
10545       continue;
10546
10547     if (((unsigned)EltIdx == (i + NumElems)) &&
10548         (SndLaneEltIdx < 0 ||
10549          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
10550       MaskValue |= (1 << i);
10551     else
10552       return false;
10553   }
10554
10555   if (MaskOut)
10556     *MaskOut = MaskValue;
10557   return true;
10558 }
10559
10560 // Try to lower a shuffle node into a simple blend instruction.
10561 // This function assumes isBlendMask returns true for this
10562 // SuffleVectorSDNode
10563 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
10564                                           unsigned MaskValue,
10565                                           const X86Subtarget *Subtarget,
10566                                           SelectionDAG &DAG) {
10567   MVT VT = SVOp->getSimpleValueType(0);
10568   MVT EltVT = VT.getVectorElementType();
10569   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
10570                      Subtarget->hasInt256() && "Trying to lower a "
10571                                                "VECTOR_SHUFFLE to a Blend but "
10572                                                "with the wrong mask"));
10573   SDValue V1 = SVOp->getOperand(0);
10574   SDValue V2 = SVOp->getOperand(1);
10575   SDLoc dl(SVOp);
10576   unsigned NumElems = VT.getVectorNumElements();
10577
10578   // Convert i32 vectors to floating point if it is not AVX2.
10579   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10580   MVT BlendVT = VT;
10581   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10582     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10583                                NumElems);
10584     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
10585     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
10586   }
10587
10588   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
10589                             DAG.getConstant(MaskValue, MVT::i32));
10590   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10591 }
10592
10593 /// In vector type \p VT, return true if the element at index \p InputIdx
10594 /// falls on a different 128-bit lane than \p OutputIdx.
10595 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
10596                                      unsigned OutputIdx) {
10597   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
10598   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
10599 }
10600
10601 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
10602 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
10603 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
10604 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
10605 /// zero.
10606 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
10607                          SelectionDAG &DAG) {
10608   MVT VT = V1.getSimpleValueType();
10609   assert(VT.is128BitVector() || VT.is256BitVector());
10610
10611   MVT EltVT = VT.getVectorElementType();
10612   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
10613   unsigned NumElts = VT.getVectorNumElements();
10614
10615   SmallVector<SDValue, 32> PshufbMask;
10616   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
10617     int InputIdx = MaskVals[OutputIdx];
10618     unsigned InputByteIdx;
10619
10620     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
10621       InputByteIdx = 0x80;
10622     else {
10623       // Cross lane is not allowed.
10624       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
10625         return SDValue();
10626       InputByteIdx = InputIdx * EltSizeInBytes;
10627       // Index is an byte offset within the 128-bit lane.
10628       InputByteIdx &= 0xf;
10629     }
10630
10631     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
10632       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
10633       if (InputByteIdx != 0x80)
10634         ++InputByteIdx;
10635     }
10636   }
10637
10638   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
10639   if (ShufVT != VT)
10640     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
10641   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
10642                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
10643 }
10644
10645 // v8i16 shuffles - Prefer shuffles in the following order:
10646 // 1. [all]   pshuflw, pshufhw, optional move
10647 // 2. [ssse3] 1 x pshufb
10648 // 3. [ssse3] 2 x pshufb + 1 x por
10649 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
10650 static SDValue
10651 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
10652                          SelectionDAG &DAG) {
10653   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10654   SDValue V1 = SVOp->getOperand(0);
10655   SDValue V2 = SVOp->getOperand(1);
10656   SDLoc dl(SVOp);
10657   SmallVector<int, 8> MaskVals;
10658
10659   // Determine if more than 1 of the words in each of the low and high quadwords
10660   // of the result come from the same quadword of one of the two inputs.  Undef
10661   // mask values count as coming from any quadword, for better codegen.
10662   //
10663   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
10664   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
10665   unsigned LoQuad[] = { 0, 0, 0, 0 };
10666   unsigned HiQuad[] = { 0, 0, 0, 0 };
10667   // Indices of quads used.
10668   std::bitset<4> InputQuads;
10669   for (unsigned i = 0; i < 8; ++i) {
10670     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
10671     int EltIdx = SVOp->getMaskElt(i);
10672     MaskVals.push_back(EltIdx);
10673     if (EltIdx < 0) {
10674       ++Quad[0];
10675       ++Quad[1];
10676       ++Quad[2];
10677       ++Quad[3];
10678       continue;
10679     }
10680     ++Quad[EltIdx / 4];
10681     InputQuads.set(EltIdx / 4);
10682   }
10683
10684   int BestLoQuad = -1;
10685   unsigned MaxQuad = 1;
10686   for (unsigned i = 0; i < 4; ++i) {
10687     if (LoQuad[i] > MaxQuad) {
10688       BestLoQuad = i;
10689       MaxQuad = LoQuad[i];
10690     }
10691   }
10692
10693   int BestHiQuad = -1;
10694   MaxQuad = 1;
10695   for (unsigned i = 0; i < 4; ++i) {
10696     if (HiQuad[i] > MaxQuad) {
10697       BestHiQuad = i;
10698       MaxQuad = HiQuad[i];
10699     }
10700   }
10701
10702   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
10703   // of the two input vectors, shuffle them into one input vector so only a
10704   // single pshufb instruction is necessary. If there are more than 2 input
10705   // quads, disable the next transformation since it does not help SSSE3.
10706   bool V1Used = InputQuads[0] || InputQuads[1];
10707   bool V2Used = InputQuads[2] || InputQuads[3];
10708   if (Subtarget->hasSSSE3()) {
10709     if (InputQuads.count() == 2 && V1Used && V2Used) {
10710       BestLoQuad = InputQuads[0] ? 0 : 1;
10711       BestHiQuad = InputQuads[2] ? 2 : 3;
10712     }
10713     if (InputQuads.count() > 2) {
10714       BestLoQuad = -1;
10715       BestHiQuad = -1;
10716     }
10717   }
10718
10719   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
10720   // the shuffle mask.  If a quad is scored as -1, that means that it contains
10721   // words from all 4 input quadwords.
10722   SDValue NewV;
10723   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
10724     int MaskV[] = {
10725       BestLoQuad < 0 ? 0 : BestLoQuad,
10726       BestHiQuad < 0 ? 1 : BestHiQuad
10727     };
10728     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
10729                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
10730                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
10731     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
10732
10733     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
10734     // source words for the shuffle, to aid later transformations.
10735     bool AllWordsInNewV = true;
10736     bool InOrder[2] = { true, true };
10737     for (unsigned i = 0; i != 8; ++i) {
10738       int idx = MaskVals[i];
10739       if (idx != (int)i)
10740         InOrder[i/4] = false;
10741       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
10742         continue;
10743       AllWordsInNewV = false;
10744       break;
10745     }
10746
10747     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
10748     if (AllWordsInNewV) {
10749       for (int i = 0; i != 8; ++i) {
10750         int idx = MaskVals[i];
10751         if (idx < 0)
10752           continue;
10753         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
10754         if ((idx != i) && idx < 4)
10755           pshufhw = false;
10756         if ((idx != i) && idx > 3)
10757           pshuflw = false;
10758       }
10759       V1 = NewV;
10760       V2Used = false;
10761       BestLoQuad = 0;
10762       BestHiQuad = 1;
10763     }
10764
10765     // If we've eliminated the use of V2, and the new mask is a pshuflw or
10766     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
10767     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
10768       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
10769       unsigned TargetMask = 0;
10770       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
10771                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
10772       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
10773       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
10774                              getShufflePSHUFLWImmediate(SVOp);
10775       V1 = NewV.getOperand(0);
10776       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
10777     }
10778   }
10779
10780   // Promote splats to a larger type which usually leads to more efficient code.
10781   // FIXME: Is this true if pshufb is available?
10782   if (SVOp->isSplat())
10783     return PromoteSplat(SVOp, DAG);
10784
10785   // If we have SSSE3, and all words of the result are from 1 input vector,
10786   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
10787   // is present, fall back to case 4.
10788   if (Subtarget->hasSSSE3()) {
10789     SmallVector<SDValue,16> pshufbMask;
10790
10791     // If we have elements from both input vectors, set the high bit of the
10792     // shuffle mask element to zero out elements that come from V2 in the V1
10793     // mask, and elements that come from V1 in the V2 mask, so that the two
10794     // results can be OR'd together.
10795     bool TwoInputs = V1Used && V2Used;
10796     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
10797     if (!TwoInputs)
10798       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10799
10800     // Calculate the shuffle mask for the second input, shuffle it, and
10801     // OR it with the first shuffled input.
10802     CommuteVectorShuffleMask(MaskVals, 8);
10803     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
10804     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
10805     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10806   }
10807
10808   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
10809   // and update MaskVals with new element order.
10810   std::bitset<8> InOrder;
10811   if (BestLoQuad >= 0) {
10812     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
10813     for (int i = 0; i != 4; ++i) {
10814       int idx = MaskVals[i];
10815       if (idx < 0) {
10816         InOrder.set(i);
10817       } else if ((idx / 4) == BestLoQuad) {
10818         MaskV[i] = idx & 3;
10819         InOrder.set(i);
10820       }
10821     }
10822     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
10823                                 &MaskV[0]);
10824
10825     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
10826       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
10827       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
10828                                   NewV.getOperand(0),
10829                                   getShufflePSHUFLWImmediate(SVOp), DAG);
10830     }
10831   }
10832
10833   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
10834   // and update MaskVals with the new element order.
10835   if (BestHiQuad >= 0) {
10836     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
10837     for (unsigned i = 4; i != 8; ++i) {
10838       int idx = MaskVals[i];
10839       if (idx < 0) {
10840         InOrder.set(i);
10841       } else if ((idx / 4) == BestHiQuad) {
10842         MaskV[i] = (idx & 3) + 4;
10843         InOrder.set(i);
10844       }
10845     }
10846     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
10847                                 &MaskV[0]);
10848
10849     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
10850       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
10851       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
10852                                   NewV.getOperand(0),
10853                                   getShufflePSHUFHWImmediate(SVOp), DAG);
10854     }
10855   }
10856
10857   // In case BestHi & BestLo were both -1, which means each quadword has a word
10858   // from each of the four input quadwords, calculate the InOrder bitvector now
10859   // before falling through to the insert/extract cleanup.
10860   if (BestLoQuad == -1 && BestHiQuad == -1) {
10861     NewV = V1;
10862     for (int i = 0; i != 8; ++i)
10863       if (MaskVals[i] < 0 || MaskVals[i] == i)
10864         InOrder.set(i);
10865   }
10866
10867   // The other elements are put in the right place using pextrw and pinsrw.
10868   for (unsigned i = 0; i != 8; ++i) {
10869     if (InOrder[i])
10870       continue;
10871     int EltIdx = MaskVals[i];
10872     if (EltIdx < 0)
10873       continue;
10874     SDValue ExtOp = (EltIdx < 8) ?
10875       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
10876                   DAG.getIntPtrConstant(EltIdx)) :
10877       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
10878                   DAG.getIntPtrConstant(EltIdx - 8));
10879     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
10880                        DAG.getIntPtrConstant(i));
10881   }
10882   return NewV;
10883 }
10884
10885 /// \brief v16i16 shuffles
10886 ///
10887 /// FIXME: We only support generation of a single pshufb currently.  We can
10888 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
10889 /// well (e.g 2 x pshufb + 1 x por).
10890 static SDValue
10891 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
10892   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10893   SDValue V1 = SVOp->getOperand(0);
10894   SDValue V2 = SVOp->getOperand(1);
10895   SDLoc dl(SVOp);
10896
10897   if (V2.getOpcode() != ISD::UNDEF)
10898     return SDValue();
10899
10900   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
10901   return getPSHUFB(MaskVals, V1, dl, DAG);
10902 }
10903
10904 // v16i8 shuffles - Prefer shuffles in the following order:
10905 // 1. [ssse3] 1 x pshufb
10906 // 2. [ssse3] 2 x pshufb + 1 x por
10907 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
10908 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
10909                                         const X86Subtarget* Subtarget,
10910                                         SelectionDAG &DAG) {
10911   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10912   SDValue V1 = SVOp->getOperand(0);
10913   SDValue V2 = SVOp->getOperand(1);
10914   SDLoc dl(SVOp);
10915   ArrayRef<int> MaskVals = SVOp->getMask();
10916
10917   // Promote splats to a larger type which usually leads to more efficient code.
10918   // FIXME: Is this true if pshufb is available?
10919   if (SVOp->isSplat())
10920     return PromoteSplat(SVOp, DAG);
10921
10922   // If we have SSSE3, case 1 is generated when all result bytes come from
10923   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
10924   // present, fall back to case 3.
10925
10926   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
10927   if (Subtarget->hasSSSE3()) {
10928     SmallVector<SDValue,16> pshufbMask;
10929
10930     // If all result elements are from one input vector, then only translate
10931     // undef mask values to 0x80 (zero out result) in the pshufb mask.
10932     //
10933     // Otherwise, we have elements from both input vectors, and must zero out
10934     // elements that come from V2 in the first mask, and V1 in the second mask
10935     // so that we can OR them together.
10936     for (unsigned i = 0; i != 16; ++i) {
10937       int EltIdx = MaskVals[i];
10938       if (EltIdx < 0 || EltIdx >= 16)
10939         EltIdx = 0x80;
10940       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
10941     }
10942     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
10943                      DAG.getNode(ISD::BUILD_VECTOR, dl,
10944                                  MVT::v16i8, pshufbMask));
10945
10946     // As PSHUFB will zero elements with negative indices, it's safe to ignore
10947     // the 2nd operand if it's undefined or zero.
10948     if (V2.getOpcode() == ISD::UNDEF ||
10949         ISD::isBuildVectorAllZeros(V2.getNode()))
10950       return V1;
10951
10952     // Calculate the shuffle mask for the second input, shuffle it, and
10953     // OR it with the first shuffled input.
10954     pshufbMask.clear();
10955     for (unsigned i = 0; i != 16; ++i) {
10956       int EltIdx = MaskVals[i];
10957       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
10958       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
10959     }
10960     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
10961                      DAG.getNode(ISD::BUILD_VECTOR, dl,
10962                                  MVT::v16i8, pshufbMask));
10963     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
10964   }
10965
10966   // No SSSE3 - Calculate in place words and then fix all out of place words
10967   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
10968   // the 16 different words that comprise the two doublequadword input vectors.
10969   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10970   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
10971   SDValue NewV = V1;
10972   for (int i = 0; i != 8; ++i) {
10973     int Elt0 = MaskVals[i*2];
10974     int Elt1 = MaskVals[i*2+1];
10975
10976     // This word of the result is all undef, skip it.
10977     if (Elt0 < 0 && Elt1 < 0)
10978       continue;
10979
10980     // This word of the result is already in the correct place, skip it.
10981     if ((Elt0 == i*2) && (Elt1 == i*2+1))
10982       continue;
10983
10984     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
10985     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
10986     SDValue InsElt;
10987
10988     // If Elt0 and Elt1 are defined, are consecutive, and can be load
10989     // using a single extract together, load it and store it.
10990     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
10991       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
10992                            DAG.getIntPtrConstant(Elt1 / 2));
10993       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
10994                         DAG.getIntPtrConstant(i));
10995       continue;
10996     }
10997
10998     // If Elt1 is defined, extract it from the appropriate source.  If the
10999     // source byte is not also odd, shift the extracted word left 8 bits
11000     // otherwise clear the bottom 8 bits if we need to do an or.
11001     if (Elt1 >= 0) {
11002       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11003                            DAG.getIntPtrConstant(Elt1 / 2));
11004       if ((Elt1 & 1) == 0)
11005         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
11006                              DAG.getConstant(8,
11007                                   TLI.getShiftAmountTy(InsElt.getValueType())));
11008       else if (Elt0 >= 0)
11009         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
11010                              DAG.getConstant(0xFF00, MVT::i16));
11011     }
11012     // If Elt0 is defined, extract it from the appropriate source.  If the
11013     // source byte is not also even, shift the extracted word right 8 bits. If
11014     // Elt1 was also defined, OR the extracted values together before
11015     // inserting them in the result.
11016     if (Elt0 >= 0) {
11017       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
11018                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
11019       if ((Elt0 & 1) != 0)
11020         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
11021                               DAG.getConstant(8,
11022                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
11023       else if (Elt1 >= 0)
11024         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
11025                              DAG.getConstant(0x00FF, MVT::i16));
11026       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
11027                          : InsElt0;
11028     }
11029     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11030                        DAG.getIntPtrConstant(i));
11031   }
11032   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
11033 }
11034
11035 // v32i8 shuffles - Translate to VPSHUFB if possible.
11036 static
11037 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
11038                                  const X86Subtarget *Subtarget,
11039                                  SelectionDAG &DAG) {
11040   MVT VT = SVOp->getSimpleValueType(0);
11041   SDValue V1 = SVOp->getOperand(0);
11042   SDValue V2 = SVOp->getOperand(1);
11043   SDLoc dl(SVOp);
11044   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11045
11046   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11047   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
11048   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
11049
11050   // VPSHUFB may be generated if
11051   // (1) one of input vector is undefined or zeroinitializer.
11052   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
11053   // And (2) the mask indexes don't cross the 128-bit lane.
11054   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
11055       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
11056     return SDValue();
11057
11058   if (V1IsAllZero && !V2IsAllZero) {
11059     CommuteVectorShuffleMask(MaskVals, 32);
11060     V1 = V2;
11061   }
11062   return getPSHUFB(MaskVals, V1, dl, DAG);
11063 }
11064
11065 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
11066 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
11067 /// done when every pair / quad of shuffle mask elements point to elements in
11068 /// the right sequence. e.g.
11069 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
11070 static
11071 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
11072                                  SelectionDAG &DAG) {
11073   MVT VT = SVOp->getSimpleValueType(0);
11074   SDLoc dl(SVOp);
11075   unsigned NumElems = VT.getVectorNumElements();
11076   MVT NewVT;
11077   unsigned Scale;
11078   switch (VT.SimpleTy) {
11079   default: llvm_unreachable("Unexpected!");
11080   case MVT::v2i64:
11081   case MVT::v2f64:
11082            return SDValue(SVOp, 0);
11083   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
11084   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
11085   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
11086   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
11087   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
11088   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
11089   }
11090
11091   SmallVector<int, 8> MaskVec;
11092   for (unsigned i = 0; i != NumElems; i += Scale) {
11093     int StartIdx = -1;
11094     for (unsigned j = 0; j != Scale; ++j) {
11095       int EltIdx = SVOp->getMaskElt(i+j);
11096       if (EltIdx < 0)
11097         continue;
11098       if (StartIdx < 0)
11099         StartIdx = (EltIdx / Scale);
11100       if (EltIdx != (int)(StartIdx*Scale + j))
11101         return SDValue();
11102     }
11103     MaskVec.push_back(StartIdx);
11104   }
11105
11106   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
11107   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
11108   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
11109 }
11110
11111 /// getVZextMovL - Return a zero-extending vector move low node.
11112 ///
11113 static SDValue getVZextMovL(MVT VT, MVT OpVT,
11114                             SDValue SrcOp, SelectionDAG &DAG,
11115                             const X86Subtarget *Subtarget, SDLoc dl) {
11116   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
11117     LoadSDNode *LD = nullptr;
11118     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
11119       LD = dyn_cast<LoadSDNode>(SrcOp);
11120     if (!LD) {
11121       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
11122       // instead.
11123       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
11124       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
11125           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11126           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
11127           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
11128         // PR2108
11129         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
11130         return DAG.getNode(ISD::BITCAST, dl, VT,
11131                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11132                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11133                                                    OpVT,
11134                                                    SrcOp.getOperand(0)
11135                                                           .getOperand(0))));
11136       }
11137     }
11138   }
11139
11140   return DAG.getNode(ISD::BITCAST, dl, VT,
11141                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11142                                  DAG.getNode(ISD::BITCAST, dl,
11143                                              OpVT, SrcOp)));
11144 }
11145
11146 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
11147 /// which could not be matched by any known target speficic shuffle
11148 static SDValue
11149 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11150
11151   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
11152   if (NewOp.getNode())
11153     return NewOp;
11154
11155   MVT VT = SVOp->getSimpleValueType(0);
11156
11157   unsigned NumElems = VT.getVectorNumElements();
11158   unsigned NumLaneElems = NumElems / 2;
11159
11160   SDLoc dl(SVOp);
11161   MVT EltVT = VT.getVectorElementType();
11162   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
11163   SDValue Output[2];
11164
11165   SmallVector<int, 16> Mask;
11166   for (unsigned l = 0; l < 2; ++l) {
11167     // Build a shuffle mask for the output, discovering on the fly which
11168     // input vectors to use as shuffle operands (recorded in InputUsed).
11169     // If building a suitable shuffle vector proves too hard, then bail
11170     // out with UseBuildVector set.
11171     bool UseBuildVector = false;
11172     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
11173     unsigned LaneStart = l * NumLaneElems;
11174     for (unsigned i = 0; i != NumLaneElems; ++i) {
11175       // The mask element.  This indexes into the input.
11176       int Idx = SVOp->getMaskElt(i+LaneStart);
11177       if (Idx < 0) {
11178         // the mask element does not index into any input vector.
11179         Mask.push_back(-1);
11180         continue;
11181       }
11182
11183       // The input vector this mask element indexes into.
11184       int Input = Idx / NumLaneElems;
11185
11186       // Turn the index into an offset from the start of the input vector.
11187       Idx -= Input * NumLaneElems;
11188
11189       // Find or create a shuffle vector operand to hold this input.
11190       unsigned OpNo;
11191       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
11192         if (InputUsed[OpNo] == Input)
11193           // This input vector is already an operand.
11194           break;
11195         if (InputUsed[OpNo] < 0) {
11196           // Create a new operand for this input vector.
11197           InputUsed[OpNo] = Input;
11198           break;
11199         }
11200       }
11201
11202       if (OpNo >= array_lengthof(InputUsed)) {
11203         // More than two input vectors used!  Give up on trying to create a
11204         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
11205         UseBuildVector = true;
11206         break;
11207       }
11208
11209       // Add the mask index for the new shuffle vector.
11210       Mask.push_back(Idx + OpNo * NumLaneElems);
11211     }
11212
11213     if (UseBuildVector) {
11214       SmallVector<SDValue, 16> SVOps;
11215       for (unsigned i = 0; i != NumLaneElems; ++i) {
11216         // The mask element.  This indexes into the input.
11217         int Idx = SVOp->getMaskElt(i+LaneStart);
11218         if (Idx < 0) {
11219           SVOps.push_back(DAG.getUNDEF(EltVT));
11220           continue;
11221         }
11222
11223         // The input vector this mask element indexes into.
11224         int Input = Idx / NumElems;
11225
11226         // Turn the index into an offset from the start of the input vector.
11227         Idx -= Input * NumElems;
11228
11229         // Extract the vector element by hand.
11230         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
11231                                     SVOp->getOperand(Input),
11232                                     DAG.getIntPtrConstant(Idx)));
11233       }
11234
11235       // Construct the output using a BUILD_VECTOR.
11236       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
11237     } else if (InputUsed[0] < 0) {
11238       // No input vectors were used! The result is undefined.
11239       Output[l] = DAG.getUNDEF(NVT);
11240     } else {
11241       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
11242                                         (InputUsed[0] % 2) * NumLaneElems,
11243                                         DAG, dl);
11244       // If only one input was used, use an undefined vector for the other.
11245       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
11246         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
11247                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
11248       // At least one input vector was used. Create a new shuffle vector.
11249       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
11250     }
11251
11252     Mask.clear();
11253   }
11254
11255   // Concatenate the result back
11256   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
11257 }
11258
11259 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
11260 /// 4 elements, and match them with several different shuffle types.
11261 static SDValue
11262 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11263   SDValue V1 = SVOp->getOperand(0);
11264   SDValue V2 = SVOp->getOperand(1);
11265   SDLoc dl(SVOp);
11266   MVT VT = SVOp->getSimpleValueType(0);
11267
11268   assert(VT.is128BitVector() && "Unsupported vector size");
11269
11270   std::pair<int, int> Locs[4];
11271   int Mask1[] = { -1, -1, -1, -1 };
11272   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
11273
11274   unsigned NumHi = 0;
11275   unsigned NumLo = 0;
11276   for (unsigned i = 0; i != 4; ++i) {
11277     int Idx = PermMask[i];
11278     if (Idx < 0) {
11279       Locs[i] = std::make_pair(-1, -1);
11280     } else {
11281       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
11282       if (Idx < 4) {
11283         Locs[i] = std::make_pair(0, NumLo);
11284         Mask1[NumLo] = Idx;
11285         NumLo++;
11286       } else {
11287         Locs[i] = std::make_pair(1, NumHi);
11288         if (2+NumHi < 4)
11289           Mask1[2+NumHi] = Idx;
11290         NumHi++;
11291       }
11292     }
11293   }
11294
11295   if (NumLo <= 2 && NumHi <= 2) {
11296     // If no more than two elements come from either vector. This can be
11297     // implemented with two shuffles. First shuffle gather the elements.
11298     // The second shuffle, which takes the first shuffle as both of its
11299     // vector operands, put the elements into the right order.
11300     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11301
11302     int Mask2[] = { -1, -1, -1, -1 };
11303
11304     for (unsigned i = 0; i != 4; ++i)
11305       if (Locs[i].first != -1) {
11306         unsigned Idx = (i < 2) ? 0 : 4;
11307         Idx += Locs[i].first * 2 + Locs[i].second;
11308         Mask2[i] = Idx;
11309       }
11310
11311     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
11312   }
11313
11314   if (NumLo == 3 || NumHi == 3) {
11315     // Otherwise, we must have three elements from one vector, call it X, and
11316     // one element from the other, call it Y.  First, use a shufps to build an
11317     // intermediate vector with the one element from Y and the element from X
11318     // that will be in the same half in the final destination (the indexes don't
11319     // matter). Then, use a shufps to build the final vector, taking the half
11320     // containing the element from Y from the intermediate, and the other half
11321     // from X.
11322     if (NumHi == 3) {
11323       // Normalize it so the 3 elements come from V1.
11324       CommuteVectorShuffleMask(PermMask, 4);
11325       std::swap(V1, V2);
11326     }
11327
11328     // Find the element from V2.
11329     unsigned HiIndex;
11330     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
11331       int Val = PermMask[HiIndex];
11332       if (Val < 0)
11333         continue;
11334       if (Val >= 4)
11335         break;
11336     }
11337
11338     Mask1[0] = PermMask[HiIndex];
11339     Mask1[1] = -1;
11340     Mask1[2] = PermMask[HiIndex^1];
11341     Mask1[3] = -1;
11342     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11343
11344     if (HiIndex >= 2) {
11345       Mask1[0] = PermMask[0];
11346       Mask1[1] = PermMask[1];
11347       Mask1[2] = HiIndex & 1 ? 6 : 4;
11348       Mask1[3] = HiIndex & 1 ? 4 : 6;
11349       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11350     }
11351
11352     Mask1[0] = HiIndex & 1 ? 2 : 0;
11353     Mask1[1] = HiIndex & 1 ? 0 : 2;
11354     Mask1[2] = PermMask[2];
11355     Mask1[3] = PermMask[3];
11356     if (Mask1[2] >= 0)
11357       Mask1[2] += 4;
11358     if (Mask1[3] >= 0)
11359       Mask1[3] += 4;
11360     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
11361   }
11362
11363   // Break it into (shuffle shuffle_hi, shuffle_lo).
11364   int LoMask[] = { -1, -1, -1, -1 };
11365   int HiMask[] = { -1, -1, -1, -1 };
11366
11367   int *MaskPtr = LoMask;
11368   unsigned MaskIdx = 0;
11369   unsigned LoIdx = 0;
11370   unsigned HiIdx = 2;
11371   for (unsigned i = 0; i != 4; ++i) {
11372     if (i == 2) {
11373       MaskPtr = HiMask;
11374       MaskIdx = 1;
11375       LoIdx = 0;
11376       HiIdx = 2;
11377     }
11378     int Idx = PermMask[i];
11379     if (Idx < 0) {
11380       Locs[i] = std::make_pair(-1, -1);
11381     } else if (Idx < 4) {
11382       Locs[i] = std::make_pair(MaskIdx, LoIdx);
11383       MaskPtr[LoIdx] = Idx;
11384       LoIdx++;
11385     } else {
11386       Locs[i] = std::make_pair(MaskIdx, HiIdx);
11387       MaskPtr[HiIdx] = Idx;
11388       HiIdx++;
11389     }
11390   }
11391
11392   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
11393   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
11394   int MaskOps[] = { -1, -1, -1, -1 };
11395   for (unsigned i = 0; i != 4; ++i)
11396     if (Locs[i].first != -1)
11397       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
11398   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
11399 }
11400
11401 static bool MayFoldVectorLoad(SDValue V) {
11402   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
11403     V = V.getOperand(0);
11404
11405   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
11406     V = V.getOperand(0);
11407   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
11408       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
11409     // BUILD_VECTOR (load), undef
11410     V = V.getOperand(0);
11411
11412   return MayFoldLoad(V);
11413 }
11414
11415 static
11416 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
11417   MVT VT = Op.getSimpleValueType();
11418
11419   // Canonizalize to v2f64.
11420   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
11421   return DAG.getNode(ISD::BITCAST, dl, VT,
11422                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
11423                                           V1, DAG));
11424 }
11425
11426 static
11427 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
11428                         bool HasSSE2) {
11429   SDValue V1 = Op.getOperand(0);
11430   SDValue V2 = Op.getOperand(1);
11431   MVT VT = Op.getSimpleValueType();
11432
11433   assert(VT != MVT::v2i64 && "unsupported shuffle type");
11434
11435   if (HasSSE2 && VT == MVT::v2f64)
11436     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
11437
11438   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
11439   return DAG.getNode(ISD::BITCAST, dl, VT,
11440                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
11441                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
11442                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
11443 }
11444
11445 static
11446 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
11447   SDValue V1 = Op.getOperand(0);
11448   SDValue V2 = Op.getOperand(1);
11449   MVT VT = Op.getSimpleValueType();
11450
11451   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
11452          "unsupported shuffle type");
11453
11454   if (V2.getOpcode() == ISD::UNDEF)
11455     V2 = V1;
11456
11457   // v4i32 or v4f32
11458   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
11459 }
11460
11461 static
11462 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
11463   SDValue V1 = Op.getOperand(0);
11464   SDValue V2 = Op.getOperand(1);
11465   MVT VT = Op.getSimpleValueType();
11466   unsigned NumElems = VT.getVectorNumElements();
11467
11468   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
11469   // operand of these instructions is only memory, so check if there's a
11470   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
11471   // same masks.
11472   bool CanFoldLoad = false;
11473
11474   // Trivial case, when V2 comes from a load.
11475   if (MayFoldVectorLoad(V2))
11476     CanFoldLoad = true;
11477
11478   // When V1 is a load, it can be folded later into a store in isel, example:
11479   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
11480   //    turns into:
11481   //  (MOVLPSmr addr:$src1, VR128:$src2)
11482   // So, recognize this potential and also use MOVLPS or MOVLPD
11483   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
11484     CanFoldLoad = true;
11485
11486   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11487   if (CanFoldLoad) {
11488     if (HasSSE2 && NumElems == 2)
11489       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
11490
11491     if (NumElems == 4)
11492       // If we don't care about the second element, proceed to use movss.
11493       if (SVOp->getMaskElt(1) != -1)
11494         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
11495   }
11496
11497   // movl and movlp will both match v2i64, but v2i64 is never matched by
11498   // movl earlier because we make it strict to avoid messing with the movlp load
11499   // folding logic (see the code above getMOVLP call). Match it here then,
11500   // this is horrible, but will stay like this until we move all shuffle
11501   // matching to x86 specific nodes. Note that for the 1st condition all
11502   // types are matched with movsd.
11503   if (HasSSE2) {
11504     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
11505     // as to remove this logic from here, as much as possible
11506     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
11507       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
11508     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
11509   }
11510
11511   assert(VT != MVT::v4i32 && "unsupported shuffle type");
11512
11513   // Invert the operand order and use SHUFPS to match it.
11514   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
11515                               getShuffleSHUFImmediate(SVOp), DAG);
11516 }
11517
11518 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
11519                                          SelectionDAG &DAG) {
11520   SDLoc dl(Load);
11521   MVT VT = Load->getSimpleValueType(0);
11522   MVT EVT = VT.getVectorElementType();
11523   SDValue Addr = Load->getOperand(1);
11524   SDValue NewAddr = DAG.getNode(
11525       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
11526       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
11527
11528   SDValue NewLoad =
11529       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
11530                   DAG.getMachineFunction().getMachineMemOperand(
11531                       Load->getMemOperand(), 0, EVT.getStoreSize()));
11532   return NewLoad;
11533 }
11534
11535 // It is only safe to call this function if isINSERTPSMask is true for
11536 // this shufflevector mask.
11537 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
11538                            SelectionDAG &DAG) {
11539   // Generate an insertps instruction when inserting an f32 from memory onto a
11540   // v4f32 or when copying a member from one v4f32 to another.
11541   // We also use it for transferring i32 from one register to another,
11542   // since it simply copies the same bits.
11543   // If we're transferring an i32 from memory to a specific element in a
11544   // register, we output a generic DAG that will match the PINSRD
11545   // instruction.
11546   MVT VT = SVOp->getSimpleValueType(0);
11547   MVT EVT = VT.getVectorElementType();
11548   SDValue V1 = SVOp->getOperand(0);
11549   SDValue V2 = SVOp->getOperand(1);
11550   auto Mask = SVOp->getMask();
11551   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
11552          "unsupported vector type for insertps/pinsrd");
11553
11554   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
11555   auto FromV2Predicate = [](const int &i) { return i >= 4; };
11556   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
11557
11558   SDValue From;
11559   SDValue To;
11560   unsigned DestIndex;
11561   if (FromV1 == 1) {
11562     From = V1;
11563     To = V2;
11564     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
11565                 Mask.begin();
11566
11567     // If we have 1 element from each vector, we have to check if we're
11568     // changing V1's element's place. If so, we're done. Otherwise, we
11569     // should assume we're changing V2's element's place and behave
11570     // accordingly.
11571     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
11572     assert(DestIndex <= INT32_MAX && "truncated destination index");
11573     if (FromV1 == FromV2 &&
11574         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
11575       From = V2;
11576       To = V1;
11577       DestIndex =
11578           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
11579     }
11580   } else {
11581     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
11582            "More than one element from V1 and from V2, or no elements from one "
11583            "of the vectors. This case should not have returned true from "
11584            "isINSERTPSMask");
11585     From = V2;
11586     To = V1;
11587     DestIndex =
11588         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
11589   }
11590
11591   // Get an index into the source vector in the range [0,4) (the mask is
11592   // in the range [0,8) because it can address V1 and V2)
11593   unsigned SrcIndex = Mask[DestIndex] % 4;
11594   if (MayFoldLoad(From)) {
11595     // Trivial case, when From comes from a load and is only used by the
11596     // shuffle. Make it use insertps from the vector that we need from that
11597     // load.
11598     SDValue NewLoad =
11599         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
11600     if (!NewLoad.getNode())
11601       return SDValue();
11602
11603     if (EVT == MVT::f32) {
11604       // Create this as a scalar to vector to match the instruction pattern.
11605       SDValue LoadScalarToVector =
11606           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
11607       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
11608       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
11609                          InsertpsMask);
11610     } else { // EVT == MVT::i32
11611       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
11612       // instruction, to match the PINSRD instruction, which loads an i32 to a
11613       // certain vector element.
11614       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
11615                          DAG.getConstant(DestIndex, MVT::i32));
11616     }
11617   }
11618
11619   // Vector-element-to-vector
11620   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
11621   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
11622 }
11623
11624 // Reduce a vector shuffle to zext.
11625 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
11626                                     SelectionDAG &DAG) {
11627   // PMOVZX is only available from SSE41.
11628   if (!Subtarget->hasSSE41())
11629     return SDValue();
11630
11631   MVT VT = Op.getSimpleValueType();
11632
11633   // Only AVX2 support 256-bit vector integer extending.
11634   if (!Subtarget->hasInt256() && VT.is256BitVector())
11635     return SDValue();
11636
11637   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11638   SDLoc DL(Op);
11639   SDValue V1 = Op.getOperand(0);
11640   SDValue V2 = Op.getOperand(1);
11641   unsigned NumElems = VT.getVectorNumElements();
11642
11643   // Extending is an unary operation and the element type of the source vector
11644   // won't be equal to or larger than i64.
11645   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
11646       VT.getVectorElementType() == MVT::i64)
11647     return SDValue();
11648
11649   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
11650   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
11651   while ((1U << Shift) < NumElems) {
11652     if (SVOp->getMaskElt(1U << Shift) == 1)
11653       break;
11654     Shift += 1;
11655     // The maximal ratio is 8, i.e. from i8 to i64.
11656     if (Shift > 3)
11657       return SDValue();
11658   }
11659
11660   // Check the shuffle mask.
11661   unsigned Mask = (1U << Shift) - 1;
11662   for (unsigned i = 0; i != NumElems; ++i) {
11663     int EltIdx = SVOp->getMaskElt(i);
11664     if ((i & Mask) != 0 && EltIdx != -1)
11665       return SDValue();
11666     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
11667       return SDValue();
11668   }
11669
11670   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
11671   MVT NeVT = MVT::getIntegerVT(NBits);
11672   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
11673
11674   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
11675     return SDValue();
11676
11677   return DAG.getNode(ISD::BITCAST, DL, VT,
11678                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
11679 }
11680
11681 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11682                                       SelectionDAG &DAG) {
11683   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11684   MVT VT = Op.getSimpleValueType();
11685   SDLoc dl(Op);
11686   SDValue V1 = Op.getOperand(0);
11687   SDValue V2 = Op.getOperand(1);
11688
11689   if (isZeroShuffle(SVOp))
11690     return getZeroVector(VT, Subtarget, DAG, dl);
11691
11692   // Handle splat operations
11693   if (SVOp->isSplat()) {
11694     // Use vbroadcast whenever the splat comes from a foldable load
11695     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
11696     if (Broadcast.getNode())
11697       return Broadcast;
11698   }
11699
11700   // Check integer expanding shuffles.
11701   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
11702   if (NewOp.getNode())
11703     return NewOp;
11704
11705   // If the shuffle can be profitably rewritten as a narrower shuffle, then
11706   // do it!
11707   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
11708       VT == MVT::v32i8) {
11709     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
11710     if (NewOp.getNode())
11711       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
11712   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
11713     // FIXME: Figure out a cleaner way to do this.
11714     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
11715       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
11716       if (NewOp.getNode()) {
11717         MVT NewVT = NewOp.getSimpleValueType();
11718         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
11719                                NewVT, true, false))
11720           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
11721                               dl);
11722       }
11723     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
11724       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
11725       if (NewOp.getNode()) {
11726         MVT NewVT = NewOp.getSimpleValueType();
11727         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
11728           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
11729                               dl);
11730       }
11731     }
11732   }
11733   return SDValue();
11734 }
11735
11736 SDValue
11737 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
11738   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11739   SDValue V1 = Op.getOperand(0);
11740   SDValue V2 = Op.getOperand(1);
11741   MVT VT = Op.getSimpleValueType();
11742   SDLoc dl(Op);
11743   unsigned NumElems = VT.getVectorNumElements();
11744   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11745   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11746   bool V1IsSplat = false;
11747   bool V2IsSplat = false;
11748   bool HasSSE2 = Subtarget->hasSSE2();
11749   bool HasFp256    = Subtarget->hasFp256();
11750   bool HasInt256   = Subtarget->hasInt256();
11751   MachineFunction &MF = DAG.getMachineFunction();
11752   bool OptForSize = MF.getFunction()->getAttributes().
11753     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
11754
11755   // Check if we should use the experimental vector shuffle lowering. If so,
11756   // delegate completely to that code path.
11757   if (ExperimentalVectorShuffleLowering)
11758     return lowerVectorShuffle(Op, Subtarget, DAG);
11759
11760   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
11761
11762   if (V1IsUndef && V2IsUndef)
11763     return DAG.getUNDEF(VT);
11764
11765   // When we create a shuffle node we put the UNDEF node to second operand,
11766   // but in some cases the first operand may be transformed to UNDEF.
11767   // In this case we should just commute the node.
11768   if (V1IsUndef)
11769     return DAG.getCommutedVectorShuffle(*SVOp);
11770
11771   // Vector shuffle lowering takes 3 steps:
11772   //
11773   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
11774   //    narrowing and commutation of operands should be handled.
11775   // 2) Matching of shuffles with known shuffle masks to x86 target specific
11776   //    shuffle nodes.
11777   // 3) Rewriting of unmatched masks into new generic shuffle operations,
11778   //    so the shuffle can be broken into other shuffles and the legalizer can
11779   //    try the lowering again.
11780   //
11781   // The general idea is that no vector_shuffle operation should be left to
11782   // be matched during isel, all of them must be converted to a target specific
11783   // node here.
11784
11785   // Normalize the input vectors. Here splats, zeroed vectors, profitable
11786   // narrowing and commutation of operands should be handled. The actual code
11787   // doesn't include all of those, work in progress...
11788   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
11789   if (NewOp.getNode())
11790     return NewOp;
11791
11792   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
11793
11794   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
11795   // unpckh_undef). Only use pshufd if speed is more important than size.
11796   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
11797     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
11798   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
11799     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
11800
11801   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
11802       V2IsUndef && MayFoldVectorLoad(V1))
11803     return getMOVDDup(Op, dl, V1, DAG);
11804
11805   if (isMOVHLPS_v_undef_Mask(M, VT))
11806     return getMOVHighToLow(Op, dl, DAG);
11807
11808   // Use to match splats
11809   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
11810       (VT == MVT::v2f64 || VT == MVT::v2i64))
11811     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
11812
11813   if (isPSHUFDMask(M, VT)) {
11814     // The actual implementation will match the mask in the if above and then
11815     // during isel it can match several different instructions, not only pshufd
11816     // as its name says, sad but true, emulate the behavior for now...
11817     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
11818       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
11819
11820     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
11821
11822     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
11823       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
11824
11825     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
11826       return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1, TargetMask,
11827                                   DAG);
11828
11829     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
11830                                 TargetMask, DAG);
11831   }
11832
11833   if (isPALIGNRMask(M, VT, Subtarget))
11834     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
11835                                 getShufflePALIGNRImmediate(SVOp),
11836                                 DAG);
11837
11838   if (isVALIGNMask(M, VT, Subtarget))
11839     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
11840                                 getShuffleVALIGNImmediate(SVOp),
11841                                 DAG);
11842
11843   // Check if this can be converted into a logical shift.
11844   bool isLeft = false;
11845   unsigned ShAmt = 0;
11846   SDValue ShVal;
11847   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
11848   if (isShift && ShVal.hasOneUse()) {
11849     // If the shifted value has multiple uses, it may be cheaper to use
11850     // v_set0 + movlhps or movhlps, etc.
11851     MVT EltVT = VT.getVectorElementType();
11852     ShAmt *= EltVT.getSizeInBits();
11853     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
11854   }
11855
11856   if (isMOVLMask(M, VT)) {
11857     if (ISD::isBuildVectorAllZeros(V1.getNode()))
11858       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
11859     if (!isMOVLPMask(M, VT)) {
11860       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
11861         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
11862
11863       if (VT == MVT::v4i32 || VT == MVT::v4f32)
11864         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
11865     }
11866   }
11867
11868   // FIXME: fold these into legal mask.
11869   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
11870     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
11871
11872   if (isMOVHLPSMask(M, VT))
11873     return getMOVHighToLow(Op, dl, DAG);
11874
11875   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
11876     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
11877
11878   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
11879     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
11880
11881   if (isMOVLPMask(M, VT))
11882     return getMOVLP(Op, dl, DAG, HasSSE2);
11883
11884   if (ShouldXformToMOVHLPS(M, VT) ||
11885       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
11886     return DAG.getCommutedVectorShuffle(*SVOp);
11887
11888   if (isShift) {
11889     // No better options. Use a vshldq / vsrldq.
11890     MVT EltVT = VT.getVectorElementType();
11891     ShAmt *= EltVT.getSizeInBits();
11892     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
11893   }
11894
11895   bool Commuted = false;
11896   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
11897   // 1,1,1,1 -> v8i16 though.
11898   BitVector UndefElements;
11899   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
11900     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
11901       V1IsSplat = true;
11902   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
11903     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
11904       V2IsSplat = true;
11905
11906   // Canonicalize the splat or undef, if present, to be on the RHS.
11907   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
11908     CommuteVectorShuffleMask(M, NumElems);
11909     std::swap(V1, V2);
11910     std::swap(V1IsSplat, V2IsSplat);
11911     Commuted = true;
11912   }
11913
11914   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
11915     // Shuffling low element of v1 into undef, just return v1.
11916     if (V2IsUndef)
11917       return V1;
11918     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
11919     // the instruction selector will not match, so get a canonical MOVL with
11920     // swapped operands to undo the commute.
11921     return getMOVL(DAG, dl, VT, V2, V1);
11922   }
11923
11924   if (isUNPCKLMask(M, VT, HasInt256))
11925     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
11926
11927   if (isUNPCKHMask(M, VT, HasInt256))
11928     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
11929
11930   if (V2IsSplat) {
11931     // Normalize mask so all entries that point to V2 points to its first
11932     // element then try to match unpck{h|l} again. If match, return a
11933     // new vector_shuffle with the corrected mask.p
11934     SmallVector<int, 8> NewMask(M.begin(), M.end());
11935     NormalizeMask(NewMask, NumElems);
11936     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
11937       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
11938     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
11939       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
11940   }
11941
11942   if (Commuted) {
11943     // Commute is back and try unpck* again.
11944     // FIXME: this seems wrong.
11945     CommuteVectorShuffleMask(M, NumElems);
11946     std::swap(V1, V2);
11947     std::swap(V1IsSplat, V2IsSplat);
11948
11949     if (isUNPCKLMask(M, VT, HasInt256))
11950       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
11951
11952     if (isUNPCKHMask(M, VT, HasInt256))
11953       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
11954   }
11955
11956   // Normalize the node to match x86 shuffle ops if needed
11957   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
11958     return DAG.getCommutedVectorShuffle(*SVOp);
11959
11960   // The checks below are all present in isShuffleMaskLegal, but they are
11961   // inlined here right now to enable us to directly emit target specific
11962   // nodes, and remove one by one until they don't return Op anymore.
11963
11964   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
11965       SVOp->getSplatIndex() == 0 && V2IsUndef) {
11966     if (VT == MVT::v2f64 || VT == MVT::v2i64)
11967       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
11968   }
11969
11970   if (isPSHUFHWMask(M, VT, HasInt256))
11971     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
11972                                 getShufflePSHUFHWImmediate(SVOp),
11973                                 DAG);
11974
11975   if (isPSHUFLWMask(M, VT, HasInt256))
11976     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
11977                                 getShufflePSHUFLWImmediate(SVOp),
11978                                 DAG);
11979
11980   unsigned MaskValue;
11981   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
11982                   &MaskValue))
11983     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
11984
11985   if (isSHUFPMask(M, VT))
11986     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
11987                                 getShuffleSHUFImmediate(SVOp), DAG);
11988
11989   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
11990     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
11991   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
11992     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
11993
11994   //===--------------------------------------------------------------------===//
11995   // Generate target specific nodes for 128 or 256-bit shuffles only
11996   // supported in the AVX instruction set.
11997   //
11998
11999   // Handle VMOVDDUPY permutations
12000   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
12001     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
12002
12003   // Handle VPERMILPS/D* permutations
12004   if (isVPERMILPMask(M, VT)) {
12005     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
12006       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
12007                                   getShuffleSHUFImmediate(SVOp), DAG);
12008     return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1,
12009                                 getShuffleSHUFImmediate(SVOp), DAG);
12010   }
12011
12012   unsigned Idx;
12013   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
12014     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
12015                               Idx*(NumElems/2), DAG, dl);
12016
12017   // Handle VPERM2F128/VPERM2I128 permutations
12018   if (isVPERM2X128Mask(M, VT, HasFp256))
12019     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
12020                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
12021
12022   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
12023     return getINSERTPS(SVOp, dl, DAG);
12024
12025   unsigned Imm8;
12026   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
12027     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
12028
12029   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
12030       VT.is512BitVector()) {
12031     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
12032     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
12033     SmallVector<SDValue, 16> permclMask;
12034     for (unsigned i = 0; i != NumElems; ++i) {
12035       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
12036     }
12037
12038     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
12039     if (V2IsUndef)
12040       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
12041       return DAG.getNode(X86ISD::VPERMV, dl, VT,
12042                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
12043     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
12044                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
12045   }
12046
12047   //===--------------------------------------------------------------------===//
12048   // Since no target specific shuffle was selected for this generic one,
12049   // lower it into other known shuffles. FIXME: this isn't true yet, but
12050   // this is the plan.
12051   //
12052
12053   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
12054   if (VT == MVT::v8i16) {
12055     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
12056     if (NewOp.getNode())
12057       return NewOp;
12058   }
12059
12060   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
12061     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
12062     if (NewOp.getNode())
12063       return NewOp;
12064   }
12065
12066   if (VT == MVT::v16i8) {
12067     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
12068     if (NewOp.getNode())
12069       return NewOp;
12070   }
12071
12072   if (VT == MVT::v32i8) {
12073     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
12074     if (NewOp.getNode())
12075       return NewOp;
12076   }
12077
12078   // Handle all 128-bit wide vectors with 4 elements, and match them with
12079   // several different shuffle types.
12080   if (NumElems == 4 && VT.is128BitVector())
12081     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
12082
12083   // Handle general 256-bit shuffles
12084   if (VT.is256BitVector())
12085     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
12086
12087   return SDValue();
12088 }
12089
12090 // This function assumes its argument is a BUILD_VECTOR of constants or
12091 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
12092 // true.
12093 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
12094                                     unsigned &MaskValue) {
12095   MaskValue = 0;
12096   unsigned NumElems = BuildVector->getNumOperands();
12097   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
12098   unsigned NumLanes = (NumElems - 1) / 8 + 1;
12099   unsigned NumElemsInLane = NumElems / NumLanes;
12100
12101   // Blend for v16i16 should be symetric for the both lanes.
12102   for (unsigned i = 0; i < NumElemsInLane; ++i) {
12103     SDValue EltCond = BuildVector->getOperand(i);
12104     SDValue SndLaneEltCond =
12105         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
12106
12107     int Lane1Cond = -1, Lane2Cond = -1;
12108     if (isa<ConstantSDNode>(EltCond))
12109       Lane1Cond = !isZero(EltCond);
12110     if (isa<ConstantSDNode>(SndLaneEltCond))
12111       Lane2Cond = !isZero(SndLaneEltCond);
12112
12113     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
12114       // Lane1Cond != 0, means we want the first argument.
12115       // Lane1Cond == 0, means we want the second argument.
12116       // The encoding of this argument is 0 for the first argument, 1
12117       // for the second. Therefore, invert the condition.
12118       MaskValue |= !Lane1Cond << i;
12119     else if (Lane1Cond < 0)
12120       MaskValue |= !Lane2Cond << i;
12121     else
12122       return false;
12123   }
12124   return true;
12125 }
12126
12127 /// \brief Try to lower a VSELECT instruction to an immediate-controlled blend
12128 /// instruction.
12129 static SDValue lowerVSELECTtoBLENDI(SDValue Op, const X86Subtarget *Subtarget,
12130                                     SelectionDAG &DAG) {
12131   SDValue Cond = Op.getOperand(0);
12132   SDValue LHS = Op.getOperand(1);
12133   SDValue RHS = Op.getOperand(2);
12134   SDLoc dl(Op);
12135   MVT VT = Op.getSimpleValueType();
12136   MVT EltVT = VT.getVectorElementType();
12137   unsigned NumElems = VT.getVectorNumElements();
12138
12139   // There is no blend with immediate in AVX-512.
12140   if (VT.is512BitVector())
12141     return SDValue();
12142
12143   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
12144     return SDValue();
12145   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
12146     return SDValue();
12147
12148   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
12149     return SDValue();
12150
12151   // Check the mask for BLEND and build the value.
12152   unsigned MaskValue = 0;
12153   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
12154     return SDValue();
12155
12156   // Convert i32 vectors to floating point if it is not AVX2.
12157   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
12158   MVT BlendVT = VT;
12159   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
12160     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
12161                                NumElems);
12162     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
12163     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
12164   }
12165
12166   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
12167                             DAG.getConstant(MaskValue, MVT::i32));
12168   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
12169 }
12170
12171 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
12172   // A vselect where all conditions and data are constants can be optimized into
12173   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
12174   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
12175       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
12176       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
12177     return SDValue();
12178
12179   SDValue BlendOp = lowerVSELECTtoBLENDI(Op, Subtarget, DAG);
12180   if (BlendOp.getNode())
12181     return BlendOp;
12182
12183   // Some types for vselect were previously set to Expand, not Legal or
12184   // Custom. Return an empty SDValue so we fall-through to Expand, after
12185   // the Custom lowering phase.
12186   MVT VT = Op.getSimpleValueType();
12187   switch (VT.SimpleTy) {
12188   default:
12189     break;
12190   case MVT::v8i16:
12191   case MVT::v16i16:
12192     if (Subtarget->hasBWI() && Subtarget->hasVLX())
12193       break;
12194     return SDValue();
12195   }
12196
12197   // We couldn't create a "Blend with immediate" node.
12198   // This node should still be legal, but we'll have to emit a blendv*
12199   // instruction.
12200   return Op;
12201 }
12202
12203 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
12204   MVT VT = Op.getSimpleValueType();
12205   SDLoc dl(Op);
12206
12207   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
12208     return SDValue();
12209
12210   if (VT.getSizeInBits() == 8) {
12211     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
12212                                   Op.getOperand(0), Op.getOperand(1));
12213     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12214                                   DAG.getValueType(VT));
12215     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12216   }
12217
12218   if (VT.getSizeInBits() == 16) {
12219     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12220     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
12221     if (Idx == 0)
12222       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12223                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12224                                      DAG.getNode(ISD::BITCAST, dl,
12225                                                  MVT::v4i32,
12226                                                  Op.getOperand(0)),
12227                                      Op.getOperand(1)));
12228     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
12229                                   Op.getOperand(0), Op.getOperand(1));
12230     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12231                                   DAG.getValueType(VT));
12232     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12233   }
12234
12235   if (VT == MVT::f32) {
12236     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
12237     // the result back to FR32 register. It's only worth matching if the
12238     // result has a single use which is a store or a bitcast to i32.  And in
12239     // the case of a store, it's not worth it if the index is a constant 0,
12240     // because a MOVSSmr can be used instead, which is smaller and faster.
12241     if (!Op.hasOneUse())
12242       return SDValue();
12243     SDNode *User = *Op.getNode()->use_begin();
12244     if ((User->getOpcode() != ISD::STORE ||
12245          (isa<ConstantSDNode>(Op.getOperand(1)) &&
12246           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
12247         (User->getOpcode() != ISD::BITCAST ||
12248          User->getValueType(0) != MVT::i32))
12249       return SDValue();
12250     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12251                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
12252                                               Op.getOperand(0)),
12253                                               Op.getOperand(1));
12254     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
12255   }
12256
12257   if (VT == MVT::i32 || VT == MVT::i64) {
12258     // ExtractPS/pextrq works with constant index.
12259     if (isa<ConstantSDNode>(Op.getOperand(1)))
12260       return Op;
12261   }
12262   return SDValue();
12263 }
12264
12265 /// Extract one bit from mask vector, like v16i1 or v8i1.
12266 /// AVX-512 feature.
12267 SDValue
12268 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
12269   SDValue Vec = Op.getOperand(0);
12270   SDLoc dl(Vec);
12271   MVT VecVT = Vec.getSimpleValueType();
12272   SDValue Idx = Op.getOperand(1);
12273   MVT EltVT = Op.getSimpleValueType();
12274
12275   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
12276
12277   // variable index can't be handled in mask registers,
12278   // extend vector to VR512
12279   if (!isa<ConstantSDNode>(Idx)) {
12280     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12281     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
12282     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
12283                               ExtVT.getVectorElementType(), Ext, Idx);
12284     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
12285   }
12286
12287   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12288   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12289   unsigned MaxSift = rc->getSize()*8 - 1;
12290   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
12291                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12292   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
12293                     DAG.getConstant(MaxSift, MVT::i8));
12294   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
12295                        DAG.getIntPtrConstant(0));
12296 }
12297
12298 SDValue
12299 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
12300                                            SelectionDAG &DAG) const {
12301   SDLoc dl(Op);
12302   SDValue Vec = Op.getOperand(0);
12303   MVT VecVT = Vec.getSimpleValueType();
12304   SDValue Idx = Op.getOperand(1);
12305
12306   if (Op.getSimpleValueType() == MVT::i1)
12307     return ExtractBitFromMaskVector(Op, DAG);
12308
12309   if (!isa<ConstantSDNode>(Idx)) {
12310     if (VecVT.is512BitVector() ||
12311         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
12312          VecVT.getVectorElementType().getSizeInBits() == 32)) {
12313
12314       MVT MaskEltVT =
12315         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
12316       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
12317                                     MaskEltVT.getSizeInBits());
12318
12319       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
12320       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
12321                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
12322                                 Idx, DAG.getConstant(0, getPointerTy()));
12323       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
12324       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
12325                         Perm, DAG.getConstant(0, getPointerTy()));
12326     }
12327     return SDValue();
12328   }
12329
12330   // If this is a 256-bit vector result, first extract the 128-bit vector and
12331   // then extract the element from the 128-bit vector.
12332   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
12333
12334     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12335     // Get the 128-bit vector.
12336     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
12337     MVT EltVT = VecVT.getVectorElementType();
12338
12339     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
12340
12341     //if (IdxVal >= NumElems/2)
12342     //  IdxVal -= NumElems/2;
12343     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
12344     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
12345                        DAG.getConstant(IdxVal, MVT::i32));
12346   }
12347
12348   assert(VecVT.is128BitVector() && "Unexpected vector length");
12349
12350   if (Subtarget->hasSSE41()) {
12351     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
12352     if (Res.getNode())
12353       return Res;
12354   }
12355
12356   MVT VT = Op.getSimpleValueType();
12357   // TODO: handle v16i8.
12358   if (VT.getSizeInBits() == 16) {
12359     SDValue Vec = Op.getOperand(0);
12360     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12361     if (Idx == 0)
12362       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12363                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12364                                      DAG.getNode(ISD::BITCAST, dl,
12365                                                  MVT::v4i32, Vec),
12366                                      Op.getOperand(1)));
12367     // Transform it so it match pextrw which produces a 32-bit result.
12368     MVT EltVT = MVT::i32;
12369     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
12370                                   Op.getOperand(0), Op.getOperand(1));
12371     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
12372                                   DAG.getValueType(VT));
12373     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12374   }
12375
12376   if (VT.getSizeInBits() == 32) {
12377     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12378     if (Idx == 0)
12379       return Op;
12380
12381     // SHUFPS the element to the lowest double word, then movss.
12382     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
12383     MVT VVT = Op.getOperand(0).getSimpleValueType();
12384     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12385                                        DAG.getUNDEF(VVT), Mask);
12386     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12387                        DAG.getIntPtrConstant(0));
12388   }
12389
12390   if (VT.getSizeInBits() == 64) {
12391     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
12392     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
12393     //        to match extract_elt for f64.
12394     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12395     if (Idx == 0)
12396       return Op;
12397
12398     // UNPCKHPD the element to the lowest double word, then movsd.
12399     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
12400     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
12401     int Mask[2] = { 1, -1 };
12402     MVT VVT = Op.getOperand(0).getSimpleValueType();
12403     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12404                                        DAG.getUNDEF(VVT), Mask);
12405     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12406                        DAG.getIntPtrConstant(0));
12407   }
12408
12409   return SDValue();
12410 }
12411
12412 /// Insert one bit to mask vector, like v16i1 or v8i1.
12413 /// AVX-512 feature.
12414 SDValue 
12415 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
12416   SDLoc dl(Op);
12417   SDValue Vec = Op.getOperand(0);
12418   SDValue Elt = Op.getOperand(1);
12419   SDValue Idx = Op.getOperand(2);
12420   MVT VecVT = Vec.getSimpleValueType();
12421
12422   if (!isa<ConstantSDNode>(Idx)) {
12423     // Non constant index. Extend source and destination,
12424     // insert element and then truncate the result.
12425     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12426     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
12427     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
12428       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
12429       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
12430     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
12431   }
12432
12433   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12434   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
12435   if (Vec.getOpcode() == ISD::UNDEF)
12436     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12437                        DAG.getConstant(IdxVal, MVT::i8));
12438   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12439   unsigned MaxSift = rc->getSize()*8 - 1;
12440   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12441                     DAG.getConstant(MaxSift, MVT::i8));
12442   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
12443                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12444   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
12445 }
12446
12447 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12448                                                   SelectionDAG &DAG) const {
12449   MVT VT = Op.getSimpleValueType();
12450   MVT EltVT = VT.getVectorElementType();
12451
12452   if (EltVT == MVT::i1)
12453     return InsertBitToMaskVector(Op, DAG);
12454
12455   SDLoc dl(Op);
12456   SDValue N0 = Op.getOperand(0);
12457   SDValue N1 = Op.getOperand(1);
12458   SDValue N2 = Op.getOperand(2);
12459   if (!isa<ConstantSDNode>(N2))
12460     return SDValue();
12461   auto *N2C = cast<ConstantSDNode>(N2);
12462   unsigned IdxVal = N2C->getZExtValue();
12463
12464   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
12465   // into that, and then insert the subvector back into the result.
12466   if (VT.is256BitVector() || VT.is512BitVector()) {
12467     // Get the desired 128-bit vector half.
12468     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
12469
12470     // Insert the element into the desired half.
12471     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
12472     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
12473
12474     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
12475                     DAG.getConstant(IdxIn128, MVT::i32));
12476
12477     // Insert the changed part back to the 256-bit vector
12478     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
12479   }
12480   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
12481
12482   if (Subtarget->hasSSE41()) {
12483     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
12484       unsigned Opc;
12485       if (VT == MVT::v8i16) {
12486         Opc = X86ISD::PINSRW;
12487       } else {
12488         assert(VT == MVT::v16i8);
12489         Opc = X86ISD::PINSRB;
12490       }
12491
12492       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
12493       // argument.
12494       if (N1.getValueType() != MVT::i32)
12495         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12496       if (N2.getValueType() != MVT::i32)
12497         N2 = DAG.getIntPtrConstant(IdxVal);
12498       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
12499     }
12500
12501     if (EltVT == MVT::f32) {
12502       // Bits [7:6] of the constant are the source select.  This will always be
12503       //  zero here.  The DAG Combiner may combine an extract_elt index into
12504       //  these
12505       //  bits.  For example (insert (extract, 3), 2) could be matched by
12506       //  putting
12507       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
12508       // Bits [5:4] of the constant are the destination select.  This is the
12509       //  value of the incoming immediate.
12510       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
12511       //   combine either bitwise AND or insert of float 0.0 to set these bits.
12512       N2 = DAG.getIntPtrConstant(IdxVal << 4);
12513       // Create this as a scalar to vector..
12514       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
12515       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
12516     }
12517
12518     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
12519       // PINSR* works with constant index.
12520       return Op;
12521     }
12522   }
12523
12524   if (EltVT == MVT::i8)
12525     return SDValue();
12526
12527   if (EltVT.getSizeInBits() == 16) {
12528     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12529     // as its second argument.
12530     if (N1.getValueType() != MVT::i32)
12531       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12532     if (N2.getValueType() != MVT::i32)
12533       N2 = DAG.getIntPtrConstant(IdxVal);
12534     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12535   }
12536   return SDValue();
12537 }
12538
12539 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12540   SDLoc dl(Op);
12541   MVT OpVT = Op.getSimpleValueType();
12542
12543   // If this is a 256-bit vector result, first insert into a 128-bit
12544   // vector and then insert into the 256-bit vector.
12545   if (!OpVT.is128BitVector()) {
12546     // Insert into a 128-bit vector.
12547     unsigned SizeFactor = OpVT.getSizeInBits()/128;
12548     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12549                                  OpVT.getVectorNumElements() / SizeFactor);
12550
12551     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12552
12553     // Insert the 128-bit vector.
12554     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12555   }
12556
12557   if (OpVT == MVT::v1i64 &&
12558       Op.getOperand(0).getValueType() == MVT::i64)
12559     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12560
12561   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12562   assert(OpVT.is128BitVector() && "Expected an SSE type!");
12563   return DAG.getNode(ISD::BITCAST, dl, OpVT,
12564                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
12565 }
12566
12567 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
12568 // a simple subregister reference or explicit instructions to grab
12569 // upper bits of a vector.
12570 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12571                                       SelectionDAG &DAG) {
12572   SDLoc dl(Op);
12573   SDValue In =  Op.getOperand(0);
12574   SDValue Idx = Op.getOperand(1);
12575   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12576   MVT ResVT   = Op.getSimpleValueType();
12577   MVT InVT    = In.getSimpleValueType();
12578
12579   if (Subtarget->hasFp256()) {
12580     if (ResVT.is128BitVector() &&
12581         (InVT.is256BitVector() || InVT.is512BitVector()) &&
12582         isa<ConstantSDNode>(Idx)) {
12583       return Extract128BitVector(In, IdxVal, DAG, dl);
12584     }
12585     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12586         isa<ConstantSDNode>(Idx)) {
12587       return Extract256BitVector(In, IdxVal, DAG, dl);
12588     }
12589   }
12590   return SDValue();
12591 }
12592
12593 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12594 // simple superregister reference or explicit instructions to insert
12595 // the upper bits of a vector.
12596 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12597                                      SelectionDAG &DAG) {
12598   if (Subtarget->hasFp256()) {
12599     SDLoc dl(Op.getNode());
12600     SDValue Vec = Op.getNode()->getOperand(0);
12601     SDValue SubVec = Op.getNode()->getOperand(1);
12602     SDValue Idx = Op.getNode()->getOperand(2);
12603
12604     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
12605          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
12606         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
12607         isa<ConstantSDNode>(Idx)) {
12608       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12609       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12610     }
12611
12612     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
12613         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
12614         isa<ConstantSDNode>(Idx)) {
12615       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12616       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12617     }
12618   }
12619   return SDValue();
12620 }
12621
12622 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12623 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12624 // one of the above mentioned nodes. It has to be wrapped because otherwise
12625 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12626 // be used to form addressing mode. These wrapped nodes will be selected
12627 // into MOV32ri.
12628 SDValue
12629 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12630   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12631
12632   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12633   // global base reg.
12634   unsigned char OpFlag = 0;
12635   unsigned WrapperKind = X86ISD::Wrapper;
12636   CodeModel::Model M = DAG.getTarget().getCodeModel();
12637
12638   if (Subtarget->isPICStyleRIPRel() &&
12639       (M == CodeModel::Small || M == CodeModel::Kernel))
12640     WrapperKind = X86ISD::WrapperRIP;
12641   else if (Subtarget->isPICStyleGOT())
12642     OpFlag = X86II::MO_GOTOFF;
12643   else if (Subtarget->isPICStyleStubPIC())
12644     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12645
12646   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
12647                                              CP->getAlignment(),
12648                                              CP->getOffset(), OpFlag);
12649   SDLoc DL(CP);
12650   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
12651   // With PIC, the address is actually $g + Offset.
12652   if (OpFlag) {
12653     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12654                          DAG.getNode(X86ISD::GlobalBaseReg,
12655                                      SDLoc(), getPointerTy()),
12656                          Result);
12657   }
12658
12659   return Result;
12660 }
12661
12662 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12663   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12664
12665   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12666   // global base reg.
12667   unsigned char OpFlag = 0;
12668   unsigned WrapperKind = X86ISD::Wrapper;
12669   CodeModel::Model M = DAG.getTarget().getCodeModel();
12670
12671   if (Subtarget->isPICStyleRIPRel() &&
12672       (M == CodeModel::Small || M == CodeModel::Kernel))
12673     WrapperKind = X86ISD::WrapperRIP;
12674   else if (Subtarget->isPICStyleGOT())
12675     OpFlag = X86II::MO_GOTOFF;
12676   else if (Subtarget->isPICStyleStubPIC())
12677     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12678
12679   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
12680                                           OpFlag);
12681   SDLoc DL(JT);
12682   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
12683
12684   // With PIC, the address is actually $g + Offset.
12685   if (OpFlag)
12686     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12687                          DAG.getNode(X86ISD::GlobalBaseReg,
12688                                      SDLoc(), getPointerTy()),
12689                          Result);
12690
12691   return Result;
12692 }
12693
12694 SDValue
12695 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12696   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12697
12698   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12699   // global base reg.
12700   unsigned char OpFlag = 0;
12701   unsigned WrapperKind = X86ISD::Wrapper;
12702   CodeModel::Model M = DAG.getTarget().getCodeModel();
12703
12704   if (Subtarget->isPICStyleRIPRel() &&
12705       (M == CodeModel::Small || M == CodeModel::Kernel)) {
12706     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12707       OpFlag = X86II::MO_GOTPCREL;
12708     WrapperKind = X86ISD::WrapperRIP;
12709   } else if (Subtarget->isPICStyleGOT()) {
12710     OpFlag = X86II::MO_GOT;
12711   } else if (Subtarget->isPICStyleStubPIC()) {
12712     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12713   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12714     OpFlag = X86II::MO_DARWIN_NONLAZY;
12715   }
12716
12717   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
12718
12719   SDLoc DL(Op);
12720   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
12721
12722   // With PIC, the address is actually $g + Offset.
12723   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12724       !Subtarget->is64Bit()) {
12725     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12726                          DAG.getNode(X86ISD::GlobalBaseReg,
12727                                      SDLoc(), getPointerTy()),
12728                          Result);
12729   }
12730
12731   // For symbols that require a load from a stub to get the address, emit the
12732   // load.
12733   if (isGlobalStubReference(OpFlag))
12734     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
12735                          MachinePointerInfo::getGOT(), false, false, false, 0);
12736
12737   return Result;
12738 }
12739
12740 SDValue
12741 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12742   // Create the TargetBlockAddressAddress node.
12743   unsigned char OpFlags =
12744     Subtarget->ClassifyBlockAddressReference();
12745   CodeModel::Model M = DAG.getTarget().getCodeModel();
12746   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12747   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12748   SDLoc dl(Op);
12749   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
12750                                              OpFlags);
12751
12752   if (Subtarget->isPICStyleRIPRel() &&
12753       (M == CodeModel::Small || M == CodeModel::Kernel))
12754     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
12755   else
12756     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
12757
12758   // With PIC, the address is actually $g + Offset.
12759   if (isGlobalRelativeToPICBase(OpFlags)) {
12760     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
12761                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
12762                          Result);
12763   }
12764
12765   return Result;
12766 }
12767
12768 SDValue
12769 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12770                                       int64_t Offset, SelectionDAG &DAG) const {
12771   // Create the TargetGlobalAddress node, folding in the constant
12772   // offset if it is legal.
12773   unsigned char OpFlags =
12774       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12775   CodeModel::Model M = DAG.getTarget().getCodeModel();
12776   SDValue Result;
12777   if (OpFlags == X86II::MO_NO_FLAG &&
12778       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12779     // A direct static reference to a global.
12780     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
12781     Offset = 0;
12782   } else {
12783     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
12784   }
12785
12786   if (Subtarget->isPICStyleRIPRel() &&
12787       (M == CodeModel::Small || M == CodeModel::Kernel))
12788     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
12789   else
12790     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
12791
12792   // With PIC, the address is actually $g + Offset.
12793   if (isGlobalRelativeToPICBase(OpFlags)) {
12794     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
12795                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
12796                          Result);
12797   }
12798
12799   // For globals that require a load from a stub to get the address, emit the
12800   // load.
12801   if (isGlobalStubReference(OpFlags))
12802     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
12803                          MachinePointerInfo::getGOT(), false, false, false, 0);
12804
12805   // If there was a non-zero offset that we didn't fold, create an explicit
12806   // addition for it.
12807   if (Offset != 0)
12808     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
12809                          DAG.getConstant(Offset, getPointerTy()));
12810
12811   return Result;
12812 }
12813
12814 SDValue
12815 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12816   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12817   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12818   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12819 }
12820
12821 static SDValue
12822 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12823            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12824            unsigned char OperandFlags, bool LocalDynamic = false) {
12825   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12826   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12827   SDLoc dl(GA);
12828   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12829                                            GA->getValueType(0),
12830                                            GA->getOffset(),
12831                                            OperandFlags);
12832
12833   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12834                                            : X86ISD::TLSADDR;
12835
12836   if (InFlag) {
12837     SDValue Ops[] = { Chain,  TGA, *InFlag };
12838     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12839   } else {
12840     SDValue Ops[]  = { Chain, TGA };
12841     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12842   }
12843
12844   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12845   MFI->setAdjustsStack(true);
12846   MFI->setHasCalls(true);
12847
12848   SDValue Flag = Chain.getValue(1);
12849   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12850 }
12851
12852 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12853 static SDValue
12854 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12855                                 const EVT PtrVT) {
12856   SDValue InFlag;
12857   SDLoc dl(GA);  // ? function entry point might be better
12858   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12859                                    DAG.getNode(X86ISD::GlobalBaseReg,
12860                                                SDLoc(), PtrVT), InFlag);
12861   InFlag = Chain.getValue(1);
12862
12863   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12864 }
12865
12866 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12867 static SDValue
12868 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12869                                 const EVT PtrVT) {
12870   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12871                     X86::RAX, X86II::MO_TLSGD);
12872 }
12873
12874 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12875                                            SelectionDAG &DAG,
12876                                            const EVT PtrVT,
12877                                            bool is64Bit) {
12878   SDLoc dl(GA);
12879
12880   // Get the start address of the TLS block for this module.
12881   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12882       .getInfo<X86MachineFunctionInfo>();
12883   MFI->incNumLocalDynamicTLSAccesses();
12884
12885   SDValue Base;
12886   if (is64Bit) {
12887     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12888                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12889   } else {
12890     SDValue InFlag;
12891     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12892         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12893     InFlag = Chain.getValue(1);
12894     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12895                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12896   }
12897
12898   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12899   // of Base.
12900
12901   // Build x@dtpoff.
12902   unsigned char OperandFlags = X86II::MO_DTPOFF;
12903   unsigned WrapperKind = X86ISD::Wrapper;
12904   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12905                                            GA->getValueType(0),
12906                                            GA->getOffset(), OperandFlags);
12907   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12908
12909   // Add x@dtpoff with the base.
12910   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12911 }
12912
12913 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12914 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12915                                    const EVT PtrVT, TLSModel::Model model,
12916                                    bool is64Bit, bool isPIC) {
12917   SDLoc dl(GA);
12918
12919   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12920   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12921                                                          is64Bit ? 257 : 256));
12922
12923   SDValue ThreadPointer =
12924       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
12925                   MachinePointerInfo(Ptr), false, false, false, 0);
12926
12927   unsigned char OperandFlags = 0;
12928   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12929   // initialexec.
12930   unsigned WrapperKind = X86ISD::Wrapper;
12931   if (model == TLSModel::LocalExec) {
12932     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12933   } else if (model == TLSModel::InitialExec) {
12934     if (is64Bit) {
12935       OperandFlags = X86II::MO_GOTTPOFF;
12936       WrapperKind = X86ISD::WrapperRIP;
12937     } else {
12938       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12939     }
12940   } else {
12941     llvm_unreachable("Unexpected model");
12942   }
12943
12944   // emit "addl x@ntpoff,%eax" (local exec)
12945   // or "addl x@indntpoff,%eax" (initial exec)
12946   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12947   SDValue TGA =
12948       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12949                                  GA->getOffset(), OperandFlags);
12950   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12951
12952   if (model == TLSModel::InitialExec) {
12953     if (isPIC && !is64Bit) {
12954       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12955                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12956                            Offset);
12957     }
12958
12959     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12960                          MachinePointerInfo::getGOT(), false, false, false, 0);
12961   }
12962
12963   // The address of the thread local variable is the add of the thread
12964   // pointer with the offset of the variable.
12965   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12966 }
12967
12968 SDValue
12969 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12970
12971   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12972   const GlobalValue *GV = GA->getGlobal();
12973
12974   if (Subtarget->isTargetELF()) {
12975     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12976
12977     switch (model) {
12978       case TLSModel::GeneralDynamic:
12979         if (Subtarget->is64Bit())
12980           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
12981         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
12982       case TLSModel::LocalDynamic:
12983         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
12984                                            Subtarget->is64Bit());
12985       case TLSModel::InitialExec:
12986       case TLSModel::LocalExec:
12987         return LowerToTLSExecModel(
12988             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
12989             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
12990     }
12991     llvm_unreachable("Unknown TLS model.");
12992   }
12993
12994   if (Subtarget->isTargetDarwin()) {
12995     // Darwin only has one model of TLS.  Lower to that.
12996     unsigned char OpFlag = 0;
12997     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12998                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12999
13000     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13001     // global base reg.
13002     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
13003                  !Subtarget->is64Bit();
13004     if (PIC32)
13005       OpFlag = X86II::MO_TLVP_PIC_BASE;
13006     else
13007       OpFlag = X86II::MO_TLVP;
13008     SDLoc DL(Op);
13009     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
13010                                                 GA->getValueType(0),
13011                                                 GA->getOffset(), OpFlag);
13012     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13013
13014     // With PIC32, the address is actually $g + Offset.
13015     if (PIC32)
13016       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13017                            DAG.getNode(X86ISD::GlobalBaseReg,
13018                                        SDLoc(), getPointerTy()),
13019                            Offset);
13020
13021     // Lowering the machine isd will make sure everything is in the right
13022     // location.
13023     SDValue Chain = DAG.getEntryNode();
13024     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13025     SDValue Args[] = { Chain, Offset };
13026     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
13027
13028     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
13029     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13030     MFI->setAdjustsStack(true);
13031
13032     // And our return value (tls address) is in the standard call return value
13033     // location.
13034     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13035     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
13036                               Chain.getValue(1));
13037   }
13038
13039   if (Subtarget->isTargetKnownWindowsMSVC() ||
13040       Subtarget->isTargetWindowsGNU()) {
13041     // Just use the implicit TLS architecture
13042     // Need to generate someting similar to:
13043     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
13044     //                                  ; from TEB
13045     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
13046     //   mov     rcx, qword [rdx+rcx*8]
13047     //   mov     eax, .tls$:tlsvar
13048     //   [rax+rcx] contains the address
13049     // Windows 64bit: gs:0x58
13050     // Windows 32bit: fs:__tls_array
13051
13052     SDLoc dl(GA);
13053     SDValue Chain = DAG.getEntryNode();
13054
13055     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
13056     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
13057     // use its literal value of 0x2C.
13058     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
13059                                         ? Type::getInt8PtrTy(*DAG.getContext(),
13060                                                              256)
13061                                         : Type::getInt32PtrTy(*DAG.getContext(),
13062                                                               257));
13063
13064     SDValue TlsArray =
13065         Subtarget->is64Bit()
13066             ? DAG.getIntPtrConstant(0x58)
13067             : (Subtarget->isTargetWindowsGNU()
13068                    ? DAG.getIntPtrConstant(0x2C)
13069                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
13070
13071     SDValue ThreadPointer =
13072         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
13073                     MachinePointerInfo(Ptr), false, false, false, 0);
13074
13075     // Load the _tls_index variable
13076     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
13077     if (Subtarget->is64Bit())
13078       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
13079                            IDX, MachinePointerInfo(), MVT::i32,
13080                            false, false, false, 0);
13081     else
13082       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
13083                         false, false, false, 0);
13084
13085     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
13086                                     getPointerTy());
13087     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
13088
13089     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
13090     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
13091                       false, false, false, 0);
13092
13093     // Get the offset of start of .tls section
13094     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13095                                              GA->getValueType(0),
13096                                              GA->getOffset(), X86II::MO_SECREL);
13097     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
13098
13099     // The address of the thread local variable is the add of the thread
13100     // pointer with the offset of the variable.
13101     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
13102   }
13103
13104   llvm_unreachable("TLS not implemented for this target.");
13105 }
13106
13107 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
13108 /// and take a 2 x i32 value to shift plus a shift amount.
13109 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
13110   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
13111   MVT VT = Op.getSimpleValueType();
13112   unsigned VTBits = VT.getSizeInBits();
13113   SDLoc dl(Op);
13114   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
13115   SDValue ShOpLo = Op.getOperand(0);
13116   SDValue ShOpHi = Op.getOperand(1);
13117   SDValue ShAmt  = Op.getOperand(2);
13118   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
13119   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
13120   // during isel.
13121   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13122                                   DAG.getConstant(VTBits - 1, MVT::i8));
13123   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
13124                                      DAG.getConstant(VTBits - 1, MVT::i8))
13125                        : DAG.getConstant(0, VT);
13126
13127   SDValue Tmp2, Tmp3;
13128   if (Op.getOpcode() == ISD::SHL_PARTS) {
13129     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
13130     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
13131   } else {
13132     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
13133     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
13134   }
13135
13136   // If the shift amount is larger or equal than the width of a part we can't
13137   // rely on the results of shld/shrd. Insert a test and select the appropriate
13138   // values for large shift amounts.
13139   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13140                                 DAG.getConstant(VTBits, MVT::i8));
13141   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13142                              AndNode, DAG.getConstant(0, MVT::i8));
13143
13144   SDValue Hi, Lo;
13145   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13146   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
13147   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
13148
13149   if (Op.getOpcode() == ISD::SHL_PARTS) {
13150     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13151     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13152   } else {
13153     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13154     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13155   }
13156
13157   SDValue Ops[2] = { Lo, Hi };
13158   return DAG.getMergeValues(Ops, dl);
13159 }
13160
13161 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
13162                                            SelectionDAG &DAG) const {
13163   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13164
13165   if (SrcVT.isVector())
13166     return SDValue();
13167
13168   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
13169          "Unknown SINT_TO_FP to lower!");
13170
13171   // These are really Legal; return the operand so the caller accepts it as
13172   // Legal.
13173   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
13174     return Op;
13175   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
13176       Subtarget->is64Bit()) {
13177     return Op;
13178   }
13179
13180   SDLoc dl(Op);
13181   unsigned Size = SrcVT.getSizeInBits()/8;
13182   MachineFunction &MF = DAG.getMachineFunction();
13183   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
13184   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13185   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13186                                StackSlot,
13187                                MachinePointerInfo::getFixedStack(SSFI),
13188                                false, false, 0);
13189   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
13190 }
13191
13192 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
13193                                      SDValue StackSlot,
13194                                      SelectionDAG &DAG) const {
13195   // Build the FILD
13196   SDLoc DL(Op);
13197   SDVTList Tys;
13198   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
13199   if (useSSE)
13200     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
13201   else
13202     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
13203
13204   unsigned ByteSize = SrcVT.getSizeInBits()/8;
13205
13206   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
13207   MachineMemOperand *MMO;
13208   if (FI) {
13209     int SSFI = FI->getIndex();
13210     MMO =
13211       DAG.getMachineFunction()
13212       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13213                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
13214   } else {
13215     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
13216     StackSlot = StackSlot.getOperand(1);
13217   }
13218   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
13219   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
13220                                            X86ISD::FILD, DL,
13221                                            Tys, Ops, SrcVT, MMO);
13222
13223   if (useSSE) {
13224     Chain = Result.getValue(1);
13225     SDValue InFlag = Result.getValue(2);
13226
13227     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
13228     // shouldn't be necessary except that RFP cannot be live across
13229     // multiple blocks. When stackifier is fixed, they can be uncoupled.
13230     MachineFunction &MF = DAG.getMachineFunction();
13231     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
13232     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
13233     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13234     Tys = DAG.getVTList(MVT::Other);
13235     SDValue Ops[] = {
13236       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
13237     };
13238     MachineMemOperand *MMO =
13239       DAG.getMachineFunction()
13240       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13241                             MachineMemOperand::MOStore, SSFISize, SSFISize);
13242
13243     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
13244                                     Ops, Op.getValueType(), MMO);
13245     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
13246                          MachinePointerInfo::getFixedStack(SSFI),
13247                          false, false, false, 0);
13248   }
13249
13250   return Result;
13251 }
13252
13253 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
13254 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
13255                                                SelectionDAG &DAG) const {
13256   // This algorithm is not obvious. Here it is what we're trying to output:
13257   /*
13258      movq       %rax,  %xmm0
13259      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
13260      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
13261      #ifdef __SSE3__
13262        haddpd   %xmm0, %xmm0
13263      #else
13264        pshufd   $0x4e, %xmm0, %xmm1
13265        addpd    %xmm1, %xmm0
13266      #endif
13267   */
13268
13269   SDLoc dl(Op);
13270   LLVMContext *Context = DAG.getContext();
13271
13272   // Build some magic constants.
13273   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
13274   Constant *C0 = ConstantDataVector::get(*Context, CV0);
13275   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
13276
13277   SmallVector<Constant*,2> CV1;
13278   CV1.push_back(
13279     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13280                                       APInt(64, 0x4330000000000000ULL))));
13281   CV1.push_back(
13282     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13283                                       APInt(64, 0x4530000000000000ULL))));
13284   Constant *C1 = ConstantVector::get(CV1);
13285   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
13286
13287   // Load the 64-bit value into an XMM register.
13288   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
13289                             Op.getOperand(0));
13290   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
13291                               MachinePointerInfo::getConstantPool(),
13292                               false, false, false, 16);
13293   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
13294                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
13295                               CLod0);
13296
13297   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
13298                               MachinePointerInfo::getConstantPool(),
13299                               false, false, false, 16);
13300   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
13301   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
13302   SDValue Result;
13303
13304   if (Subtarget->hasSSE3()) {
13305     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
13306     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
13307   } else {
13308     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
13309     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
13310                                            S2F, 0x4E, DAG);
13311     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
13312                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
13313                          Sub);
13314   }
13315
13316   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
13317                      DAG.getIntPtrConstant(0));
13318 }
13319
13320 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
13321 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
13322                                                SelectionDAG &DAG) const {
13323   SDLoc dl(Op);
13324   // FP constant to bias correct the final result.
13325   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13326                                    MVT::f64);
13327
13328   // Load the 32-bit value into an XMM register.
13329   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
13330                              Op.getOperand(0));
13331
13332   // Zero out the upper parts of the register.
13333   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
13334
13335   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13336                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
13337                      DAG.getIntPtrConstant(0));
13338
13339   // Or the load with the bias.
13340   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
13341                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13342                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13343                                                    MVT::v2f64, Load)),
13344                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13345                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13346                                                    MVT::v2f64, Bias)));
13347   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13348                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
13349                    DAG.getIntPtrConstant(0));
13350
13351   // Subtract the bias.
13352   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
13353
13354   // Handle final rounding.
13355   EVT DestVT = Op.getValueType();
13356
13357   if (DestVT.bitsLT(MVT::f64))
13358     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
13359                        DAG.getIntPtrConstant(0));
13360   if (DestVT.bitsGT(MVT::f64))
13361     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
13362
13363   // Handle final rounding.
13364   return Sub;
13365 }
13366
13367 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
13368                                      const X86Subtarget &Subtarget) {
13369   // The algorithm is the following:
13370   // #ifdef __SSE4_1__
13371   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13372   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13373   //                                 (uint4) 0x53000000, 0xaa);
13374   // #else
13375   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13376   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13377   // #endif
13378   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13379   //     return (float4) lo + fhi;
13380
13381   SDLoc DL(Op);
13382   SDValue V = Op->getOperand(0);
13383   EVT VecIntVT = V.getValueType();
13384   bool Is128 = VecIntVT == MVT::v4i32;
13385   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
13386   unsigned NumElts = VecIntVT.getVectorNumElements();
13387   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
13388          "Unsupported custom type");
13389   assert(NumElts <= 8 && "The size of the constant array must be fixed");
13390
13391   // In the #idef/#else code, we have in common:
13392   // - The vector of constants:
13393   // -- 0x4b000000
13394   // -- 0x53000000
13395   // - A shift:
13396   // -- v >> 16
13397
13398   // Create the splat vector for 0x4b000000.
13399   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
13400   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
13401                            CstLow, CstLow, CstLow, CstLow};
13402   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13403                                   makeArrayRef(&CstLowArray[0], NumElts));
13404   // Create the splat vector for 0x53000000.
13405   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
13406   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
13407                             CstHigh, CstHigh, CstHigh, CstHigh};
13408   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13409                                    makeArrayRef(&CstHighArray[0], NumElts));
13410
13411   // Create the right shift.
13412   SDValue CstShift = DAG.getConstant(16, MVT::i32);
13413   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
13414                              CstShift, CstShift, CstShift, CstShift};
13415   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13416                                     makeArrayRef(&CstShiftArray[0], NumElts));
13417   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
13418
13419   SDValue Low, High;
13420   if (Subtarget.hasSSE41()) {
13421     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
13422     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13423     SDValue VecCstLowBitcast =
13424         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
13425     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
13426     // Low will be bitcasted right away, so do not bother bitcasting back to its
13427     // original type.
13428     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
13429                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
13430     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13431     //                                 (uint4) 0x53000000, 0xaa);
13432     SDValue VecCstHighBitcast =
13433         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
13434     SDValue VecShiftBitcast =
13435         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
13436     // High will be bitcasted right away, so do not bother bitcasting back to
13437     // its original type.
13438     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
13439                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
13440   } else {
13441     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
13442     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13443                                      CstMask, CstMask, CstMask);
13444     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13445     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13446     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13447
13448     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13449     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13450   }
13451
13452   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13453   SDValue CstFAdd = DAG.getConstantFP(
13454       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
13455   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13456                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13457   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13458                                    makeArrayRef(&CstFAddArray[0], NumElts));
13459
13460   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13461   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
13462   SDValue FHigh =
13463       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13464   //     return (float4) lo + fhi;
13465   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
13466   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13467 }
13468
13469 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13470                                                SelectionDAG &DAG) const {
13471   SDValue N0 = Op.getOperand(0);
13472   MVT SVT = N0.getSimpleValueType();
13473   SDLoc dl(Op);
13474
13475   switch (SVT.SimpleTy) {
13476   default:
13477     llvm_unreachable("Custom UINT_TO_FP is not supported!");
13478   case MVT::v4i8:
13479   case MVT::v4i16:
13480   case MVT::v8i8:
13481   case MVT::v8i16: {
13482     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13483     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13484                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13485   }
13486   case MVT::v4i32:
13487   case MVT::v8i32:
13488     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13489   }
13490   llvm_unreachable(nullptr);
13491 }
13492
13493 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13494                                            SelectionDAG &DAG) const {
13495   SDValue N0 = Op.getOperand(0);
13496   SDLoc dl(Op);
13497
13498   if (Op.getValueType().isVector())
13499     return lowerUINT_TO_FP_vec(Op, DAG);
13500
13501   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13502   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13503   // the optimization here.
13504   if (DAG.SignBitIsZero(N0))
13505     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13506
13507   MVT SrcVT = N0.getSimpleValueType();
13508   MVT DstVT = Op.getSimpleValueType();
13509   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13510     return LowerUINT_TO_FP_i64(Op, DAG);
13511   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13512     return LowerUINT_TO_FP_i32(Op, DAG);
13513   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13514     return SDValue();
13515
13516   // Make a 64-bit buffer, and use it to build an FILD.
13517   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13518   if (SrcVT == MVT::i32) {
13519     SDValue WordOff = DAG.getConstant(4, getPointerTy());
13520     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
13521                                      getPointerTy(), StackSlot, WordOff);
13522     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13523                                   StackSlot, MachinePointerInfo(),
13524                                   false, false, 0);
13525     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
13526                                   OffsetSlot, MachinePointerInfo(),
13527                                   false, false, 0);
13528     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13529     return Fild;
13530   }
13531
13532   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13533   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13534                                StackSlot, MachinePointerInfo(),
13535                                false, false, 0);
13536   // For i64 source, we need to add the appropriate power of 2 if the input
13537   // was negative.  This is the same as the optimization in
13538   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13539   // we must be careful to do the computation in x87 extended precision, not
13540   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13541   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13542   MachineMemOperand *MMO =
13543     DAG.getMachineFunction()
13544     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13545                           MachineMemOperand::MOLoad, 8, 8);
13546
13547   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13548   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13549   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13550                                          MVT::i64, MMO);
13551
13552   APInt FF(32, 0x5F800000ULL);
13553
13554   // Check whether the sign bit is set.
13555   SDValue SignSet = DAG.getSetCC(dl,
13556                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
13557                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
13558                                  ISD::SETLT);
13559
13560   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13561   SDValue FudgePtr = DAG.getConstantPool(
13562                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
13563                                          getPointerTy());
13564
13565   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13566   SDValue Zero = DAG.getIntPtrConstant(0);
13567   SDValue Four = DAG.getIntPtrConstant(4);
13568   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13569                                Zero, Four);
13570   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
13571
13572   // Load the value out, extending it from f32 to f80.
13573   // FIXME: Avoid the extend by constructing the right constant pool?
13574   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
13575                                  FudgePtr, MachinePointerInfo::getConstantPool(),
13576                                  MVT::f32, false, false, false, 4);
13577   // Extend everything to 80 bits to force it to be done on x87.
13578   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13579   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
13580 }
13581
13582 std::pair<SDValue,SDValue>
13583 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13584                                     bool IsSigned, bool IsReplace) const {
13585   SDLoc DL(Op);
13586
13587   EVT DstTy = Op.getValueType();
13588
13589   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
13590     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13591     DstTy = MVT::i64;
13592   }
13593
13594   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13595          DstTy.getSimpleVT() >= MVT::i16 &&
13596          "Unknown FP_TO_INT to lower!");
13597
13598   // These are really Legal.
13599   if (DstTy == MVT::i32 &&
13600       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13601     return std::make_pair(SDValue(), SDValue());
13602   if (Subtarget->is64Bit() &&
13603       DstTy == MVT::i64 &&
13604       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13605     return std::make_pair(SDValue(), SDValue());
13606
13607   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
13608   // stack slot, or into the FTOL runtime function.
13609   MachineFunction &MF = DAG.getMachineFunction();
13610   unsigned MemSize = DstTy.getSizeInBits()/8;
13611   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13612   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13613
13614   unsigned Opc;
13615   if (!IsSigned && isIntegerTypeFTOL(DstTy))
13616     Opc = X86ISD::WIN_FTOL;
13617   else
13618     switch (DstTy.getSimpleVT().SimpleTy) {
13619     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13620     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13621     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13622     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13623     }
13624
13625   SDValue Chain = DAG.getEntryNode();
13626   SDValue Value = Op.getOperand(0);
13627   EVT TheVT = Op.getOperand(0).getValueType();
13628   // FIXME This causes a redundant load/store if the SSE-class value is already
13629   // in memory, such as if it is on the callstack.
13630   if (isScalarFPTypeInSSEReg(TheVT)) {
13631     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13632     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13633                          MachinePointerInfo::getFixedStack(SSFI),
13634                          false, false, 0);
13635     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13636     SDValue Ops[] = {
13637       Chain, StackSlot, DAG.getValueType(TheVT)
13638     };
13639
13640     MachineMemOperand *MMO =
13641       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13642                               MachineMemOperand::MOLoad, MemSize, MemSize);
13643     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13644     Chain = Value.getValue(1);
13645     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13646     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13647   }
13648
13649   MachineMemOperand *MMO =
13650     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13651                             MachineMemOperand::MOStore, MemSize, MemSize);
13652
13653   if (Opc != X86ISD::WIN_FTOL) {
13654     // Build the FP_TO_INT*_IN_MEM
13655     SDValue Ops[] = { Chain, Value, StackSlot };
13656     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13657                                            Ops, DstTy, MMO);
13658     return std::make_pair(FIST, StackSlot);
13659   } else {
13660     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
13661       DAG.getVTList(MVT::Other, MVT::Glue),
13662       Chain, Value);
13663     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
13664       MVT::i32, ftol.getValue(1));
13665     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
13666       MVT::i32, eax.getValue(2));
13667     SDValue Ops[] = { eax, edx };
13668     SDValue pair = IsReplace
13669       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
13670       : DAG.getMergeValues(Ops, DL);
13671     return std::make_pair(pair, SDValue());
13672   }
13673 }
13674
13675 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13676                               const X86Subtarget *Subtarget) {
13677   MVT VT = Op->getSimpleValueType(0);
13678   SDValue In = Op->getOperand(0);
13679   MVT InVT = In.getSimpleValueType();
13680   SDLoc dl(Op);
13681
13682   // Optimize vectors in AVX mode:
13683   //
13684   //   v8i16 -> v8i32
13685   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13686   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13687   //   Concat upper and lower parts.
13688   //
13689   //   v4i32 -> v4i64
13690   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13691   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13692   //   Concat upper and lower parts.
13693   //
13694
13695   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13696       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13697       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13698     return SDValue();
13699
13700   if (Subtarget->hasInt256())
13701     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13702
13703   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13704   SDValue Undef = DAG.getUNDEF(InVT);
13705   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13706   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13707   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13708
13709   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13710                              VT.getVectorNumElements()/2);
13711
13712   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
13713   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
13714
13715   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13716 }
13717
13718 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13719                                         SelectionDAG &DAG) {
13720   MVT VT = Op->getSimpleValueType(0);
13721   SDValue In = Op->getOperand(0);
13722   MVT InVT = In.getSimpleValueType();
13723   SDLoc DL(Op);
13724   unsigned int NumElts = VT.getVectorNumElements();
13725   if (NumElts != 8 && NumElts != 16)
13726     return SDValue();
13727
13728   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13729     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13730
13731   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
13732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13733   // Now we have only mask extension
13734   assert(InVT.getVectorElementType() == MVT::i1);
13735   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
13736   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
13737   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13738   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13739   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
13740                            MachinePointerInfo::getConstantPool(),
13741                            false, false, false, Alignment);
13742
13743   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
13744   if (VT.is512BitVector())
13745     return Brcst;
13746   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
13747 }
13748
13749 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13750                                SelectionDAG &DAG) {
13751   if (Subtarget->hasFp256()) {
13752     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
13753     if (Res.getNode())
13754       return Res;
13755   }
13756
13757   return SDValue();
13758 }
13759
13760 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13761                                 SelectionDAG &DAG) {
13762   SDLoc DL(Op);
13763   MVT VT = Op.getSimpleValueType();
13764   SDValue In = Op.getOperand(0);
13765   MVT SVT = In.getSimpleValueType();
13766
13767   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13768     return LowerZERO_EXTEND_AVX512(Op, DAG);
13769
13770   if (Subtarget->hasFp256()) {
13771     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
13772     if (Res.getNode())
13773       return Res;
13774   }
13775
13776   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13777          VT.getVectorNumElements() != SVT.getVectorNumElements());
13778   return SDValue();
13779 }
13780
13781 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13782   SDLoc DL(Op);
13783   MVT VT = Op.getSimpleValueType();
13784   SDValue In = Op.getOperand(0);
13785   MVT InVT = In.getSimpleValueType();
13786
13787   if (VT == MVT::i1) {
13788     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13789            "Invalid scalar TRUNCATE operation");
13790     if (InVT.getSizeInBits() >= 32)
13791       return SDValue();
13792     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13793     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13794   }
13795   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13796          "Invalid TRUNCATE operation");
13797
13798   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
13799     if (VT.getVectorElementType().getSizeInBits() >=8)
13800       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13801
13802     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13803     unsigned NumElts = InVT.getVectorNumElements();
13804     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13805     if (InVT.getSizeInBits() < 512) {
13806       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13807       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13808       InVT = ExtVT;
13809     }
13810     
13811     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
13812     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
13813     SDValue CP = DAG.getConstantPool(C, getPointerTy());
13814     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13815     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
13816                            MachinePointerInfo::getConstantPool(),
13817                            false, false, false, Alignment);
13818     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
13819     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13820     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13821   }
13822
13823   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13824     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13825     if (Subtarget->hasInt256()) {
13826       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13827       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
13828       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13829                                 ShufMask);
13830       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13831                          DAG.getIntPtrConstant(0));
13832     }
13833
13834     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13835                                DAG.getIntPtrConstant(0));
13836     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13837                                DAG.getIntPtrConstant(2));
13838     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
13839     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
13840     static const int ShufMask[] = {0, 2, 4, 6};
13841     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13842   }
13843
13844   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13845     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13846     if (Subtarget->hasInt256()) {
13847       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
13848
13849       SmallVector<SDValue,32> pshufbMask;
13850       for (unsigned i = 0; i < 2; ++i) {
13851         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13852         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13853         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13854         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13855         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13856         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13857         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13858         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13859         for (unsigned j = 0; j < 8; ++j)
13860           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13861       }
13862       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13863       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13864       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
13865
13866       static const int ShufMask[] = {0,  2,  -1,  -1};
13867       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13868                                 &ShufMask[0]);
13869       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13870                        DAG.getIntPtrConstant(0));
13871       return DAG.getNode(ISD::BITCAST, DL, VT, In);
13872     }
13873
13874     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13875                                DAG.getIntPtrConstant(0));
13876
13877     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13878                                DAG.getIntPtrConstant(4));
13879
13880     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
13881     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
13882
13883     // The PSHUFB mask:
13884     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13885                                    -1, -1, -1, -1, -1, -1, -1, -1};
13886
13887     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13888     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13889     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13890
13891     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
13892     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
13893
13894     // The MOVLHPS Mask:
13895     static const int ShufMask2[] = {0, 1, 4, 5};
13896     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13897     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
13898   }
13899
13900   // Handle truncation of V256 to V128 using shuffles.
13901   if (!VT.is128BitVector() || !InVT.is256BitVector())
13902     return SDValue();
13903
13904   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13905
13906   unsigned NumElems = VT.getVectorNumElements();
13907   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13908
13909   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13910   // Prepare truncation shuffle mask
13911   for (unsigned i = 0; i != NumElems; ++i)
13912     MaskVec[i] = i * 2;
13913   SDValue V = DAG.getVectorShuffle(NVT, DL,
13914                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
13915                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13916   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13917                      DAG.getIntPtrConstant(0));
13918 }
13919
13920 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13921                                            SelectionDAG &DAG) const {
13922   assert(!Op.getSimpleValueType().isVector());
13923
13924   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13925     /*IsSigned=*/ true, /*IsReplace=*/ false);
13926   SDValue FIST = Vals.first, StackSlot = Vals.second;
13927   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13928   if (!FIST.getNode()) return Op;
13929
13930   if (StackSlot.getNode())
13931     // Load the result.
13932     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13933                        FIST, StackSlot, MachinePointerInfo(),
13934                        false, false, false, 0);
13935
13936   // The node is the result.
13937   return FIST;
13938 }
13939
13940 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13941                                            SelectionDAG &DAG) const {
13942   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13943     /*IsSigned=*/ false, /*IsReplace=*/ false);
13944   SDValue FIST = Vals.first, StackSlot = Vals.second;
13945   assert(FIST.getNode() && "Unexpected failure");
13946
13947   if (StackSlot.getNode())
13948     // Load the result.
13949     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13950                        FIST, StackSlot, MachinePointerInfo(),
13951                        false, false, false, 0);
13952
13953   // The node is the result.
13954   return FIST;
13955 }
13956
13957 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13958   SDLoc DL(Op);
13959   MVT VT = Op.getSimpleValueType();
13960   SDValue In = Op.getOperand(0);
13961   MVT SVT = In.getSimpleValueType();
13962
13963   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13964
13965   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13966                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13967                                  In, DAG.getUNDEF(SVT)));
13968 }
13969
13970 /// The only differences between FABS and FNEG are the mask and the logic op.
13971 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13972 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13973   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13974          "Wrong opcode for lowering FABS or FNEG.");
13975
13976   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13977
13978   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13979   // into an FNABS. We'll lower the FABS after that if it is still in use.
13980   if (IsFABS)
13981     for (SDNode *User : Op->uses())
13982       if (User->getOpcode() == ISD::FNEG)
13983         return Op;
13984
13985   SDValue Op0 = Op.getOperand(0);
13986   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13987
13988   SDLoc dl(Op);
13989   MVT VT = Op.getSimpleValueType();
13990   // Assume scalar op for initialization; update for vector if needed.
13991   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
13992   // generate a 16-byte vector constant and logic op even for the scalar case.
13993   // Using a 16-byte mask allows folding the load of the mask with
13994   // the logic op, so it can save (~4 bytes) on code size.
13995   MVT EltVT = VT;
13996   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
13997   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13998   // decide if we should generate a 16-byte constant mask when we only need 4 or
13999   // 8 bytes for the scalar case.
14000   if (VT.isVector()) {
14001     EltVT = VT.getVectorElementType();
14002     NumElts = VT.getVectorNumElements();
14003   }
14004   
14005   unsigned EltBits = EltVT.getSizeInBits();
14006   LLVMContext *Context = DAG.getContext();
14007   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
14008   APInt MaskElt =
14009     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
14010   Constant *C = ConstantInt::get(*Context, MaskElt);
14011   C = ConstantVector::getSplat(NumElts, C);
14012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14013   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
14014   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14015   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14016                              MachinePointerInfo::getConstantPool(),
14017                              false, false, false, Alignment);
14018
14019   if (VT.isVector()) {
14020     // For a vector, cast operands to a vector type, perform the logic op,
14021     // and cast the result back to the original value type.
14022     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
14023     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
14024     SDValue Operand = IsFNABS ?
14025       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
14026       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
14027     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
14028     return DAG.getNode(ISD::BITCAST, dl, VT,
14029                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
14030   }
14031   
14032   // If not vector, then scalar.
14033   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
14034   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
14035   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
14036 }
14037
14038 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
14039   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14040   LLVMContext *Context = DAG.getContext();
14041   SDValue Op0 = Op.getOperand(0);
14042   SDValue Op1 = Op.getOperand(1);
14043   SDLoc dl(Op);
14044   MVT VT = Op.getSimpleValueType();
14045   MVT SrcVT = Op1.getSimpleValueType();
14046
14047   // If second operand is smaller, extend it first.
14048   if (SrcVT.bitsLT(VT)) {
14049     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
14050     SrcVT = VT;
14051   }
14052   // And if it is bigger, shrink it first.
14053   if (SrcVT.bitsGT(VT)) {
14054     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
14055     SrcVT = VT;
14056   }
14057
14058   // At this point the operands and the result should have the same
14059   // type, and that won't be f80 since that is not custom lowered.
14060
14061   // First get the sign bit of second operand.
14062   SmallVector<Constant*,4> CV;
14063   if (SrcVT == MVT::f64) {
14064     const fltSemantics &Sem = APFloat::IEEEdouble;
14065     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
14066     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
14067   } else {
14068     const fltSemantics &Sem = APFloat::IEEEsingle;
14069     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
14070     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14071     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14072     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14073   }
14074   Constant *C = ConstantVector::get(CV);
14075   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14076   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
14077                               MachinePointerInfo::getConstantPool(),
14078                               false, false, false, 16);
14079   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
14080
14081   // Shift sign bit right or left if the two operands have different types.
14082   if (SrcVT.bitsGT(VT)) {
14083     // Op0 is MVT::f32, Op1 is MVT::f64.
14084     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
14085     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
14086                           DAG.getConstant(32, MVT::i32));
14087     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
14088     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
14089                           DAG.getIntPtrConstant(0));
14090   }
14091
14092   // Clear first operand sign bit.
14093   CV.clear();
14094   if (VT == MVT::f64) {
14095     const fltSemantics &Sem = APFloat::IEEEdouble;
14096     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
14097                                                    APInt(64, ~(1ULL << 63)))));
14098     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
14099   } else {
14100     const fltSemantics &Sem = APFloat::IEEEsingle;
14101     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
14102                                                    APInt(32, ~(1U << 31)))));
14103     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14104     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14105     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14106   }
14107   C = ConstantVector::get(CV);
14108   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14109   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14110                               MachinePointerInfo::getConstantPool(),
14111                               false, false, false, 16);
14112   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
14113
14114   // Or the value with the sign bit.
14115   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
14116 }
14117
14118 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
14119   SDValue N0 = Op.getOperand(0);
14120   SDLoc dl(Op);
14121   MVT VT = Op.getSimpleValueType();
14122
14123   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
14124   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
14125                                   DAG.getConstant(1, VT));
14126   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
14127 }
14128
14129 // Check whether an OR'd tree is PTEST-able.
14130 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
14131                                       SelectionDAG &DAG) {
14132   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
14133
14134   if (!Subtarget->hasSSE41())
14135     return SDValue();
14136
14137   if (!Op->hasOneUse())
14138     return SDValue();
14139
14140   SDNode *N = Op.getNode();
14141   SDLoc DL(N);
14142
14143   SmallVector<SDValue, 8> Opnds;
14144   DenseMap<SDValue, unsigned> VecInMap;
14145   SmallVector<SDValue, 8> VecIns;
14146   EVT VT = MVT::Other;
14147
14148   // Recognize a special case where a vector is casted into wide integer to
14149   // test all 0s.
14150   Opnds.push_back(N->getOperand(0));
14151   Opnds.push_back(N->getOperand(1));
14152
14153   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14154     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
14155     // BFS traverse all OR'd operands.
14156     if (I->getOpcode() == ISD::OR) {
14157       Opnds.push_back(I->getOperand(0));
14158       Opnds.push_back(I->getOperand(1));
14159       // Re-evaluate the number of nodes to be traversed.
14160       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14161       continue;
14162     }
14163
14164     // Quit if a non-EXTRACT_VECTOR_ELT
14165     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14166       return SDValue();
14167
14168     // Quit if without a constant index.
14169     SDValue Idx = I->getOperand(1);
14170     if (!isa<ConstantSDNode>(Idx))
14171       return SDValue();
14172
14173     SDValue ExtractedFromVec = I->getOperand(0);
14174     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
14175     if (M == VecInMap.end()) {
14176       VT = ExtractedFromVec.getValueType();
14177       // Quit if not 128/256-bit vector.
14178       if (!VT.is128BitVector() && !VT.is256BitVector())
14179         return SDValue();
14180       // Quit if not the same type.
14181       if (VecInMap.begin() != VecInMap.end() &&
14182           VT != VecInMap.begin()->first.getValueType())
14183         return SDValue();
14184       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
14185       VecIns.push_back(ExtractedFromVec);
14186     }
14187     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14188   }
14189
14190   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14191          "Not extracted from 128-/256-bit vector.");
14192
14193   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
14194
14195   for (DenseMap<SDValue, unsigned>::const_iterator
14196         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
14197     // Quit if not all elements are used.
14198     if (I->second != FullMask)
14199       return SDValue();
14200   }
14201
14202   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
14203
14204   // Cast all vectors into TestVT for PTEST.
14205   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
14206     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
14207
14208   // If more than one full vectors are evaluated, OR them first before PTEST.
14209   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
14210     // Each iteration will OR 2 nodes and append the result until there is only
14211     // 1 node left, i.e. the final OR'd value of all vectors.
14212     SDValue LHS = VecIns[Slot];
14213     SDValue RHS = VecIns[Slot + 1];
14214     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
14215   }
14216
14217   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
14218                      VecIns.back(), VecIns.back());
14219 }
14220
14221 /// \brief return true if \c Op has a use that doesn't just read flags.
14222 static bool hasNonFlagsUse(SDValue Op) {
14223   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
14224        ++UI) {
14225     SDNode *User = *UI;
14226     unsigned UOpNo = UI.getOperandNo();
14227     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
14228       // Look pass truncate.
14229       UOpNo = User->use_begin().getOperandNo();
14230       User = *User->use_begin();
14231     }
14232
14233     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
14234         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
14235       return true;
14236   }
14237   return false;
14238 }
14239
14240 /// Emit nodes that will be selected as "test Op0,Op0", or something
14241 /// equivalent.
14242 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
14243                                     SelectionDAG &DAG) const {
14244   if (Op.getValueType() == MVT::i1)
14245     // KORTEST instruction should be selected
14246     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14247                        DAG.getConstant(0, Op.getValueType()));
14248
14249   // CF and OF aren't always set the way we want. Determine which
14250   // of these we need.
14251   bool NeedCF = false;
14252   bool NeedOF = false;
14253   switch (X86CC) {
14254   default: break;
14255   case X86::COND_A: case X86::COND_AE:
14256   case X86::COND_B: case X86::COND_BE:
14257     NeedCF = true;
14258     break;
14259   case X86::COND_G: case X86::COND_GE:
14260   case X86::COND_L: case X86::COND_LE:
14261   case X86::COND_O: case X86::COND_NO: {
14262     // Check if we really need to set the
14263     // Overflow flag. If NoSignedWrap is present
14264     // that is not actually needed.
14265     switch (Op->getOpcode()) {
14266     case ISD::ADD:
14267     case ISD::SUB:
14268     case ISD::MUL:
14269     case ISD::SHL: {
14270       const BinaryWithFlagsSDNode *BinNode =
14271           cast<BinaryWithFlagsSDNode>(Op.getNode());
14272       if (BinNode->hasNoSignedWrap())
14273         break;
14274     }
14275     default:
14276       NeedOF = true;
14277       break;
14278     }
14279     break;
14280   }
14281   }
14282   // See if we can use the EFLAGS value from the operand instead of
14283   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14284   // we prove that the arithmetic won't overflow, we can't use OF or CF.
14285   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14286     // Emit a CMP with 0, which is the TEST pattern.
14287     //if (Op.getValueType() == MVT::i1)
14288     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14289     //                     DAG.getConstant(0, MVT::i1));
14290     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14291                        DAG.getConstant(0, Op.getValueType()));
14292   }
14293   unsigned Opcode = 0;
14294   unsigned NumOperands = 0;
14295
14296   // Truncate operations may prevent the merge of the SETCC instruction
14297   // and the arithmetic instruction before it. Attempt to truncate the operands
14298   // of the arithmetic instruction and use a reduced bit-width instruction.
14299   bool NeedTruncation = false;
14300   SDValue ArithOp = Op;
14301   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14302     SDValue Arith = Op->getOperand(0);
14303     // Both the trunc and the arithmetic op need to have one user each.
14304     if (Arith->hasOneUse())
14305       switch (Arith.getOpcode()) {
14306         default: break;
14307         case ISD::ADD:
14308         case ISD::SUB:
14309         case ISD::AND:
14310         case ISD::OR:
14311         case ISD::XOR: {
14312           NeedTruncation = true;
14313           ArithOp = Arith;
14314         }
14315       }
14316   }
14317
14318   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14319   // which may be the result of a CAST.  We use the variable 'Op', which is the
14320   // non-casted variable when we check for possible users.
14321   switch (ArithOp.getOpcode()) {
14322   case ISD::ADD:
14323     // Due to an isel shortcoming, be conservative if this add is likely to be
14324     // selected as part of a load-modify-store instruction. When the root node
14325     // in a match is a store, isel doesn't know how to remap non-chain non-flag
14326     // uses of other nodes in the match, such as the ADD in this case. This
14327     // leads to the ADD being left around and reselected, with the result being
14328     // two adds in the output.  Alas, even if none our users are stores, that
14329     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
14330     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
14331     // climbing the DAG back to the root, and it doesn't seem to be worth the
14332     // effort.
14333     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14334          UE = Op.getNode()->use_end(); UI != UE; ++UI)
14335       if (UI->getOpcode() != ISD::CopyToReg &&
14336           UI->getOpcode() != ISD::SETCC &&
14337           UI->getOpcode() != ISD::STORE)
14338         goto default_case;
14339
14340     if (ConstantSDNode *C =
14341         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14342       // An add of one will be selected as an INC.
14343       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
14344         Opcode = X86ISD::INC;
14345         NumOperands = 1;
14346         break;
14347       }
14348
14349       // An add of negative one (subtract of one) will be selected as a DEC.
14350       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
14351         Opcode = X86ISD::DEC;
14352         NumOperands = 1;
14353         break;
14354       }
14355     }
14356
14357     // Otherwise use a regular EFLAGS-setting add.
14358     Opcode = X86ISD::ADD;
14359     NumOperands = 2;
14360     break;
14361   case ISD::SHL:
14362   case ISD::SRL:
14363     // If we have a constant logical shift that's only used in a comparison
14364     // against zero turn it into an equivalent AND. This allows turning it into
14365     // a TEST instruction later.
14366     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14367         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14368       EVT VT = Op.getValueType();
14369       unsigned BitWidth = VT.getSizeInBits();
14370       unsigned ShAmt = Op->getConstantOperandVal(1);
14371       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14372         break;
14373       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14374                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14375                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14376       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14377         break;
14378       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14379                                 DAG.getConstant(Mask, VT));
14380       DAG.ReplaceAllUsesWith(Op, New);
14381       Op = New;
14382     }
14383     break;
14384
14385   case ISD::AND:
14386     // If the primary and result isn't used, don't bother using X86ISD::AND,
14387     // because a TEST instruction will be better.
14388     if (!hasNonFlagsUse(Op))
14389       break;
14390     // FALL THROUGH
14391   case ISD::SUB:
14392   case ISD::OR:
14393   case ISD::XOR:
14394     // Due to the ISEL shortcoming noted above, be conservative if this op is
14395     // likely to be selected as part of a load-modify-store instruction.
14396     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14397            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14398       if (UI->getOpcode() == ISD::STORE)
14399         goto default_case;
14400
14401     // Otherwise use a regular EFLAGS-setting instruction.
14402     switch (ArithOp.getOpcode()) {
14403     default: llvm_unreachable("unexpected operator!");
14404     case ISD::SUB: Opcode = X86ISD::SUB; break;
14405     case ISD::XOR: Opcode = X86ISD::XOR; break;
14406     case ISD::AND: Opcode = X86ISD::AND; break;
14407     case ISD::OR: {
14408       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14409         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14410         if (EFLAGS.getNode())
14411           return EFLAGS;
14412       }
14413       Opcode = X86ISD::OR;
14414       break;
14415     }
14416     }
14417
14418     NumOperands = 2;
14419     break;
14420   case X86ISD::ADD:
14421   case X86ISD::SUB:
14422   case X86ISD::INC:
14423   case X86ISD::DEC:
14424   case X86ISD::OR:
14425   case X86ISD::XOR:
14426   case X86ISD::AND:
14427     return SDValue(Op.getNode(), 1);
14428   default:
14429   default_case:
14430     break;
14431   }
14432
14433   // If we found that truncation is beneficial, perform the truncation and
14434   // update 'Op'.
14435   if (NeedTruncation) {
14436     EVT VT = Op.getValueType();
14437     SDValue WideVal = Op->getOperand(0);
14438     EVT WideVT = WideVal.getValueType();
14439     unsigned ConvertedOp = 0;
14440     // Use a target machine opcode to prevent further DAGCombine
14441     // optimizations that may separate the arithmetic operations
14442     // from the setcc node.
14443     switch (WideVal.getOpcode()) {
14444       default: break;
14445       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14446       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14447       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14448       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14449       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14450     }
14451
14452     if (ConvertedOp) {
14453       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14454       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14455         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14456         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14457         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14458       }
14459     }
14460   }
14461
14462   if (Opcode == 0)
14463     // Emit a CMP with 0, which is the TEST pattern.
14464     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14465                        DAG.getConstant(0, Op.getValueType()));
14466
14467   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14468   SmallVector<SDValue, 4> Ops;
14469   for (unsigned i = 0; i != NumOperands; ++i)
14470     Ops.push_back(Op.getOperand(i));
14471
14472   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14473   DAG.ReplaceAllUsesWith(Op, New);
14474   return SDValue(New.getNode(), 1);
14475 }
14476
14477 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14478 /// equivalent.
14479 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14480                                    SDLoc dl, SelectionDAG &DAG) const {
14481   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
14482     if (C->getAPIntValue() == 0)
14483       return EmitTest(Op0, X86CC, dl, DAG);
14484
14485      if (Op0.getValueType() == MVT::i1)
14486        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
14487   }
14488  
14489   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14490        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14491     // Do the comparison at i32 if it's smaller, besides the Atom case. 
14492     // This avoids subregister aliasing issues. Keep the smaller reference 
14493     // if we're optimizing for size, however, as that'll allow better folding 
14494     // of memory operations.
14495     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14496         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
14497              AttributeSet::FunctionIndex, Attribute::MinSize) &&
14498         !Subtarget->isAtom()) {
14499       unsigned ExtendOp =
14500           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14501       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14502       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14503     }
14504     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14505     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14506     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14507                               Op0, Op1);
14508     return SDValue(Sub.getNode(), 1);
14509   }
14510   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14511 }
14512
14513 /// Convert a comparison if required by the subtarget.
14514 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14515                                                  SelectionDAG &DAG) const {
14516   // If the subtarget does not support the FUCOMI instruction, floating-point
14517   // comparisons have to be converted.
14518   if (Subtarget->hasCMov() ||
14519       Cmp.getOpcode() != X86ISD::CMP ||
14520       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14521       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14522     return Cmp;
14523
14524   // The instruction selector will select an FUCOM instruction instead of
14525   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14526   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14527   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14528   SDLoc dl(Cmp);
14529   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14530   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14531   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14532                             DAG.getConstant(8, MVT::i8));
14533   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14534   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14535 }
14536
14537 /// The minimum architected relative accuracy is 2^-12. We need one
14538 /// Newton-Raphson step to have a good float result (24 bits of precision).
14539 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14540                                             DAGCombinerInfo &DCI,
14541                                             unsigned &RefinementSteps,
14542                                             bool &UseOneConstNR) const {
14543   // FIXME: We should use instruction latency models to calculate the cost of
14544   // each potential sequence, but this is very hard to do reliably because
14545   // at least Intel's Core* chips have variable timing based on the number of
14546   // significant digits in the divisor and/or sqrt operand.
14547   if (!Subtarget->useSqrtEst())
14548     return SDValue();
14549
14550   EVT VT = Op.getValueType();
14551   
14552   // SSE1 has rsqrtss and rsqrtps.
14553   // TODO: Add support for AVX512 (v16f32).
14554   // It is likely not profitable to do this for f64 because a double-precision
14555   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14556   // instructions: convert to single, rsqrtss, convert back to double, refine
14557   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14558   // along with FMA, this could be a throughput win.
14559   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14560       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14561     RefinementSteps = 1;
14562     UseOneConstNR = false;
14563     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14564   }
14565   return SDValue();
14566 }
14567
14568 /// The minimum architected relative accuracy is 2^-12. We need one
14569 /// Newton-Raphson step to have a good float result (24 bits of precision).
14570 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14571                                             DAGCombinerInfo &DCI,
14572                                             unsigned &RefinementSteps) const {
14573   // FIXME: We should use instruction latency models to calculate the cost of
14574   // each potential sequence, but this is very hard to do reliably because
14575   // at least Intel's Core* chips have variable timing based on the number of
14576   // significant digits in the divisor.
14577   if (!Subtarget->useReciprocalEst())
14578     return SDValue();
14579   
14580   EVT VT = Op.getValueType();
14581   
14582   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14583   // TODO: Add support for AVX512 (v16f32).
14584   // It is likely not profitable to do this for f64 because a double-precision
14585   // reciprocal estimate with refinement on x86 prior to FMA requires
14586   // 15 instructions: convert to single, rcpss, convert back to double, refine
14587   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14588   // along with FMA, this could be a throughput win.
14589   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14590       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14591     RefinementSteps = ReciprocalEstimateRefinementSteps;
14592     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14593   }
14594   return SDValue();
14595 }
14596
14597 static bool isAllOnes(SDValue V) {
14598   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
14599   return C && C->isAllOnesValue();
14600 }
14601
14602 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14603 /// if it's possible.
14604 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14605                                      SDLoc dl, SelectionDAG &DAG) const {
14606   SDValue Op0 = And.getOperand(0);
14607   SDValue Op1 = And.getOperand(1);
14608   if (Op0.getOpcode() == ISD::TRUNCATE)
14609     Op0 = Op0.getOperand(0);
14610   if (Op1.getOpcode() == ISD::TRUNCATE)
14611     Op1 = Op1.getOperand(0);
14612
14613   SDValue LHS, RHS;
14614   if (Op1.getOpcode() == ISD::SHL)
14615     std::swap(Op0, Op1);
14616   if (Op0.getOpcode() == ISD::SHL) {
14617     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
14618       if (And00C->getZExtValue() == 1) {
14619         // If we looked past a truncate, check that it's only truncating away
14620         // known zeros.
14621         unsigned BitWidth = Op0.getValueSizeInBits();
14622         unsigned AndBitWidth = And.getValueSizeInBits();
14623         if (BitWidth > AndBitWidth) {
14624           APInt Zeros, Ones;
14625           DAG.computeKnownBits(Op0, Zeros, Ones);
14626           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14627             return SDValue();
14628         }
14629         LHS = Op1;
14630         RHS = Op0.getOperand(1);
14631       }
14632   } else if (Op1.getOpcode() == ISD::Constant) {
14633     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14634     uint64_t AndRHSVal = AndRHS->getZExtValue();
14635     SDValue AndLHS = Op0;
14636
14637     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14638       LHS = AndLHS.getOperand(0);
14639       RHS = AndLHS.getOperand(1);
14640     }
14641
14642     // Use BT if the immediate can't be encoded in a TEST instruction.
14643     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14644       LHS = AndLHS;
14645       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
14646     }
14647   }
14648
14649   if (LHS.getNode()) {
14650     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14651     // instruction.  Since the shift amount is in-range-or-undefined, we know
14652     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14653     // the encoding for the i16 version is larger than the i32 version.
14654     // Also promote i16 to i32 for performance / code size reason.
14655     if (LHS.getValueType() == MVT::i8 ||
14656         LHS.getValueType() == MVT::i16)
14657       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14658
14659     // If the operand types disagree, extend the shift amount to match.  Since
14660     // BT ignores high bits (like shifts) we can use anyextend.
14661     if (LHS.getValueType() != RHS.getValueType())
14662       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14663
14664     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14665     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14666     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14667                        DAG.getConstant(Cond, MVT::i8), BT);
14668   }
14669
14670   return SDValue();
14671 }
14672
14673 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14674 /// mask CMPs.
14675 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14676                               SDValue &Op1) {
14677   unsigned SSECC;
14678   bool Swap = false;
14679
14680   // SSE Condition code mapping:
14681   //  0 - EQ
14682   //  1 - LT
14683   //  2 - LE
14684   //  3 - UNORD
14685   //  4 - NEQ
14686   //  5 - NLT
14687   //  6 - NLE
14688   //  7 - ORD
14689   switch (SetCCOpcode) {
14690   default: llvm_unreachable("Unexpected SETCC condition");
14691   case ISD::SETOEQ:
14692   case ISD::SETEQ:  SSECC = 0; break;
14693   case ISD::SETOGT:
14694   case ISD::SETGT:  Swap = true; // Fallthrough
14695   case ISD::SETLT:
14696   case ISD::SETOLT: SSECC = 1; break;
14697   case ISD::SETOGE:
14698   case ISD::SETGE:  Swap = true; // Fallthrough
14699   case ISD::SETLE:
14700   case ISD::SETOLE: SSECC = 2; break;
14701   case ISD::SETUO:  SSECC = 3; break;
14702   case ISD::SETUNE:
14703   case ISD::SETNE:  SSECC = 4; break;
14704   case ISD::SETULE: Swap = true; // Fallthrough
14705   case ISD::SETUGE: SSECC = 5; break;
14706   case ISD::SETULT: Swap = true; // Fallthrough
14707   case ISD::SETUGT: SSECC = 6; break;
14708   case ISD::SETO:   SSECC = 7; break;
14709   case ISD::SETUEQ:
14710   case ISD::SETONE: SSECC = 8; break;
14711   }
14712   if (Swap)
14713     std::swap(Op0, Op1);
14714
14715   return SSECC;
14716 }
14717
14718 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14719 // ones, and then concatenate the result back.
14720 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14721   MVT VT = Op.getSimpleValueType();
14722
14723   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14724          "Unsupported value type for operation");
14725
14726   unsigned NumElems = VT.getVectorNumElements();
14727   SDLoc dl(Op);
14728   SDValue CC = Op.getOperand(2);
14729
14730   // Extract the LHS vectors
14731   SDValue LHS = Op.getOperand(0);
14732   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14733   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14734
14735   // Extract the RHS vectors
14736   SDValue RHS = Op.getOperand(1);
14737   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14738   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14739
14740   // Issue the operation on the smaller types and concatenate the result back
14741   MVT EltVT = VT.getVectorElementType();
14742   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14743   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14744                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14745                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14746 }
14747
14748 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14749                                      const X86Subtarget *Subtarget) {
14750   SDValue Op0 = Op.getOperand(0);
14751   SDValue Op1 = Op.getOperand(1);
14752   SDValue CC = Op.getOperand(2);
14753   MVT VT = Op.getSimpleValueType();
14754   SDLoc dl(Op);
14755
14756   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14757          Op.getValueType().getScalarType() == MVT::i1 &&
14758          "Cannot set masked compare for this operation");
14759
14760   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14761   unsigned  Opc = 0;
14762   bool Unsigned = false;
14763   bool Swap = false;
14764   unsigned SSECC;
14765   switch (SetCCOpcode) {
14766   default: llvm_unreachable("Unexpected SETCC condition");
14767   case ISD::SETNE:  SSECC = 4; break;
14768   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14769   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14770   case ISD::SETLT:  Swap = true; //fall-through
14771   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14772   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14773   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14774   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14775   case ISD::SETULE: Unsigned = true; //fall-through
14776   case ISD::SETLE:  SSECC = 2; break;
14777   }
14778
14779   if (Swap)
14780     std::swap(Op0, Op1);
14781   if (Opc)
14782     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14783   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14784   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14785                      DAG.getConstant(SSECC, MVT::i8));
14786 }
14787
14788 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14789 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14790 /// return an empty value.
14791 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14792 {
14793   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14794   if (!BV)
14795     return SDValue();
14796
14797   MVT VT = Op1.getSimpleValueType();
14798   MVT EVT = VT.getVectorElementType();
14799   unsigned n = VT.getVectorNumElements();
14800   SmallVector<SDValue, 8> ULTOp1;
14801
14802   for (unsigned i = 0; i < n; ++i) {
14803     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14804     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14805       return SDValue();
14806
14807     // Avoid underflow.
14808     APInt Val = Elt->getAPIntValue();
14809     if (Val == 0)
14810       return SDValue();
14811
14812     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
14813   }
14814
14815   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14816 }
14817
14818 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14819                            SelectionDAG &DAG) {
14820   SDValue Op0 = Op.getOperand(0);
14821   SDValue Op1 = Op.getOperand(1);
14822   SDValue CC = Op.getOperand(2);
14823   MVT VT = Op.getSimpleValueType();
14824   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14825   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14826   SDLoc dl(Op);
14827
14828   if (isFP) {
14829 #ifndef NDEBUG
14830     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14831     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14832 #endif
14833
14834     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14835     unsigned Opc = X86ISD::CMPP;
14836     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14837       assert(VT.getVectorNumElements() <= 16);
14838       Opc = X86ISD::CMPM;
14839     }
14840     // In the two special cases we can't handle, emit two comparisons.
14841     if (SSECC == 8) {
14842       unsigned CC0, CC1;
14843       unsigned CombineOpc;
14844       if (SetCCOpcode == ISD::SETUEQ) {
14845         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14846       } else {
14847         assert(SetCCOpcode == ISD::SETONE);
14848         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14849       }
14850
14851       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14852                                  DAG.getConstant(CC0, MVT::i8));
14853       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14854                                  DAG.getConstant(CC1, MVT::i8));
14855       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14856     }
14857     // Handle all other FP comparisons here.
14858     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14859                        DAG.getConstant(SSECC, MVT::i8));
14860   }
14861
14862   // Break 256-bit integer vector compare into smaller ones.
14863   if (VT.is256BitVector() && !Subtarget->hasInt256())
14864     return Lower256IntVSETCC(Op, DAG);
14865
14866   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14867   EVT OpVT = Op1.getValueType();
14868   if (Subtarget->hasAVX512()) {
14869     if (Op1.getValueType().is512BitVector() ||
14870         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14871         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14872       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14873
14874     // In AVX-512 architecture setcc returns mask with i1 elements,
14875     // But there is no compare instruction for i8 and i16 elements in KNL.
14876     // We are not talking about 512-bit operands in this case, these
14877     // types are illegal.
14878     if (MaskResult &&
14879         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14880          OpVT.getVectorElementType().getSizeInBits() >= 8))
14881       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14882                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14883   }
14884
14885   // We are handling one of the integer comparisons here.  Since SSE only has
14886   // GT and EQ comparisons for integer, swapping operands and multiple
14887   // operations may be required for some comparisons.
14888   unsigned Opc;
14889   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14890   bool Subus = false;
14891
14892   switch (SetCCOpcode) {
14893   default: llvm_unreachable("Unexpected SETCC condition");
14894   case ISD::SETNE:  Invert = true;
14895   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14896   case ISD::SETLT:  Swap = true;
14897   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14898   case ISD::SETGE:  Swap = true;
14899   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14900                     Invert = true; break;
14901   case ISD::SETULT: Swap = true;
14902   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14903                     FlipSigns = true; break;
14904   case ISD::SETUGE: Swap = true;
14905   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14906                     FlipSigns = true; Invert = true; break;
14907   }
14908
14909   // Special case: Use min/max operations for SETULE/SETUGE
14910   MVT VET = VT.getVectorElementType();
14911   bool hasMinMax =
14912        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14913     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14914
14915   if (hasMinMax) {
14916     switch (SetCCOpcode) {
14917     default: break;
14918     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
14919     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
14920     }
14921
14922     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14923   }
14924
14925   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14926   if (!MinMax && hasSubus) {
14927     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14928     // Op0 u<= Op1:
14929     //   t = psubus Op0, Op1
14930     //   pcmpeq t, <0..0>
14931     switch (SetCCOpcode) {
14932     default: break;
14933     case ISD::SETULT: {
14934       // If the comparison is against a constant we can turn this into a
14935       // setule.  With psubus, setule does not require a swap.  This is
14936       // beneficial because the constant in the register is no longer
14937       // destructed as the destination so it can be hoisted out of a loop.
14938       // Only do this pre-AVX since vpcmp* is no longer destructive.
14939       if (Subtarget->hasAVX())
14940         break;
14941       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14942       if (ULEOp1.getNode()) {
14943         Op1 = ULEOp1;
14944         Subus = true; Invert = false; Swap = false;
14945       }
14946       break;
14947     }
14948     // Psubus is better than flip-sign because it requires no inversion.
14949     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14950     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14951     }
14952
14953     if (Subus) {
14954       Opc = X86ISD::SUBUS;
14955       FlipSigns = false;
14956     }
14957   }
14958
14959   if (Swap)
14960     std::swap(Op0, Op1);
14961
14962   // Check that the operation in question is available (most are plain SSE2,
14963   // but PCMPGTQ and PCMPEQQ have different requirements).
14964   if (VT == MVT::v2i64) {
14965     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14966       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14967
14968       // First cast everything to the right type.
14969       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
14970       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
14971
14972       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14973       // bits of the inputs before performing those operations. The lower
14974       // compare is always unsigned.
14975       SDValue SB;
14976       if (FlipSigns) {
14977         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
14978       } else {
14979         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
14980         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
14981         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14982                          Sign, Zero, Sign, Zero);
14983       }
14984       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14985       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14986
14987       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14988       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14989       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14990
14991       // Create masks for only the low parts/high parts of the 64 bit integers.
14992       static const int MaskHi[] = { 1, 1, 3, 3 };
14993       static const int MaskLo[] = { 0, 0, 2, 2 };
14994       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14995       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14996       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14997
14998       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14999       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
15000
15001       if (Invert)
15002         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15003
15004       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15005     }
15006
15007     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
15008       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
15009       // pcmpeqd + pshufd + pand.
15010       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
15011
15012       // First cast everything to the right type.
15013       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15014       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15015
15016       // Do the compare.
15017       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
15018
15019       // Make sure the lower and upper halves are both all-ones.
15020       static const int Mask[] = { 1, 0, 3, 2 };
15021       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
15022       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
15023
15024       if (Invert)
15025         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15026
15027       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15028     }
15029   }
15030
15031   // Since SSE has no unsigned integer comparisons, we need to flip the sign
15032   // bits of the inputs before performing those operations.
15033   if (FlipSigns) {
15034     EVT EltVT = VT.getVectorElementType();
15035     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
15036     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
15037     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
15038   }
15039
15040   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
15041
15042   // If the logical-not of the result is required, perform that now.
15043   if (Invert)
15044     Result = DAG.getNOT(dl, Result, VT);
15045
15046   if (MinMax)
15047     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
15048
15049   if (Subus)
15050     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
15051                          getZeroVector(VT, Subtarget, DAG, dl));
15052
15053   return Result;
15054 }
15055
15056 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
15057
15058   MVT VT = Op.getSimpleValueType();
15059
15060   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
15061
15062   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
15063          && "SetCC type must be 8-bit or 1-bit integer");
15064   SDValue Op0 = Op.getOperand(0);
15065   SDValue Op1 = Op.getOperand(1);
15066   SDLoc dl(Op);
15067   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
15068
15069   // Optimize to BT if possible.
15070   // Lower (X & (1 << N)) == 0 to BT(X, N).
15071   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
15072   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
15073   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
15074       Op1.getOpcode() == ISD::Constant &&
15075       cast<ConstantSDNode>(Op1)->isNullValue() &&
15076       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15077     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
15078     if (NewSetCC.getNode())
15079       return NewSetCC;
15080   }
15081
15082   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
15083   // these.
15084   if (Op1.getOpcode() == ISD::Constant &&
15085       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
15086        cast<ConstantSDNode>(Op1)->isNullValue()) &&
15087       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15088
15089     // If the input is a setcc, then reuse the input setcc or use a new one with
15090     // the inverted condition.
15091     if (Op0.getOpcode() == X86ISD::SETCC) {
15092       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
15093       bool Invert = (CC == ISD::SETNE) ^
15094         cast<ConstantSDNode>(Op1)->isNullValue();
15095       if (!Invert)
15096         return Op0;
15097
15098       CCode = X86::GetOppositeBranchCondition(CCode);
15099       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15100                                   DAG.getConstant(CCode, MVT::i8),
15101                                   Op0.getOperand(1));
15102       if (VT == MVT::i1)
15103         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15104       return SetCC;
15105     }
15106   }
15107   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
15108       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
15109       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15110
15111     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
15112     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
15113   }
15114
15115   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
15116   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
15117   if (X86CC == X86::COND_INVALID)
15118     return SDValue();
15119
15120   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
15121   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
15122   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15123                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
15124   if (VT == MVT::i1)
15125     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15126   return SetCC;
15127 }
15128
15129 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
15130 static bool isX86LogicalCmp(SDValue Op) {
15131   unsigned Opc = Op.getNode()->getOpcode();
15132   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
15133       Opc == X86ISD::SAHF)
15134     return true;
15135   if (Op.getResNo() == 1 &&
15136       (Opc == X86ISD::ADD ||
15137        Opc == X86ISD::SUB ||
15138        Opc == X86ISD::ADC ||
15139        Opc == X86ISD::SBB ||
15140        Opc == X86ISD::SMUL ||
15141        Opc == X86ISD::UMUL ||
15142        Opc == X86ISD::INC ||
15143        Opc == X86ISD::DEC ||
15144        Opc == X86ISD::OR ||
15145        Opc == X86ISD::XOR ||
15146        Opc == X86ISD::AND))
15147     return true;
15148
15149   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15150     return true;
15151
15152   return false;
15153 }
15154
15155 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15156   if (V.getOpcode() != ISD::TRUNCATE)
15157     return false;
15158
15159   SDValue VOp0 = V.getOperand(0);
15160   unsigned InBits = VOp0.getValueSizeInBits();
15161   unsigned Bits = V.getValueSizeInBits();
15162   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15163 }
15164
15165 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15166   bool addTest = true;
15167   SDValue Cond  = Op.getOperand(0);
15168   SDValue Op1 = Op.getOperand(1);
15169   SDValue Op2 = Op.getOperand(2);
15170   SDLoc DL(Op);
15171   EVT VT = Op1.getValueType();
15172   SDValue CC;
15173
15174   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15175   // are available. Otherwise fp cmovs get lowered into a less efficient branch
15176   // sequence later on.
15177   if (Cond.getOpcode() == ISD::SETCC &&
15178       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15179        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15180       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
15181     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15182     int SSECC = translateX86FSETCC(
15183         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15184
15185     if (SSECC != 8) {
15186       if (Subtarget->hasAVX512()) {
15187         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15188                                   DAG.getConstant(SSECC, MVT::i8));
15189         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15190       }
15191       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15192                                 DAG.getConstant(SSECC, MVT::i8));
15193       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15194       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15195       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15196     }
15197   }
15198
15199   if (Cond.getOpcode() == ISD::SETCC) {
15200     SDValue NewCond = LowerSETCC(Cond, DAG);
15201     if (NewCond.getNode())
15202       Cond = NewCond;
15203   }
15204
15205   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15206   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15207   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15208   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15209   if (Cond.getOpcode() == X86ISD::SETCC &&
15210       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15211       isZero(Cond.getOperand(1).getOperand(1))) {
15212     SDValue Cmp = Cond.getOperand(1);
15213
15214     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15215
15216     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
15217         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15218       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
15219
15220       SDValue CmpOp0 = Cmp.getOperand(0);
15221       // Apply further optimizations for special cases
15222       // (select (x != 0), -1, 0) -> neg & sbb
15223       // (select (x == 0), 0, -1) -> neg & sbb
15224       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
15225         if (YC->isNullValue() &&
15226             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
15227           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15228           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15229                                     DAG.getConstant(0, CmpOp0.getValueType()),
15230                                     CmpOp0);
15231           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15232                                     DAG.getConstant(X86::COND_B, MVT::i8),
15233                                     SDValue(Neg.getNode(), 1));
15234           return Res;
15235         }
15236
15237       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15238                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
15239       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15240
15241       SDValue Res =   // Res = 0 or -1.
15242         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15243                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
15244
15245       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
15246         Res = DAG.getNOT(DL, Res, Res.getValueType());
15247
15248       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
15249       if (!N2C || !N2C->isNullValue())
15250         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15251       return Res;
15252     }
15253   }
15254
15255   // Look past (and (setcc_carry (cmp ...)), 1).
15256   if (Cond.getOpcode() == ISD::AND &&
15257       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15258     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15259     if (C && C->getAPIntValue() == 1)
15260       Cond = Cond.getOperand(0);
15261   }
15262
15263   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15264   // setting operand in place of the X86ISD::SETCC.
15265   unsigned CondOpcode = Cond.getOpcode();
15266   if (CondOpcode == X86ISD::SETCC ||
15267       CondOpcode == X86ISD::SETCC_CARRY) {
15268     CC = Cond.getOperand(0);
15269
15270     SDValue Cmp = Cond.getOperand(1);
15271     unsigned Opc = Cmp.getOpcode();
15272     MVT VT = Op.getSimpleValueType();
15273
15274     bool IllegalFPCMov = false;
15275     if (VT.isFloatingPoint() && !VT.isVector() &&
15276         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15277       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15278
15279     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15280         Opc == X86ISD::BT) { // FIXME
15281       Cond = Cmp;
15282       addTest = false;
15283     }
15284   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15285              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15286              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15287               Cond.getOperand(0).getValueType() != MVT::i8)) {
15288     SDValue LHS = Cond.getOperand(0);
15289     SDValue RHS = Cond.getOperand(1);
15290     unsigned X86Opcode;
15291     unsigned X86Cond;
15292     SDVTList VTs;
15293     switch (CondOpcode) {
15294     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15295     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15296     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15297     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15298     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15299     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15300     default: llvm_unreachable("unexpected overflowing operator");
15301     }
15302     if (CondOpcode == ISD::UMULO)
15303       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15304                           MVT::i32);
15305     else
15306       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15307
15308     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15309
15310     if (CondOpcode == ISD::UMULO)
15311       Cond = X86Op.getValue(2);
15312     else
15313       Cond = X86Op.getValue(1);
15314
15315     CC = DAG.getConstant(X86Cond, MVT::i8);
15316     addTest = false;
15317   }
15318
15319   if (addTest) {
15320     // Look pass the truncate if the high bits are known zero.
15321     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15322         Cond = Cond.getOperand(0);
15323
15324     // We know the result of AND is compared against zero. Try to match
15325     // it to BT.
15326     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15327       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
15328       if (NewSetCC.getNode()) {
15329         CC = NewSetCC.getOperand(0);
15330         Cond = NewSetCC.getOperand(1);
15331         addTest = false;
15332       }
15333     }
15334   }
15335
15336   if (addTest) {
15337     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15338     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15339   }
15340
15341   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15342   // a <  b ?  0 : -1 -> RES = setcc_carry
15343   // a >= b ? -1 :  0 -> RES = setcc_carry
15344   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15345   if (Cond.getOpcode() == X86ISD::SUB) {
15346     Cond = ConvertCmpIfNecessary(Cond, DAG);
15347     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15348
15349     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15350         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
15351       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15352                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
15353       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
15354         return DAG.getNOT(DL, Res, Res.getValueType());
15355       return Res;
15356     }
15357   }
15358
15359   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15360   // widen the cmov and push the truncate through. This avoids introducing a new
15361   // branch during isel and doesn't add any extensions.
15362   if (Op.getValueType() == MVT::i8 &&
15363       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15364     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15365     if (T1.getValueType() == T2.getValueType() &&
15366         // Blacklist CopyFromReg to avoid partial register stalls.
15367         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15368       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15369       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15370       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15371     }
15372   }
15373
15374   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15375   // condition is true.
15376   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15377   SDValue Ops[] = { Op2, Op1, CC, Cond };
15378   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15379 }
15380
15381 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
15382                                        SelectionDAG &DAG) {
15383   MVT VT = Op->getSimpleValueType(0);
15384   SDValue In = Op->getOperand(0);
15385   MVT InVT = In.getSimpleValueType();
15386   MVT VTElt = VT.getVectorElementType();
15387   MVT InVTElt = InVT.getVectorElementType();
15388   SDLoc dl(Op);
15389
15390   // SKX processor
15391   if ((InVTElt == MVT::i1) &&
15392       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15393         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15394
15395        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15396         VTElt.getSizeInBits() <= 16)) ||
15397
15398        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15399         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15400     
15401        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15402         VTElt.getSizeInBits() >= 32))))
15403     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15404     
15405   unsigned int NumElts = VT.getVectorNumElements();
15406
15407   if (NumElts != 8 && NumElts != 16)
15408     return SDValue();
15409
15410   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
15411     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15412
15413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15414   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15415
15416   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
15417   Constant *C = ConstantInt::get(*DAG.getContext(),
15418     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
15419
15420   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
15421   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
15422   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
15423                           MachinePointerInfo::getConstantPool(),
15424                           false, false, false, Alignment);
15425   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
15426   if (VT.is512BitVector())
15427     return Brcst;
15428   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
15429 }
15430
15431 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15432                                 SelectionDAG &DAG) {
15433   MVT VT = Op->getSimpleValueType(0);
15434   SDValue In = Op->getOperand(0);
15435   MVT InVT = In.getSimpleValueType();
15436   SDLoc dl(Op);
15437
15438   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15439     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15440
15441   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15442       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15443       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15444     return SDValue();
15445
15446   if (Subtarget->hasInt256())
15447     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15448
15449   // Optimize vectors in AVX mode
15450   // Sign extend  v8i16 to v8i32 and
15451   //              v4i32 to v4i64
15452   //
15453   // Divide input vector into two parts
15454   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15455   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15456   // concat the vectors to original VT
15457
15458   unsigned NumElems = InVT.getVectorNumElements();
15459   SDValue Undef = DAG.getUNDEF(InVT);
15460
15461   SmallVector<int,8> ShufMask1(NumElems, -1);
15462   for (unsigned i = 0; i != NumElems/2; ++i)
15463     ShufMask1[i] = i;
15464
15465   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15466
15467   SmallVector<int,8> ShufMask2(NumElems, -1);
15468   for (unsigned i = 0; i != NumElems/2; ++i)
15469     ShufMask2[i] = i + NumElems/2;
15470
15471   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15472
15473   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15474                                 VT.getVectorNumElements()/2);
15475
15476   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15477   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15478
15479   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15480 }
15481
15482 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15483 // may emit an illegal shuffle but the expansion is still better than scalar
15484 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15485 // we'll emit a shuffle and a arithmetic shift.
15486 // TODO: It is possible to support ZExt by zeroing the undef values during
15487 // the shuffle phase or after the shuffle.
15488 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15489                                  SelectionDAG &DAG) {
15490   MVT RegVT = Op.getSimpleValueType();
15491   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15492   assert(RegVT.isInteger() &&
15493          "We only custom lower integer vector sext loads.");
15494
15495   // Nothing useful we can do without SSE2 shuffles.
15496   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15497
15498   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15499   SDLoc dl(Ld);
15500   EVT MemVT = Ld->getMemoryVT();
15501   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15502   unsigned RegSz = RegVT.getSizeInBits();
15503
15504   ISD::LoadExtType Ext = Ld->getExtensionType();
15505
15506   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15507          && "Only anyext and sext are currently implemented.");
15508   assert(MemVT != RegVT && "Cannot extend to the same type");
15509   assert(MemVT.isVector() && "Must load a vector from memory");
15510
15511   unsigned NumElems = RegVT.getVectorNumElements();
15512   unsigned MemSz = MemVT.getSizeInBits();
15513   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15514
15515   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15516     // The only way in which we have a legal 256-bit vector result but not the
15517     // integer 256-bit operations needed to directly lower a sextload is if we
15518     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15519     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15520     // correctly legalized. We do this late to allow the canonical form of
15521     // sextload to persist throughout the rest of the DAG combiner -- it wants
15522     // to fold together any extensions it can, and so will fuse a sign_extend
15523     // of an sextload into a sextload targeting a wider value.
15524     SDValue Load;
15525     if (MemSz == 128) {
15526       // Just switch this to a normal load.
15527       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15528                                        "it must be a legal 128-bit vector "
15529                                        "type!");
15530       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15531                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15532                   Ld->isInvariant(), Ld->getAlignment());
15533     } else {
15534       assert(MemSz < 128 &&
15535              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15536       // Do an sext load to a 128-bit vector type. We want to use the same
15537       // number of elements, but elements half as wide. This will end up being
15538       // recursively lowered by this routine, but will succeed as we definitely
15539       // have all the necessary features if we're using AVX1.
15540       EVT HalfEltVT =
15541           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15542       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15543       Load =
15544           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15545                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15546                          Ld->isNonTemporal(), Ld->isInvariant(),
15547                          Ld->getAlignment());
15548     }
15549
15550     // Replace chain users with the new chain.
15551     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15552     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15553
15554     // Finally, do a normal sign-extend to the desired register.
15555     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15556   }
15557
15558   // All sizes must be a power of two.
15559   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15560          "Non-power-of-two elements are not custom lowered!");
15561
15562   // Attempt to load the original value using scalar loads.
15563   // Find the largest scalar type that divides the total loaded size.
15564   MVT SclrLoadTy = MVT::i8;
15565   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15566        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15567     MVT Tp = (MVT::SimpleValueType)tp;
15568     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15569       SclrLoadTy = Tp;
15570     }
15571   }
15572
15573   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15574   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15575       (64 <= MemSz))
15576     SclrLoadTy = MVT::f64;
15577
15578   // Calculate the number of scalar loads that we need to perform
15579   // in order to load our vector from memory.
15580   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15581
15582   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15583          "Can only lower sext loads with a single scalar load!");
15584
15585   unsigned loadRegZize = RegSz;
15586   if (Ext == ISD::SEXTLOAD && RegSz == 256)
15587     loadRegZize /= 2;
15588
15589   // Represent our vector as a sequence of elements which are the
15590   // largest scalar that we can load.
15591   EVT LoadUnitVecVT = EVT::getVectorVT(
15592       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15593
15594   // Represent the data using the same element type that is stored in
15595   // memory. In practice, we ''widen'' MemVT.
15596   EVT WideVecVT =
15597       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15598                        loadRegZize / MemVT.getScalarType().getSizeInBits());
15599
15600   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15601          "Invalid vector type");
15602
15603   // We can't shuffle using an illegal type.
15604   assert(TLI.isTypeLegal(WideVecVT) &&
15605          "We only lower types that form legal widened vector types");
15606
15607   SmallVector<SDValue, 8> Chains;
15608   SDValue Ptr = Ld->getBasePtr();
15609   SDValue Increment =
15610       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
15611   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15612
15613   for (unsigned i = 0; i < NumLoads; ++i) {
15614     // Perform a single load.
15615     SDValue ScalarLoad =
15616         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15617                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15618                     Ld->getAlignment());
15619     Chains.push_back(ScalarLoad.getValue(1));
15620     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15621     // another round of DAGCombining.
15622     if (i == 0)
15623       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15624     else
15625       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15626                         ScalarLoad, DAG.getIntPtrConstant(i));
15627
15628     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15629   }
15630
15631   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15632
15633   // Bitcast the loaded value to a vector of the original element type, in
15634   // the size of the target vector type.
15635   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15636   unsigned SizeRatio = RegSz / MemSz;
15637
15638   if (Ext == ISD::SEXTLOAD) {
15639     // If we have SSE4.1, we can directly emit a VSEXT node.
15640     if (Subtarget->hasSSE41()) {
15641       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15642       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15643       return Sext;
15644     }
15645
15646     // Otherwise we'll shuffle the small elements in the high bits of the
15647     // larger type and perform an arithmetic shift. If the shift is not legal
15648     // it's better to scalarize.
15649     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
15650            "We can't implement a sext load without an arithmetic right shift!");
15651
15652     // Redistribute the loaded elements into the different locations.
15653     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15654     for (unsigned i = 0; i != NumElems; ++i)
15655       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
15656
15657     SDValue Shuff = DAG.getVectorShuffle(
15658         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15659
15660     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15661
15662     // Build the arithmetic shift.
15663     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
15664                    MemVT.getVectorElementType().getSizeInBits();
15665     Shuff =
15666         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
15667
15668     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15669     return Shuff;
15670   }
15671
15672   // Redistribute the loaded elements into the different locations.
15673   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15674   for (unsigned i = 0; i != NumElems; ++i)
15675     ShuffleVec[i * SizeRatio] = i;
15676
15677   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15678                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15679
15680   // Bitcast to the requested type.
15681   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15682   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15683   return Shuff;
15684 }
15685
15686 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15687 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15688 // from the AND / OR.
15689 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15690   Opc = Op.getOpcode();
15691   if (Opc != ISD::OR && Opc != ISD::AND)
15692     return false;
15693   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15694           Op.getOperand(0).hasOneUse() &&
15695           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15696           Op.getOperand(1).hasOneUse());
15697 }
15698
15699 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15700 // 1 and that the SETCC node has a single use.
15701 static bool isXor1OfSetCC(SDValue Op) {
15702   if (Op.getOpcode() != ISD::XOR)
15703     return false;
15704   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15705   if (N1C && N1C->getAPIntValue() == 1) {
15706     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15707       Op.getOperand(0).hasOneUse();
15708   }
15709   return false;
15710 }
15711
15712 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15713   bool addTest = true;
15714   SDValue Chain = Op.getOperand(0);
15715   SDValue Cond  = Op.getOperand(1);
15716   SDValue Dest  = Op.getOperand(2);
15717   SDLoc dl(Op);
15718   SDValue CC;
15719   bool Inverted = false;
15720
15721   if (Cond.getOpcode() == ISD::SETCC) {
15722     // Check for setcc([su]{add,sub,mul}o == 0).
15723     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15724         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15725         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15726         Cond.getOperand(0).getResNo() == 1 &&
15727         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15728          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15729          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15730          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15731          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15732          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15733       Inverted = true;
15734       Cond = Cond.getOperand(0);
15735     } else {
15736       SDValue NewCond = LowerSETCC(Cond, DAG);
15737       if (NewCond.getNode())
15738         Cond = NewCond;
15739     }
15740   }
15741 #if 0
15742   // FIXME: LowerXALUO doesn't handle these!!
15743   else if (Cond.getOpcode() == X86ISD::ADD  ||
15744            Cond.getOpcode() == X86ISD::SUB  ||
15745            Cond.getOpcode() == X86ISD::SMUL ||
15746            Cond.getOpcode() == X86ISD::UMUL)
15747     Cond = LowerXALUO(Cond, DAG);
15748 #endif
15749
15750   // Look pass (and (setcc_carry (cmp ...)), 1).
15751   if (Cond.getOpcode() == ISD::AND &&
15752       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15753     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15754     if (C && C->getAPIntValue() == 1)
15755       Cond = Cond.getOperand(0);
15756   }
15757
15758   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15759   // setting operand in place of the X86ISD::SETCC.
15760   unsigned CondOpcode = Cond.getOpcode();
15761   if (CondOpcode == X86ISD::SETCC ||
15762       CondOpcode == X86ISD::SETCC_CARRY) {
15763     CC = Cond.getOperand(0);
15764
15765     SDValue Cmp = Cond.getOperand(1);
15766     unsigned Opc = Cmp.getOpcode();
15767     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15768     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15769       Cond = Cmp;
15770       addTest = false;
15771     } else {
15772       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15773       default: break;
15774       case X86::COND_O:
15775       case X86::COND_B:
15776         // These can only come from an arithmetic instruction with overflow,
15777         // e.g. SADDO, UADDO.
15778         Cond = Cond.getNode()->getOperand(1);
15779         addTest = false;
15780         break;
15781       }
15782     }
15783   }
15784   CondOpcode = Cond.getOpcode();
15785   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15786       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15787       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15788        Cond.getOperand(0).getValueType() != MVT::i8)) {
15789     SDValue LHS = Cond.getOperand(0);
15790     SDValue RHS = Cond.getOperand(1);
15791     unsigned X86Opcode;
15792     unsigned X86Cond;
15793     SDVTList VTs;
15794     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15795     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15796     // X86ISD::INC).
15797     switch (CondOpcode) {
15798     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15799     case ISD::SADDO:
15800       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15801         if (C->isOne()) {
15802           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15803           break;
15804         }
15805       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15806     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15807     case ISD::SSUBO:
15808       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15809         if (C->isOne()) {
15810           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15811           break;
15812         }
15813       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15814     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15815     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15816     default: llvm_unreachable("unexpected overflowing operator");
15817     }
15818     if (Inverted)
15819       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15820     if (CondOpcode == ISD::UMULO)
15821       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15822                           MVT::i32);
15823     else
15824       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15825
15826     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15827
15828     if (CondOpcode == ISD::UMULO)
15829       Cond = X86Op.getValue(2);
15830     else
15831       Cond = X86Op.getValue(1);
15832
15833     CC = DAG.getConstant(X86Cond, MVT::i8);
15834     addTest = false;
15835   } else {
15836     unsigned CondOpc;
15837     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15838       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15839       if (CondOpc == ISD::OR) {
15840         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15841         // two branches instead of an explicit OR instruction with a
15842         // separate test.
15843         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15844             isX86LogicalCmp(Cmp)) {
15845           CC = Cond.getOperand(0).getOperand(0);
15846           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15847                               Chain, Dest, CC, Cmp);
15848           CC = Cond.getOperand(1).getOperand(0);
15849           Cond = Cmp;
15850           addTest = false;
15851         }
15852       } else { // ISD::AND
15853         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15854         // two branches instead of an explicit AND instruction with a
15855         // separate test. However, we only do this if this block doesn't
15856         // have a fall-through edge, because this requires an explicit
15857         // jmp when the condition is false.
15858         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15859             isX86LogicalCmp(Cmp) &&
15860             Op.getNode()->hasOneUse()) {
15861           X86::CondCode CCode =
15862             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15863           CCode = X86::GetOppositeBranchCondition(CCode);
15864           CC = DAG.getConstant(CCode, MVT::i8);
15865           SDNode *User = *Op.getNode()->use_begin();
15866           // Look for an unconditional branch following this conditional branch.
15867           // We need this because we need to reverse the successors in order
15868           // to implement FCMP_OEQ.
15869           if (User->getOpcode() == ISD::BR) {
15870             SDValue FalseBB = User->getOperand(1);
15871             SDNode *NewBR =
15872               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15873             assert(NewBR == User);
15874             (void)NewBR;
15875             Dest = FalseBB;
15876
15877             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15878                                 Chain, Dest, CC, Cmp);
15879             X86::CondCode CCode =
15880               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15881             CCode = X86::GetOppositeBranchCondition(CCode);
15882             CC = DAG.getConstant(CCode, MVT::i8);
15883             Cond = Cmp;
15884             addTest = false;
15885           }
15886         }
15887       }
15888     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15889       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15890       // It should be transformed during dag combiner except when the condition
15891       // is set by a arithmetics with overflow node.
15892       X86::CondCode CCode =
15893         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15894       CCode = X86::GetOppositeBranchCondition(CCode);
15895       CC = DAG.getConstant(CCode, MVT::i8);
15896       Cond = Cond.getOperand(0).getOperand(1);
15897       addTest = false;
15898     } else if (Cond.getOpcode() == ISD::SETCC &&
15899                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15900       // For FCMP_OEQ, we can emit
15901       // two branches instead of an explicit AND instruction with a
15902       // separate test. However, we only do this if this block doesn't
15903       // have a fall-through edge, because this requires an explicit
15904       // jmp when the condition is false.
15905       if (Op.getNode()->hasOneUse()) {
15906         SDNode *User = *Op.getNode()->use_begin();
15907         // Look for an unconditional branch following this conditional branch.
15908         // We need this because we need to reverse the successors in order
15909         // to implement FCMP_OEQ.
15910         if (User->getOpcode() == ISD::BR) {
15911           SDValue FalseBB = User->getOperand(1);
15912           SDNode *NewBR =
15913             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15914           assert(NewBR == User);
15915           (void)NewBR;
15916           Dest = FalseBB;
15917
15918           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15919                                     Cond.getOperand(0), Cond.getOperand(1));
15920           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15921           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15922           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15923                               Chain, Dest, CC, Cmp);
15924           CC = DAG.getConstant(X86::COND_P, MVT::i8);
15925           Cond = Cmp;
15926           addTest = false;
15927         }
15928       }
15929     } else if (Cond.getOpcode() == ISD::SETCC &&
15930                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15931       // For FCMP_UNE, we can emit
15932       // two branches instead of an explicit AND instruction with a
15933       // separate test. However, we only do this if this block doesn't
15934       // have a fall-through edge, because this requires an explicit
15935       // jmp when the condition is false.
15936       if (Op.getNode()->hasOneUse()) {
15937         SDNode *User = *Op.getNode()->use_begin();
15938         // Look for an unconditional branch following this conditional branch.
15939         // We need this because we need to reverse the successors in order
15940         // to implement FCMP_UNE.
15941         if (User->getOpcode() == ISD::BR) {
15942           SDValue FalseBB = User->getOperand(1);
15943           SDNode *NewBR =
15944             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15945           assert(NewBR == User);
15946           (void)NewBR;
15947
15948           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15949                                     Cond.getOperand(0), Cond.getOperand(1));
15950           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15951           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15952           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15953                               Chain, Dest, CC, Cmp);
15954           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
15955           Cond = Cmp;
15956           addTest = false;
15957           Dest = FalseBB;
15958         }
15959       }
15960     }
15961   }
15962
15963   if (addTest) {
15964     // Look pass the truncate if the high bits are known zero.
15965     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15966         Cond = Cond.getOperand(0);
15967
15968     // We know the result of AND is compared against zero. Try to match
15969     // it to BT.
15970     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15971       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15972       if (NewSetCC.getNode()) {
15973         CC = NewSetCC.getOperand(0);
15974         Cond = NewSetCC.getOperand(1);
15975         addTest = false;
15976       }
15977     }
15978   }
15979
15980   if (addTest) {
15981     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15982     CC = DAG.getConstant(X86Cond, MVT::i8);
15983     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15984   }
15985   Cond = ConvertCmpIfNecessary(Cond, DAG);
15986   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15987                      Chain, Dest, CC, Cond);
15988 }
15989
15990 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15991 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15992 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15993 // that the guard pages used by the OS virtual memory manager are allocated in
15994 // correct sequence.
15995 SDValue
15996 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15997                                            SelectionDAG &DAG) const {
15998   MachineFunction &MF = DAG.getMachineFunction();
15999   bool SplitStack = MF.shouldSplitStack();
16000   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
16001                SplitStack;
16002   SDLoc dl(Op);
16003
16004   if (!Lower) {
16005     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16006     SDNode* Node = Op.getNode();
16007
16008     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
16009     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
16010         " not tell us which reg is the stack pointer!");
16011     EVT VT = Node->getValueType(0);
16012     SDValue Tmp1 = SDValue(Node, 0);
16013     SDValue Tmp2 = SDValue(Node, 1);
16014     SDValue Tmp3 = Node->getOperand(2);
16015     SDValue Chain = Tmp1.getOperand(0);
16016
16017     // Chain the dynamic stack allocation so that it doesn't modify the stack
16018     // pointer when other instructions are using the stack.
16019     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
16020         SDLoc(Node));
16021
16022     SDValue Size = Tmp2.getOperand(1);
16023     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
16024     Chain = SP.getValue(1);
16025     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
16026     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
16027     unsigned StackAlign = TFI.getStackAlignment();
16028     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
16029     if (Align > StackAlign)
16030       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
16031           DAG.getConstant(-(uint64_t)Align, VT));
16032     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
16033
16034     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
16035         DAG.getIntPtrConstant(0, true), SDValue(),
16036         SDLoc(Node));
16037
16038     SDValue Ops[2] = { Tmp1, Tmp2 };
16039     return DAG.getMergeValues(Ops, dl);
16040   }
16041
16042   // Get the inputs.
16043   SDValue Chain = Op.getOperand(0);
16044   SDValue Size  = Op.getOperand(1);
16045   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16046   EVT VT = Op.getNode()->getValueType(0);
16047
16048   bool Is64Bit = Subtarget->is64Bit();
16049   EVT SPTy = getPointerTy();
16050
16051   if (SplitStack) {
16052     MachineRegisterInfo &MRI = MF.getRegInfo();
16053
16054     if (Is64Bit) {
16055       // The 64 bit implementation of segmented stacks needs to clobber both r10
16056       // r11. This makes it impossible to use it along with nested parameters.
16057       const Function *F = MF.getFunction();
16058
16059       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16060            I != E; ++I)
16061         if (I->hasNestAttr())
16062           report_fatal_error("Cannot use segmented stacks with functions that "
16063                              "have nested arguments.");
16064     }
16065
16066     const TargetRegisterClass *AddrRegClass =
16067       getRegClassFor(getPointerTy());
16068     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16069     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16070     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16071                                 DAG.getRegister(Vreg, SPTy));
16072     SDValue Ops1[2] = { Value, Chain };
16073     return DAG.getMergeValues(Ops1, dl);
16074   } else {
16075     SDValue Flag;
16076     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16077
16078     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16079     Flag = Chain.getValue(1);
16080     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16081
16082     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16083
16084     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16085         DAG.getSubtarget().getRegisterInfo());
16086     unsigned SPReg = RegInfo->getStackRegister();
16087     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16088     Chain = SP.getValue(1);
16089
16090     if (Align) {
16091       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16092                        DAG.getConstant(-(uint64_t)Align, VT));
16093       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16094     }
16095
16096     SDValue Ops1[2] = { SP, Chain };
16097     return DAG.getMergeValues(Ops1, dl);
16098   }
16099 }
16100
16101 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16102   MachineFunction &MF = DAG.getMachineFunction();
16103   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16104
16105   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16106   SDLoc DL(Op);
16107
16108   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
16109     // vastart just stores the address of the VarArgsFrameIndex slot into the
16110     // memory location argument.
16111     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16112                                    getPointerTy());
16113     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16114                         MachinePointerInfo(SV), false, false, 0);
16115   }
16116
16117   // __va_list_tag:
16118   //   gp_offset         (0 - 6 * 8)
16119   //   fp_offset         (48 - 48 + 8 * 16)
16120   //   overflow_arg_area (point to parameters coming in memory).
16121   //   reg_save_area
16122   SmallVector<SDValue, 8> MemOps;
16123   SDValue FIN = Op.getOperand(1);
16124   // Store gp_offset
16125   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16126                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16127                                                MVT::i32),
16128                                FIN, MachinePointerInfo(SV), false, false, 0);
16129   MemOps.push_back(Store);
16130
16131   // Store fp_offset
16132   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16133                     FIN, DAG.getIntPtrConstant(4));
16134   Store = DAG.getStore(Op.getOperand(0), DL,
16135                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
16136                                        MVT::i32),
16137                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16138   MemOps.push_back(Store);
16139
16140   // Store ptr to overflow_arg_area
16141   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16142                     FIN, DAG.getIntPtrConstant(4));
16143   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16144                                     getPointerTy());
16145   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16146                        MachinePointerInfo(SV, 8),
16147                        false, false, 0);
16148   MemOps.push_back(Store);
16149
16150   // Store ptr to reg_save_area.
16151   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16152                     FIN, DAG.getIntPtrConstant(8));
16153   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
16154                                     getPointerTy());
16155   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
16156                        MachinePointerInfo(SV, 16), false, false, 0);
16157   MemOps.push_back(Store);
16158   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16159 }
16160
16161 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16162   assert(Subtarget->is64Bit() &&
16163          "LowerVAARG only handles 64-bit va_arg!");
16164   assert((Subtarget->isTargetLinux() ||
16165           Subtarget->isTargetDarwin()) &&
16166           "Unhandled target in LowerVAARG");
16167   assert(Op.getNode()->getNumOperands() == 4);
16168   SDValue Chain = Op.getOperand(0);
16169   SDValue SrcPtr = Op.getOperand(1);
16170   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16171   unsigned Align = Op.getConstantOperandVal(3);
16172   SDLoc dl(Op);
16173
16174   EVT ArgVT = Op.getNode()->getValueType(0);
16175   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16176   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
16177   uint8_t ArgMode;
16178
16179   // Decide which area this value should be read from.
16180   // TODO: Implement the AMD64 ABI in its entirety. This simple
16181   // selection mechanism works only for the basic types.
16182   if (ArgVT == MVT::f80) {
16183     llvm_unreachable("va_arg for f80 not yet implemented");
16184   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16185     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16186   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16187     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16188   } else {
16189     llvm_unreachable("Unhandled argument type in LowerVAARG");
16190   }
16191
16192   if (ArgMode == 2) {
16193     // Sanity Check: Make sure using fp_offset makes sense.
16194     assert(!DAG.getTarget().Options.UseSoftFloat &&
16195            !(DAG.getMachineFunction()
16196                 .getFunction()->getAttributes()
16197                 .hasAttribute(AttributeSet::FunctionIndex,
16198                               Attribute::NoImplicitFloat)) &&
16199            Subtarget->hasSSE1());
16200   }
16201
16202   // Insert VAARG_64 node into the DAG
16203   // VAARG_64 returns two values: Variable Argument Address, Chain
16204   SmallVector<SDValue, 11> InstOps;
16205   InstOps.push_back(Chain);
16206   InstOps.push_back(SrcPtr);
16207   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
16208   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
16209   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
16210   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
16211   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16212                                           VTs, InstOps, MVT::i64,
16213                                           MachinePointerInfo(SV),
16214                                           /*Align=*/0,
16215                                           /*Volatile=*/false,
16216                                           /*ReadMem=*/true,
16217                                           /*WriteMem=*/true);
16218   Chain = VAARG.getValue(1);
16219
16220   // Load the next argument and return it
16221   return DAG.getLoad(ArgVT, dl,
16222                      Chain,
16223                      VAARG,
16224                      MachinePointerInfo(),
16225                      false, false, false, 0);
16226 }
16227
16228 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16229                            SelectionDAG &DAG) {
16230   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
16231   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16232   SDValue Chain = Op.getOperand(0);
16233   SDValue DstPtr = Op.getOperand(1);
16234   SDValue SrcPtr = Op.getOperand(2);
16235   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16236   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16237   SDLoc DL(Op);
16238
16239   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16240                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
16241                        false,
16242                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16243 }
16244
16245 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16246 // amount is a constant. Takes immediate version of shift as input.
16247 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16248                                           SDValue SrcOp, uint64_t ShiftAmt,
16249                                           SelectionDAG &DAG) {
16250   MVT ElementType = VT.getVectorElementType();
16251
16252   // Fold this packed shift into its first operand if ShiftAmt is 0.
16253   if (ShiftAmt == 0)
16254     return SrcOp;
16255
16256   // Check for ShiftAmt >= element width
16257   if (ShiftAmt >= ElementType.getSizeInBits()) {
16258     if (Opc == X86ISD::VSRAI)
16259       ShiftAmt = ElementType.getSizeInBits() - 1;
16260     else
16261       return DAG.getConstant(0, VT);
16262   }
16263
16264   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16265          && "Unknown target vector shift-by-constant node");
16266
16267   // Fold this packed vector shift into a build vector if SrcOp is a
16268   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16269   if (VT == SrcOp.getSimpleValueType() &&
16270       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16271     SmallVector<SDValue, 8> Elts;
16272     unsigned NumElts = SrcOp->getNumOperands();
16273     ConstantSDNode *ND;
16274
16275     switch(Opc) {
16276     default: llvm_unreachable(nullptr);
16277     case X86ISD::VSHLI:
16278       for (unsigned i=0; i!=NumElts; ++i) {
16279         SDValue CurrentOp = SrcOp->getOperand(i);
16280         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16281           Elts.push_back(CurrentOp);
16282           continue;
16283         }
16284         ND = cast<ConstantSDNode>(CurrentOp);
16285         const APInt &C = ND->getAPIntValue();
16286         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
16287       }
16288       break;
16289     case X86ISD::VSRLI:
16290       for (unsigned i=0; i!=NumElts; ++i) {
16291         SDValue CurrentOp = SrcOp->getOperand(i);
16292         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16293           Elts.push_back(CurrentOp);
16294           continue;
16295         }
16296         ND = cast<ConstantSDNode>(CurrentOp);
16297         const APInt &C = ND->getAPIntValue();
16298         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
16299       }
16300       break;
16301     case X86ISD::VSRAI:
16302       for (unsigned i=0; i!=NumElts; ++i) {
16303         SDValue CurrentOp = SrcOp->getOperand(i);
16304         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16305           Elts.push_back(CurrentOp);
16306           continue;
16307         }
16308         ND = cast<ConstantSDNode>(CurrentOp);
16309         const APInt &C = ND->getAPIntValue();
16310         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
16311       }
16312       break;
16313     }
16314
16315     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16316   }
16317
16318   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
16319 }
16320
16321 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16322 // may or may not be a constant. Takes immediate version of shift as input.
16323 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16324                                    SDValue SrcOp, SDValue ShAmt,
16325                                    SelectionDAG &DAG) {
16326   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
16327
16328   // Catch shift-by-constant.
16329   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16330     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16331                                       CShAmt->getZExtValue(), DAG);
16332
16333   // Change opcode to non-immediate version
16334   switch (Opc) {
16335     default: llvm_unreachable("Unknown target vector shift node");
16336     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16337     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16338     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16339   }
16340
16341   // Need to build a vector containing shift amount
16342   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
16343   SDValue ShOps[4];
16344   ShOps[0] = ShAmt;
16345   ShOps[1] = DAG.getConstant(0, MVT::i32);
16346   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
16347   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
16348
16349   // The return type has to be a 128-bit type with the same element
16350   // type as the input type.
16351   MVT EltVT = VT.getVectorElementType();
16352   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16353
16354   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
16355   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16356 }
16357
16358 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16359 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16360 /// necessary casting for \p Mask when lowering masking intrinsics.
16361 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16362                                     SDValue PreservedSrc,
16363                                     const X86Subtarget *Subtarget,
16364                                     SelectionDAG &DAG) {
16365     EVT VT = Op.getValueType();
16366     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16367                                   MVT::i1, VT.getVectorNumElements());
16368     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16369                                      Mask.getValueType().getSizeInBits());
16370     SDLoc dl(Op);
16371
16372     assert(MaskVT.isSimple() && "invalid mask type");
16373
16374     if (isAllOnes(Mask))
16375       return Op;
16376
16377     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16378     // are extracted by EXTRACT_SUBVECTOR.
16379     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16380                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
16381                               DAG.getIntPtrConstant(0));
16382
16383     switch (Op.getOpcode()) {
16384       default: break;
16385       case X86ISD::PCMPEQM:
16386       case X86ISD::PCMPGTM:
16387       case X86ISD::CMPM:
16388       case X86ISD::CMPMU:
16389         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16390     }
16391     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16392       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16393     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
16394 }
16395
16396 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
16397     switch (IntNo) {
16398     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16399     case Intrinsic::x86_fma_vfmadd_ps:
16400     case Intrinsic::x86_fma_vfmadd_pd:
16401     case Intrinsic::x86_fma_vfmadd_ps_256:
16402     case Intrinsic::x86_fma_vfmadd_pd_256:
16403     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
16404     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
16405       return X86ISD::FMADD;
16406     case Intrinsic::x86_fma_vfmsub_ps:
16407     case Intrinsic::x86_fma_vfmsub_pd:
16408     case Intrinsic::x86_fma_vfmsub_ps_256:
16409     case Intrinsic::x86_fma_vfmsub_pd_256:
16410     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
16411     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
16412       return X86ISD::FMSUB;
16413     case Intrinsic::x86_fma_vfnmadd_ps:
16414     case Intrinsic::x86_fma_vfnmadd_pd:
16415     case Intrinsic::x86_fma_vfnmadd_ps_256:
16416     case Intrinsic::x86_fma_vfnmadd_pd_256:
16417     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
16418     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
16419       return X86ISD::FNMADD;
16420     case Intrinsic::x86_fma_vfnmsub_ps:
16421     case Intrinsic::x86_fma_vfnmsub_pd:
16422     case Intrinsic::x86_fma_vfnmsub_ps_256:
16423     case Intrinsic::x86_fma_vfnmsub_pd_256:
16424     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
16425     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
16426       return X86ISD::FNMSUB;
16427     case Intrinsic::x86_fma_vfmaddsub_ps:
16428     case Intrinsic::x86_fma_vfmaddsub_pd:
16429     case Intrinsic::x86_fma_vfmaddsub_ps_256:
16430     case Intrinsic::x86_fma_vfmaddsub_pd_256:
16431     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
16432     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
16433       return X86ISD::FMADDSUB;
16434     case Intrinsic::x86_fma_vfmsubadd_ps:
16435     case Intrinsic::x86_fma_vfmsubadd_pd:
16436     case Intrinsic::x86_fma_vfmsubadd_ps_256:
16437     case Intrinsic::x86_fma_vfmsubadd_pd_256:
16438     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
16439     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
16440       return X86ISD::FMSUBADD;
16441     }
16442 }
16443
16444 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16445                                        SelectionDAG &DAG) {
16446   SDLoc dl(Op);
16447   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16448   EVT VT = Op.getValueType();
16449   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16450   if (IntrData) {
16451     switch(IntrData->Type) {
16452     case INTR_TYPE_1OP:
16453       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16454     case INTR_TYPE_2OP:
16455       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16456         Op.getOperand(2));
16457     case INTR_TYPE_3OP:
16458       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16459         Op.getOperand(2), Op.getOperand(3));
16460     case INTR_TYPE_1OP_MASK_RM: {
16461       SDValue Src = Op.getOperand(1);
16462       SDValue Src0 = Op.getOperand(2);
16463       SDValue Mask = Op.getOperand(3);
16464       SDValue RoundingMode = Op.getOperand(4);
16465       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16466                                               RoundingMode),
16467                                   Mask, Src0, Subtarget, DAG);
16468     }
16469                                               
16470     case CMP_MASK:
16471     case CMP_MASK_CC: {
16472       // Comparison intrinsics with masks.
16473       // Example of transformation:
16474       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16475       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16476       // (i8 (bitcast
16477       //   (v8i1 (insert_subvector undef,
16478       //           (v2i1 (and (PCMPEQM %a, %b),
16479       //                      (extract_subvector
16480       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16481       EVT VT = Op.getOperand(1).getValueType();
16482       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16483                                     VT.getVectorNumElements());
16484       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16485       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16486                                        Mask.getValueType().getSizeInBits());
16487       SDValue Cmp;
16488       if (IntrData->Type == CMP_MASK_CC) {
16489         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16490                     Op.getOperand(2), Op.getOperand(3));
16491       } else {
16492         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16493         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16494                     Op.getOperand(2));
16495       }
16496       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16497                                              DAG.getTargetConstant(0, MaskVT),
16498                                              Subtarget, DAG);
16499       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16500                                 DAG.getUNDEF(BitcastVT), CmpMask,
16501                                 DAG.getIntPtrConstant(0));
16502       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
16503     }
16504     case COMI: { // Comparison intrinsics
16505       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16506       SDValue LHS = Op.getOperand(1);
16507       SDValue RHS = Op.getOperand(2);
16508       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
16509       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16510       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16511       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16512                                   DAG.getConstant(X86CC, MVT::i8), Cond);
16513       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16514     }
16515     case VSHIFT:
16516       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16517                                  Op.getOperand(1), Op.getOperand(2), DAG);
16518     case VSHIFT_MASK:
16519       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16520                                                       Op.getOperand(1), Op.getOperand(2), DAG),
16521                                   Op.getOperand(4), Op.getOperand(3), Subtarget, DAG);;
16522     default:
16523       break;
16524     }
16525   }
16526
16527   switch (IntNo) {
16528   default: return SDValue();    // Don't custom lower most intrinsics.
16529
16530   // Arithmetic intrinsics.
16531   case Intrinsic::x86_sse2_pmulu_dq:
16532   case Intrinsic::x86_avx2_pmulu_dq:
16533     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
16534                        Op.getOperand(1), Op.getOperand(2));
16535
16536   case Intrinsic::x86_sse41_pmuldq:
16537   case Intrinsic::x86_avx2_pmul_dq:
16538     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
16539                        Op.getOperand(1), Op.getOperand(2));
16540
16541   case Intrinsic::x86_sse2_pmulhu_w:
16542   case Intrinsic::x86_avx2_pmulhu_w:
16543     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
16544                        Op.getOperand(1), Op.getOperand(2));
16545
16546   case Intrinsic::x86_sse2_pmulh_w:
16547   case Intrinsic::x86_avx2_pmulh_w:
16548     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
16549                        Op.getOperand(1), Op.getOperand(2));
16550
16551   // SSE/SSE2/AVX floating point max/min intrinsics.
16552   case Intrinsic::x86_sse_max_ps:
16553   case Intrinsic::x86_sse2_max_pd:
16554   case Intrinsic::x86_avx_max_ps_256:
16555   case Intrinsic::x86_avx_max_pd_256:
16556   case Intrinsic::x86_sse_min_ps:
16557   case Intrinsic::x86_sse2_min_pd:
16558   case Intrinsic::x86_avx_min_ps_256:
16559   case Intrinsic::x86_avx_min_pd_256: {
16560     unsigned Opcode;
16561     switch (IntNo) {
16562     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16563     case Intrinsic::x86_sse_max_ps:
16564     case Intrinsic::x86_sse2_max_pd:
16565     case Intrinsic::x86_avx_max_ps_256:
16566     case Intrinsic::x86_avx_max_pd_256:
16567       Opcode = X86ISD::FMAX;
16568       break;
16569     case Intrinsic::x86_sse_min_ps:
16570     case Intrinsic::x86_sse2_min_pd:
16571     case Intrinsic::x86_avx_min_ps_256:
16572     case Intrinsic::x86_avx_min_pd_256:
16573       Opcode = X86ISD::FMIN;
16574       break;
16575     }
16576     return DAG.getNode(Opcode, dl, Op.getValueType(),
16577                        Op.getOperand(1), Op.getOperand(2));
16578   }
16579
16580   // AVX2 variable shift intrinsics
16581   case Intrinsic::x86_avx2_psllv_d:
16582   case Intrinsic::x86_avx2_psllv_q:
16583   case Intrinsic::x86_avx2_psllv_d_256:
16584   case Intrinsic::x86_avx2_psllv_q_256:
16585   case Intrinsic::x86_avx2_psrlv_d:
16586   case Intrinsic::x86_avx2_psrlv_q:
16587   case Intrinsic::x86_avx2_psrlv_d_256:
16588   case Intrinsic::x86_avx2_psrlv_q_256:
16589   case Intrinsic::x86_avx2_psrav_d:
16590   case Intrinsic::x86_avx2_psrav_d_256: {
16591     unsigned Opcode;
16592     switch (IntNo) {
16593     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16594     case Intrinsic::x86_avx2_psllv_d:
16595     case Intrinsic::x86_avx2_psllv_q:
16596     case Intrinsic::x86_avx2_psllv_d_256:
16597     case Intrinsic::x86_avx2_psllv_q_256:
16598       Opcode = ISD::SHL;
16599       break;
16600     case Intrinsic::x86_avx2_psrlv_d:
16601     case Intrinsic::x86_avx2_psrlv_q:
16602     case Intrinsic::x86_avx2_psrlv_d_256:
16603     case Intrinsic::x86_avx2_psrlv_q_256:
16604       Opcode = ISD::SRL;
16605       break;
16606     case Intrinsic::x86_avx2_psrav_d:
16607     case Intrinsic::x86_avx2_psrav_d_256:
16608       Opcode = ISD::SRA;
16609       break;
16610     }
16611     return DAG.getNode(Opcode, dl, Op.getValueType(),
16612                        Op.getOperand(1), Op.getOperand(2));
16613   }
16614
16615   case Intrinsic::x86_sse2_packssdw_128:
16616   case Intrinsic::x86_sse2_packsswb_128:
16617   case Intrinsic::x86_avx2_packssdw:
16618   case Intrinsic::x86_avx2_packsswb:
16619     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
16620                        Op.getOperand(1), Op.getOperand(2));
16621
16622   case Intrinsic::x86_sse2_packuswb_128:
16623   case Intrinsic::x86_sse41_packusdw:
16624   case Intrinsic::x86_avx2_packuswb:
16625   case Intrinsic::x86_avx2_packusdw:
16626     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
16627                        Op.getOperand(1), Op.getOperand(2));
16628
16629   case Intrinsic::x86_ssse3_pshuf_b_128:
16630   case Intrinsic::x86_avx2_pshuf_b:
16631     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
16632                        Op.getOperand(1), Op.getOperand(2));
16633
16634   case Intrinsic::x86_sse2_pshuf_d:
16635     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
16636                        Op.getOperand(1), Op.getOperand(2));
16637
16638   case Intrinsic::x86_sse2_pshufl_w:
16639     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
16640                        Op.getOperand(1), Op.getOperand(2));
16641
16642   case Intrinsic::x86_sse2_pshufh_w:
16643     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
16644                        Op.getOperand(1), Op.getOperand(2));
16645
16646   case Intrinsic::x86_ssse3_psign_b_128:
16647   case Intrinsic::x86_ssse3_psign_w_128:
16648   case Intrinsic::x86_ssse3_psign_d_128:
16649   case Intrinsic::x86_avx2_psign_b:
16650   case Intrinsic::x86_avx2_psign_w:
16651   case Intrinsic::x86_avx2_psign_d:
16652     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
16653                        Op.getOperand(1), Op.getOperand(2));
16654
16655   case Intrinsic::x86_avx2_permd:
16656   case Intrinsic::x86_avx2_permps:
16657     // Operands intentionally swapped. Mask is last operand to intrinsic,
16658     // but second operand for node/instruction.
16659     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16660                        Op.getOperand(2), Op.getOperand(1));
16661
16662   case Intrinsic::x86_avx512_mask_valign_q_512:
16663   case Intrinsic::x86_avx512_mask_valign_d_512:
16664     // Vector source operands are swapped.
16665     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
16666                                             Op.getValueType(), Op.getOperand(2),
16667                                             Op.getOperand(1),
16668                                             Op.getOperand(3)),
16669                                 Op.getOperand(5), Op.getOperand(4),
16670                                 Subtarget, DAG);
16671
16672   // ptest and testp intrinsics. The intrinsic these come from are designed to
16673   // return an integer value, not just an instruction so lower it to the ptest
16674   // or testp pattern and a setcc for the result.
16675   case Intrinsic::x86_sse41_ptestz:
16676   case Intrinsic::x86_sse41_ptestc:
16677   case Intrinsic::x86_sse41_ptestnzc:
16678   case Intrinsic::x86_avx_ptestz_256:
16679   case Intrinsic::x86_avx_ptestc_256:
16680   case Intrinsic::x86_avx_ptestnzc_256:
16681   case Intrinsic::x86_avx_vtestz_ps:
16682   case Intrinsic::x86_avx_vtestc_ps:
16683   case Intrinsic::x86_avx_vtestnzc_ps:
16684   case Intrinsic::x86_avx_vtestz_pd:
16685   case Intrinsic::x86_avx_vtestc_pd:
16686   case Intrinsic::x86_avx_vtestnzc_pd:
16687   case Intrinsic::x86_avx_vtestz_ps_256:
16688   case Intrinsic::x86_avx_vtestc_ps_256:
16689   case Intrinsic::x86_avx_vtestnzc_ps_256:
16690   case Intrinsic::x86_avx_vtestz_pd_256:
16691   case Intrinsic::x86_avx_vtestc_pd_256:
16692   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16693     bool IsTestPacked = false;
16694     unsigned X86CC;
16695     switch (IntNo) {
16696     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16697     case Intrinsic::x86_avx_vtestz_ps:
16698     case Intrinsic::x86_avx_vtestz_pd:
16699     case Intrinsic::x86_avx_vtestz_ps_256:
16700     case Intrinsic::x86_avx_vtestz_pd_256:
16701       IsTestPacked = true; // Fallthrough
16702     case Intrinsic::x86_sse41_ptestz:
16703     case Intrinsic::x86_avx_ptestz_256:
16704       // ZF = 1
16705       X86CC = X86::COND_E;
16706       break;
16707     case Intrinsic::x86_avx_vtestc_ps:
16708     case Intrinsic::x86_avx_vtestc_pd:
16709     case Intrinsic::x86_avx_vtestc_ps_256:
16710     case Intrinsic::x86_avx_vtestc_pd_256:
16711       IsTestPacked = true; // Fallthrough
16712     case Intrinsic::x86_sse41_ptestc:
16713     case Intrinsic::x86_avx_ptestc_256:
16714       // CF = 1
16715       X86CC = X86::COND_B;
16716       break;
16717     case Intrinsic::x86_avx_vtestnzc_ps:
16718     case Intrinsic::x86_avx_vtestnzc_pd:
16719     case Intrinsic::x86_avx_vtestnzc_ps_256:
16720     case Intrinsic::x86_avx_vtestnzc_pd_256:
16721       IsTestPacked = true; // Fallthrough
16722     case Intrinsic::x86_sse41_ptestnzc:
16723     case Intrinsic::x86_avx_ptestnzc_256:
16724       // ZF and CF = 0
16725       X86CC = X86::COND_A;
16726       break;
16727     }
16728
16729     SDValue LHS = Op.getOperand(1);
16730     SDValue RHS = Op.getOperand(2);
16731     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16732     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16733     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
16734     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16735     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16736   }
16737   case Intrinsic::x86_avx512_kortestz_w:
16738   case Intrinsic::x86_avx512_kortestc_w: {
16739     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16740     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
16741     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
16742     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
16743     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16744     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16745     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16746   }
16747
16748   case Intrinsic::x86_sse42_pcmpistria128:
16749   case Intrinsic::x86_sse42_pcmpestria128:
16750   case Intrinsic::x86_sse42_pcmpistric128:
16751   case Intrinsic::x86_sse42_pcmpestric128:
16752   case Intrinsic::x86_sse42_pcmpistrio128:
16753   case Intrinsic::x86_sse42_pcmpestrio128:
16754   case Intrinsic::x86_sse42_pcmpistris128:
16755   case Intrinsic::x86_sse42_pcmpestris128:
16756   case Intrinsic::x86_sse42_pcmpistriz128:
16757   case Intrinsic::x86_sse42_pcmpestriz128: {
16758     unsigned Opcode;
16759     unsigned X86CC;
16760     switch (IntNo) {
16761     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16762     case Intrinsic::x86_sse42_pcmpistria128:
16763       Opcode = X86ISD::PCMPISTRI;
16764       X86CC = X86::COND_A;
16765       break;
16766     case Intrinsic::x86_sse42_pcmpestria128:
16767       Opcode = X86ISD::PCMPESTRI;
16768       X86CC = X86::COND_A;
16769       break;
16770     case Intrinsic::x86_sse42_pcmpistric128:
16771       Opcode = X86ISD::PCMPISTRI;
16772       X86CC = X86::COND_B;
16773       break;
16774     case Intrinsic::x86_sse42_pcmpestric128:
16775       Opcode = X86ISD::PCMPESTRI;
16776       X86CC = X86::COND_B;
16777       break;
16778     case Intrinsic::x86_sse42_pcmpistrio128:
16779       Opcode = X86ISD::PCMPISTRI;
16780       X86CC = X86::COND_O;
16781       break;
16782     case Intrinsic::x86_sse42_pcmpestrio128:
16783       Opcode = X86ISD::PCMPESTRI;
16784       X86CC = X86::COND_O;
16785       break;
16786     case Intrinsic::x86_sse42_pcmpistris128:
16787       Opcode = X86ISD::PCMPISTRI;
16788       X86CC = X86::COND_S;
16789       break;
16790     case Intrinsic::x86_sse42_pcmpestris128:
16791       Opcode = X86ISD::PCMPESTRI;
16792       X86CC = X86::COND_S;
16793       break;
16794     case Intrinsic::x86_sse42_pcmpistriz128:
16795       Opcode = X86ISD::PCMPISTRI;
16796       X86CC = X86::COND_E;
16797       break;
16798     case Intrinsic::x86_sse42_pcmpestriz128:
16799       Opcode = X86ISD::PCMPESTRI;
16800       X86CC = X86::COND_E;
16801       break;
16802     }
16803     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16804     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16805     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16806     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16807                                 DAG.getConstant(X86CC, MVT::i8),
16808                                 SDValue(PCMP.getNode(), 1));
16809     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16810   }
16811
16812   case Intrinsic::x86_sse42_pcmpistri128:
16813   case Intrinsic::x86_sse42_pcmpestri128: {
16814     unsigned Opcode;
16815     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16816       Opcode = X86ISD::PCMPISTRI;
16817     else
16818       Opcode = X86ISD::PCMPESTRI;
16819
16820     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16821     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16822     return DAG.getNode(Opcode, dl, VTs, NewOps);
16823   }
16824
16825   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
16826   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
16827   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
16828   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
16829   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
16830   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
16831   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
16832   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
16833   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
16834   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
16835   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
16836   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
16837     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
16838     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
16839       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
16840                                               dl, Op.getValueType(),
16841                                               Op.getOperand(1),
16842                                               Op.getOperand(2),
16843                                               Op.getOperand(3)),
16844                                   Op.getOperand(4), Op.getOperand(1),
16845                                   Subtarget, DAG);
16846     else
16847       return SDValue();
16848   }
16849
16850   case Intrinsic::x86_fma_vfmadd_ps:
16851   case Intrinsic::x86_fma_vfmadd_pd:
16852   case Intrinsic::x86_fma_vfmsub_ps:
16853   case Intrinsic::x86_fma_vfmsub_pd:
16854   case Intrinsic::x86_fma_vfnmadd_ps:
16855   case Intrinsic::x86_fma_vfnmadd_pd:
16856   case Intrinsic::x86_fma_vfnmsub_ps:
16857   case Intrinsic::x86_fma_vfnmsub_pd:
16858   case Intrinsic::x86_fma_vfmaddsub_ps:
16859   case Intrinsic::x86_fma_vfmaddsub_pd:
16860   case Intrinsic::x86_fma_vfmsubadd_ps:
16861   case Intrinsic::x86_fma_vfmsubadd_pd:
16862   case Intrinsic::x86_fma_vfmadd_ps_256:
16863   case Intrinsic::x86_fma_vfmadd_pd_256:
16864   case Intrinsic::x86_fma_vfmsub_ps_256:
16865   case Intrinsic::x86_fma_vfmsub_pd_256:
16866   case Intrinsic::x86_fma_vfnmadd_ps_256:
16867   case Intrinsic::x86_fma_vfnmadd_pd_256:
16868   case Intrinsic::x86_fma_vfnmsub_ps_256:
16869   case Intrinsic::x86_fma_vfnmsub_pd_256:
16870   case Intrinsic::x86_fma_vfmaddsub_ps_256:
16871   case Intrinsic::x86_fma_vfmaddsub_pd_256:
16872   case Intrinsic::x86_fma_vfmsubadd_ps_256:
16873   case Intrinsic::x86_fma_vfmsubadd_pd_256:
16874     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
16875                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
16876   }
16877 }
16878
16879 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16880                               SDValue Src, SDValue Mask, SDValue Base,
16881                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16882                               const X86Subtarget * Subtarget) {
16883   SDLoc dl(Op);
16884   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16885   assert(C && "Invalid scale type");
16886   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
16887   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16888                              Index.getSimpleValueType().getVectorNumElements());
16889   SDValue MaskInReg;
16890   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16891   if (MaskC)
16892     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
16893   else
16894     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
16895   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16896   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
16897   SDValue Segment = DAG.getRegister(0, MVT::i32);
16898   if (Src.getOpcode() == ISD::UNDEF)
16899     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16900   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16901   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16902   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16903   return DAG.getMergeValues(RetOps, dl);
16904 }
16905
16906 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16907                                SDValue Src, SDValue Mask, SDValue Base,
16908                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16909   SDLoc dl(Op);
16910   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16911   assert(C && "Invalid scale type");
16912   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
16913   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
16914   SDValue Segment = DAG.getRegister(0, MVT::i32);
16915   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16916                              Index.getSimpleValueType().getVectorNumElements());
16917   SDValue MaskInReg;
16918   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16919   if (MaskC)
16920     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
16921   else
16922     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
16923   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16924   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16925   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16926   return SDValue(Res, 1);
16927 }
16928
16929 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16930                                SDValue Mask, SDValue Base, SDValue Index,
16931                                SDValue ScaleOp, SDValue Chain) {
16932   SDLoc dl(Op);
16933   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16934   assert(C && "Invalid scale type");
16935   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
16936   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
16937   SDValue Segment = DAG.getRegister(0, MVT::i32);
16938   EVT MaskVT =
16939     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16940   SDValue MaskInReg;
16941   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16942   if (MaskC)
16943     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
16944   else
16945     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
16946   //SDVTList VTs = DAG.getVTList(MVT::Other);
16947   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16948   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16949   return SDValue(Res, 0);
16950 }
16951
16952 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16953 // read performance monitor counters (x86_rdpmc).
16954 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16955                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16956                               SmallVectorImpl<SDValue> &Results) {
16957   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16958   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16959   SDValue LO, HI;
16960
16961   // The ECX register is used to select the index of the performance counter
16962   // to read.
16963   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16964                                    N->getOperand(2));
16965   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16966
16967   // Reads the content of a 64-bit performance counter and returns it in the
16968   // registers EDX:EAX.
16969   if (Subtarget->is64Bit()) {
16970     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16971     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16972                             LO.getValue(2));
16973   } else {
16974     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16975     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16976                             LO.getValue(2));
16977   }
16978   Chain = HI.getValue(1);
16979
16980   if (Subtarget->is64Bit()) {
16981     // The EAX register is loaded with the low-order 32 bits. The EDX register
16982     // is loaded with the supported high-order bits of the counter.
16983     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16984                               DAG.getConstant(32, MVT::i8));
16985     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16986     Results.push_back(Chain);
16987     return;
16988   }
16989
16990   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16991   SDValue Ops[] = { LO, HI };
16992   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16993   Results.push_back(Pair);
16994   Results.push_back(Chain);
16995 }
16996
16997 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16998 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16999 // also used to custom lower READCYCLECOUNTER nodes.
17000 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17001                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17002                               SmallVectorImpl<SDValue> &Results) {
17003   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17004   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17005   SDValue LO, HI;
17006
17007   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17008   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17009   // and the EAX register is loaded with the low-order 32 bits.
17010   if (Subtarget->is64Bit()) {
17011     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17012     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17013                             LO.getValue(2));
17014   } else {
17015     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17016     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17017                             LO.getValue(2));
17018   }
17019   SDValue Chain = HI.getValue(1);
17020
17021   if (Opcode == X86ISD::RDTSCP_DAG) {
17022     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17023
17024     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17025     // the ECX register. Add 'ecx' explicitly to the chain.
17026     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17027                                      HI.getValue(2));
17028     // Explicitly store the content of ECX at the location passed in input
17029     // to the 'rdtscp' intrinsic.
17030     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17031                          MachinePointerInfo(), false, false, 0);
17032   }
17033
17034   if (Subtarget->is64Bit()) {
17035     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17036     // the EAX register is loaded with the low-order 32 bits.
17037     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17038                               DAG.getConstant(32, MVT::i8));
17039     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17040     Results.push_back(Chain);
17041     return;
17042   }
17043
17044   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17045   SDValue Ops[] = { LO, HI };
17046   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17047   Results.push_back(Pair);
17048   Results.push_back(Chain);
17049 }
17050
17051 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17052                                      SelectionDAG &DAG) {
17053   SmallVector<SDValue, 2> Results;
17054   SDLoc DL(Op);
17055   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17056                           Results);
17057   return DAG.getMergeValues(Results, DL);
17058 }
17059
17060
17061 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17062                                       SelectionDAG &DAG) {
17063   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17064
17065   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17066   if (!IntrData)
17067     return SDValue();
17068
17069   SDLoc dl(Op);
17070   switch(IntrData->Type) {
17071   default:
17072     llvm_unreachable("Unknown Intrinsic Type");
17073     break;    
17074   case RDSEED:
17075   case RDRAND: {
17076     // Emit the node with the right value type.
17077     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17078     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17079
17080     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17081     // Otherwise return the value from Rand, which is always 0, casted to i32.
17082     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17083                       DAG.getConstant(1, Op->getValueType(1)),
17084                       DAG.getConstant(X86::COND_B, MVT::i32),
17085                       SDValue(Result.getNode(), 1) };
17086     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17087                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17088                                   Ops);
17089
17090     // Return { result, isValid, chain }.
17091     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17092                        SDValue(Result.getNode(), 2));
17093   }
17094   case GATHER: {
17095   //gather(v1, mask, index, base, scale);
17096     SDValue Chain = Op.getOperand(0);
17097     SDValue Src   = Op.getOperand(2);
17098     SDValue Base  = Op.getOperand(3);
17099     SDValue Index = Op.getOperand(4);
17100     SDValue Mask  = Op.getOperand(5);
17101     SDValue Scale = Op.getOperand(6);
17102     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
17103                           Subtarget);
17104   }
17105   case SCATTER: {
17106   //scatter(base, mask, index, v1, scale);
17107     SDValue Chain = Op.getOperand(0);
17108     SDValue Base  = Op.getOperand(2);
17109     SDValue Mask  = Op.getOperand(3);
17110     SDValue Index = Op.getOperand(4);
17111     SDValue Src   = Op.getOperand(5);
17112     SDValue Scale = Op.getOperand(6);
17113     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
17114   }
17115   case PREFETCH: {
17116     SDValue Hint = Op.getOperand(6);
17117     unsigned HintVal;
17118     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
17119         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
17120       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
17121     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17122     SDValue Chain = Op.getOperand(0);
17123     SDValue Mask  = Op.getOperand(2);
17124     SDValue Index = Op.getOperand(3);
17125     SDValue Base  = Op.getOperand(4);
17126     SDValue Scale = Op.getOperand(5);
17127     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17128   }
17129   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17130   case RDTSC: {
17131     SmallVector<SDValue, 2> Results;
17132     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
17133     return DAG.getMergeValues(Results, dl);
17134   }
17135   // Read Performance Monitoring Counters.
17136   case RDPMC: {
17137     SmallVector<SDValue, 2> Results;
17138     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17139     return DAG.getMergeValues(Results, dl);
17140   }
17141   // XTEST intrinsics.
17142   case XTEST: {
17143     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17144     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17145     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17146                                 DAG.getConstant(X86::COND_NE, MVT::i8),
17147                                 InTrans);
17148     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17149     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17150                        Ret, SDValue(InTrans.getNode(), 1));
17151   }
17152   // ADC/ADCX/SBB
17153   case ADX: {
17154     SmallVector<SDValue, 2> Results;
17155     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17156     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17157     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17158                                 DAG.getConstant(-1, MVT::i8));
17159     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17160                               Op.getOperand(4), GenCF.getValue(1));
17161     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17162                                  Op.getOperand(5), MachinePointerInfo(),
17163                                  false, false, 0);
17164     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17165                                 DAG.getConstant(X86::COND_B, MVT::i8),
17166                                 Res.getValue(1));
17167     Results.push_back(SetCC);
17168     Results.push_back(Store);
17169     return DAG.getMergeValues(Results, dl);
17170   }
17171   }
17172 }
17173
17174 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17175                                            SelectionDAG &DAG) const {
17176   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17177   MFI->setReturnAddressIsTaken(true);
17178
17179   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17180     return SDValue();
17181
17182   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17183   SDLoc dl(Op);
17184   EVT PtrVT = getPointerTy();
17185
17186   if (Depth > 0) {
17187     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17188     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17189         DAG.getSubtarget().getRegisterInfo());
17190     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
17191     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17192                        DAG.getNode(ISD::ADD, dl, PtrVT,
17193                                    FrameAddr, Offset),
17194                        MachinePointerInfo(), false, false, false, 0);
17195   }
17196
17197   // Just load the return address.
17198   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17199   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17200                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17201 }
17202
17203 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17204   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17205   MFI->setFrameAddressIsTaken(true);
17206
17207   EVT VT = Op.getValueType();
17208   SDLoc dl(Op);  // FIXME probably not meaningful
17209   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17210   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17211       DAG.getSubtarget().getRegisterInfo());
17212   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17213   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17214           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17215          "Invalid Frame Register!");
17216   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17217   while (Depth--)
17218     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17219                             MachinePointerInfo(),
17220                             false, false, false, 0);
17221   return FrameAddr;
17222 }
17223
17224 // FIXME? Maybe this could be a TableGen attribute on some registers and
17225 // this table could be generated automatically from RegInfo.
17226 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
17227                                               EVT VT) const {
17228   unsigned Reg = StringSwitch<unsigned>(RegName)
17229                        .Case("esp", X86::ESP)
17230                        .Case("rsp", X86::RSP)
17231                        .Default(0);
17232   if (Reg)
17233     return Reg;
17234   report_fatal_error("Invalid register name global variable");
17235 }
17236
17237 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17238                                                      SelectionDAG &DAG) const {
17239   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17240       DAG.getSubtarget().getRegisterInfo());
17241   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
17242 }
17243
17244 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17245   SDValue Chain     = Op.getOperand(0);
17246   SDValue Offset    = Op.getOperand(1);
17247   SDValue Handler   = Op.getOperand(2);
17248   SDLoc dl      (Op);
17249
17250   EVT PtrVT = getPointerTy();
17251   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17252       DAG.getSubtarget().getRegisterInfo());
17253   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17254   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17255           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17256          "Invalid Frame Register!");
17257   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17258   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17259
17260   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17261                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
17262   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17263   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17264                        false, false, 0);
17265   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17266
17267   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17268                      DAG.getRegister(StoreAddrReg, PtrVT));
17269 }
17270
17271 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17272                                                SelectionDAG &DAG) const {
17273   SDLoc DL(Op);
17274   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17275                      DAG.getVTList(MVT::i32, MVT::Other),
17276                      Op.getOperand(0), Op.getOperand(1));
17277 }
17278
17279 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17280                                                 SelectionDAG &DAG) const {
17281   SDLoc DL(Op);
17282   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17283                      Op.getOperand(0), Op.getOperand(1));
17284 }
17285
17286 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17287   return Op.getOperand(0);
17288 }
17289
17290 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17291                                                 SelectionDAG &DAG) const {
17292   SDValue Root = Op.getOperand(0);
17293   SDValue Trmp = Op.getOperand(1); // trampoline
17294   SDValue FPtr = Op.getOperand(2); // nested function
17295   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17296   SDLoc dl (Op);
17297
17298   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17299   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
17300
17301   if (Subtarget->is64Bit()) {
17302     SDValue OutChains[6];
17303
17304     // Large code-model.
17305     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17306     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17307
17308     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17309     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17310
17311     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17312
17313     // Load the pointer to the nested function into R11.
17314     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17315     SDValue Addr = Trmp;
17316     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17317                                 Addr, MachinePointerInfo(TrmpAddr),
17318                                 false, false, 0);
17319
17320     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17321                        DAG.getConstant(2, MVT::i64));
17322     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17323                                 MachinePointerInfo(TrmpAddr, 2),
17324                                 false, false, 2);
17325
17326     // Load the 'nest' parameter value into R10.
17327     // R10 is specified in X86CallingConv.td
17328     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17329     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17330                        DAG.getConstant(10, MVT::i64));
17331     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17332                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17333                                 false, false, 0);
17334
17335     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17336                        DAG.getConstant(12, MVT::i64));
17337     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17338                                 MachinePointerInfo(TrmpAddr, 12),
17339                                 false, false, 2);
17340
17341     // Jump to the nested function.
17342     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17343     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17344                        DAG.getConstant(20, MVT::i64));
17345     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17346                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17347                                 false, false, 0);
17348
17349     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17350     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17351                        DAG.getConstant(22, MVT::i64));
17352     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
17353                                 MachinePointerInfo(TrmpAddr, 22),
17354                                 false, false, 0);
17355
17356     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17357   } else {
17358     const Function *Func =
17359       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17360     CallingConv::ID CC = Func->getCallingConv();
17361     unsigned NestReg;
17362
17363     switch (CC) {
17364     default:
17365       llvm_unreachable("Unsupported calling convention");
17366     case CallingConv::C:
17367     case CallingConv::X86_StdCall: {
17368       // Pass 'nest' parameter in ECX.
17369       // Must be kept in sync with X86CallingConv.td
17370       NestReg = X86::ECX;
17371
17372       // Check that ECX wasn't needed by an 'inreg' parameter.
17373       FunctionType *FTy = Func->getFunctionType();
17374       const AttributeSet &Attrs = Func->getAttributes();
17375
17376       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17377         unsigned InRegCount = 0;
17378         unsigned Idx = 1;
17379
17380         for (FunctionType::param_iterator I = FTy->param_begin(),
17381              E = FTy->param_end(); I != E; ++I, ++Idx)
17382           if (Attrs.hasAttribute(Idx, Attribute::InReg))
17383             // FIXME: should only count parameters that are lowered to integers.
17384             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
17385
17386         if (InRegCount > 2) {
17387           report_fatal_error("Nest register in use - reduce number of inreg"
17388                              " parameters!");
17389         }
17390       }
17391       break;
17392     }
17393     case CallingConv::X86_FastCall:
17394     case CallingConv::X86_ThisCall:
17395     case CallingConv::Fast:
17396       // Pass 'nest' parameter in EAX.
17397       // Must be kept in sync with X86CallingConv.td
17398       NestReg = X86::EAX;
17399       break;
17400     }
17401
17402     SDValue OutChains[4];
17403     SDValue Addr, Disp;
17404
17405     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17406                        DAG.getConstant(10, MVT::i32));
17407     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17408
17409     // This is storing the opcode for MOV32ri.
17410     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17411     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17412     OutChains[0] = DAG.getStore(Root, dl,
17413                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
17414                                 Trmp, MachinePointerInfo(TrmpAddr),
17415                                 false, false, 0);
17416
17417     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17418                        DAG.getConstant(1, MVT::i32));
17419     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17420                                 MachinePointerInfo(TrmpAddr, 1),
17421                                 false, false, 1);
17422
17423     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17424     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17425                        DAG.getConstant(5, MVT::i32));
17426     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
17427                                 MachinePointerInfo(TrmpAddr, 5),
17428                                 false, false, 1);
17429
17430     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17431                        DAG.getConstant(6, MVT::i32));
17432     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17433                                 MachinePointerInfo(TrmpAddr, 6),
17434                                 false, false, 1);
17435
17436     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17437   }
17438 }
17439
17440 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17441                                             SelectionDAG &DAG) const {
17442   /*
17443    The rounding mode is in bits 11:10 of FPSR, and has the following
17444    settings:
17445      00 Round to nearest
17446      01 Round to -inf
17447      10 Round to +inf
17448      11 Round to 0
17449
17450   FLT_ROUNDS, on the other hand, expects the following:
17451     -1 Undefined
17452      0 Round to 0
17453      1 Round to nearest
17454      2 Round to +inf
17455      3 Round to -inf
17456
17457   To perform the conversion, we do:
17458     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17459   */
17460
17461   MachineFunction &MF = DAG.getMachineFunction();
17462   const TargetMachine &TM = MF.getTarget();
17463   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
17464   unsigned StackAlignment = TFI.getStackAlignment();
17465   MVT VT = Op.getSimpleValueType();
17466   SDLoc DL(Op);
17467
17468   // Save FP Control Word to stack slot
17469   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17470   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
17471
17472   MachineMemOperand *MMO =
17473    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
17474                            MachineMemOperand::MOStore, 2, 2);
17475
17476   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17477   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17478                                           DAG.getVTList(MVT::Other),
17479                                           Ops, MVT::i16, MMO);
17480
17481   // Load FP Control Word from stack slot
17482   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17483                             MachinePointerInfo(), false, false, false, 0);
17484
17485   // Transform as necessary
17486   SDValue CWD1 =
17487     DAG.getNode(ISD::SRL, DL, MVT::i16,
17488                 DAG.getNode(ISD::AND, DL, MVT::i16,
17489                             CWD, DAG.getConstant(0x800, MVT::i16)),
17490                 DAG.getConstant(11, MVT::i8));
17491   SDValue CWD2 =
17492     DAG.getNode(ISD::SRL, DL, MVT::i16,
17493                 DAG.getNode(ISD::AND, DL, MVT::i16,
17494                             CWD, DAG.getConstant(0x400, MVT::i16)),
17495                 DAG.getConstant(9, MVT::i8));
17496
17497   SDValue RetVal =
17498     DAG.getNode(ISD::AND, DL, MVT::i16,
17499                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17500                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17501                             DAG.getConstant(1, MVT::i16)),
17502                 DAG.getConstant(3, MVT::i16));
17503
17504   return DAG.getNode((VT.getSizeInBits() < 16 ?
17505                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17506 }
17507
17508 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17509   MVT VT = Op.getSimpleValueType();
17510   EVT OpVT = VT;
17511   unsigned NumBits = VT.getSizeInBits();
17512   SDLoc dl(Op);
17513
17514   Op = Op.getOperand(0);
17515   if (VT == MVT::i8) {
17516     // Zero extend to i32 since there is not an i8 bsr.
17517     OpVT = MVT::i32;
17518     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17519   }
17520
17521   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17522   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17523   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17524
17525   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17526   SDValue Ops[] = {
17527     Op,
17528     DAG.getConstant(NumBits+NumBits-1, OpVT),
17529     DAG.getConstant(X86::COND_E, MVT::i8),
17530     Op.getValue(1)
17531   };
17532   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17533
17534   // Finally xor with NumBits-1.
17535   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17536
17537   if (VT == MVT::i8)
17538     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17539   return Op;
17540 }
17541
17542 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17543   MVT VT = Op.getSimpleValueType();
17544   EVT OpVT = VT;
17545   unsigned NumBits = VT.getSizeInBits();
17546   SDLoc dl(Op);
17547
17548   Op = Op.getOperand(0);
17549   if (VT == MVT::i8) {
17550     // Zero extend to i32 since there is not an i8 bsr.
17551     OpVT = MVT::i32;
17552     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17553   }
17554
17555   // Issue a bsr (scan bits in reverse).
17556   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17557   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17558
17559   // And xor with NumBits-1.
17560   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17561
17562   if (VT == MVT::i8)
17563     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17564   return Op;
17565 }
17566
17567 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17568   MVT VT = Op.getSimpleValueType();
17569   unsigned NumBits = VT.getSizeInBits();
17570   SDLoc dl(Op);
17571   Op = Op.getOperand(0);
17572
17573   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17574   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17575   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17576
17577   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17578   SDValue Ops[] = {
17579     Op,
17580     DAG.getConstant(NumBits, VT),
17581     DAG.getConstant(X86::COND_E, MVT::i8),
17582     Op.getValue(1)
17583   };
17584   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17585 }
17586
17587 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17588 // ones, and then concatenate the result back.
17589 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17590   MVT VT = Op.getSimpleValueType();
17591
17592   assert(VT.is256BitVector() && VT.isInteger() &&
17593          "Unsupported value type for operation");
17594
17595   unsigned NumElems = VT.getVectorNumElements();
17596   SDLoc dl(Op);
17597
17598   // Extract the LHS vectors
17599   SDValue LHS = Op.getOperand(0);
17600   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17601   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17602
17603   // Extract the RHS vectors
17604   SDValue RHS = Op.getOperand(1);
17605   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17606   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17607
17608   MVT EltVT = VT.getVectorElementType();
17609   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17610
17611   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17612                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17613                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17614 }
17615
17616 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17617   assert(Op.getSimpleValueType().is256BitVector() &&
17618          Op.getSimpleValueType().isInteger() &&
17619          "Only handle AVX 256-bit vector integer operation");
17620   return Lower256IntArith(Op, DAG);
17621 }
17622
17623 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17624   assert(Op.getSimpleValueType().is256BitVector() &&
17625          Op.getSimpleValueType().isInteger() &&
17626          "Only handle AVX 256-bit vector integer operation");
17627   return Lower256IntArith(Op, DAG);
17628 }
17629
17630 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17631                         SelectionDAG &DAG) {
17632   SDLoc dl(Op);
17633   MVT VT = Op.getSimpleValueType();
17634
17635   // Decompose 256-bit ops into smaller 128-bit ops.
17636   if (VT.is256BitVector() && !Subtarget->hasInt256())
17637     return Lower256IntArith(Op, DAG);
17638
17639   SDValue A = Op.getOperand(0);
17640   SDValue B = Op.getOperand(1);
17641
17642   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17643   if (VT == MVT::v4i32) {
17644     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17645            "Should not custom lower when pmuldq is available!");
17646
17647     // Extract the odd parts.
17648     static const int UnpackMask[] = { 1, -1, 3, -1 };
17649     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17650     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17651
17652     // Multiply the even parts.
17653     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17654     // Now multiply odd parts.
17655     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17656
17657     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
17658     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
17659
17660     // Merge the two vectors back together with a shuffle. This expands into 2
17661     // shuffles.
17662     static const int ShufMask[] = { 0, 4, 2, 6 };
17663     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17664   }
17665
17666   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17667          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17668
17669   //  Ahi = psrlqi(a, 32);
17670   //  Bhi = psrlqi(b, 32);
17671   //
17672   //  AloBlo = pmuludq(a, b);
17673   //  AloBhi = pmuludq(a, Bhi);
17674   //  AhiBlo = pmuludq(Ahi, b);
17675
17676   //  AloBhi = psllqi(AloBhi, 32);
17677   //  AhiBlo = psllqi(AhiBlo, 32);
17678   //  return AloBlo + AloBhi + AhiBlo;
17679
17680   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17681   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17682
17683   // Bit cast to 32-bit vectors for MULUDQ
17684   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17685                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17686   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
17687   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
17688   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
17689   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
17690
17691   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17692   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17693   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17694
17695   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17696   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17697
17698   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17699   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17700 }
17701
17702 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17703   assert(Subtarget->isTargetWin64() && "Unexpected target");
17704   EVT VT = Op.getValueType();
17705   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17706          "Unexpected return type for lowering");
17707
17708   RTLIB::Libcall LC;
17709   bool isSigned;
17710   switch (Op->getOpcode()) {
17711   default: llvm_unreachable("Unexpected request for libcall!");
17712   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17713   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17714   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17715   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17716   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17717   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17718   }
17719
17720   SDLoc dl(Op);
17721   SDValue InChain = DAG.getEntryNode();
17722
17723   TargetLowering::ArgListTy Args;
17724   TargetLowering::ArgListEntry Entry;
17725   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17726     EVT ArgVT = Op->getOperand(i).getValueType();
17727     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17728            "Unexpected argument type for lowering");
17729     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17730     Entry.Node = StackPtr;
17731     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17732                            false, false, 16);
17733     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17734     Entry.Ty = PointerType::get(ArgTy,0);
17735     Entry.isSExt = false;
17736     Entry.isZExt = false;
17737     Args.push_back(Entry);
17738   }
17739
17740   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17741                                          getPointerTy());
17742
17743   TargetLowering::CallLoweringInfo CLI(DAG);
17744   CLI.setDebugLoc(dl).setChain(InChain)
17745     .setCallee(getLibcallCallingConv(LC),
17746                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17747                Callee, std::move(Args), 0)
17748     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17749
17750   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17751   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
17752 }
17753
17754 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17755                              SelectionDAG &DAG) {
17756   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17757   EVT VT = Op0.getValueType();
17758   SDLoc dl(Op);
17759
17760   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17761          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17762
17763   // PMULxD operations multiply each even value (starting at 0) of LHS with
17764   // the related value of RHS and produce a widen result.
17765   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17766   // => <2 x i64> <ae|cg>
17767   //
17768   // In other word, to have all the results, we need to perform two PMULxD:
17769   // 1. one with the even values.
17770   // 2. one with the odd values.
17771   // To achieve #2, with need to place the odd values at an even position.
17772   //
17773   // Place the odd value at an even position (basically, shift all values 1
17774   // step to the left):
17775   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17776   // <a|b|c|d> => <b|undef|d|undef>
17777   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17778   // <e|f|g|h> => <f|undef|h|undef>
17779   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17780
17781   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17782   // ints.
17783   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17784   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17785   unsigned Opcode =
17786       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17787   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17788   // => <2 x i64> <ae|cg>
17789   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
17790                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17791   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17792   // => <2 x i64> <bf|dh>
17793   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
17794                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17795
17796   // Shuffle it back into the right order.
17797   SDValue Highs, Lows;
17798   if (VT == MVT::v8i32) {
17799     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17800     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17801     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17802     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17803   } else {
17804     const int HighMask[] = {1, 5, 3, 7};
17805     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17806     const int LowMask[] = {0, 4, 2, 6};
17807     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17808   }
17809
17810   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17811   // unsigned multiply.
17812   if (IsSigned && !Subtarget->hasSSE41()) {
17813     SDValue ShAmt =
17814         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
17815     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17816                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17817     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17818                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17819
17820     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17821     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17822   }
17823
17824   // The first result of MUL_LOHI is actually the low value, followed by the
17825   // high value.
17826   SDValue Ops[] = {Lows, Highs};
17827   return DAG.getMergeValues(Ops, dl);
17828 }
17829
17830 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17831                                          const X86Subtarget *Subtarget) {
17832   MVT VT = Op.getSimpleValueType();
17833   SDLoc dl(Op);
17834   SDValue R = Op.getOperand(0);
17835   SDValue Amt = Op.getOperand(1);
17836
17837   // Optimize shl/srl/sra with constant shift amount.
17838   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17839     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17840       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17841
17842       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
17843           (Subtarget->hasInt256() &&
17844            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
17845           (Subtarget->hasAVX512() &&
17846            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
17847         if (Op.getOpcode() == ISD::SHL)
17848           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
17849                                             DAG);
17850         if (Op.getOpcode() == ISD::SRL)
17851           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
17852                                             DAG);
17853         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
17854           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
17855                                             DAG);
17856       }
17857
17858       if (VT == MVT::v16i8) {
17859         if (Op.getOpcode() == ISD::SHL) {
17860           // Make a large shift.
17861           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
17862                                                    MVT::v8i16, R, ShiftAmt,
17863                                                    DAG);
17864           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
17865           // Zero out the rightmost bits.
17866           SmallVector<SDValue, 16> V(16,
17867                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
17868                                                      MVT::i8));
17869           return DAG.getNode(ISD::AND, dl, VT, SHL,
17870                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17871         }
17872         if (Op.getOpcode() == ISD::SRL) {
17873           // Make a large shift.
17874           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
17875                                                    MVT::v8i16, R, ShiftAmt,
17876                                                    DAG);
17877           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
17878           // Zero out the leftmost bits.
17879           SmallVector<SDValue, 16> V(16,
17880                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
17881                                                      MVT::i8));
17882           return DAG.getNode(ISD::AND, dl, VT, SRL,
17883                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17884         }
17885         if (Op.getOpcode() == ISD::SRA) {
17886           if (ShiftAmt == 7) {
17887             // R s>> 7  ===  R s< 0
17888             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17889             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17890           }
17891
17892           // R s>> a === ((R u>> a) ^ m) - m
17893           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17894           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
17895                                                          MVT::i8));
17896           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17897           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17898           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17899           return Res;
17900         }
17901         llvm_unreachable("Unknown shift opcode.");
17902       }
17903
17904       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
17905         if (Op.getOpcode() == ISD::SHL) {
17906           // Make a large shift.
17907           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
17908                                                    MVT::v16i16, R, ShiftAmt,
17909                                                    DAG);
17910           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
17911           // Zero out the rightmost bits.
17912           SmallVector<SDValue, 32> V(32,
17913                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
17914                                                      MVT::i8));
17915           return DAG.getNode(ISD::AND, dl, VT, SHL,
17916                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17917         }
17918         if (Op.getOpcode() == ISD::SRL) {
17919           // Make a large shift.
17920           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
17921                                                    MVT::v16i16, R, ShiftAmt,
17922                                                    DAG);
17923           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
17924           // Zero out the leftmost bits.
17925           SmallVector<SDValue, 32> V(32,
17926                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
17927                                                      MVT::i8));
17928           return DAG.getNode(ISD::AND, dl, VT, SRL,
17929                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17930         }
17931         if (Op.getOpcode() == ISD::SRA) {
17932           if (ShiftAmt == 7) {
17933             // R s>> 7  ===  R s< 0
17934             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17935             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17936           }
17937
17938           // R s>> a === ((R u>> a) ^ m) - m
17939           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17940           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
17941                                                          MVT::i8));
17942           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17943           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17944           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17945           return Res;
17946         }
17947         llvm_unreachable("Unknown shift opcode.");
17948       }
17949     }
17950   }
17951
17952   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17953   if (!Subtarget->is64Bit() &&
17954       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17955       Amt.getOpcode() == ISD::BITCAST &&
17956       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17957     Amt = Amt.getOperand(0);
17958     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17959                      VT.getVectorNumElements();
17960     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17961     uint64_t ShiftAmt = 0;
17962     for (unsigned i = 0; i != Ratio; ++i) {
17963       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17964       if (!C)
17965         return SDValue();
17966       // 6 == Log2(64)
17967       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17968     }
17969     // Check remaining shift amounts.
17970     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17971       uint64_t ShAmt = 0;
17972       for (unsigned j = 0; j != Ratio; ++j) {
17973         ConstantSDNode *C =
17974           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17975         if (!C)
17976           return SDValue();
17977         // 6 == Log2(64)
17978         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17979       }
17980       if (ShAmt != ShiftAmt)
17981         return SDValue();
17982     }
17983     switch (Op.getOpcode()) {
17984     default:
17985       llvm_unreachable("Unknown shift opcode!");
17986     case ISD::SHL:
17987       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
17988                                         DAG);
17989     case ISD::SRL:
17990       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
17991                                         DAG);
17992     case ISD::SRA:
17993       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
17994                                         DAG);
17995     }
17996   }
17997
17998   return SDValue();
17999 }
18000
18001 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18002                                         const X86Subtarget* Subtarget) {
18003   MVT VT = Op.getSimpleValueType();
18004   SDLoc dl(Op);
18005   SDValue R = Op.getOperand(0);
18006   SDValue Amt = Op.getOperand(1);
18007
18008   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
18009       VT == MVT::v4i32 || VT == MVT::v8i16 ||
18010       (Subtarget->hasInt256() &&
18011        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
18012         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18013        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18014     SDValue BaseShAmt;
18015     EVT EltVT = VT.getVectorElementType();
18016
18017     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18018       unsigned NumElts = VT.getVectorNumElements();
18019       unsigned i, j;
18020       for (i = 0; i != NumElts; ++i) {
18021         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
18022           continue;
18023         break;
18024       }
18025       for (j = i; j != NumElts; ++j) {
18026         SDValue Arg = Amt.getOperand(j);
18027         if (Arg.getOpcode() == ISD::UNDEF) continue;
18028         if (Arg != Amt.getOperand(i))
18029           break;
18030       }
18031       if (i != NumElts && j == NumElts)
18032         BaseShAmt = Amt.getOperand(i);
18033     } else {
18034       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18035         Amt = Amt.getOperand(0);
18036       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
18037                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
18038         SDValue InVec = Amt.getOperand(0);
18039         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18040           unsigned NumElts = InVec.getValueType().getVectorNumElements();
18041           unsigned i = 0;
18042           for (; i != NumElts; ++i) {
18043             SDValue Arg = InVec.getOperand(i);
18044             if (Arg.getOpcode() == ISD::UNDEF) continue;
18045             BaseShAmt = Arg;
18046             break;
18047           }
18048         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18049            if (ConstantSDNode *C =
18050                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18051              unsigned SplatIdx =
18052                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
18053              if (C->getZExtValue() == SplatIdx)
18054                BaseShAmt = InVec.getOperand(1);
18055            }
18056         }
18057         if (!BaseShAmt.getNode())
18058           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
18059                                   DAG.getIntPtrConstant(0));
18060       }
18061     }
18062
18063     if (BaseShAmt.getNode()) {
18064       if (EltVT.bitsGT(MVT::i32))
18065         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
18066       else if (EltVT.bitsLT(MVT::i32))
18067         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18068
18069       switch (Op.getOpcode()) {
18070       default:
18071         llvm_unreachable("Unknown shift opcode!");
18072       case ISD::SHL:
18073         switch (VT.SimpleTy) {
18074         default: return SDValue();
18075         case MVT::v2i64:
18076         case MVT::v4i32:
18077         case MVT::v8i16:
18078         case MVT::v4i64:
18079         case MVT::v8i32:
18080         case MVT::v16i16:
18081         case MVT::v16i32:
18082         case MVT::v8i64:
18083           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
18084         }
18085       case ISD::SRA:
18086         switch (VT.SimpleTy) {
18087         default: return SDValue();
18088         case MVT::v4i32:
18089         case MVT::v8i16:
18090         case MVT::v8i32:
18091         case MVT::v16i16:
18092         case MVT::v16i32:
18093         case MVT::v8i64:
18094           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
18095         }
18096       case ISD::SRL:
18097         switch (VT.SimpleTy) {
18098         default: return SDValue();
18099         case MVT::v2i64:
18100         case MVT::v4i32:
18101         case MVT::v8i16:
18102         case MVT::v4i64:
18103         case MVT::v8i32:
18104         case MVT::v16i16:
18105         case MVT::v16i32:
18106         case MVT::v8i64:
18107           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
18108         }
18109       }
18110     }
18111   }
18112
18113   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18114   if (!Subtarget->is64Bit() &&
18115       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
18116       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
18117       Amt.getOpcode() == ISD::BITCAST &&
18118       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18119     Amt = Amt.getOperand(0);
18120     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18121                      VT.getVectorNumElements();
18122     std::vector<SDValue> Vals(Ratio);
18123     for (unsigned i = 0; i != Ratio; ++i)
18124       Vals[i] = Amt.getOperand(i);
18125     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18126       for (unsigned j = 0; j != Ratio; ++j)
18127         if (Vals[j] != Amt.getOperand(i + j))
18128           return SDValue();
18129     }
18130     switch (Op.getOpcode()) {
18131     default:
18132       llvm_unreachable("Unknown shift opcode!");
18133     case ISD::SHL:
18134       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
18135     case ISD::SRL:
18136       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
18137     case ISD::SRA:
18138       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
18139     }
18140   }
18141
18142   return SDValue();
18143 }
18144
18145 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18146                           SelectionDAG &DAG) {
18147   MVT VT = Op.getSimpleValueType();
18148   SDLoc dl(Op);
18149   SDValue R = Op.getOperand(0);
18150   SDValue Amt = Op.getOperand(1);
18151   SDValue V;
18152
18153   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18154   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18155
18156   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
18157   if (V.getNode())
18158     return V;
18159
18160   V = LowerScalarVariableShift(Op, DAG, Subtarget);
18161   if (V.getNode())
18162       return V;
18163
18164   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
18165     return Op;
18166   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
18167   if (Subtarget->hasInt256()) {
18168     if (Op.getOpcode() == ISD::SRL &&
18169         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18170          VT == MVT::v4i64 || VT == MVT::v8i32))
18171       return Op;
18172     if (Op.getOpcode() == ISD::SHL &&
18173         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18174          VT == MVT::v4i64 || VT == MVT::v8i32))
18175       return Op;
18176     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
18177       return Op;
18178   }
18179
18180   // If possible, lower this packed shift into a vector multiply instead of
18181   // expanding it into a sequence of scalar shifts.
18182   // Do this only if the vector shift count is a constant build_vector.
18183   if (Op.getOpcode() == ISD::SHL && 
18184       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18185        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18186       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18187     SmallVector<SDValue, 8> Elts;
18188     EVT SVT = VT.getScalarType();
18189     unsigned SVTBits = SVT.getSizeInBits();
18190     const APInt &One = APInt(SVTBits, 1);
18191     unsigned NumElems = VT.getVectorNumElements();
18192
18193     for (unsigned i=0; i !=NumElems; ++i) {
18194       SDValue Op = Amt->getOperand(i);
18195       if (Op->getOpcode() == ISD::UNDEF) {
18196         Elts.push_back(Op);
18197         continue;
18198       }
18199
18200       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18201       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18202       uint64_t ShAmt = C.getZExtValue();
18203       if (ShAmt >= SVTBits) {
18204         Elts.push_back(DAG.getUNDEF(SVT));
18205         continue;
18206       }
18207       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
18208     }
18209     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18210     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18211   }
18212
18213   // Lower SHL with variable shift amount.
18214   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18215     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
18216
18217     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
18218     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
18219     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18220     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18221   }
18222
18223   // If possible, lower this shift as a sequence of two shifts by
18224   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18225   // Example:
18226   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18227   //
18228   // Could be rewritten as:
18229   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18230   //
18231   // The advantage is that the two shifts from the example would be
18232   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18233   // the vector shift into four scalar shifts plus four pairs of vector
18234   // insert/extract.
18235   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18236       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18237     unsigned TargetOpcode = X86ISD::MOVSS;
18238     bool CanBeSimplified;
18239     // The splat value for the first packed shift (the 'X' from the example).
18240     SDValue Amt1 = Amt->getOperand(0);
18241     // The splat value for the second packed shift (the 'Y' from the example).
18242     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18243                                         Amt->getOperand(2);
18244
18245     // See if it is possible to replace this node with a sequence of
18246     // two shifts followed by a MOVSS/MOVSD
18247     if (VT == MVT::v4i32) {
18248       // Check if it is legal to use a MOVSS.
18249       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18250                         Amt2 == Amt->getOperand(3);
18251       if (!CanBeSimplified) {
18252         // Otherwise, check if we can still simplify this node using a MOVSD.
18253         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18254                           Amt->getOperand(2) == Amt->getOperand(3);
18255         TargetOpcode = X86ISD::MOVSD;
18256         Amt2 = Amt->getOperand(2);
18257       }
18258     } else {
18259       // Do similar checks for the case where the machine value type
18260       // is MVT::v8i16.
18261       CanBeSimplified = Amt1 == Amt->getOperand(1);
18262       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18263         CanBeSimplified = Amt2 == Amt->getOperand(i);
18264
18265       if (!CanBeSimplified) {
18266         TargetOpcode = X86ISD::MOVSD;
18267         CanBeSimplified = true;
18268         Amt2 = Amt->getOperand(4);
18269         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18270           CanBeSimplified = Amt1 == Amt->getOperand(i);
18271         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18272           CanBeSimplified = Amt2 == Amt->getOperand(j);
18273       }
18274     }
18275     
18276     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18277         isa<ConstantSDNode>(Amt2)) {
18278       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18279       EVT CastVT = MVT::v4i32;
18280       SDValue Splat1 = 
18281         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
18282       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18283       SDValue Splat2 = 
18284         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
18285       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18286       if (TargetOpcode == X86ISD::MOVSD)
18287         CastVT = MVT::v2i64;
18288       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
18289       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
18290       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18291                                             BitCast1, DAG);
18292       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
18293     }
18294   }
18295
18296   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
18297     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
18298
18299     // a = a << 5;
18300     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
18301     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
18302
18303     // Turn 'a' into a mask suitable for VSELECT
18304     SDValue VSelM = DAG.getConstant(0x80, VT);
18305     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18306     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18307
18308     SDValue CM1 = DAG.getConstant(0x0f, VT);
18309     SDValue CM2 = DAG.getConstant(0x3f, VT);
18310
18311     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
18312     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
18313     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
18314     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18315     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18316
18317     // a += a
18318     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18319     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18320     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18321
18322     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
18323     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
18324     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
18325     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18326     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18327
18328     // a += a
18329     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18330     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18331     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18332
18333     // return VSELECT(r, r+r, a);
18334     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
18335                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
18336     return R;
18337   }
18338
18339   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18340   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18341   // solution better.
18342   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18343     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
18344     unsigned ExtOpc =
18345         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18346     R = DAG.getNode(ExtOpc, dl, NewVT, R);
18347     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
18348     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18349                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
18350     }
18351
18352   // Decompose 256-bit shifts into smaller 128-bit shifts.
18353   if (VT.is256BitVector()) {
18354     unsigned NumElems = VT.getVectorNumElements();
18355     MVT EltVT = VT.getVectorElementType();
18356     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18357
18358     // Extract the two vectors
18359     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18360     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18361
18362     // Recreate the shift amount vectors
18363     SDValue Amt1, Amt2;
18364     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18365       // Constant shift amount
18366       SmallVector<SDValue, 4> Amt1Csts;
18367       SmallVector<SDValue, 4> Amt2Csts;
18368       for (unsigned i = 0; i != NumElems/2; ++i)
18369         Amt1Csts.push_back(Amt->getOperand(i));
18370       for (unsigned i = NumElems/2; i != NumElems; ++i)
18371         Amt2Csts.push_back(Amt->getOperand(i));
18372
18373       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18374       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18375     } else {
18376       // Variable shift amount
18377       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18378       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18379     }
18380
18381     // Issue new vector shifts for the smaller types
18382     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18383     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18384
18385     // Concatenate the result back
18386     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18387   }
18388
18389   return SDValue();
18390 }
18391
18392 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18393   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18394   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18395   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18396   // has only one use.
18397   SDNode *N = Op.getNode();
18398   SDValue LHS = N->getOperand(0);
18399   SDValue RHS = N->getOperand(1);
18400   unsigned BaseOp = 0;
18401   unsigned Cond = 0;
18402   SDLoc DL(Op);
18403   switch (Op.getOpcode()) {
18404   default: llvm_unreachable("Unknown ovf instruction!");
18405   case ISD::SADDO:
18406     // A subtract of one will be selected as a INC. Note that INC doesn't
18407     // set CF, so we can't do this for UADDO.
18408     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18409       if (C->isOne()) {
18410         BaseOp = X86ISD::INC;
18411         Cond = X86::COND_O;
18412         break;
18413       }
18414     BaseOp = X86ISD::ADD;
18415     Cond = X86::COND_O;
18416     break;
18417   case ISD::UADDO:
18418     BaseOp = X86ISD::ADD;
18419     Cond = X86::COND_B;
18420     break;
18421   case ISD::SSUBO:
18422     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18423     // set CF, so we can't do this for USUBO.
18424     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18425       if (C->isOne()) {
18426         BaseOp = X86ISD::DEC;
18427         Cond = X86::COND_O;
18428         break;
18429       }
18430     BaseOp = X86ISD::SUB;
18431     Cond = X86::COND_O;
18432     break;
18433   case ISD::USUBO:
18434     BaseOp = X86ISD::SUB;
18435     Cond = X86::COND_B;
18436     break;
18437   case ISD::SMULO:
18438     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18439     Cond = X86::COND_O;
18440     break;
18441   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18442     if (N->getValueType(0) == MVT::i8) {
18443       BaseOp = X86ISD::UMUL8;
18444       Cond = X86::COND_O;
18445       break;
18446     }
18447     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18448                                  MVT::i32);
18449     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18450
18451     SDValue SetCC =
18452       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18453                   DAG.getConstant(X86::COND_O, MVT::i32),
18454                   SDValue(Sum.getNode(), 2));
18455
18456     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18457   }
18458   }
18459
18460   // Also sets EFLAGS.
18461   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18462   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18463
18464   SDValue SetCC =
18465     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18466                 DAG.getConstant(Cond, MVT::i32),
18467                 SDValue(Sum.getNode(), 1));
18468
18469   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18470 }
18471
18472 // Sign extension of the low part of vector elements. This may be used either
18473 // when sign extend instructions are not available or if the vector element
18474 // sizes already match the sign-extended size. If the vector elements are in
18475 // their pre-extended size and sign extend instructions are available, that will
18476 // be handled by LowerSIGN_EXTEND.
18477 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
18478                                                   SelectionDAG &DAG) const {
18479   SDLoc dl(Op);
18480   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
18481   MVT VT = Op.getSimpleValueType();
18482
18483   if (!Subtarget->hasSSE2() || !VT.isVector())
18484     return SDValue();
18485
18486   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
18487                       ExtraVT.getScalarType().getSizeInBits();
18488
18489   switch (VT.SimpleTy) {
18490     default: return SDValue();
18491     case MVT::v8i32:
18492     case MVT::v16i16:
18493       if (!Subtarget->hasFp256())
18494         return SDValue();
18495       if (!Subtarget->hasInt256()) {
18496         // needs to be split
18497         unsigned NumElems = VT.getVectorNumElements();
18498
18499         // Extract the LHS vectors
18500         SDValue LHS = Op.getOperand(0);
18501         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18502         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18503
18504         MVT EltVT = VT.getVectorElementType();
18505         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18506
18507         EVT ExtraEltVT = ExtraVT.getVectorElementType();
18508         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
18509         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
18510                                    ExtraNumElems/2);
18511         SDValue Extra = DAG.getValueType(ExtraVT);
18512
18513         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
18514         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
18515
18516         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
18517       }
18518       // fall through
18519     case MVT::v4i32:
18520     case MVT::v8i16: {
18521       SDValue Op0 = Op.getOperand(0);
18522
18523       // This is a sign extension of some low part of vector elements without
18524       // changing the size of the vector elements themselves:
18525       // Shift-Left + Shift-Right-Algebraic.
18526       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
18527                                                BitsDiff, DAG);
18528       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
18529                                         DAG);
18530     }
18531   }
18532 }
18533
18534 /// Returns true if the operand type is exactly twice the native width, and
18535 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18536 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18537 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18538 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
18539   const X86Subtarget &Subtarget =
18540       getTargetMachine().getSubtarget<X86Subtarget>();
18541   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18542
18543   if (OpWidth == 64)
18544     return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18545   else if (OpWidth == 128)
18546     return Subtarget.hasCmpxchg16b();
18547   else
18548     return false;
18549 }
18550
18551 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18552   return needsCmpXchgNb(SI->getValueOperand()->getType());
18553 }
18554
18555 // Note: this turns large loads into lock cmpxchg8b/16b.
18556 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18557 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18558   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18559   return needsCmpXchgNb(PTy->getElementType());
18560 }
18561
18562 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18563   const X86Subtarget &Subtarget =
18564       getTargetMachine().getSubtarget<X86Subtarget>();
18565   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
18566   const Type *MemType = AI->getType();
18567
18568   // If the operand is too big, we must see if cmpxchg8/16b is available
18569   // and default to library calls otherwise.
18570   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18571     return needsCmpXchgNb(MemType);
18572
18573   AtomicRMWInst::BinOp Op = AI->getOperation();
18574   switch (Op) {
18575   default:
18576     llvm_unreachable("Unknown atomic operation");
18577   case AtomicRMWInst::Xchg:
18578   case AtomicRMWInst::Add:
18579   case AtomicRMWInst::Sub:
18580     // It's better to use xadd, xsub or xchg for these in all cases.
18581     return false;
18582   case AtomicRMWInst::Or:
18583   case AtomicRMWInst::And:
18584   case AtomicRMWInst::Xor:
18585     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18586     // prefix to a normal instruction for these operations.
18587     return !AI->use_empty();
18588   case AtomicRMWInst::Nand:
18589   case AtomicRMWInst::Max:
18590   case AtomicRMWInst::Min:
18591   case AtomicRMWInst::UMax:
18592   case AtomicRMWInst::UMin:
18593     // These always require a non-trivial set of data operations on x86. We must
18594     // use a cmpxchg loop.
18595     return true;
18596   }
18597 }
18598
18599 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18600   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18601   // no-sse2). There isn't any reason to disable it if the target processor
18602   // supports it.
18603   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18604 }
18605
18606 LoadInst *
18607 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18608   const X86Subtarget &Subtarget =
18609       getTargetMachine().getSubtarget<X86Subtarget>();
18610   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
18611   const Type *MemType = AI->getType();
18612   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18613   // there is no benefit in turning such RMWs into loads, and it is actually
18614   // harmful as it introduces a mfence.
18615   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18616     return nullptr;
18617
18618   auto Builder = IRBuilder<>(AI);
18619   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18620   auto SynchScope = AI->getSynchScope();
18621   // We must restrict the ordering to avoid generating loads with Release or
18622   // ReleaseAcquire orderings.
18623   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18624   auto Ptr = AI->getPointerOperand();
18625
18626   // Before the load we need a fence. Here is an example lifted from
18627   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18628   // is required:
18629   // Thread 0:
18630   //   x.store(1, relaxed);
18631   //   r1 = y.fetch_add(0, release);
18632   // Thread 1:
18633   //   y.fetch_add(42, acquire);
18634   //   r2 = x.load(relaxed);
18635   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18636   // lowered to just a load without a fence. A mfence flushes the store buffer,
18637   // making the optimization clearly correct.
18638   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18639   // otherwise, we might be able to be more agressive on relaxed idempotent
18640   // rmw. In practice, they do not look useful, so we don't try to be
18641   // especially clever.
18642   if (SynchScope == SingleThread) {
18643     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18644     // the IR level, so we must wrap it in an intrinsic.
18645     return nullptr;
18646   } else if (hasMFENCE(Subtarget)) {
18647     Function *MFence = llvm::Intrinsic::getDeclaration(M,
18648             Intrinsic::x86_sse2_mfence);
18649     Builder.CreateCall(MFence);
18650   } else {
18651     // FIXME: it might make sense to use a locked operation here but on a
18652     // different cache-line to prevent cache-line bouncing. In practice it
18653     // is probably a small win, and x86 processors without mfence are rare
18654     // enough that we do not bother.
18655     return nullptr;
18656   }
18657
18658   // Finally we can emit the atomic load.
18659   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18660           AI->getType()->getPrimitiveSizeInBits());
18661   Loaded->setAtomic(Order, SynchScope);
18662   AI->replaceAllUsesWith(Loaded);
18663   AI->eraseFromParent();
18664   return Loaded;
18665 }
18666
18667 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18668                                  SelectionDAG &DAG) {
18669   SDLoc dl(Op);
18670   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18671     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18672   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18673     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18674
18675   // The only fence that needs an instruction is a sequentially-consistent
18676   // cross-thread fence.
18677   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18678     if (hasMFENCE(*Subtarget))
18679       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18680
18681     SDValue Chain = Op.getOperand(0);
18682     SDValue Zero = DAG.getConstant(0, MVT::i32);
18683     SDValue Ops[] = {
18684       DAG.getRegister(X86::ESP, MVT::i32), // Base
18685       DAG.getTargetConstant(1, MVT::i8),   // Scale
18686       DAG.getRegister(0, MVT::i32),        // Index
18687       DAG.getTargetConstant(0, MVT::i32),  // Disp
18688       DAG.getRegister(0, MVT::i32),        // Segment.
18689       Zero,
18690       Chain
18691     };
18692     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18693     return SDValue(Res, 0);
18694   }
18695
18696   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18697   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18698 }
18699
18700 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18701                              SelectionDAG &DAG) {
18702   MVT T = Op.getSimpleValueType();
18703   SDLoc DL(Op);
18704   unsigned Reg = 0;
18705   unsigned size = 0;
18706   switch(T.SimpleTy) {
18707   default: llvm_unreachable("Invalid value type!");
18708   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18709   case MVT::i16: Reg = X86::AX;  size = 2; break;
18710   case MVT::i32: Reg = X86::EAX; size = 4; break;
18711   case MVT::i64:
18712     assert(Subtarget->is64Bit() && "Node not type legal!");
18713     Reg = X86::RAX; size = 8;
18714     break;
18715   }
18716   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18717                                   Op.getOperand(2), SDValue());
18718   SDValue Ops[] = { cpIn.getValue(0),
18719                     Op.getOperand(1),
18720                     Op.getOperand(3),
18721                     DAG.getTargetConstant(size, MVT::i8),
18722                     cpIn.getValue(1) };
18723   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18724   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18725   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18726                                            Ops, T, MMO);
18727
18728   SDValue cpOut =
18729     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18730   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18731                                       MVT::i32, cpOut.getValue(2));
18732   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18733                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
18734
18735   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18736   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18737   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18738   return SDValue();
18739 }
18740
18741 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18742                             SelectionDAG &DAG) {
18743   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18744   MVT DstVT = Op.getSimpleValueType();
18745
18746   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18747     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18748     if (DstVT != MVT::f64)
18749       // This conversion needs to be expanded.
18750       return SDValue();
18751
18752     SDValue InVec = Op->getOperand(0);
18753     SDLoc dl(Op);
18754     unsigned NumElts = SrcVT.getVectorNumElements();
18755     EVT SVT = SrcVT.getVectorElementType();
18756
18757     // Widen the vector in input in the case of MVT::v2i32.
18758     // Example: from MVT::v2i32 to MVT::v4i32.
18759     SmallVector<SDValue, 16> Elts;
18760     for (unsigned i = 0, e = NumElts; i != e; ++i)
18761       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18762                                  DAG.getIntPtrConstant(i)));
18763
18764     // Explicitly mark the extra elements as Undef.
18765     SDValue Undef = DAG.getUNDEF(SVT);
18766     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
18767       Elts.push_back(Undef);
18768
18769     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18770     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18771     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
18772     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18773                        DAG.getIntPtrConstant(0));
18774   }
18775
18776   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18777          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18778   assert((DstVT == MVT::i64 ||
18779           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18780          "Unexpected custom BITCAST");
18781   // i64 <=> MMX conversions are Legal.
18782   if (SrcVT==MVT::i64 && DstVT.isVector())
18783     return Op;
18784   if (DstVT==MVT::i64 && SrcVT.isVector())
18785     return Op;
18786   // MMX <=> MMX conversions are Legal.
18787   if (SrcVT.isVector() && DstVT.isVector())
18788     return Op;
18789   // All other conversions need to be expanded.
18790   return SDValue();
18791 }
18792
18793 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18794   SDNode *Node = Op.getNode();
18795   SDLoc dl(Node);
18796   EVT T = Node->getValueType(0);
18797   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18798                               DAG.getConstant(0, T), Node->getOperand(2));
18799   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18800                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18801                        Node->getOperand(0),
18802                        Node->getOperand(1), negOp,
18803                        cast<AtomicSDNode>(Node)->getMemOperand(),
18804                        cast<AtomicSDNode>(Node)->getOrdering(),
18805                        cast<AtomicSDNode>(Node)->getSynchScope());
18806 }
18807
18808 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18809   SDNode *Node = Op.getNode();
18810   SDLoc dl(Node);
18811   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18812
18813   // Convert seq_cst store -> xchg
18814   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18815   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18816   //        (The only way to get a 16-byte store is cmpxchg16b)
18817   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18818   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18819       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18820     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18821                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18822                                  Node->getOperand(0),
18823                                  Node->getOperand(1), Node->getOperand(2),
18824                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18825                                  cast<AtomicSDNode>(Node)->getOrdering(),
18826                                  cast<AtomicSDNode>(Node)->getSynchScope());
18827     return Swap.getValue(1);
18828   }
18829   // Other atomic stores have a simple pattern.
18830   return Op;
18831 }
18832
18833 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18834   EVT VT = Op.getNode()->getSimpleValueType(0);
18835
18836   // Let legalize expand this if it isn't a legal type yet.
18837   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18838     return SDValue();
18839
18840   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18841
18842   unsigned Opc;
18843   bool ExtraOp = false;
18844   switch (Op.getOpcode()) {
18845   default: llvm_unreachable("Invalid code");
18846   case ISD::ADDC: Opc = X86ISD::ADD; break;
18847   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18848   case ISD::SUBC: Opc = X86ISD::SUB; break;
18849   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18850   }
18851
18852   if (!ExtraOp)
18853     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18854                        Op.getOperand(1));
18855   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18856                      Op.getOperand(1), Op.getOperand(2));
18857 }
18858
18859 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18860                             SelectionDAG &DAG) {
18861   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18862
18863   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18864   // which returns the values as { float, float } (in XMM0) or
18865   // { double, double } (which is returned in XMM0, XMM1).
18866   SDLoc dl(Op);
18867   SDValue Arg = Op.getOperand(0);
18868   EVT ArgVT = Arg.getValueType();
18869   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18870
18871   TargetLowering::ArgListTy Args;
18872   TargetLowering::ArgListEntry Entry;
18873
18874   Entry.Node = Arg;
18875   Entry.Ty = ArgTy;
18876   Entry.isSExt = false;
18877   Entry.isZExt = false;
18878   Args.push_back(Entry);
18879
18880   bool isF64 = ArgVT == MVT::f64;
18881   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18882   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18883   // the results are returned via SRet in memory.
18884   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18886   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
18887
18888   Type *RetTy = isF64
18889     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
18890     : (Type*)VectorType::get(ArgTy, 4);
18891
18892   TargetLowering::CallLoweringInfo CLI(DAG);
18893   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18894     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18895
18896   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18897
18898   if (isF64)
18899     // Returned in xmm0 and xmm1.
18900     return CallResult.first;
18901
18902   // Returned in bits 0:31 and 32:64 xmm0.
18903   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18904                                CallResult.first, DAG.getIntPtrConstant(0));
18905   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18906                                CallResult.first, DAG.getIntPtrConstant(1));
18907   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18908   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18909 }
18910
18911 /// LowerOperation - Provide custom lowering hooks for some operations.
18912 ///
18913 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18914   switch (Op.getOpcode()) {
18915   default: llvm_unreachable("Should not custom lower this!");
18916   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
18917   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18918   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18919     return LowerCMP_SWAP(Op, Subtarget, DAG);
18920   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18921   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18922   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18923   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
18924   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
18925   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18926   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18927   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18928   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18929   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18930   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18931   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18932   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18933   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18934   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18935   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18936   case ISD::SHL_PARTS:
18937   case ISD::SRA_PARTS:
18938   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18939   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18940   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18941   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18942   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18943   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18944   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18945   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18946   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18947   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18948   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18949   case ISD::FABS:
18950   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18951   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18952   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18953   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18954   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18955   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18956   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18957   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18958   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18959   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18960   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18961   case ISD::INTRINSIC_VOID:
18962   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18963   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18964   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18965   case ISD::FRAME_TO_ARGS_OFFSET:
18966                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18967   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18968   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18969   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18970   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18971   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18972   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18973   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18974   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18975   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18976   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18977   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18978   case ISD::UMUL_LOHI:
18979   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18980   case ISD::SRA:
18981   case ISD::SRL:
18982   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18983   case ISD::SADDO:
18984   case ISD::UADDO:
18985   case ISD::SSUBO:
18986   case ISD::USUBO:
18987   case ISD::SMULO:
18988   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18989   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18990   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18991   case ISD::ADDC:
18992   case ISD::ADDE:
18993   case ISD::SUBC:
18994   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18995   case ISD::ADD:                return LowerADD(Op, DAG);
18996   case ISD::SUB:                return LowerSUB(Op, DAG);
18997   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18998   }
18999 }
19000
19001 /// ReplaceNodeResults - Replace a node with an illegal result type
19002 /// with a new node built out of custom code.
19003 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19004                                            SmallVectorImpl<SDValue>&Results,
19005                                            SelectionDAG &DAG) const {
19006   SDLoc dl(N);
19007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19008   switch (N->getOpcode()) {
19009   default:
19010     llvm_unreachable("Do not know how to custom type legalize this operation!");
19011   case ISD::SIGN_EXTEND_INREG:
19012   case ISD::ADDC:
19013   case ISD::ADDE:
19014   case ISD::SUBC:
19015   case ISD::SUBE:
19016     // We don't want to expand or promote these.
19017     return;
19018   case ISD::SDIV:
19019   case ISD::UDIV:
19020   case ISD::SREM:
19021   case ISD::UREM:
19022   case ISD::SDIVREM:
19023   case ISD::UDIVREM: {
19024     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19025     Results.push_back(V);
19026     return;
19027   }
19028   case ISD::FP_TO_SINT:
19029   case ISD::FP_TO_UINT: {
19030     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19031
19032     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
19033       return;
19034
19035     std::pair<SDValue,SDValue> Vals =
19036         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19037     SDValue FIST = Vals.first, StackSlot = Vals.second;
19038     if (FIST.getNode()) {
19039       EVT VT = N->getValueType(0);
19040       // Return a load from the stack slot.
19041       if (StackSlot.getNode())
19042         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19043                                       MachinePointerInfo(),
19044                                       false, false, false, 0));
19045       else
19046         Results.push_back(FIST);
19047     }
19048     return;
19049   }
19050   case ISD::UINT_TO_FP: {
19051     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19052     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19053         N->getValueType(0) != MVT::v2f32)
19054       return;
19055     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19056                                  N->getOperand(0));
19057     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
19058                                      MVT::f64);
19059     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19060     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19061                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
19062     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
19063     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19064     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19065     return;
19066   }
19067   case ISD::FP_ROUND: {
19068     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19069         return;
19070     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19071     Results.push_back(V);
19072     return;
19073   }
19074   case ISD::INTRINSIC_W_CHAIN: {
19075     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19076     switch (IntNo) {
19077     default : llvm_unreachable("Do not know how to custom type "
19078                                "legalize this intrinsic operation!");
19079     case Intrinsic::x86_rdtsc:
19080       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19081                                      Results);
19082     case Intrinsic::x86_rdtscp:
19083       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19084                                      Results);
19085     case Intrinsic::x86_rdpmc:
19086       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19087     }
19088   }
19089   case ISD::READCYCLECOUNTER: {
19090     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19091                                    Results);
19092   }
19093   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19094     EVT T = N->getValueType(0);
19095     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19096     bool Regs64bit = T == MVT::i128;
19097     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19098     SDValue cpInL, cpInH;
19099     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19100                         DAG.getConstant(0, HalfT));
19101     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19102                         DAG.getConstant(1, HalfT));
19103     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19104                              Regs64bit ? X86::RAX : X86::EAX,
19105                              cpInL, SDValue());
19106     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19107                              Regs64bit ? X86::RDX : X86::EDX,
19108                              cpInH, cpInL.getValue(1));
19109     SDValue swapInL, swapInH;
19110     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19111                           DAG.getConstant(0, HalfT));
19112     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19113                           DAG.getConstant(1, HalfT));
19114     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19115                                Regs64bit ? X86::RBX : X86::EBX,
19116                                swapInL, cpInH.getValue(1));
19117     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19118                                Regs64bit ? X86::RCX : X86::ECX,
19119                                swapInH, swapInL.getValue(1));
19120     SDValue Ops[] = { swapInH.getValue(0),
19121                       N->getOperand(1),
19122                       swapInH.getValue(1) };
19123     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19124     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19125     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19126                                   X86ISD::LCMPXCHG8_DAG;
19127     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19128     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19129                                         Regs64bit ? X86::RAX : X86::EAX,
19130                                         HalfT, Result.getValue(1));
19131     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19132                                         Regs64bit ? X86::RDX : X86::EDX,
19133                                         HalfT, cpOutL.getValue(2));
19134     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19135
19136     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19137                                         MVT::i32, cpOutH.getValue(2));
19138     SDValue Success =
19139         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19140                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19141     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19142
19143     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19144     Results.push_back(Success);
19145     Results.push_back(EFLAGS.getValue(1));
19146     return;
19147   }
19148   case ISD::ATOMIC_SWAP:
19149   case ISD::ATOMIC_LOAD_ADD:
19150   case ISD::ATOMIC_LOAD_SUB:
19151   case ISD::ATOMIC_LOAD_AND:
19152   case ISD::ATOMIC_LOAD_OR:
19153   case ISD::ATOMIC_LOAD_XOR:
19154   case ISD::ATOMIC_LOAD_NAND:
19155   case ISD::ATOMIC_LOAD_MIN:
19156   case ISD::ATOMIC_LOAD_MAX:
19157   case ISD::ATOMIC_LOAD_UMIN:
19158   case ISD::ATOMIC_LOAD_UMAX:
19159   case ISD::ATOMIC_LOAD: {
19160     // Delegate to generic TypeLegalization. Situations we can really handle
19161     // should have already been dealt with by AtomicExpandPass.cpp.
19162     break;
19163   }
19164   case ISD::BITCAST: {
19165     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19166     EVT DstVT = N->getValueType(0);
19167     EVT SrcVT = N->getOperand(0)->getValueType(0);
19168
19169     if (SrcVT != MVT::f64 ||
19170         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19171       return;
19172
19173     unsigned NumElts = DstVT.getVectorNumElements();
19174     EVT SVT = DstVT.getVectorElementType();
19175     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19176     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19177                                    MVT::v2f64, N->getOperand(0));
19178     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
19179
19180     if (ExperimentalVectorWideningLegalization) {
19181       // If we are legalizing vectors by widening, we already have the desired
19182       // legal vector type, just return it.
19183       Results.push_back(ToVecInt);
19184       return;
19185     }
19186
19187     SmallVector<SDValue, 8> Elts;
19188     for (unsigned i = 0, e = NumElts; i != e; ++i)
19189       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19190                                    ToVecInt, DAG.getIntPtrConstant(i)));
19191
19192     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19193   }
19194   }
19195 }
19196
19197 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19198   switch (Opcode) {
19199   default: return nullptr;
19200   case X86ISD::BSF:                return "X86ISD::BSF";
19201   case X86ISD::BSR:                return "X86ISD::BSR";
19202   case X86ISD::SHLD:               return "X86ISD::SHLD";
19203   case X86ISD::SHRD:               return "X86ISD::SHRD";
19204   case X86ISD::FAND:               return "X86ISD::FAND";
19205   case X86ISD::FANDN:              return "X86ISD::FANDN";
19206   case X86ISD::FOR:                return "X86ISD::FOR";
19207   case X86ISD::FXOR:               return "X86ISD::FXOR";
19208   case X86ISD::FSRL:               return "X86ISD::FSRL";
19209   case X86ISD::FILD:               return "X86ISD::FILD";
19210   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19211   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19212   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19213   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19214   case X86ISD::FLD:                return "X86ISD::FLD";
19215   case X86ISD::FST:                return "X86ISD::FST";
19216   case X86ISD::CALL:               return "X86ISD::CALL";
19217   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19218   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19219   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19220   case X86ISD::BT:                 return "X86ISD::BT";
19221   case X86ISD::CMP:                return "X86ISD::CMP";
19222   case X86ISD::COMI:               return "X86ISD::COMI";
19223   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19224   case X86ISD::CMPM:               return "X86ISD::CMPM";
19225   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19226   case X86ISD::SETCC:              return "X86ISD::SETCC";
19227   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19228   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19229   case X86ISD::CMOV:               return "X86ISD::CMOV";
19230   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19231   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19232   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19233   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19234   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19235   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19236   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19237   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19238   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19239   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19240   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19241   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19242   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19243   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19244   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19245   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19246   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19247   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19248   case X86ISD::HADD:               return "X86ISD::HADD";
19249   case X86ISD::HSUB:               return "X86ISD::HSUB";
19250   case X86ISD::FHADD:              return "X86ISD::FHADD";
19251   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19252   case X86ISD::UMAX:               return "X86ISD::UMAX";
19253   case X86ISD::UMIN:               return "X86ISD::UMIN";
19254   case X86ISD::SMAX:               return "X86ISD::SMAX";
19255   case X86ISD::SMIN:               return "X86ISD::SMIN";
19256   case X86ISD::FMAX:               return "X86ISD::FMAX";
19257   case X86ISD::FMIN:               return "X86ISD::FMIN";
19258   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19259   case X86ISD::FMINC:              return "X86ISD::FMINC";
19260   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19261   case X86ISD::FRCP:               return "X86ISD::FRCP";
19262   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19263   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19264   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19265   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19266   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19267   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19268   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19269   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19270   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19271   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19272   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19273   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19274   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19275   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19276   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19277   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19278   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19279   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
19280   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19281   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19282   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19283   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19284   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19285   case X86ISD::VSHL:               return "X86ISD::VSHL";
19286   case X86ISD::VSRL:               return "X86ISD::VSRL";
19287   case X86ISD::VSRA:               return "X86ISD::VSRA";
19288   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19289   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19290   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19291   case X86ISD::CMPP:               return "X86ISD::CMPP";
19292   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19293   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19294   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19295   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19296   case X86ISD::ADD:                return "X86ISD::ADD";
19297   case X86ISD::SUB:                return "X86ISD::SUB";
19298   case X86ISD::ADC:                return "X86ISD::ADC";
19299   case X86ISD::SBB:                return "X86ISD::SBB";
19300   case X86ISD::SMUL:               return "X86ISD::SMUL";
19301   case X86ISD::UMUL:               return "X86ISD::UMUL";
19302   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19303   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19304   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19305   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19306   case X86ISD::INC:                return "X86ISD::INC";
19307   case X86ISD::DEC:                return "X86ISD::DEC";
19308   case X86ISD::OR:                 return "X86ISD::OR";
19309   case X86ISD::XOR:                return "X86ISD::XOR";
19310   case X86ISD::AND:                return "X86ISD::AND";
19311   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19312   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19313   case X86ISD::PTEST:              return "X86ISD::PTEST";
19314   case X86ISD::TESTP:              return "X86ISD::TESTP";
19315   case X86ISD::TESTM:              return "X86ISD::TESTM";
19316   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19317   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19318   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19319   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19320   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19321   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19322   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19323   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19324   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19325   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19326   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19327   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19328   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19329   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19330   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19331   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19332   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19333   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19334   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19335   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19336   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19337   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19338   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19339   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
19340   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19341   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19342   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19343   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19344   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19345   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19346   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19347   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19348   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19349   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19350   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19351   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19352   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19353   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19354   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19355   case X86ISD::SAHF:               return "X86ISD::SAHF";
19356   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19357   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19358   case X86ISD::FMADD:              return "X86ISD::FMADD";
19359   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19360   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19361   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19362   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19363   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19364   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19365   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19366   case X86ISD::XTEST:              return "X86ISD::XTEST";
19367   }
19368 }
19369
19370 // isLegalAddressingMode - Return true if the addressing mode represented
19371 // by AM is legal for this target, for a load/store of the specified type.
19372 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
19373                                               Type *Ty) const {
19374   // X86 supports extremely general addressing modes.
19375   CodeModel::Model M = getTargetMachine().getCodeModel();
19376   Reloc::Model R = getTargetMachine().getRelocationModel();
19377
19378   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19379   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19380     return false;
19381
19382   if (AM.BaseGV) {
19383     unsigned GVFlags =
19384       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19385
19386     // If a reference to this global requires an extra load, we can't fold it.
19387     if (isGlobalStubReference(GVFlags))
19388       return false;
19389
19390     // If BaseGV requires a register for the PIC base, we cannot also have a
19391     // BaseReg specified.
19392     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19393       return false;
19394
19395     // If lower 4G is not available, then we must use rip-relative addressing.
19396     if ((M != CodeModel::Small || R != Reloc::Static) &&
19397         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19398       return false;
19399   }
19400
19401   switch (AM.Scale) {
19402   case 0:
19403   case 1:
19404   case 2:
19405   case 4:
19406   case 8:
19407     // These scales always work.
19408     break;
19409   case 3:
19410   case 5:
19411   case 9:
19412     // These scales are formed with basereg+scalereg.  Only accept if there is
19413     // no basereg yet.
19414     if (AM.HasBaseReg)
19415       return false;
19416     break;
19417   default:  // Other stuff never works.
19418     return false;
19419   }
19420
19421   return true;
19422 }
19423
19424 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19425   unsigned Bits = Ty->getScalarSizeInBits();
19426
19427   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19428   // particularly cheaper than those without.
19429   if (Bits == 8)
19430     return false;
19431
19432   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19433   // variable shifts just as cheap as scalar ones.
19434   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19435     return false;
19436
19437   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19438   // fully general vector.
19439   return true;
19440 }
19441
19442 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19443   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19444     return false;
19445   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19446   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19447   return NumBits1 > NumBits2;
19448 }
19449
19450 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19451   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19452     return false;
19453
19454   if (!isTypeLegal(EVT::getEVT(Ty1)))
19455     return false;
19456
19457   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19458
19459   // Assuming the caller doesn't have a zeroext or signext return parameter,
19460   // truncation all the way down to i1 is valid.
19461   return true;
19462 }
19463
19464 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19465   return isInt<32>(Imm);
19466 }
19467
19468 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19469   // Can also use sub to handle negated immediates.
19470   return isInt<32>(Imm);
19471 }
19472
19473 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19474   if (!VT1.isInteger() || !VT2.isInteger())
19475     return false;
19476   unsigned NumBits1 = VT1.getSizeInBits();
19477   unsigned NumBits2 = VT2.getSizeInBits();
19478   return NumBits1 > NumBits2;
19479 }
19480
19481 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19482   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19483   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19484 }
19485
19486 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19487   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19488   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19489 }
19490
19491 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19492   EVT VT1 = Val.getValueType();
19493   if (isZExtFree(VT1, VT2))
19494     return true;
19495
19496   if (Val.getOpcode() != ISD::LOAD)
19497     return false;
19498
19499   if (!VT1.isSimple() || !VT1.isInteger() ||
19500       !VT2.isSimple() || !VT2.isInteger())
19501     return false;
19502
19503   switch (VT1.getSimpleVT().SimpleTy) {
19504   default: break;
19505   case MVT::i8:
19506   case MVT::i16:
19507   case MVT::i32:
19508     // X86 has 8, 16, and 32-bit zero-extending loads.
19509     return true;
19510   }
19511
19512   return false;
19513 }
19514
19515 bool
19516 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19517   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
19518     return false;
19519
19520   VT = VT.getScalarType();
19521
19522   if (!VT.isSimple())
19523     return false;
19524
19525   switch (VT.getSimpleVT().SimpleTy) {
19526   case MVT::f32:
19527   case MVT::f64:
19528     return true;
19529   default:
19530     break;
19531   }
19532
19533   return false;
19534 }
19535
19536 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19537   // i16 instructions are longer (0x66 prefix) and potentially slower.
19538   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19539 }
19540
19541 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19542 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19543 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19544 /// are assumed to be legal.
19545 bool
19546 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19547                                       EVT VT) const {
19548   if (!VT.isSimple())
19549     return false;
19550
19551   MVT SVT = VT.getSimpleVT();
19552
19553   // Very little shuffling can be done for 64-bit vectors right now.
19554   if (VT.getSizeInBits() == 64)
19555     return false;
19556
19557   // If this is a single-input shuffle with no 128 bit lane crossings we can
19558   // lower it into pshufb.
19559   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
19560       (SVT.is256BitVector() && Subtarget->hasInt256())) {
19561     bool isLegal = true;
19562     for (unsigned I = 0, E = M.size(); I != E; ++I) {
19563       if (M[I] >= (int)SVT.getVectorNumElements() ||
19564           ShuffleCrosses128bitLane(SVT, I, M[I])) {
19565         isLegal = false;
19566         break;
19567       }
19568     }
19569     if (isLegal)
19570       return true;
19571   }
19572
19573   // FIXME: blends, shifts.
19574   return (SVT.getVectorNumElements() == 2 ||
19575           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
19576           isMOVLMask(M, SVT) ||
19577           isMOVHLPSMask(M, SVT) ||
19578           isSHUFPMask(M, SVT) ||
19579           isPSHUFDMask(M, SVT) ||
19580           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
19581           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
19582           isPALIGNRMask(M, SVT, Subtarget) ||
19583           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
19584           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
19585           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
19586           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
19587           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()) ||
19588           (Subtarget->hasSSE41() && isINSERTPSMask(M, SVT)));
19589 }
19590
19591 bool
19592 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19593                                           EVT VT) const {
19594   if (!VT.isSimple())
19595     return false;
19596
19597   MVT SVT = VT.getSimpleVT();
19598   unsigned NumElts = SVT.getVectorNumElements();
19599   // FIXME: This collection of masks seems suspect.
19600   if (NumElts == 2)
19601     return true;
19602   if (NumElts == 4 && SVT.is128BitVector()) {
19603     return (isMOVLMask(Mask, SVT)  ||
19604             isCommutedMOVLMask(Mask, SVT, true) ||
19605             isSHUFPMask(Mask, SVT) ||
19606             isSHUFPMask(Mask, SVT, /* Commuted */ true) ||
19607             isBlendMask(Mask, SVT, Subtarget->hasSSE41(),
19608                         Subtarget->hasInt256()));
19609   }
19610   return false;
19611 }
19612
19613 //===----------------------------------------------------------------------===//
19614 //                           X86 Scheduler Hooks
19615 //===----------------------------------------------------------------------===//
19616
19617 /// Utility function to emit xbegin specifying the start of an RTM region.
19618 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19619                                      const TargetInstrInfo *TII) {
19620   DebugLoc DL = MI->getDebugLoc();
19621
19622   const BasicBlock *BB = MBB->getBasicBlock();
19623   MachineFunction::iterator I = MBB;
19624   ++I;
19625
19626   // For the v = xbegin(), we generate
19627   //
19628   // thisMBB:
19629   //  xbegin sinkMBB
19630   //
19631   // mainMBB:
19632   //  eax = -1
19633   //
19634   // sinkMBB:
19635   //  v = eax
19636
19637   MachineBasicBlock *thisMBB = MBB;
19638   MachineFunction *MF = MBB->getParent();
19639   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19640   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19641   MF->insert(I, mainMBB);
19642   MF->insert(I, sinkMBB);
19643
19644   // Transfer the remainder of BB and its successor edges to sinkMBB.
19645   sinkMBB->splice(sinkMBB->begin(), MBB,
19646                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19647   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19648
19649   // thisMBB:
19650   //  xbegin sinkMBB
19651   //  # fallthrough to mainMBB
19652   //  # abortion to sinkMBB
19653   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19654   thisMBB->addSuccessor(mainMBB);
19655   thisMBB->addSuccessor(sinkMBB);
19656
19657   // mainMBB:
19658   //  EAX = -1
19659   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19660   mainMBB->addSuccessor(sinkMBB);
19661
19662   // sinkMBB:
19663   // EAX is live into the sinkMBB
19664   sinkMBB->addLiveIn(X86::EAX);
19665   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19666           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19667     .addReg(X86::EAX);
19668
19669   MI->eraseFromParent();
19670   return sinkMBB;
19671 }
19672
19673 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19674 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19675 // in the .td file.
19676 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19677                                        const TargetInstrInfo *TII) {
19678   unsigned Opc;
19679   switch (MI->getOpcode()) {
19680   default: llvm_unreachable("illegal opcode!");
19681   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19682   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19683   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19684   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19685   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19686   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19687   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19688   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19689   }
19690
19691   DebugLoc dl = MI->getDebugLoc();
19692   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19693
19694   unsigned NumArgs = MI->getNumOperands();
19695   for (unsigned i = 1; i < NumArgs; ++i) {
19696     MachineOperand &Op = MI->getOperand(i);
19697     if (!(Op.isReg() && Op.isImplicit()))
19698       MIB.addOperand(Op);
19699   }
19700   if (MI->hasOneMemOperand())
19701     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19702
19703   BuildMI(*BB, MI, dl,
19704     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19705     .addReg(X86::XMM0);
19706
19707   MI->eraseFromParent();
19708   return BB;
19709 }
19710
19711 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19712 // defs in an instruction pattern
19713 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19714                                        const TargetInstrInfo *TII) {
19715   unsigned Opc;
19716   switch (MI->getOpcode()) {
19717   default: llvm_unreachable("illegal opcode!");
19718   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19719   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19720   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19721   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19722   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19723   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19724   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19725   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19726   }
19727
19728   DebugLoc dl = MI->getDebugLoc();
19729   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19730
19731   unsigned NumArgs = MI->getNumOperands(); // remove the results
19732   for (unsigned i = 1; i < NumArgs; ++i) {
19733     MachineOperand &Op = MI->getOperand(i);
19734     if (!(Op.isReg() && Op.isImplicit()))
19735       MIB.addOperand(Op);
19736   }
19737   if (MI->hasOneMemOperand())
19738     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19739
19740   BuildMI(*BB, MI, dl,
19741     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19742     .addReg(X86::ECX);
19743
19744   MI->eraseFromParent();
19745   return BB;
19746 }
19747
19748 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19749                                        const TargetInstrInfo *TII,
19750                                        const X86Subtarget* Subtarget) {
19751   DebugLoc dl = MI->getDebugLoc();
19752
19753   // Address into RAX/EAX, other two args into ECX, EDX.
19754   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19755   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19756   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19757   for (int i = 0; i < X86::AddrNumOperands; ++i)
19758     MIB.addOperand(MI->getOperand(i));
19759
19760   unsigned ValOps = X86::AddrNumOperands;
19761   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19762     .addReg(MI->getOperand(ValOps).getReg());
19763   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19764     .addReg(MI->getOperand(ValOps+1).getReg());
19765
19766   // The instruction doesn't actually take any operands though.
19767   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19768
19769   MI->eraseFromParent(); // The pseudo is gone now.
19770   return BB;
19771 }
19772
19773 MachineBasicBlock *
19774 X86TargetLowering::EmitVAARG64WithCustomInserter(
19775                    MachineInstr *MI,
19776                    MachineBasicBlock *MBB) const {
19777   // Emit va_arg instruction on X86-64.
19778
19779   // Operands to this pseudo-instruction:
19780   // 0  ) Output        : destination address (reg)
19781   // 1-5) Input         : va_list address (addr, i64mem)
19782   // 6  ) ArgSize       : Size (in bytes) of vararg type
19783   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19784   // 8  ) Align         : Alignment of type
19785   // 9  ) EFLAGS (implicit-def)
19786
19787   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19788   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
19789
19790   unsigned DestReg = MI->getOperand(0).getReg();
19791   MachineOperand &Base = MI->getOperand(1);
19792   MachineOperand &Scale = MI->getOperand(2);
19793   MachineOperand &Index = MI->getOperand(3);
19794   MachineOperand &Disp = MI->getOperand(4);
19795   MachineOperand &Segment = MI->getOperand(5);
19796   unsigned ArgSize = MI->getOperand(6).getImm();
19797   unsigned ArgMode = MI->getOperand(7).getImm();
19798   unsigned Align = MI->getOperand(8).getImm();
19799
19800   // Memory Reference
19801   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19802   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19803   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19804
19805   // Machine Information
19806   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
19807   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19808   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19809   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19810   DebugLoc DL = MI->getDebugLoc();
19811
19812   // struct va_list {
19813   //   i32   gp_offset
19814   //   i32   fp_offset
19815   //   i64   overflow_area (address)
19816   //   i64   reg_save_area (address)
19817   // }
19818   // sizeof(va_list) = 24
19819   // alignment(va_list) = 8
19820
19821   unsigned TotalNumIntRegs = 6;
19822   unsigned TotalNumXMMRegs = 8;
19823   bool UseGPOffset = (ArgMode == 1);
19824   bool UseFPOffset = (ArgMode == 2);
19825   unsigned MaxOffset = TotalNumIntRegs * 8 +
19826                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19827
19828   /* Align ArgSize to a multiple of 8 */
19829   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19830   bool NeedsAlign = (Align > 8);
19831
19832   MachineBasicBlock *thisMBB = MBB;
19833   MachineBasicBlock *overflowMBB;
19834   MachineBasicBlock *offsetMBB;
19835   MachineBasicBlock *endMBB;
19836
19837   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19838   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19839   unsigned OffsetReg = 0;
19840
19841   if (!UseGPOffset && !UseFPOffset) {
19842     // If we only pull from the overflow region, we don't create a branch.
19843     // We don't need to alter control flow.
19844     OffsetDestReg = 0; // unused
19845     OverflowDestReg = DestReg;
19846
19847     offsetMBB = nullptr;
19848     overflowMBB = thisMBB;
19849     endMBB = thisMBB;
19850   } else {
19851     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19852     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19853     // If not, pull from overflow_area. (branch to overflowMBB)
19854     //
19855     //       thisMBB
19856     //         |     .
19857     //         |        .
19858     //     offsetMBB   overflowMBB
19859     //         |        .
19860     //         |     .
19861     //        endMBB
19862
19863     // Registers for the PHI in endMBB
19864     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19865     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19866
19867     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19868     MachineFunction *MF = MBB->getParent();
19869     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19870     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19871     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19872
19873     MachineFunction::iterator MBBIter = MBB;
19874     ++MBBIter;
19875
19876     // Insert the new basic blocks
19877     MF->insert(MBBIter, offsetMBB);
19878     MF->insert(MBBIter, overflowMBB);
19879     MF->insert(MBBIter, endMBB);
19880
19881     // Transfer the remainder of MBB and its successor edges to endMBB.
19882     endMBB->splice(endMBB->begin(), thisMBB,
19883                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19884     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19885
19886     // Make offsetMBB and overflowMBB successors of thisMBB
19887     thisMBB->addSuccessor(offsetMBB);
19888     thisMBB->addSuccessor(overflowMBB);
19889
19890     // endMBB is a successor of both offsetMBB and overflowMBB
19891     offsetMBB->addSuccessor(endMBB);
19892     overflowMBB->addSuccessor(endMBB);
19893
19894     // Load the offset value into a register
19895     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19896     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19897       .addOperand(Base)
19898       .addOperand(Scale)
19899       .addOperand(Index)
19900       .addDisp(Disp, UseFPOffset ? 4 : 0)
19901       .addOperand(Segment)
19902       .setMemRefs(MMOBegin, MMOEnd);
19903
19904     // Check if there is enough room left to pull this argument.
19905     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19906       .addReg(OffsetReg)
19907       .addImm(MaxOffset + 8 - ArgSizeA8);
19908
19909     // Branch to "overflowMBB" if offset >= max
19910     // Fall through to "offsetMBB" otherwise
19911     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19912       .addMBB(overflowMBB);
19913   }
19914
19915   // In offsetMBB, emit code to use the reg_save_area.
19916   if (offsetMBB) {
19917     assert(OffsetReg != 0);
19918
19919     // Read the reg_save_area address.
19920     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19921     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19922       .addOperand(Base)
19923       .addOperand(Scale)
19924       .addOperand(Index)
19925       .addDisp(Disp, 16)
19926       .addOperand(Segment)
19927       .setMemRefs(MMOBegin, MMOEnd);
19928
19929     // Zero-extend the offset
19930     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19931       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19932         .addImm(0)
19933         .addReg(OffsetReg)
19934         .addImm(X86::sub_32bit);
19935
19936     // Add the offset to the reg_save_area to get the final address.
19937     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19938       .addReg(OffsetReg64)
19939       .addReg(RegSaveReg);
19940
19941     // Compute the offset for the next argument
19942     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19943     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19944       .addReg(OffsetReg)
19945       .addImm(UseFPOffset ? 16 : 8);
19946
19947     // Store it back into the va_list.
19948     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19949       .addOperand(Base)
19950       .addOperand(Scale)
19951       .addOperand(Index)
19952       .addDisp(Disp, UseFPOffset ? 4 : 0)
19953       .addOperand(Segment)
19954       .addReg(NextOffsetReg)
19955       .setMemRefs(MMOBegin, MMOEnd);
19956
19957     // Jump to endMBB
19958     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
19959       .addMBB(endMBB);
19960   }
19961
19962   //
19963   // Emit code to use overflow area
19964   //
19965
19966   // Load the overflow_area address into a register.
19967   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19968   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19969     .addOperand(Base)
19970     .addOperand(Scale)
19971     .addOperand(Index)
19972     .addDisp(Disp, 8)
19973     .addOperand(Segment)
19974     .setMemRefs(MMOBegin, MMOEnd);
19975
19976   // If we need to align it, do so. Otherwise, just copy the address
19977   // to OverflowDestReg.
19978   if (NeedsAlign) {
19979     // Align the overflow address
19980     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19981     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19982
19983     // aligned_addr = (addr + (align-1)) & ~(align-1)
19984     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19985       .addReg(OverflowAddrReg)
19986       .addImm(Align-1);
19987
19988     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19989       .addReg(TmpReg)
19990       .addImm(~(uint64_t)(Align-1));
19991   } else {
19992     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19993       .addReg(OverflowAddrReg);
19994   }
19995
19996   // Compute the next overflow address after this argument.
19997   // (the overflow address should be kept 8-byte aligned)
19998   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19999   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20000     .addReg(OverflowDestReg)
20001     .addImm(ArgSizeA8);
20002
20003   // Store the new overflow address.
20004   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20005     .addOperand(Base)
20006     .addOperand(Scale)
20007     .addOperand(Index)
20008     .addDisp(Disp, 8)
20009     .addOperand(Segment)
20010     .addReg(NextAddrReg)
20011     .setMemRefs(MMOBegin, MMOEnd);
20012
20013   // If we branched, emit the PHI to the front of endMBB.
20014   if (offsetMBB) {
20015     BuildMI(*endMBB, endMBB->begin(), DL,
20016             TII->get(X86::PHI), DestReg)
20017       .addReg(OffsetDestReg).addMBB(offsetMBB)
20018       .addReg(OverflowDestReg).addMBB(overflowMBB);
20019   }
20020
20021   // Erase the pseudo instruction
20022   MI->eraseFromParent();
20023
20024   return endMBB;
20025 }
20026
20027 MachineBasicBlock *
20028 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20029                                                  MachineInstr *MI,
20030                                                  MachineBasicBlock *MBB) const {
20031   // Emit code to save XMM registers to the stack. The ABI says that the
20032   // number of registers to save is given in %al, so it's theoretically
20033   // possible to do an indirect jump trick to avoid saving all of them,
20034   // however this code takes a simpler approach and just executes all
20035   // of the stores if %al is non-zero. It's less code, and it's probably
20036   // easier on the hardware branch predictor, and stores aren't all that
20037   // expensive anyway.
20038
20039   // Create the new basic blocks. One block contains all the XMM stores,
20040   // and one block is the final destination regardless of whether any
20041   // stores were performed.
20042   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20043   MachineFunction *F = MBB->getParent();
20044   MachineFunction::iterator MBBIter = MBB;
20045   ++MBBIter;
20046   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20047   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20048   F->insert(MBBIter, XMMSaveMBB);
20049   F->insert(MBBIter, EndMBB);
20050
20051   // Transfer the remainder of MBB and its successor edges to EndMBB.
20052   EndMBB->splice(EndMBB->begin(), MBB,
20053                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20054   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20055
20056   // The original block will now fall through to the XMM save block.
20057   MBB->addSuccessor(XMMSaveMBB);
20058   // The XMMSaveMBB will fall through to the end block.
20059   XMMSaveMBB->addSuccessor(EndMBB);
20060
20061   // Now add the instructions.
20062   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20063   DebugLoc DL = MI->getDebugLoc();
20064
20065   unsigned CountReg = MI->getOperand(0).getReg();
20066   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20067   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20068
20069   if (!Subtarget->isTargetWin64()) {
20070     // If %al is 0, branch around the XMM save block.
20071     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20072     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
20073     MBB->addSuccessor(EndMBB);
20074   }
20075
20076   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20077   // that was just emitted, but clearly shouldn't be "saved".
20078   assert((MI->getNumOperands() <= 3 ||
20079           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20080           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20081          && "Expected last argument to be EFLAGS");
20082   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20083   // In the XMM save block, save all the XMM argument registers.
20084   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20085     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20086     MachineMemOperand *MMO =
20087       F->getMachineMemOperand(
20088           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
20089         MachineMemOperand::MOStore,
20090         /*Size=*/16, /*Align=*/16);
20091     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20092       .addFrameIndex(RegSaveFrameIndex)
20093       .addImm(/*Scale=*/1)
20094       .addReg(/*IndexReg=*/0)
20095       .addImm(/*Disp=*/Offset)
20096       .addReg(/*Segment=*/0)
20097       .addReg(MI->getOperand(i).getReg())
20098       .addMemOperand(MMO);
20099   }
20100
20101   MI->eraseFromParent();   // The pseudo instruction is gone now.
20102
20103   return EndMBB;
20104 }
20105
20106 // The EFLAGS operand of SelectItr might be missing a kill marker
20107 // because there were multiple uses of EFLAGS, and ISel didn't know
20108 // which to mark. Figure out whether SelectItr should have had a
20109 // kill marker, and set it if it should. Returns the correct kill
20110 // marker value.
20111 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20112                                      MachineBasicBlock* BB,
20113                                      const TargetRegisterInfo* TRI) {
20114   // Scan forward through BB for a use/def of EFLAGS.
20115   MachineBasicBlock::iterator miI(std::next(SelectItr));
20116   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20117     const MachineInstr& mi = *miI;
20118     if (mi.readsRegister(X86::EFLAGS))
20119       return false;
20120     if (mi.definesRegister(X86::EFLAGS))
20121       break; // Should have kill-flag - update below.
20122   }
20123
20124   // If we hit the end of the block, check whether EFLAGS is live into a
20125   // successor.
20126   if (miI == BB->end()) {
20127     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20128                                           sEnd = BB->succ_end();
20129          sItr != sEnd; ++sItr) {
20130       MachineBasicBlock* succ = *sItr;
20131       if (succ->isLiveIn(X86::EFLAGS))
20132         return false;
20133     }
20134   }
20135
20136   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20137   // out. SelectMI should have a kill flag on EFLAGS.
20138   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20139   return true;
20140 }
20141
20142 MachineBasicBlock *
20143 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20144                                      MachineBasicBlock *BB) const {
20145   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20146   DebugLoc DL = MI->getDebugLoc();
20147
20148   // To "insert" a SELECT_CC instruction, we actually have to insert the
20149   // diamond control-flow pattern.  The incoming instruction knows the
20150   // destination vreg to set, the condition code register to branch on, the
20151   // true/false values to select between, and a branch opcode to use.
20152   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20153   MachineFunction::iterator It = BB;
20154   ++It;
20155
20156   //  thisMBB:
20157   //  ...
20158   //   TrueVal = ...
20159   //   cmpTY ccX, r1, r2
20160   //   bCC copy1MBB
20161   //   fallthrough --> copy0MBB
20162   MachineBasicBlock *thisMBB = BB;
20163   MachineFunction *F = BB->getParent();
20164   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20165   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20166   F->insert(It, copy0MBB);
20167   F->insert(It, sinkMBB);
20168
20169   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20170   // live into the sink and copy blocks.
20171   const TargetRegisterInfo *TRI =
20172       BB->getParent()->getSubtarget().getRegisterInfo();
20173   if (!MI->killsRegister(X86::EFLAGS) &&
20174       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
20175     copy0MBB->addLiveIn(X86::EFLAGS);
20176     sinkMBB->addLiveIn(X86::EFLAGS);
20177   }
20178
20179   // Transfer the remainder of BB and its successor edges to sinkMBB.
20180   sinkMBB->splice(sinkMBB->begin(), BB,
20181                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
20182   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20183
20184   // Add the true and fallthrough blocks as its successors.
20185   BB->addSuccessor(copy0MBB);
20186   BB->addSuccessor(sinkMBB);
20187
20188   // Create the conditional branch instruction.
20189   unsigned Opc =
20190     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20191   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20192
20193   //  copy0MBB:
20194   //   %FalseValue = ...
20195   //   # fallthrough to sinkMBB
20196   copy0MBB->addSuccessor(sinkMBB);
20197
20198   //  sinkMBB:
20199   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20200   //  ...
20201   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20202           TII->get(X86::PHI), MI->getOperand(0).getReg())
20203     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20204     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20205
20206   MI->eraseFromParent();   // The pseudo instruction is gone now.
20207   return sinkMBB;
20208 }
20209
20210 MachineBasicBlock *
20211 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20212                                         MachineBasicBlock *BB) const {
20213   MachineFunction *MF = BB->getParent();
20214   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20215   DebugLoc DL = MI->getDebugLoc();
20216   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20217
20218   assert(MF->shouldSplitStack());
20219
20220   const bool Is64Bit = Subtarget->is64Bit();
20221   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20222
20223   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20224   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20225
20226   // BB:
20227   //  ... [Till the alloca]
20228   // If stacklet is not large enough, jump to mallocMBB
20229   //
20230   // bumpMBB:
20231   //  Allocate by subtracting from RSP
20232   //  Jump to continueMBB
20233   //
20234   // mallocMBB:
20235   //  Allocate by call to runtime
20236   //
20237   // continueMBB:
20238   //  ...
20239   //  [rest of original BB]
20240   //
20241
20242   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20243   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20244   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20245
20246   MachineRegisterInfo &MRI = MF->getRegInfo();
20247   const TargetRegisterClass *AddrRegClass =
20248     getRegClassFor(getPointerTy());
20249
20250   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20251     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20252     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20253     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20254     sizeVReg = MI->getOperand(1).getReg(),
20255     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20256
20257   MachineFunction::iterator MBBIter = BB;
20258   ++MBBIter;
20259
20260   MF->insert(MBBIter, bumpMBB);
20261   MF->insert(MBBIter, mallocMBB);
20262   MF->insert(MBBIter, continueMBB);
20263
20264   continueMBB->splice(continueMBB->begin(), BB,
20265                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20266   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20267
20268   // Add code to the main basic block to check if the stack limit has been hit,
20269   // and if so, jump to mallocMBB otherwise to bumpMBB.
20270   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20271   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20272     .addReg(tmpSPVReg).addReg(sizeVReg);
20273   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20274     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20275     .addReg(SPLimitVReg);
20276   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
20277
20278   // bumpMBB simply decreases the stack pointer, since we know the current
20279   // stacklet has enough space.
20280   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20281     .addReg(SPLimitVReg);
20282   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20283     .addReg(SPLimitVReg);
20284   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20285
20286   // Calls into a routine in libgcc to allocate more space from the heap.
20287   const uint32_t *RegMask = MF->getTarget()
20288                                 .getSubtargetImpl()
20289                                 ->getRegisterInfo()
20290                                 ->getCallPreservedMask(CallingConv::C);
20291   if (IsLP64) {
20292     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20293       .addReg(sizeVReg);
20294     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20295       .addExternalSymbol("__morestack_allocate_stack_space")
20296       .addRegMask(RegMask)
20297       .addReg(X86::RDI, RegState::Implicit)
20298       .addReg(X86::RAX, RegState::ImplicitDefine);
20299   } else if (Is64Bit) {
20300     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20301       .addReg(sizeVReg);
20302     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20303       .addExternalSymbol("__morestack_allocate_stack_space")
20304       .addRegMask(RegMask)
20305       .addReg(X86::EDI, RegState::Implicit)
20306       .addReg(X86::EAX, RegState::ImplicitDefine);
20307   } else {
20308     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20309       .addImm(12);
20310     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20311     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20312       .addExternalSymbol("__morestack_allocate_stack_space")
20313       .addRegMask(RegMask)
20314       .addReg(X86::EAX, RegState::ImplicitDefine);
20315   }
20316
20317   if (!Is64Bit)
20318     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20319       .addImm(16);
20320
20321   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20322     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20323   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20324
20325   // Set up the CFG correctly.
20326   BB->addSuccessor(bumpMBB);
20327   BB->addSuccessor(mallocMBB);
20328   mallocMBB->addSuccessor(continueMBB);
20329   bumpMBB->addSuccessor(continueMBB);
20330
20331   // Take care of the PHI nodes.
20332   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20333           MI->getOperand(0).getReg())
20334     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20335     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20336
20337   // Delete the original pseudo instruction.
20338   MI->eraseFromParent();
20339
20340   // And we're done.
20341   return continueMBB;
20342 }
20343
20344 MachineBasicBlock *
20345 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20346                                         MachineBasicBlock *BB) const {
20347   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20348   DebugLoc DL = MI->getDebugLoc();
20349
20350   assert(!Subtarget->isTargetMacho());
20351
20352   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
20353   // non-trivial part is impdef of ESP.
20354
20355   if (Subtarget->isTargetWin64()) {
20356     if (Subtarget->isTargetCygMing()) {
20357       // ___chkstk(Mingw64):
20358       // Clobbers R10, R11, RAX and EFLAGS.
20359       // Updates RSP.
20360       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20361         .addExternalSymbol("___chkstk")
20362         .addReg(X86::RAX, RegState::Implicit)
20363         .addReg(X86::RSP, RegState::Implicit)
20364         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
20365         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
20366         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20367     } else {
20368       // __chkstk(MSVCRT): does not update stack pointer.
20369       // Clobbers R10, R11 and EFLAGS.
20370       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20371         .addExternalSymbol("__chkstk")
20372         .addReg(X86::RAX, RegState::Implicit)
20373         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20374       // RAX has the offset to be subtracted from RSP.
20375       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
20376         .addReg(X86::RSP)
20377         .addReg(X86::RAX);
20378     }
20379   } else {
20380     const char *StackProbeSymbol =
20381       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
20382
20383     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
20384       .addExternalSymbol(StackProbeSymbol)
20385       .addReg(X86::EAX, RegState::Implicit)
20386       .addReg(X86::ESP, RegState::Implicit)
20387       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
20388       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
20389       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20390   }
20391
20392   MI->eraseFromParent();   // The pseudo instruction is gone now.
20393   return BB;
20394 }
20395
20396 MachineBasicBlock *
20397 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20398                                       MachineBasicBlock *BB) const {
20399   // This is pretty easy.  We're taking the value that we received from
20400   // our load from the relocation, sticking it in either RDI (x86-64)
20401   // or EAX and doing an indirect call.  The return value will then
20402   // be in the normal return register.
20403   MachineFunction *F = BB->getParent();
20404   const X86InstrInfo *TII =
20405       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
20406   DebugLoc DL = MI->getDebugLoc();
20407
20408   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20409   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20410
20411   // Get a register mask for the lowered call.
20412   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20413   // proper register mask.
20414   const uint32_t *RegMask = F->getTarget()
20415                                 .getSubtargetImpl()
20416                                 ->getRegisterInfo()
20417                                 ->getCallPreservedMask(CallingConv::C);
20418   if (Subtarget->is64Bit()) {
20419     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20420                                       TII->get(X86::MOV64rm), X86::RDI)
20421     .addReg(X86::RIP)
20422     .addImm(0).addReg(0)
20423     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20424                       MI->getOperand(3).getTargetFlags())
20425     .addReg(0);
20426     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20427     addDirectMem(MIB, X86::RDI);
20428     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20429   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20430     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20431                                       TII->get(X86::MOV32rm), X86::EAX)
20432     .addReg(0)
20433     .addImm(0).addReg(0)
20434     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20435                       MI->getOperand(3).getTargetFlags())
20436     .addReg(0);
20437     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20438     addDirectMem(MIB, X86::EAX);
20439     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20440   } else {
20441     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20442                                       TII->get(X86::MOV32rm), X86::EAX)
20443     .addReg(TII->getGlobalBaseReg(F))
20444     .addImm(0).addReg(0)
20445     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20446                       MI->getOperand(3).getTargetFlags())
20447     .addReg(0);
20448     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20449     addDirectMem(MIB, X86::EAX);
20450     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20451   }
20452
20453   MI->eraseFromParent(); // The pseudo instruction is gone now.
20454   return BB;
20455 }
20456
20457 MachineBasicBlock *
20458 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20459                                     MachineBasicBlock *MBB) const {
20460   DebugLoc DL = MI->getDebugLoc();
20461   MachineFunction *MF = MBB->getParent();
20462   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20463   MachineRegisterInfo &MRI = MF->getRegInfo();
20464
20465   const BasicBlock *BB = MBB->getBasicBlock();
20466   MachineFunction::iterator I = MBB;
20467   ++I;
20468
20469   // Memory Reference
20470   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20471   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20472
20473   unsigned DstReg;
20474   unsigned MemOpndSlot = 0;
20475
20476   unsigned CurOp = 0;
20477
20478   DstReg = MI->getOperand(CurOp++).getReg();
20479   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20480   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20481   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20482   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20483
20484   MemOpndSlot = CurOp;
20485
20486   MVT PVT = getPointerTy();
20487   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20488          "Invalid Pointer Size!");
20489
20490   // For v = setjmp(buf), we generate
20491   //
20492   // thisMBB:
20493   //  buf[LabelOffset] = restoreMBB
20494   //  SjLjSetup restoreMBB
20495   //
20496   // mainMBB:
20497   //  v_main = 0
20498   //
20499   // sinkMBB:
20500   //  v = phi(main, restore)
20501   //
20502   // restoreMBB:
20503   //  v_restore = 1
20504
20505   MachineBasicBlock *thisMBB = MBB;
20506   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20507   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20508   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20509   MF->insert(I, mainMBB);
20510   MF->insert(I, sinkMBB);
20511   MF->push_back(restoreMBB);
20512
20513   MachineInstrBuilder MIB;
20514
20515   // Transfer the remainder of BB and its successor edges to sinkMBB.
20516   sinkMBB->splice(sinkMBB->begin(), MBB,
20517                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20518   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20519
20520   // thisMBB:
20521   unsigned PtrStoreOpc = 0;
20522   unsigned LabelReg = 0;
20523   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20524   Reloc::Model RM = MF->getTarget().getRelocationModel();
20525   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20526                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20527
20528   // Prepare IP either in reg or imm.
20529   if (!UseImmLabel) {
20530     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20531     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20532     LabelReg = MRI.createVirtualRegister(PtrRC);
20533     if (Subtarget->is64Bit()) {
20534       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20535               .addReg(X86::RIP)
20536               .addImm(0)
20537               .addReg(0)
20538               .addMBB(restoreMBB)
20539               .addReg(0);
20540     } else {
20541       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20542       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20543               .addReg(XII->getGlobalBaseReg(MF))
20544               .addImm(0)
20545               .addReg(0)
20546               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20547               .addReg(0);
20548     }
20549   } else
20550     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20551   // Store IP
20552   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20553   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20554     if (i == X86::AddrDisp)
20555       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20556     else
20557       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20558   }
20559   if (!UseImmLabel)
20560     MIB.addReg(LabelReg);
20561   else
20562     MIB.addMBB(restoreMBB);
20563   MIB.setMemRefs(MMOBegin, MMOEnd);
20564   // Setup
20565   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20566           .addMBB(restoreMBB);
20567
20568   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
20569       MF->getSubtarget().getRegisterInfo());
20570   MIB.addRegMask(RegInfo->getNoPreservedMask());
20571   thisMBB->addSuccessor(mainMBB);
20572   thisMBB->addSuccessor(restoreMBB);
20573
20574   // mainMBB:
20575   //  EAX = 0
20576   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20577   mainMBB->addSuccessor(sinkMBB);
20578
20579   // sinkMBB:
20580   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20581           TII->get(X86::PHI), DstReg)
20582     .addReg(mainDstReg).addMBB(mainMBB)
20583     .addReg(restoreDstReg).addMBB(restoreMBB);
20584
20585   // restoreMBB:
20586   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20587   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
20588   restoreMBB->addSuccessor(sinkMBB);
20589
20590   MI->eraseFromParent();
20591   return sinkMBB;
20592 }
20593
20594 MachineBasicBlock *
20595 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20596                                      MachineBasicBlock *MBB) const {
20597   DebugLoc DL = MI->getDebugLoc();
20598   MachineFunction *MF = MBB->getParent();
20599   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20600   MachineRegisterInfo &MRI = MF->getRegInfo();
20601
20602   // Memory Reference
20603   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20604   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20605
20606   MVT PVT = getPointerTy();
20607   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20608          "Invalid Pointer Size!");
20609
20610   const TargetRegisterClass *RC =
20611     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20612   unsigned Tmp = MRI.createVirtualRegister(RC);
20613   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20614   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
20615       MF->getSubtarget().getRegisterInfo());
20616   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20617   unsigned SP = RegInfo->getStackRegister();
20618
20619   MachineInstrBuilder MIB;
20620
20621   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20622   const int64_t SPOffset = 2 * PVT.getStoreSize();
20623
20624   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20625   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20626
20627   // Reload FP
20628   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20629   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20630     MIB.addOperand(MI->getOperand(i));
20631   MIB.setMemRefs(MMOBegin, MMOEnd);
20632   // Reload IP
20633   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20634   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20635     if (i == X86::AddrDisp)
20636       MIB.addDisp(MI->getOperand(i), LabelOffset);
20637     else
20638       MIB.addOperand(MI->getOperand(i));
20639   }
20640   MIB.setMemRefs(MMOBegin, MMOEnd);
20641   // Reload SP
20642   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20643   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20644     if (i == X86::AddrDisp)
20645       MIB.addDisp(MI->getOperand(i), SPOffset);
20646     else
20647       MIB.addOperand(MI->getOperand(i));
20648   }
20649   MIB.setMemRefs(MMOBegin, MMOEnd);
20650   // Jump
20651   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20652
20653   MI->eraseFromParent();
20654   return MBB;
20655 }
20656
20657 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20658 // accumulator loops. Writing back to the accumulator allows the coalescer
20659 // to remove extra copies in the loop.   
20660 MachineBasicBlock *
20661 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20662                                  MachineBasicBlock *MBB) const {
20663   MachineOperand &AddendOp = MI->getOperand(3);
20664
20665   // Bail out early if the addend isn't a register - we can't switch these.
20666   if (!AddendOp.isReg())
20667     return MBB;
20668
20669   MachineFunction &MF = *MBB->getParent();
20670   MachineRegisterInfo &MRI = MF.getRegInfo();
20671
20672   // Check whether the addend is defined by a PHI:
20673   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20674   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20675   if (!AddendDef.isPHI())
20676     return MBB;
20677
20678   // Look for the following pattern:
20679   // loop:
20680   //   %addend = phi [%entry, 0], [%loop, %result]
20681   //   ...
20682   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20683
20684   // Replace with:
20685   //   loop:
20686   //   %addend = phi [%entry, 0], [%loop, %result]
20687   //   ...
20688   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20689
20690   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20691     assert(AddendDef.getOperand(i).isReg());
20692     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20693     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20694     if (&PHISrcInst == MI) {
20695       // Found a matching instruction.
20696       unsigned NewFMAOpc = 0;
20697       switch (MI->getOpcode()) {
20698         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20699         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20700         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20701         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20702         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20703         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20704         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20705         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20706         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20707         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20708         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20709         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20710         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20711         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20712         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20713         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20714         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20715         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20716         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20717         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20718
20719         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20720         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20721         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20722         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20723         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20724         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20725         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20726         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20727         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20728         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20729         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20730         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20731         default: llvm_unreachable("Unrecognized FMA variant.");
20732       }
20733
20734       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
20735       MachineInstrBuilder MIB =
20736         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20737         .addOperand(MI->getOperand(0))
20738         .addOperand(MI->getOperand(3))
20739         .addOperand(MI->getOperand(2))
20740         .addOperand(MI->getOperand(1));
20741       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20742       MI->eraseFromParent();
20743     }
20744   }
20745
20746   return MBB;
20747 }
20748
20749 MachineBasicBlock *
20750 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20751                                                MachineBasicBlock *BB) const {
20752   switch (MI->getOpcode()) {
20753   default: llvm_unreachable("Unexpected instr type to insert");
20754   case X86::TAILJMPd64:
20755   case X86::TAILJMPr64:
20756   case X86::TAILJMPm64:
20757     llvm_unreachable("TAILJMP64 would not be touched here.");
20758   case X86::TCRETURNdi64:
20759   case X86::TCRETURNri64:
20760   case X86::TCRETURNmi64:
20761     return BB;
20762   case X86::WIN_ALLOCA:
20763     return EmitLoweredWinAlloca(MI, BB);
20764   case X86::SEG_ALLOCA_32:
20765   case X86::SEG_ALLOCA_64:
20766     return EmitLoweredSegAlloca(MI, BB);
20767   case X86::TLSCall_32:
20768   case X86::TLSCall_64:
20769     return EmitLoweredTLSCall(MI, BB);
20770   case X86::CMOV_GR8:
20771   case X86::CMOV_FR32:
20772   case X86::CMOV_FR64:
20773   case X86::CMOV_V4F32:
20774   case X86::CMOV_V2F64:
20775   case X86::CMOV_V2I64:
20776   case X86::CMOV_V8F32:
20777   case X86::CMOV_V4F64:
20778   case X86::CMOV_V4I64:
20779   case X86::CMOV_V16F32:
20780   case X86::CMOV_V8F64:
20781   case X86::CMOV_V8I64:
20782   case X86::CMOV_GR16:
20783   case X86::CMOV_GR32:
20784   case X86::CMOV_RFP32:
20785   case X86::CMOV_RFP64:
20786   case X86::CMOV_RFP80:
20787     return EmitLoweredSelect(MI, BB);
20788
20789   case X86::FP32_TO_INT16_IN_MEM:
20790   case X86::FP32_TO_INT32_IN_MEM:
20791   case X86::FP32_TO_INT64_IN_MEM:
20792   case X86::FP64_TO_INT16_IN_MEM:
20793   case X86::FP64_TO_INT32_IN_MEM:
20794   case X86::FP64_TO_INT64_IN_MEM:
20795   case X86::FP80_TO_INT16_IN_MEM:
20796   case X86::FP80_TO_INT32_IN_MEM:
20797   case X86::FP80_TO_INT64_IN_MEM: {
20798     MachineFunction *F = BB->getParent();
20799     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
20800     DebugLoc DL = MI->getDebugLoc();
20801
20802     // Change the floating point control register to use "round towards zero"
20803     // mode when truncating to an integer value.
20804     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20805     addFrameReference(BuildMI(*BB, MI, DL,
20806                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20807
20808     // Load the old value of the high byte of the control word...
20809     unsigned OldCW =
20810       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20811     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20812                       CWFrameIdx);
20813
20814     // Set the high part to be round to zero...
20815     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20816       .addImm(0xC7F);
20817
20818     // Reload the modified control word now...
20819     addFrameReference(BuildMI(*BB, MI, DL,
20820                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20821
20822     // Restore the memory image of control word to original value
20823     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20824       .addReg(OldCW);
20825
20826     // Get the X86 opcode to use.
20827     unsigned Opc;
20828     switch (MI->getOpcode()) {
20829     default: llvm_unreachable("illegal opcode!");
20830     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20831     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20832     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20833     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20834     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20835     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20836     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20837     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20838     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20839     }
20840
20841     X86AddressMode AM;
20842     MachineOperand &Op = MI->getOperand(0);
20843     if (Op.isReg()) {
20844       AM.BaseType = X86AddressMode::RegBase;
20845       AM.Base.Reg = Op.getReg();
20846     } else {
20847       AM.BaseType = X86AddressMode::FrameIndexBase;
20848       AM.Base.FrameIndex = Op.getIndex();
20849     }
20850     Op = MI->getOperand(1);
20851     if (Op.isImm())
20852       AM.Scale = Op.getImm();
20853     Op = MI->getOperand(2);
20854     if (Op.isImm())
20855       AM.IndexReg = Op.getImm();
20856     Op = MI->getOperand(3);
20857     if (Op.isGlobal()) {
20858       AM.GV = Op.getGlobal();
20859     } else {
20860       AM.Disp = Op.getImm();
20861     }
20862     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20863                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20864
20865     // Reload the original control word now.
20866     addFrameReference(BuildMI(*BB, MI, DL,
20867                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20868
20869     MI->eraseFromParent();   // The pseudo instruction is gone now.
20870     return BB;
20871   }
20872     // String/text processing lowering.
20873   case X86::PCMPISTRM128REG:
20874   case X86::VPCMPISTRM128REG:
20875   case X86::PCMPISTRM128MEM:
20876   case X86::VPCMPISTRM128MEM:
20877   case X86::PCMPESTRM128REG:
20878   case X86::VPCMPESTRM128REG:
20879   case X86::PCMPESTRM128MEM:
20880   case X86::VPCMPESTRM128MEM:
20881     assert(Subtarget->hasSSE42() &&
20882            "Target must have SSE4.2 or AVX features enabled");
20883     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
20884
20885   // String/text processing lowering.
20886   case X86::PCMPISTRIREG:
20887   case X86::VPCMPISTRIREG:
20888   case X86::PCMPISTRIMEM:
20889   case X86::VPCMPISTRIMEM:
20890   case X86::PCMPESTRIREG:
20891   case X86::VPCMPESTRIREG:
20892   case X86::PCMPESTRIMEM:
20893   case X86::VPCMPESTRIMEM:
20894     assert(Subtarget->hasSSE42() &&
20895            "Target must have SSE4.2 or AVX features enabled");
20896     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
20897
20898   // Thread synchronization.
20899   case X86::MONITOR:
20900     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
20901                        Subtarget);
20902
20903   // xbegin
20904   case X86::XBEGIN:
20905     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
20906
20907   case X86::VASTART_SAVE_XMM_REGS:
20908     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20909
20910   case X86::VAARG_64:
20911     return EmitVAARG64WithCustomInserter(MI, BB);
20912
20913   case X86::EH_SjLj_SetJmp32:
20914   case X86::EH_SjLj_SetJmp64:
20915     return emitEHSjLjSetJmp(MI, BB);
20916
20917   case X86::EH_SjLj_LongJmp32:
20918   case X86::EH_SjLj_LongJmp64:
20919     return emitEHSjLjLongJmp(MI, BB);
20920
20921   case TargetOpcode::STACKMAP:
20922   case TargetOpcode::PATCHPOINT:
20923     return emitPatchPoint(MI, BB);
20924
20925   case X86::VFMADDPDr213r:
20926   case X86::VFMADDPSr213r:
20927   case X86::VFMADDSDr213r:
20928   case X86::VFMADDSSr213r:
20929   case X86::VFMSUBPDr213r:
20930   case X86::VFMSUBPSr213r:
20931   case X86::VFMSUBSDr213r:
20932   case X86::VFMSUBSSr213r:
20933   case X86::VFNMADDPDr213r:
20934   case X86::VFNMADDPSr213r:
20935   case X86::VFNMADDSDr213r:
20936   case X86::VFNMADDSSr213r:
20937   case X86::VFNMSUBPDr213r:
20938   case X86::VFNMSUBPSr213r:
20939   case X86::VFNMSUBSDr213r:
20940   case X86::VFNMSUBSSr213r:
20941   case X86::VFMADDSUBPDr213r:
20942   case X86::VFMADDSUBPSr213r:
20943   case X86::VFMSUBADDPDr213r:
20944   case X86::VFMSUBADDPSr213r:
20945   case X86::VFMADDPDr213rY:
20946   case X86::VFMADDPSr213rY:
20947   case X86::VFMSUBPDr213rY:
20948   case X86::VFMSUBPSr213rY:
20949   case X86::VFNMADDPDr213rY:
20950   case X86::VFNMADDPSr213rY:
20951   case X86::VFNMSUBPDr213rY:
20952   case X86::VFNMSUBPSr213rY:
20953   case X86::VFMADDSUBPDr213rY:
20954   case X86::VFMADDSUBPSr213rY:
20955   case X86::VFMSUBADDPDr213rY:
20956   case X86::VFMSUBADDPSr213rY:
20957     return emitFMA3Instr(MI, BB);
20958   }
20959 }
20960
20961 //===----------------------------------------------------------------------===//
20962 //                           X86 Optimization Hooks
20963 //===----------------------------------------------------------------------===//
20964
20965 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20966                                                       APInt &KnownZero,
20967                                                       APInt &KnownOne,
20968                                                       const SelectionDAG &DAG,
20969                                                       unsigned Depth) const {
20970   unsigned BitWidth = KnownZero.getBitWidth();
20971   unsigned Opc = Op.getOpcode();
20972   assert((Opc >= ISD::BUILTIN_OP_END ||
20973           Opc == ISD::INTRINSIC_WO_CHAIN ||
20974           Opc == ISD::INTRINSIC_W_CHAIN ||
20975           Opc == ISD::INTRINSIC_VOID) &&
20976          "Should use MaskedValueIsZero if you don't know whether Op"
20977          " is a target node!");
20978
20979   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20980   switch (Opc) {
20981   default: break;
20982   case X86ISD::ADD:
20983   case X86ISD::SUB:
20984   case X86ISD::ADC:
20985   case X86ISD::SBB:
20986   case X86ISD::SMUL:
20987   case X86ISD::UMUL:
20988   case X86ISD::INC:
20989   case X86ISD::DEC:
20990   case X86ISD::OR:
20991   case X86ISD::XOR:
20992   case X86ISD::AND:
20993     // These nodes' second result is a boolean.
20994     if (Op.getResNo() == 0)
20995       break;
20996     // Fallthrough
20997   case X86ISD::SETCC:
20998     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20999     break;
21000   case ISD::INTRINSIC_WO_CHAIN: {
21001     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21002     unsigned NumLoBits = 0;
21003     switch (IntId) {
21004     default: break;
21005     case Intrinsic::x86_sse_movmsk_ps:
21006     case Intrinsic::x86_avx_movmsk_ps_256:
21007     case Intrinsic::x86_sse2_movmsk_pd:
21008     case Intrinsic::x86_avx_movmsk_pd_256:
21009     case Intrinsic::x86_mmx_pmovmskb:
21010     case Intrinsic::x86_sse2_pmovmskb_128:
21011     case Intrinsic::x86_avx2_pmovmskb: {
21012       // High bits of movmskp{s|d}, pmovmskb are known zero.
21013       switch (IntId) {
21014         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21015         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21016         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21017         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21018         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21019         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21020         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21021         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21022       }
21023       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21024       break;
21025     }
21026     }
21027     break;
21028   }
21029   }
21030 }
21031
21032 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21033   SDValue Op,
21034   const SelectionDAG &,
21035   unsigned Depth) const {
21036   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21037   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21038     return Op.getValueType().getScalarType().getSizeInBits();
21039
21040   // Fallback case.
21041   return 1;
21042 }
21043
21044 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21045 /// node is a GlobalAddress + offset.
21046 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21047                                        const GlobalValue* &GA,
21048                                        int64_t &Offset) const {
21049   if (N->getOpcode() == X86ISD::Wrapper) {
21050     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21051       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21052       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21053       return true;
21054     }
21055   }
21056   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21057 }
21058
21059 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21060 /// same as extracting the high 128-bit part of 256-bit vector and then
21061 /// inserting the result into the low part of a new 256-bit vector
21062 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21063   EVT VT = SVOp->getValueType(0);
21064   unsigned NumElems = VT.getVectorNumElements();
21065
21066   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21067   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21068     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21069         SVOp->getMaskElt(j) >= 0)
21070       return false;
21071
21072   return true;
21073 }
21074
21075 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21076 /// same as extracting the low 128-bit part of 256-bit vector and then
21077 /// inserting the result into the high part of a new 256-bit vector
21078 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21079   EVT VT = SVOp->getValueType(0);
21080   unsigned NumElems = VT.getVectorNumElements();
21081
21082   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21083   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21084     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21085         SVOp->getMaskElt(j) >= 0)
21086       return false;
21087
21088   return true;
21089 }
21090
21091 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21092 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21093                                         TargetLowering::DAGCombinerInfo &DCI,
21094                                         const X86Subtarget* Subtarget) {
21095   SDLoc dl(N);
21096   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21097   SDValue V1 = SVOp->getOperand(0);
21098   SDValue V2 = SVOp->getOperand(1);
21099   EVT VT = SVOp->getValueType(0);
21100   unsigned NumElems = VT.getVectorNumElements();
21101
21102   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21103       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21104     //
21105     //                   0,0,0,...
21106     //                      |
21107     //    V      UNDEF    BUILD_VECTOR    UNDEF
21108     //     \      /           \           /
21109     //  CONCAT_VECTOR         CONCAT_VECTOR
21110     //         \                  /
21111     //          \                /
21112     //          RESULT: V + zero extended
21113     //
21114     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21115         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21116         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21117       return SDValue();
21118
21119     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21120       return SDValue();
21121
21122     // To match the shuffle mask, the first half of the mask should
21123     // be exactly the first vector, and all the rest a splat with the
21124     // first element of the second one.
21125     for (unsigned i = 0; i != NumElems/2; ++i)
21126       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21127           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21128         return SDValue();
21129
21130     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21131     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21132       if (Ld->hasNUsesOfValue(1, 0)) {
21133         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21134         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21135         SDValue ResNode =
21136           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21137                                   Ld->getMemoryVT(),
21138                                   Ld->getPointerInfo(),
21139                                   Ld->getAlignment(),
21140                                   false/*isVolatile*/, true/*ReadMem*/,
21141                                   false/*WriteMem*/);
21142
21143         // Make sure the newly-created LOAD is in the same position as Ld in
21144         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21145         // and update uses of Ld's output chain to use the TokenFactor.
21146         if (Ld->hasAnyUseOfValue(1)) {
21147           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21148                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21149           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21150           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21151                                  SDValue(ResNode.getNode(), 1));
21152         }
21153
21154         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
21155       }
21156     }
21157
21158     // Emit a zeroed vector and insert the desired subvector on its
21159     // first half.
21160     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21161     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21162     return DCI.CombineTo(N, InsV);
21163   }
21164
21165   //===--------------------------------------------------------------------===//
21166   // Combine some shuffles into subvector extracts and inserts:
21167   //
21168
21169   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21170   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21171     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21172     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21173     return DCI.CombineTo(N, InsV);
21174   }
21175
21176   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21177   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21178     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21179     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21180     return DCI.CombineTo(N, InsV);
21181   }
21182
21183   return SDValue();
21184 }
21185
21186 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21187 /// possible.
21188 ///
21189 /// This is the leaf of the recursive combinine below. When we have found some
21190 /// chain of single-use x86 shuffle instructions and accumulated the combined
21191 /// shuffle mask represented by them, this will try to pattern match that mask
21192 /// into either a single instruction if there is a special purpose instruction
21193 /// for this operation, or into a PSHUFB instruction which is a fully general
21194 /// instruction but should only be used to replace chains over a certain depth.
21195 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21196                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21197                                    TargetLowering::DAGCombinerInfo &DCI,
21198                                    const X86Subtarget *Subtarget) {
21199   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21200
21201   // Find the operand that enters the chain. Note that multiple uses are OK
21202   // here, we're not going to remove the operand we find.
21203   SDValue Input = Op.getOperand(0);
21204   while (Input.getOpcode() == ISD::BITCAST)
21205     Input = Input.getOperand(0);
21206
21207   MVT VT = Input.getSimpleValueType();
21208   MVT RootVT = Root.getSimpleValueType();
21209   SDLoc DL(Root);
21210
21211   // Just remove no-op shuffle masks.
21212   if (Mask.size() == 1) {
21213     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
21214                   /*AddTo*/ true);
21215     return true;
21216   }
21217
21218   // Use the float domain if the operand type is a floating point type.
21219   bool FloatDomain = VT.isFloatingPoint();
21220
21221   // For floating point shuffles, we don't have free copies in the shuffle
21222   // instructions or the ability to load as part of the instruction, so
21223   // canonicalize their shuffles to UNPCK or MOV variants.
21224   //
21225   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21226   // vectors because it can have a load folded into it that UNPCK cannot. This
21227   // doesn't preclude something switching to the shorter encoding post-RA.
21228   if (FloatDomain) {
21229     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
21230       bool Lo = Mask.equals(0, 0);
21231       unsigned Shuffle;
21232       MVT ShuffleVT;
21233       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21234       // is no slower than UNPCKLPD but has the option to fold the input operand
21235       // into even an unaligned memory load.
21236       if (Lo && Subtarget->hasSSE3()) {
21237         Shuffle = X86ISD::MOVDDUP;
21238         ShuffleVT = MVT::v2f64;
21239       } else {
21240         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21241         // than the UNPCK variants.
21242         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21243         ShuffleVT = MVT::v4f32;
21244       }
21245       if (Depth == 1 && Root->getOpcode() == Shuffle)
21246         return false; // Nothing to do!
21247       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21248       DCI.AddToWorklist(Op.getNode());
21249       if (Shuffle == X86ISD::MOVDDUP)
21250         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21251       else
21252         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21253       DCI.AddToWorklist(Op.getNode());
21254       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21255                     /*AddTo*/ true);
21256       return true;
21257     }
21258     if (Subtarget->hasSSE3() &&
21259         (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
21260       bool Lo = Mask.equals(0, 0, 2, 2);
21261       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21262       MVT ShuffleVT = MVT::v4f32;
21263       if (Depth == 1 && Root->getOpcode() == Shuffle)
21264         return false; // Nothing to do!
21265       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21266       DCI.AddToWorklist(Op.getNode());
21267       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21268       DCI.AddToWorklist(Op.getNode());
21269       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21270                     /*AddTo*/ true);
21271       return true;
21272     }
21273     if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
21274       bool Lo = Mask.equals(0, 0, 1, 1);
21275       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21276       MVT ShuffleVT = MVT::v4f32;
21277       if (Depth == 1 && Root->getOpcode() == Shuffle)
21278         return false; // Nothing to do!
21279       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21280       DCI.AddToWorklist(Op.getNode());
21281       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21282       DCI.AddToWorklist(Op.getNode());
21283       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21284                     /*AddTo*/ true);
21285       return true;
21286     }
21287   }
21288
21289   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21290   // variants as none of these have single-instruction variants that are
21291   // superior to the UNPCK formulation.
21292   if (!FloatDomain &&
21293       (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
21294        Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
21295        Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
21296        Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
21297                    15))) {
21298     bool Lo = Mask[0] == 0;
21299     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21300     if (Depth == 1 && Root->getOpcode() == Shuffle)
21301       return false; // Nothing to do!
21302     MVT ShuffleVT;
21303     switch (Mask.size()) {
21304     case 8:
21305       ShuffleVT = MVT::v8i16;
21306       break;
21307     case 16:
21308       ShuffleVT = MVT::v16i8;
21309       break;
21310     default:
21311       llvm_unreachable("Impossible mask size!");
21312     };
21313     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21314     DCI.AddToWorklist(Op.getNode());
21315     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21316     DCI.AddToWorklist(Op.getNode());
21317     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21318                   /*AddTo*/ true);
21319     return true;
21320   }
21321
21322   // Don't try to re-form single instruction chains under any circumstances now
21323   // that we've done encoding canonicalization for them.
21324   if (Depth < 2)
21325     return false;
21326
21327   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21328   // can replace them with a single PSHUFB instruction profitably. Intel's
21329   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21330   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21331   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21332     SmallVector<SDValue, 16> PSHUFBMask;
21333     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
21334     int Ratio = 16 / Mask.size();
21335     for (unsigned i = 0; i < 16; ++i) {
21336       if (Mask[i / Ratio] == SM_SentinelUndef) {
21337         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21338         continue;
21339       }
21340       int M = Mask[i / Ratio] != SM_SentinelZero
21341                   ? Ratio * Mask[i / Ratio] + i % Ratio
21342                   : 255;
21343       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
21344     }
21345     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
21346     DCI.AddToWorklist(Op.getNode());
21347     SDValue PSHUFBMaskOp =
21348         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
21349     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21350     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
21351     DCI.AddToWorklist(Op.getNode());
21352     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21353                   /*AddTo*/ true);
21354     return true;
21355   }
21356
21357   // Failed to find any combines.
21358   return false;
21359 }
21360
21361 /// \brief Fully generic combining of x86 shuffle instructions.
21362 ///
21363 /// This should be the last combine run over the x86 shuffle instructions. Once
21364 /// they have been fully optimized, this will recursively consider all chains
21365 /// of single-use shuffle instructions, build a generic model of the cumulative
21366 /// shuffle operation, and check for simpler instructions which implement this
21367 /// operation. We use this primarily for two purposes:
21368 ///
21369 /// 1) Collapse generic shuffles to specialized single instructions when
21370 ///    equivalent. In most cases, this is just an encoding size win, but
21371 ///    sometimes we will collapse multiple generic shuffles into a single
21372 ///    special-purpose shuffle.
21373 /// 2) Look for sequences of shuffle instructions with 3 or more total
21374 ///    instructions, and replace them with the slightly more expensive SSSE3
21375 ///    PSHUFB instruction if available. We do this as the last combining step
21376 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21377 ///    a suitable short sequence of other instructions. The PHUFB will either
21378 ///    use a register or have to read from memory and so is slightly (but only
21379 ///    slightly) more expensive than the other shuffle instructions.
21380 ///
21381 /// Because this is inherently a quadratic operation (for each shuffle in
21382 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21383 /// This should never be an issue in practice as the shuffle lowering doesn't
21384 /// produce sequences of more than 8 instructions.
21385 ///
21386 /// FIXME: We will currently miss some cases where the redundant shuffling
21387 /// would simplify under the threshold for PSHUFB formation because of
21388 /// combine-ordering. To fix this, we should do the redundant instruction
21389 /// combining in this recursive walk.
21390 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21391                                           ArrayRef<int> RootMask,
21392                                           int Depth, bool HasPSHUFB,
21393                                           SelectionDAG &DAG,
21394                                           TargetLowering::DAGCombinerInfo &DCI,
21395                                           const X86Subtarget *Subtarget) {
21396   // Bound the depth of our recursive combine because this is ultimately
21397   // quadratic in nature.
21398   if (Depth > 8)
21399     return false;
21400
21401   // Directly rip through bitcasts to find the underlying operand.
21402   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21403     Op = Op.getOperand(0);
21404
21405   MVT VT = Op.getSimpleValueType();
21406   if (!VT.isVector())
21407     return false; // Bail if we hit a non-vector.
21408   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
21409   // version should be added.
21410   if (VT.getSizeInBits() != 128)
21411     return false;
21412
21413   assert(Root.getSimpleValueType().isVector() &&
21414          "Shuffles operate on vector types!");
21415   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21416          "Can only combine shuffles of the same vector register size.");
21417
21418   if (!isTargetShuffle(Op.getOpcode()))
21419     return false;
21420   SmallVector<int, 16> OpMask;
21421   bool IsUnary;
21422   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21423   // We only can combine unary shuffles which we can decode the mask for.
21424   if (!HaveMask || !IsUnary)
21425     return false;
21426
21427   assert(VT.getVectorNumElements() == OpMask.size() &&
21428          "Different mask size from vector size!");
21429   assert(((RootMask.size() > OpMask.size() &&
21430            RootMask.size() % OpMask.size() == 0) ||
21431           (OpMask.size() > RootMask.size() &&
21432            OpMask.size() % RootMask.size() == 0) ||
21433           OpMask.size() == RootMask.size()) &&
21434          "The smaller number of elements must divide the larger.");
21435   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21436   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21437   assert(((RootRatio == 1 && OpRatio == 1) ||
21438           (RootRatio == 1) != (OpRatio == 1)) &&
21439          "Must not have a ratio for both incoming and op masks!");
21440
21441   SmallVector<int, 16> Mask;
21442   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21443
21444   // Merge this shuffle operation's mask into our accumulated mask. Note that
21445   // this shuffle's mask will be the first applied to the input, followed by the
21446   // root mask to get us all the way to the root value arrangement. The reason
21447   // for this order is that we are recursing up the operation chain.
21448   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21449     int RootIdx = i / RootRatio;
21450     if (RootMask[RootIdx] < 0) {
21451       // This is a zero or undef lane, we're done.
21452       Mask.push_back(RootMask[RootIdx]);
21453       continue;
21454     }
21455
21456     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21457     int OpIdx = RootMaskedIdx / OpRatio;
21458     if (OpMask[OpIdx] < 0) {
21459       // The incoming lanes are zero or undef, it doesn't matter which ones we
21460       // are using.
21461       Mask.push_back(OpMask[OpIdx]);
21462       continue;
21463     }
21464
21465     // Ok, we have non-zero lanes, map them through.
21466     Mask.push_back(OpMask[OpIdx] * OpRatio +
21467                    RootMaskedIdx % OpRatio);
21468   }
21469
21470   // See if we can recurse into the operand to combine more things.
21471   switch (Op.getOpcode()) {
21472     case X86ISD::PSHUFB:
21473       HasPSHUFB = true;
21474     case X86ISD::PSHUFD:
21475     case X86ISD::PSHUFHW:
21476     case X86ISD::PSHUFLW:
21477       if (Op.getOperand(0).hasOneUse() &&
21478           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21479                                         HasPSHUFB, DAG, DCI, Subtarget))
21480         return true;
21481       break;
21482
21483     case X86ISD::UNPCKL:
21484     case X86ISD::UNPCKH:
21485       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21486       // We can't check for single use, we have to check that this shuffle is the only user.
21487       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21488           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21489                                         HasPSHUFB, DAG, DCI, Subtarget))
21490           return true;
21491       break;
21492   }
21493
21494   // Minor canonicalization of the accumulated shuffle mask to make it easier
21495   // to match below. All this does is detect masks with squential pairs of
21496   // elements, and shrink them to the half-width mask. It does this in a loop
21497   // so it will reduce the size of the mask to the minimal width mask which
21498   // performs an equivalent shuffle.
21499   SmallVector<int, 16> WidenedMask;
21500   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21501     Mask = std::move(WidenedMask);
21502     WidenedMask.clear();
21503   }
21504
21505   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21506                                 Subtarget);
21507 }
21508
21509 /// \brief Get the PSHUF-style mask from PSHUF node.
21510 ///
21511 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21512 /// PSHUF-style masks that can be reused with such instructions.
21513 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21514   SmallVector<int, 4> Mask;
21515   bool IsUnary;
21516   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
21517   (void)HaveMask;
21518   assert(HaveMask);
21519
21520   switch (N.getOpcode()) {
21521   case X86ISD::PSHUFD:
21522     return Mask;
21523   case X86ISD::PSHUFLW:
21524     Mask.resize(4);
21525     return Mask;
21526   case X86ISD::PSHUFHW:
21527     Mask.erase(Mask.begin(), Mask.begin() + 4);
21528     for (int &M : Mask)
21529       M -= 4;
21530     return Mask;
21531   default:
21532     llvm_unreachable("No valid shuffle instruction found!");
21533   }
21534 }
21535
21536 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21537 ///
21538 /// We walk up the chain and look for a combinable shuffle, skipping over
21539 /// shuffles that we could hoist this shuffle's transformation past without
21540 /// altering anything.
21541 static SDValue
21542 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21543                              SelectionDAG &DAG,
21544                              TargetLowering::DAGCombinerInfo &DCI) {
21545   assert(N.getOpcode() == X86ISD::PSHUFD &&
21546          "Called with something other than an x86 128-bit half shuffle!");
21547   SDLoc DL(N);
21548
21549   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21550   // of the shuffles in the chain so that we can form a fresh chain to replace
21551   // this one.
21552   SmallVector<SDValue, 8> Chain;
21553   SDValue V = N.getOperand(0);
21554   for (; V.hasOneUse(); V = V.getOperand(0)) {
21555     switch (V.getOpcode()) {
21556     default:
21557       return SDValue(); // Nothing combined!
21558
21559     case ISD::BITCAST:
21560       // Skip bitcasts as we always know the type for the target specific
21561       // instructions.
21562       continue;
21563
21564     case X86ISD::PSHUFD:
21565       // Found another dword shuffle.
21566       break;
21567
21568     case X86ISD::PSHUFLW:
21569       // Check that the low words (being shuffled) are the identity in the
21570       // dword shuffle, and the high words are self-contained.
21571       if (Mask[0] != 0 || Mask[1] != 1 ||
21572           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21573         return SDValue();
21574
21575       Chain.push_back(V);
21576       continue;
21577
21578     case X86ISD::PSHUFHW:
21579       // Check that the high words (being shuffled) are the identity in the
21580       // dword shuffle, and the low words are self-contained.
21581       if (Mask[2] != 2 || Mask[3] != 3 ||
21582           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21583         return SDValue();
21584
21585       Chain.push_back(V);
21586       continue;
21587
21588     case X86ISD::UNPCKL:
21589     case X86ISD::UNPCKH:
21590       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21591       // shuffle into a preceding word shuffle.
21592       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
21593         return SDValue();
21594
21595       // Search for a half-shuffle which we can combine with.
21596       unsigned CombineOp =
21597           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21598       if (V.getOperand(0) != V.getOperand(1) ||
21599           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21600         return SDValue();
21601       Chain.push_back(V);
21602       V = V.getOperand(0);
21603       do {
21604         switch (V.getOpcode()) {
21605         default:
21606           return SDValue(); // Nothing to combine.
21607
21608         case X86ISD::PSHUFLW:
21609         case X86ISD::PSHUFHW:
21610           if (V.getOpcode() == CombineOp)
21611             break;
21612
21613           Chain.push_back(V);
21614
21615           // Fallthrough!
21616         case ISD::BITCAST:
21617           V = V.getOperand(0);
21618           continue;
21619         }
21620         break;
21621       } while (V.hasOneUse());
21622       break;
21623     }
21624     // Break out of the loop if we break out of the switch.
21625     break;
21626   }
21627
21628   if (!V.hasOneUse())
21629     // We fell out of the loop without finding a viable combining instruction.
21630     return SDValue();
21631
21632   // Merge this node's mask and our incoming mask.
21633   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21634   for (int &M : Mask)
21635     M = VMask[M];
21636   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21637                   getV4X86ShuffleImm8ForMask(Mask, DAG));
21638
21639   // Rebuild the chain around this new shuffle.
21640   while (!Chain.empty()) {
21641     SDValue W = Chain.pop_back_val();
21642
21643     if (V.getValueType() != W.getOperand(0).getValueType())
21644       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
21645
21646     switch (W.getOpcode()) {
21647     default:
21648       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21649
21650     case X86ISD::UNPCKL:
21651     case X86ISD::UNPCKH:
21652       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21653       break;
21654
21655     case X86ISD::PSHUFD:
21656     case X86ISD::PSHUFLW:
21657     case X86ISD::PSHUFHW:
21658       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21659       break;
21660     }
21661   }
21662   if (V.getValueType() != N.getValueType())
21663     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
21664
21665   // Return the new chain to replace N.
21666   return V;
21667 }
21668
21669 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21670 ///
21671 /// We walk up the chain, skipping shuffles of the other half and looking
21672 /// through shuffles which switch halves trying to find a shuffle of the same
21673 /// pair of dwords.
21674 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21675                                         SelectionDAG &DAG,
21676                                         TargetLowering::DAGCombinerInfo &DCI) {
21677   assert(
21678       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21679       "Called with something other than an x86 128-bit half shuffle!");
21680   SDLoc DL(N);
21681   unsigned CombineOpcode = N.getOpcode();
21682
21683   // Walk up a single-use chain looking for a combinable shuffle.
21684   SDValue V = N.getOperand(0);
21685   for (; V.hasOneUse(); V = V.getOperand(0)) {
21686     switch (V.getOpcode()) {
21687     default:
21688       return false; // Nothing combined!
21689
21690     case ISD::BITCAST:
21691       // Skip bitcasts as we always know the type for the target specific
21692       // instructions.
21693       continue;
21694
21695     case X86ISD::PSHUFLW:
21696     case X86ISD::PSHUFHW:
21697       if (V.getOpcode() == CombineOpcode)
21698         break;
21699
21700       // Other-half shuffles are no-ops.
21701       continue;
21702     }
21703     // Break out of the loop if we break out of the switch.
21704     break;
21705   }
21706
21707   if (!V.hasOneUse())
21708     // We fell out of the loop without finding a viable combining instruction.
21709     return false;
21710
21711   // Combine away the bottom node as its shuffle will be accumulated into
21712   // a preceding shuffle.
21713   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21714
21715   // Record the old value.
21716   SDValue Old = V;
21717
21718   // Merge this node's mask and our incoming mask (adjusted to account for all
21719   // the pshufd instructions encountered).
21720   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21721   for (int &M : Mask)
21722     M = VMask[M];
21723   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21724                   getV4X86ShuffleImm8ForMask(Mask, DAG));
21725
21726   // Check that the shuffles didn't cancel each other out. If not, we need to
21727   // combine to the new one.
21728   if (Old != V)
21729     // Replace the combinable shuffle with the combined one, updating all users
21730     // so that we re-evaluate the chain here.
21731     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21732
21733   return true;
21734 }
21735
21736 /// \brief Try to combine x86 target specific shuffles.
21737 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21738                                            TargetLowering::DAGCombinerInfo &DCI,
21739                                            const X86Subtarget *Subtarget) {
21740   SDLoc DL(N);
21741   MVT VT = N.getSimpleValueType();
21742   SmallVector<int, 4> Mask;
21743
21744   switch (N.getOpcode()) {
21745   case X86ISD::PSHUFD:
21746   case X86ISD::PSHUFLW:
21747   case X86ISD::PSHUFHW:
21748     Mask = getPSHUFShuffleMask(N);
21749     assert(Mask.size() == 4);
21750     break;
21751   default:
21752     return SDValue();
21753   }
21754
21755   // Nuke no-op shuffles that show up after combining.
21756   if (isNoopShuffleMask(Mask))
21757     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21758
21759   // Look for simplifications involving one or two shuffle instructions.
21760   SDValue V = N.getOperand(0);
21761   switch (N.getOpcode()) {
21762   default:
21763     break;
21764   case X86ISD::PSHUFLW:
21765   case X86ISD::PSHUFHW:
21766     assert(VT == MVT::v8i16);
21767     (void)VT;
21768
21769     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21770       return SDValue(); // We combined away this shuffle, so we're done.
21771
21772     // See if this reduces to a PSHUFD which is no more expensive and can
21773     // combine with more operations. Note that it has to at least flip the
21774     // dwords as otherwise it would have been removed as a no-op.
21775     if (Mask[0] == 2 && Mask[1] == 3 && Mask[2] == 0 && Mask[3] == 1) {
21776       int DMask[] = {0, 1, 2, 3};
21777       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21778       DMask[DOffset + 0] = DOffset + 1;
21779       DMask[DOffset + 1] = DOffset + 0;
21780       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
21781       DCI.AddToWorklist(V.getNode());
21782       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
21783                       getV4X86ShuffleImm8ForMask(DMask, DAG));
21784       DCI.AddToWorklist(V.getNode());
21785       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
21786     }
21787
21788     // Look for shuffle patterns which can be implemented as a single unpack.
21789     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21790     // only works when we have a PSHUFD followed by two half-shuffles.
21791     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21792         (V.getOpcode() == X86ISD::PSHUFLW ||
21793          V.getOpcode() == X86ISD::PSHUFHW) &&
21794         V.getOpcode() != N.getOpcode() &&
21795         V.hasOneUse()) {
21796       SDValue D = V.getOperand(0);
21797       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21798         D = D.getOperand(0);
21799       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21800         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21801         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21802         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21803         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21804         int WordMask[8];
21805         for (int i = 0; i < 4; ++i) {
21806           WordMask[i + NOffset] = Mask[i] + NOffset;
21807           WordMask[i + VOffset] = VMask[i] + VOffset;
21808         }
21809         // Map the word mask through the DWord mask.
21810         int MappedMask[8];
21811         for (int i = 0; i < 8; ++i)
21812           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21813         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
21814         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
21815         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
21816                        std::begin(UnpackLoMask)) ||
21817             std::equal(std::begin(MappedMask), std::end(MappedMask),
21818                        std::begin(UnpackHiMask))) {
21819           // We can replace all three shuffles with an unpack.
21820           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
21821           DCI.AddToWorklist(V.getNode());
21822           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21823                                                 : X86ISD::UNPCKH,
21824                              DL, MVT::v8i16, V, V);
21825         }
21826       }
21827     }
21828
21829     break;
21830
21831   case X86ISD::PSHUFD:
21832     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21833       return NewN;
21834
21835     break;
21836   }
21837
21838   return SDValue();
21839 }
21840
21841 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21842 ///
21843 /// We combine this directly on the abstract vector shuffle nodes so it is
21844 /// easier to generically match. We also insert dummy vector shuffle nodes for
21845 /// the operands which explicitly discard the lanes which are unused by this
21846 /// operation to try to flow through the rest of the combiner the fact that
21847 /// they're unused.
21848 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21849   SDLoc DL(N);
21850   EVT VT = N->getValueType(0);
21851
21852   // We only handle target-independent shuffles.
21853   // FIXME: It would be easy and harmless to use the target shuffle mask
21854   // extraction tool to support more.
21855   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21856     return SDValue();
21857
21858   auto *SVN = cast<ShuffleVectorSDNode>(N);
21859   ArrayRef<int> Mask = SVN->getMask();
21860   SDValue V1 = N->getOperand(0);
21861   SDValue V2 = N->getOperand(1);
21862
21863   // We require the first shuffle operand to be the SUB node, and the second to
21864   // be the ADD node.
21865   // FIXME: We should support the commuted patterns.
21866   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21867     return SDValue();
21868
21869   // If there are other uses of these operations we can't fold them.
21870   if (!V1->hasOneUse() || !V2->hasOneUse())
21871     return SDValue();
21872
21873   // Ensure that both operations have the same operands. Note that we can
21874   // commute the FADD operands.
21875   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21876   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21877       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21878     return SDValue();
21879
21880   // We're looking for blends between FADD and FSUB nodes. We insist on these
21881   // nodes being lined up in a specific expected pattern.
21882   if (!(isShuffleEquivalent(Mask, 0, 3) ||
21883         isShuffleEquivalent(Mask, 0, 5, 2, 7) ||
21884         isShuffleEquivalent(Mask, 0, 9, 2, 11, 4, 13, 6, 15)))
21885     return SDValue();
21886
21887   // Only specific types are legal at this point, assert so we notice if and
21888   // when these change.
21889   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21890           VT == MVT::v4f64) &&
21891          "Unknown vector type encountered!");
21892
21893   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21894 }
21895
21896 /// PerformShuffleCombine - Performs several different shuffle combines.
21897 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21898                                      TargetLowering::DAGCombinerInfo &DCI,
21899                                      const X86Subtarget *Subtarget) {
21900   SDLoc dl(N);
21901   SDValue N0 = N->getOperand(0);
21902   SDValue N1 = N->getOperand(1);
21903   EVT VT = N->getValueType(0);
21904
21905   // Don't create instructions with illegal types after legalize types has run.
21906   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21907   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21908     return SDValue();
21909
21910   // If we have legalized the vector types, look for blends of FADD and FSUB
21911   // nodes that we can fuse into an ADDSUB node.
21912   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21913     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21914       return AddSub;
21915
21916   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21917   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21918       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21919     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21920
21921   // During Type Legalization, when promoting illegal vector types,
21922   // the backend might introduce new shuffle dag nodes and bitcasts.
21923   //
21924   // This code performs the following transformation:
21925   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21926   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21927   //
21928   // We do this only if both the bitcast and the BINOP dag nodes have
21929   // one use. Also, perform this transformation only if the new binary
21930   // operation is legal. This is to avoid introducing dag nodes that
21931   // potentially need to be further expanded (or custom lowered) into a
21932   // less optimal sequence of dag nodes.
21933   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21934       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21935       N0.getOpcode() == ISD::BITCAST) {
21936     SDValue BC0 = N0.getOperand(0);
21937     EVT SVT = BC0.getValueType();
21938     unsigned Opcode = BC0.getOpcode();
21939     unsigned NumElts = VT.getVectorNumElements();
21940     
21941     if (BC0.hasOneUse() && SVT.isVector() &&
21942         SVT.getVectorNumElements() * 2 == NumElts &&
21943         TLI.isOperationLegal(Opcode, VT)) {
21944       bool CanFold = false;
21945       switch (Opcode) {
21946       default : break;
21947       case ISD::ADD :
21948       case ISD::FADD :
21949       case ISD::SUB :
21950       case ISD::FSUB :
21951       case ISD::MUL :
21952       case ISD::FMUL :
21953         CanFold = true;
21954       }
21955
21956       unsigned SVTNumElts = SVT.getVectorNumElements();
21957       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21958       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21959         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21960       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21961         CanFold = SVOp->getMaskElt(i) < 0;
21962
21963       if (CanFold) {
21964         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
21965         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
21966         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21967         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21968       }
21969     }
21970   }
21971
21972   // Only handle 128 wide vector from here on.
21973   if (!VT.is128BitVector())
21974     return SDValue();
21975
21976   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21977   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21978   // consecutive, non-overlapping, and in the right order.
21979   SmallVector<SDValue, 16> Elts;
21980   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21981     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21982
21983   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
21984   if (LD.getNode())
21985     return LD;
21986
21987   if (isTargetShuffle(N->getOpcode())) {
21988     SDValue Shuffle =
21989         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21990     if (Shuffle.getNode())
21991       return Shuffle;
21992
21993     // Try recursively combining arbitrary sequences of x86 shuffle
21994     // instructions into higher-order shuffles. We do this after combining
21995     // specific PSHUF instruction sequences into their minimal form so that we
21996     // can evaluate how many specialized shuffle instructions are involved in
21997     // a particular chain.
21998     SmallVector<int, 1> NonceMask; // Just a placeholder.
21999     NonceMask.push_back(0);
22000     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22001                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22002                                       DCI, Subtarget))
22003       return SDValue(); // This routine will use CombineTo to replace N.
22004   }
22005
22006   return SDValue();
22007 }
22008
22009 /// PerformTruncateCombine - Converts truncate operation to
22010 /// a sequence of vector shuffle operations.
22011 /// It is possible when we truncate 256-bit vector to 128-bit vector
22012 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
22013                                       TargetLowering::DAGCombinerInfo &DCI,
22014                                       const X86Subtarget *Subtarget)  {
22015   return SDValue();
22016 }
22017
22018 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22019 /// specific shuffle of a load can be folded into a single element load.
22020 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22021 /// shuffles have been custom lowered so we need to handle those here.
22022 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22023                                          TargetLowering::DAGCombinerInfo &DCI) {
22024   if (DCI.isBeforeLegalizeOps())
22025     return SDValue();
22026
22027   SDValue InVec = N->getOperand(0);
22028   SDValue EltNo = N->getOperand(1);
22029
22030   if (!isa<ConstantSDNode>(EltNo))
22031     return SDValue();
22032
22033   EVT OriginalVT = InVec.getValueType();
22034
22035   if (InVec.getOpcode() == ISD::BITCAST) {
22036     // Don't duplicate a load with other uses.
22037     if (!InVec.hasOneUse())
22038       return SDValue();
22039     EVT BCVT = InVec.getOperand(0).getValueType();
22040     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22041       return SDValue();
22042     InVec = InVec.getOperand(0);
22043   }
22044
22045   EVT CurrentVT = InVec.getValueType();
22046
22047   if (!isTargetShuffle(InVec.getOpcode()))
22048     return SDValue();
22049
22050   // Don't duplicate a load with other uses.
22051   if (!InVec.hasOneUse())
22052     return SDValue();
22053
22054   SmallVector<int, 16> ShuffleMask;
22055   bool UnaryShuffle;
22056   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22057                             ShuffleMask, UnaryShuffle))
22058     return SDValue();
22059
22060   // Select the input vector, guarding against out of range extract vector.
22061   unsigned NumElems = CurrentVT.getVectorNumElements();
22062   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22063   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22064   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22065                                          : InVec.getOperand(1);
22066
22067   // If inputs to shuffle are the same for both ops, then allow 2 uses
22068   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22069
22070   if (LdNode.getOpcode() == ISD::BITCAST) {
22071     // Don't duplicate a load with other uses.
22072     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22073       return SDValue();
22074
22075     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22076     LdNode = LdNode.getOperand(0);
22077   }
22078
22079   if (!ISD::isNormalLoad(LdNode.getNode()))
22080     return SDValue();
22081
22082   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22083
22084   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22085     return SDValue();
22086
22087   EVT EltVT = N->getValueType(0);
22088   // If there's a bitcast before the shuffle, check if the load type and
22089   // alignment is valid.
22090   unsigned Align = LN0->getAlignment();
22091   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22092   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
22093       EltVT.getTypeForEVT(*DAG.getContext()));
22094
22095   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22096     return SDValue();
22097
22098   // All checks match so transform back to vector_shuffle so that DAG combiner
22099   // can finish the job
22100   SDLoc dl(N);
22101
22102   // Create shuffle node taking into account the case that its a unary shuffle
22103   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22104                                    : InVec.getOperand(1);
22105   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22106                                  InVec.getOperand(0), Shuffle,
22107                                  &ShuffleMask[0]);
22108   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
22109   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22110                      EltNo);
22111 }
22112
22113 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22114 /// generation and convert it from being a bunch of shuffles and extracts
22115 /// to a simple store and scalar loads to extract the elements.
22116 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22117                                          TargetLowering::DAGCombinerInfo &DCI) {
22118   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
22119   if (NewOp.getNode())
22120     return NewOp;
22121
22122   SDValue InputVector = N->getOperand(0);
22123
22124   // Detect whether we are trying to convert from mmx to i32 and the bitcast
22125   // from mmx to v2i32 has a single usage.
22126   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
22127       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
22128       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
22129     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22130                        N->getValueType(0),
22131                        InputVector.getNode()->getOperand(0));
22132
22133   // Only operate on vectors of 4 elements, where the alternative shuffling
22134   // gets to be more expensive.
22135   if (InputVector.getValueType() != MVT::v4i32)
22136     return SDValue();
22137
22138   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22139   // single use which is a sign-extend or zero-extend, and all elements are
22140   // used.
22141   SmallVector<SDNode *, 4> Uses;
22142   unsigned ExtractedElements = 0;
22143   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22144        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22145     if (UI.getUse().getResNo() != InputVector.getResNo())
22146       return SDValue();
22147
22148     SDNode *Extract = *UI;
22149     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22150       return SDValue();
22151
22152     if (Extract->getValueType(0) != MVT::i32)
22153       return SDValue();
22154     if (!Extract->hasOneUse())
22155       return SDValue();
22156     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22157         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22158       return SDValue();
22159     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22160       return SDValue();
22161
22162     // Record which element was extracted.
22163     ExtractedElements |=
22164       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22165
22166     Uses.push_back(Extract);
22167   }
22168
22169   // If not all the elements were used, this may not be worthwhile.
22170   if (ExtractedElements != 15)
22171     return SDValue();
22172
22173   // Ok, we've now decided to do the transformation.
22174   SDLoc dl(InputVector);
22175
22176   // Store the value to a temporary stack slot.
22177   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22178   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22179                             MachinePointerInfo(), false, false, 0);
22180
22181   // Replace each use (extract) with a load of the appropriate element.
22182   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22183        UE = Uses.end(); UI != UE; ++UI) {
22184     SDNode *Extract = *UI;
22185
22186     // cOMpute the element's address.
22187     SDValue Idx = Extract->getOperand(1);
22188     unsigned EltSize =
22189         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
22190     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
22191     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22192     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
22193
22194     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
22195                                      StackPtr, OffsetVal);
22196
22197     // Load the scalar.
22198     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
22199                                      ScalarAddr, MachinePointerInfo(),
22200                                      false, false, false, 0);
22201
22202     // Replace the exact with the load.
22203     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
22204   }
22205
22206   // The replacement was made in place; don't return anything.
22207   return SDValue();
22208 }
22209
22210 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22211 static std::pair<unsigned, bool>
22212 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22213                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22214   if (!VT.isVector())
22215     return std::make_pair(0, false);
22216
22217   bool NeedSplit = false;
22218   switch (VT.getSimpleVT().SimpleTy) {
22219   default: return std::make_pair(0, false);
22220   case MVT::v32i8:
22221   case MVT::v16i16:
22222   case MVT::v8i32:
22223     if (!Subtarget->hasAVX2())
22224       NeedSplit = true;
22225     if (!Subtarget->hasAVX())
22226       return std::make_pair(0, false);
22227     break;
22228   case MVT::v16i8:
22229   case MVT::v8i16:
22230   case MVT::v4i32:
22231     if (!Subtarget->hasSSE2())
22232       return std::make_pair(0, false);
22233   }
22234
22235   // SSE2 has only a small subset of the operations.
22236   bool hasUnsigned = Subtarget->hasSSE41() ||
22237                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22238   bool hasSigned = Subtarget->hasSSE41() ||
22239                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22240
22241   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22242
22243   unsigned Opc = 0;
22244   // Check for x CC y ? x : y.
22245   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22246       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22247     switch (CC) {
22248     default: break;
22249     case ISD::SETULT:
22250     case ISD::SETULE:
22251       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22252     case ISD::SETUGT:
22253     case ISD::SETUGE:
22254       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22255     case ISD::SETLT:
22256     case ISD::SETLE:
22257       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22258     case ISD::SETGT:
22259     case ISD::SETGE:
22260       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22261     }
22262   // Check for x CC y ? y : x -- a min/max with reversed arms.
22263   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22264              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22265     switch (CC) {
22266     default: break;
22267     case ISD::SETULT:
22268     case ISD::SETULE:
22269       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22270     case ISD::SETUGT:
22271     case ISD::SETUGE:
22272       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22273     case ISD::SETLT:
22274     case ISD::SETLE:
22275       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22276     case ISD::SETGT:
22277     case ISD::SETGE:
22278       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22279     }
22280   }
22281
22282   return std::make_pair(Opc, NeedSplit);
22283 }
22284
22285 static SDValue
22286 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22287                                       const X86Subtarget *Subtarget) {
22288   SDLoc dl(N);
22289   SDValue Cond = N->getOperand(0);
22290   SDValue LHS = N->getOperand(1);
22291   SDValue RHS = N->getOperand(2);
22292
22293   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22294     SDValue CondSrc = Cond->getOperand(0);
22295     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22296       Cond = CondSrc->getOperand(0);
22297   }
22298
22299   MVT VT = N->getSimpleValueType(0);
22300   MVT EltVT = VT.getVectorElementType();
22301   unsigned NumElems = VT.getVectorNumElements();
22302   // There is no blend with immediate in AVX-512.
22303   if (VT.is512BitVector())
22304     return SDValue();
22305
22306   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
22307     return SDValue();
22308   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
22309     return SDValue();
22310
22311   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22312     return SDValue();
22313
22314   // A vselect where all conditions and data are constants can be optimized into
22315   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22316   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22317       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22318     return SDValue();
22319
22320   unsigned MaskValue = 0;
22321   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22322     return SDValue();
22323
22324   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22325   for (unsigned i = 0; i < NumElems; ++i) {
22326     // Be sure we emit undef where we can.
22327     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22328       ShuffleMask[i] = -1;
22329     else
22330       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22331   }
22332
22333   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22334 }
22335
22336 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22337 /// nodes.
22338 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22339                                     TargetLowering::DAGCombinerInfo &DCI,
22340                                     const X86Subtarget *Subtarget) {
22341   SDLoc DL(N);
22342   SDValue Cond = N->getOperand(0);
22343   // Get the LHS/RHS of the select.
22344   SDValue LHS = N->getOperand(1);
22345   SDValue RHS = N->getOperand(2);
22346   EVT VT = LHS.getValueType();
22347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22348
22349   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22350   // instructions match the semantics of the common C idiom x<y?x:y but not
22351   // x<=y?x:y, because of how they handle negative zero (which can be
22352   // ignored in unsafe-math mode).
22353   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22354       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
22355       (Subtarget->hasSSE2() ||
22356        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22357     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22358
22359     unsigned Opcode = 0;
22360     // Check for x CC y ? x : y.
22361     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22362         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22363       switch (CC) {
22364       default: break;
22365       case ISD::SETULT:
22366         // Converting this to a min would handle NaNs incorrectly, and swapping
22367         // the operands would cause it to handle comparisons between positive
22368         // and negative zero incorrectly.
22369         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22370           if (!DAG.getTarget().Options.UnsafeFPMath &&
22371               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22372             break;
22373           std::swap(LHS, RHS);
22374         }
22375         Opcode = X86ISD::FMIN;
22376         break;
22377       case ISD::SETOLE:
22378         // Converting this to a min would handle comparisons between positive
22379         // and negative zero incorrectly.
22380         if (!DAG.getTarget().Options.UnsafeFPMath &&
22381             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22382           break;
22383         Opcode = X86ISD::FMIN;
22384         break;
22385       case ISD::SETULE:
22386         // Converting this to a min would handle both negative zeros and NaNs
22387         // incorrectly, but we can swap the operands to fix both.
22388         std::swap(LHS, RHS);
22389       case ISD::SETOLT:
22390       case ISD::SETLT:
22391       case ISD::SETLE:
22392         Opcode = X86ISD::FMIN;
22393         break;
22394
22395       case ISD::SETOGE:
22396         // Converting this to a max would handle comparisons between positive
22397         // and negative zero incorrectly.
22398         if (!DAG.getTarget().Options.UnsafeFPMath &&
22399             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22400           break;
22401         Opcode = X86ISD::FMAX;
22402         break;
22403       case ISD::SETUGT:
22404         // Converting this to a max would handle NaNs incorrectly, and swapping
22405         // the operands would cause it to handle comparisons between positive
22406         // and negative zero incorrectly.
22407         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22408           if (!DAG.getTarget().Options.UnsafeFPMath &&
22409               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22410             break;
22411           std::swap(LHS, RHS);
22412         }
22413         Opcode = X86ISD::FMAX;
22414         break;
22415       case ISD::SETUGE:
22416         // Converting this to a max would handle both negative zeros and NaNs
22417         // incorrectly, but we can swap the operands to fix both.
22418         std::swap(LHS, RHS);
22419       case ISD::SETOGT:
22420       case ISD::SETGT:
22421       case ISD::SETGE:
22422         Opcode = X86ISD::FMAX;
22423         break;
22424       }
22425     // Check for x CC y ? y : x -- a min/max with reversed arms.
22426     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22427                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22428       switch (CC) {
22429       default: break;
22430       case ISD::SETOGE:
22431         // Converting this to a min would handle comparisons between positive
22432         // and negative zero incorrectly, and swapping the operands would
22433         // cause it to handle NaNs incorrectly.
22434         if (!DAG.getTarget().Options.UnsafeFPMath &&
22435             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22436           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22437             break;
22438           std::swap(LHS, RHS);
22439         }
22440         Opcode = X86ISD::FMIN;
22441         break;
22442       case ISD::SETUGT:
22443         // Converting this to a min would handle NaNs incorrectly.
22444         if (!DAG.getTarget().Options.UnsafeFPMath &&
22445             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22446           break;
22447         Opcode = X86ISD::FMIN;
22448         break;
22449       case ISD::SETUGE:
22450         // Converting this to a min would handle both negative zeros and NaNs
22451         // incorrectly, but we can swap the operands to fix both.
22452         std::swap(LHS, RHS);
22453       case ISD::SETOGT:
22454       case ISD::SETGT:
22455       case ISD::SETGE:
22456         Opcode = X86ISD::FMIN;
22457         break;
22458
22459       case ISD::SETULT:
22460         // Converting this to a max would handle NaNs incorrectly.
22461         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22462           break;
22463         Opcode = X86ISD::FMAX;
22464         break;
22465       case ISD::SETOLE:
22466         // Converting this to a max would handle comparisons between positive
22467         // and negative zero incorrectly, and swapping the operands would
22468         // cause it to handle NaNs incorrectly.
22469         if (!DAG.getTarget().Options.UnsafeFPMath &&
22470             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22471           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22472             break;
22473           std::swap(LHS, RHS);
22474         }
22475         Opcode = X86ISD::FMAX;
22476         break;
22477       case ISD::SETULE:
22478         // Converting this to a max would handle both negative zeros and NaNs
22479         // incorrectly, but we can swap the operands to fix both.
22480         std::swap(LHS, RHS);
22481       case ISD::SETOLT:
22482       case ISD::SETLT:
22483       case ISD::SETLE:
22484         Opcode = X86ISD::FMAX;
22485         break;
22486       }
22487     }
22488
22489     if (Opcode)
22490       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22491   }
22492
22493   EVT CondVT = Cond.getValueType();
22494   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22495       CondVT.getVectorElementType() == MVT::i1) {
22496     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22497     // lowering on KNL. In this case we convert it to
22498     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22499     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22500     // Since SKX these selects have a proper lowering.
22501     EVT OpVT = LHS.getValueType();
22502     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22503         (OpVT.getVectorElementType() == MVT::i8 ||
22504          OpVT.getVectorElementType() == MVT::i16) &&
22505         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22506       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22507       DCI.AddToWorklist(Cond.getNode());
22508       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22509     }
22510   }
22511   // If this is a select between two integer constants, try to do some
22512   // optimizations.
22513   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22514     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22515       // Don't do this for crazy integer types.
22516       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22517         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22518         // so that TrueC (the true value) is larger than FalseC.
22519         bool NeedsCondInvert = false;
22520
22521         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22522             // Efficiently invertible.
22523             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22524              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22525               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22526           NeedsCondInvert = true;
22527           std::swap(TrueC, FalseC);
22528         }
22529
22530         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22531         if (FalseC->getAPIntValue() == 0 &&
22532             TrueC->getAPIntValue().isPowerOf2()) {
22533           if (NeedsCondInvert) // Invert the condition if needed.
22534             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22535                                DAG.getConstant(1, Cond.getValueType()));
22536
22537           // Zero extend the condition if needed.
22538           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22539
22540           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22541           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22542                              DAG.getConstant(ShAmt, MVT::i8));
22543         }
22544
22545         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22546         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22547           if (NeedsCondInvert) // Invert the condition if needed.
22548             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22549                                DAG.getConstant(1, Cond.getValueType()));
22550
22551           // Zero extend the condition if needed.
22552           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22553                              FalseC->getValueType(0), Cond);
22554           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22555                              SDValue(FalseC, 0));
22556         }
22557
22558         // Optimize cases that will turn into an LEA instruction.  This requires
22559         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22560         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22561           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22562           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22563
22564           bool isFastMultiplier = false;
22565           if (Diff < 10) {
22566             switch ((unsigned char)Diff) {
22567               default: break;
22568               case 1:  // result = add base, cond
22569               case 2:  // result = lea base(    , cond*2)
22570               case 3:  // result = lea base(cond, cond*2)
22571               case 4:  // result = lea base(    , cond*4)
22572               case 5:  // result = lea base(cond, cond*4)
22573               case 8:  // result = lea base(    , cond*8)
22574               case 9:  // result = lea base(cond, cond*8)
22575                 isFastMultiplier = true;
22576                 break;
22577             }
22578           }
22579
22580           if (isFastMultiplier) {
22581             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22582             if (NeedsCondInvert) // Invert the condition if needed.
22583               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22584                                  DAG.getConstant(1, Cond.getValueType()));
22585
22586             // Zero extend the condition if needed.
22587             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22588                                Cond);
22589             // Scale the condition by the difference.
22590             if (Diff != 1)
22591               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22592                                  DAG.getConstant(Diff, Cond.getValueType()));
22593
22594             // Add the base if non-zero.
22595             if (FalseC->getAPIntValue() != 0)
22596               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22597                                  SDValue(FalseC, 0));
22598             return Cond;
22599           }
22600         }
22601       }
22602   }
22603
22604   // Canonicalize max and min:
22605   // (x > y) ? x : y -> (x >= y) ? x : y
22606   // (x < y) ? x : y -> (x <= y) ? x : y
22607   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22608   // the need for an extra compare
22609   // against zero. e.g.
22610   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22611   // subl   %esi, %edi
22612   // testl  %edi, %edi
22613   // movl   $0, %eax
22614   // cmovgl %edi, %eax
22615   // =>
22616   // xorl   %eax, %eax
22617   // subl   %esi, $edi
22618   // cmovsl %eax, %edi
22619   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22620       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22621       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22622     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22623     switch (CC) {
22624     default: break;
22625     case ISD::SETLT:
22626     case ISD::SETGT: {
22627       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22628       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22629                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22630       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22631     }
22632     }
22633   }
22634
22635   // Early exit check
22636   if (!TLI.isTypeLegal(VT))
22637     return SDValue();
22638
22639   // Match VSELECTs into subs with unsigned saturation.
22640   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22641       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22642       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22643        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22644     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22645
22646     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22647     // left side invert the predicate to simplify logic below.
22648     SDValue Other;
22649     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22650       Other = RHS;
22651       CC = ISD::getSetCCInverse(CC, true);
22652     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22653       Other = LHS;
22654     }
22655
22656     if (Other.getNode() && Other->getNumOperands() == 2 &&
22657         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22658       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22659       SDValue CondRHS = Cond->getOperand(1);
22660
22661       // Look for a general sub with unsigned saturation first.
22662       // x >= y ? x-y : 0 --> subus x, y
22663       // x >  y ? x-y : 0 --> subus x, y
22664       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22665           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22666         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22667
22668       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22669         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22670           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22671             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22672               // If the RHS is a constant we have to reverse the const
22673               // canonicalization.
22674               // x > C-1 ? x+-C : 0 --> subus x, C
22675               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22676                   CondRHSConst->getAPIntValue() ==
22677                       (-OpRHSConst->getAPIntValue() - 1))
22678                 return DAG.getNode(
22679                     X86ISD::SUBUS, DL, VT, OpLHS,
22680                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
22681
22682           // Another special case: If C was a sign bit, the sub has been
22683           // canonicalized into a xor.
22684           // FIXME: Would it be better to use computeKnownBits to determine
22685           //        whether it's safe to decanonicalize the xor?
22686           // x s< 0 ? x^C : 0 --> subus x, C
22687           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22688               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22689               OpRHSConst->getAPIntValue().isSignBit())
22690             // Note that we have to rebuild the RHS constant here to ensure we
22691             // don't rely on particular values of undef lanes.
22692             return DAG.getNode(
22693                 X86ISD::SUBUS, DL, VT, OpLHS,
22694                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
22695         }
22696     }
22697   }
22698
22699   // Try to match a min/max vector operation.
22700   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22701     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22702     unsigned Opc = ret.first;
22703     bool NeedSplit = ret.second;
22704
22705     if (Opc && NeedSplit) {
22706       unsigned NumElems = VT.getVectorNumElements();
22707       // Extract the LHS vectors
22708       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22709       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22710
22711       // Extract the RHS vectors
22712       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22713       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22714
22715       // Create min/max for each subvector
22716       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22717       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22718
22719       // Merge the result
22720       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22721     } else if (Opc)
22722       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22723   }
22724
22725   // Simplify vector selection if condition value type matches vselect
22726   // operand type
22727   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22728     assert(Cond.getValueType().isVector() &&
22729            "vector select expects a vector selector!");
22730
22731     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22732     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22733
22734     // Try invert the condition if true value is not all 1s and false value
22735     // is not all 0s.
22736     if (!TValIsAllOnes && !FValIsAllZeros &&
22737         // Check if the selector will be produced by CMPP*/PCMP*
22738         Cond.getOpcode() == ISD::SETCC &&
22739         // Check if SETCC has already been promoted
22740         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
22741       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22742       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22743
22744       if (TValIsAllZeros || FValIsAllOnes) {
22745         SDValue CC = Cond.getOperand(2);
22746         ISD::CondCode NewCC =
22747           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22748                                Cond.getOperand(0).getValueType().isInteger());
22749         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22750         std::swap(LHS, RHS);
22751         TValIsAllOnes = FValIsAllOnes;
22752         FValIsAllZeros = TValIsAllZeros;
22753       }
22754     }
22755
22756     if (TValIsAllOnes || FValIsAllZeros) {
22757       SDValue Ret;
22758
22759       if (TValIsAllOnes && FValIsAllZeros)
22760         Ret = Cond;
22761       else if (TValIsAllOnes)
22762         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
22763                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
22764       else if (FValIsAllZeros)
22765         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22766                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
22767
22768       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
22769     }
22770   }
22771
22772   // Try to fold this VSELECT into a MOVSS/MOVSD
22773   if (N->getOpcode() == ISD::VSELECT &&
22774       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
22775     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
22776         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
22777       bool CanFold = false;
22778       unsigned NumElems = Cond.getNumOperands();
22779       SDValue A = LHS;
22780       SDValue B = RHS;
22781       
22782       if (isZero(Cond.getOperand(0))) {
22783         CanFold = true;
22784
22785         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
22786         // fold (vselect <0,-1> -> (movsd A, B)
22787         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
22788           CanFold = isAllOnes(Cond.getOperand(i));
22789       } else if (isAllOnes(Cond.getOperand(0))) {
22790         CanFold = true;
22791         std::swap(A, B);
22792
22793         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
22794         // fold (vselect <-1,0> -> (movsd B, A)
22795         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
22796           CanFold = isZero(Cond.getOperand(i));
22797       }
22798
22799       if (CanFold) {
22800         if (VT == MVT::v4i32 || VT == MVT::v4f32)
22801           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
22802         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
22803       }
22804
22805       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
22806         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
22807         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
22808         //                             (v2i64 (bitcast B)))))
22809         //
22810         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
22811         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
22812         //                             (v2f64 (bitcast B)))))
22813         //
22814         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
22815         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
22816         //                             (v2i64 (bitcast A)))))
22817         //
22818         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
22819         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
22820         //                             (v2f64 (bitcast A)))))
22821
22822         CanFold = (isZero(Cond.getOperand(0)) &&
22823                    isZero(Cond.getOperand(1)) &&
22824                    isAllOnes(Cond.getOperand(2)) &&
22825                    isAllOnes(Cond.getOperand(3)));
22826
22827         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
22828             isAllOnes(Cond.getOperand(1)) &&
22829             isZero(Cond.getOperand(2)) &&
22830             isZero(Cond.getOperand(3))) {
22831           CanFold = true;
22832           std::swap(LHS, RHS);
22833         }
22834
22835         if (CanFold) {
22836           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
22837           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
22838           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
22839           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
22840                                                 NewB, DAG);
22841           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
22842         }
22843       }
22844     }
22845   }
22846
22847   // If we know that this node is legal then we know that it is going to be
22848   // matched by one of the SSE/AVX BLEND instructions. These instructions only
22849   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
22850   // to simplify previous instructions.
22851   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22852       !DCI.isBeforeLegalize() &&
22853       // We explicitly check against v8i16 and v16i16 because, although
22854       // they're marked as Custom, they might only be legal when Cond is a
22855       // build_vector of constants. This will be taken care in a later
22856       // condition.
22857       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
22858        VT != MVT::v8i16) &&
22859       // Don't optimize vector of constants. Those are handled by
22860       // the generic code and all the bits must be properly set for
22861       // the generic optimizer.
22862       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22863     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22864
22865     // Don't optimize vector selects that map to mask-registers.
22866     if (BitWidth == 1)
22867       return SDValue();
22868
22869     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22870     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22871
22872     APInt KnownZero, KnownOne;
22873     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22874                                           DCI.isBeforeLegalizeOps());
22875     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22876         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22877                                  TLO)) {
22878       // If we changed the computation somewhere in the DAG, this change
22879       // will affect all users of Cond.
22880       // Make sure it is fine and update all the nodes so that we do not
22881       // use the generic VSELECT anymore. Otherwise, we may perform
22882       // wrong optimizations as we messed up with the actual expectation
22883       // for the vector boolean values.
22884       if (Cond != TLO.Old) {
22885         // Check all uses of that condition operand to check whether it will be
22886         // consumed by non-BLEND instructions, which may depend on all bits are
22887         // set properly.
22888         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22889              I != E; ++I)
22890           if (I->getOpcode() != ISD::VSELECT)
22891             // TODO: Add other opcodes eventually lowered into BLEND.
22892             return SDValue();
22893
22894         // Update all the users of the condition, before committing the change,
22895         // so that the VSELECT optimizations that expect the correct vector
22896         // boolean value will not be triggered.
22897         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22898              I != E; ++I)
22899           DAG.ReplaceAllUsesOfValueWith(
22900               SDValue(*I, 0),
22901               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22902                           Cond, I->getOperand(1), I->getOperand(2)));
22903         DCI.CommitTargetLoweringOpt(TLO);
22904         return SDValue();
22905       }
22906       // At this point, only Cond is changed. Change the condition
22907       // just for N to keep the opportunity to optimize all other
22908       // users their own way.
22909       DAG.ReplaceAllUsesOfValueWith(
22910           SDValue(N, 0),
22911           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22912                       TLO.New, N->getOperand(1), N->getOperand(2)));
22913       return SDValue();
22914     }
22915   }
22916
22917   // We should generate an X86ISD::BLENDI from a vselect if its argument
22918   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22919   // constants. This specific pattern gets generated when we split a
22920   // selector for a 512 bit vector in a machine without AVX512 (but with
22921   // 256-bit vectors), during legalization:
22922   //
22923   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22924   //
22925   // Iff we find this pattern and the build_vectors are built from
22926   // constants, we translate the vselect into a shuffle_vector that we
22927   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22928   if ((N->getOpcode() == ISD::VSELECT ||
22929        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22930       !DCI.isBeforeLegalize()) {
22931     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22932     if (Shuffle.getNode())
22933       return Shuffle;
22934   }
22935
22936   return SDValue();
22937 }
22938
22939 // Check whether a boolean test is testing a boolean value generated by
22940 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22941 // code.
22942 //
22943 // Simplify the following patterns:
22944 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22945 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22946 // to (Op EFLAGS Cond)
22947 //
22948 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22949 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22950 // to (Op EFLAGS !Cond)
22951 //
22952 // where Op could be BRCOND or CMOV.
22953 //
22954 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22955   // Quit if not CMP and SUB with its value result used.
22956   if (Cmp.getOpcode() != X86ISD::CMP &&
22957       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22958       return SDValue();
22959
22960   // Quit if not used as a boolean value.
22961   if (CC != X86::COND_E && CC != X86::COND_NE)
22962     return SDValue();
22963
22964   // Check CMP operands. One of them should be 0 or 1 and the other should be
22965   // an SetCC or extended from it.
22966   SDValue Op1 = Cmp.getOperand(0);
22967   SDValue Op2 = Cmp.getOperand(1);
22968
22969   SDValue SetCC;
22970   const ConstantSDNode* C = nullptr;
22971   bool needOppositeCond = (CC == X86::COND_E);
22972   bool checkAgainstTrue = false; // Is it a comparison against 1?
22973
22974   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22975     SetCC = Op2;
22976   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22977     SetCC = Op1;
22978   else // Quit if all operands are not constants.
22979     return SDValue();
22980
22981   if (C->getZExtValue() == 1) {
22982     needOppositeCond = !needOppositeCond;
22983     checkAgainstTrue = true;
22984   } else if (C->getZExtValue() != 0)
22985     // Quit if the constant is neither 0 or 1.
22986     return SDValue();
22987
22988   bool truncatedToBoolWithAnd = false;
22989   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22990   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22991          SetCC.getOpcode() == ISD::TRUNCATE ||
22992          SetCC.getOpcode() == ISD::AND) {
22993     if (SetCC.getOpcode() == ISD::AND) {
22994       int OpIdx = -1;
22995       ConstantSDNode *CS;
22996       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22997           CS->getZExtValue() == 1)
22998         OpIdx = 1;
22999       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23000           CS->getZExtValue() == 1)
23001         OpIdx = 0;
23002       if (OpIdx == -1)
23003         break;
23004       SetCC = SetCC.getOperand(OpIdx);
23005       truncatedToBoolWithAnd = true;
23006     } else
23007       SetCC = SetCC.getOperand(0);
23008   }
23009
23010   switch (SetCC.getOpcode()) {
23011   case X86ISD::SETCC_CARRY:
23012     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23013     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23014     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23015     // truncated to i1 using 'and'.
23016     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23017       break;
23018     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23019            "Invalid use of SETCC_CARRY!");
23020     // FALL THROUGH
23021   case X86ISD::SETCC:
23022     // Set the condition code or opposite one if necessary.
23023     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23024     if (needOppositeCond)
23025       CC = X86::GetOppositeBranchCondition(CC);
23026     return SetCC.getOperand(1);
23027   case X86ISD::CMOV: {
23028     // Check whether false/true value has canonical one, i.e. 0 or 1.
23029     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23030     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23031     // Quit if true value is not a constant.
23032     if (!TVal)
23033       return SDValue();
23034     // Quit if false value is not a constant.
23035     if (!FVal) {
23036       SDValue Op = SetCC.getOperand(0);
23037       // Skip 'zext' or 'trunc' node.
23038       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23039           Op.getOpcode() == ISD::TRUNCATE)
23040         Op = Op.getOperand(0);
23041       // A special case for rdrand/rdseed, where 0 is set if false cond is
23042       // found.
23043       if ((Op.getOpcode() != X86ISD::RDRAND &&
23044            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23045         return SDValue();
23046     }
23047     // Quit if false value is not the constant 0 or 1.
23048     bool FValIsFalse = true;
23049     if (FVal && FVal->getZExtValue() != 0) {
23050       if (FVal->getZExtValue() != 1)
23051         return SDValue();
23052       // If FVal is 1, opposite cond is needed.
23053       needOppositeCond = !needOppositeCond;
23054       FValIsFalse = false;
23055     }
23056     // Quit if TVal is not the constant opposite of FVal.
23057     if (FValIsFalse && TVal->getZExtValue() != 1)
23058       return SDValue();
23059     if (!FValIsFalse && TVal->getZExtValue() != 0)
23060       return SDValue();
23061     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23062     if (needOppositeCond)
23063       CC = X86::GetOppositeBranchCondition(CC);
23064     return SetCC.getOperand(3);
23065   }
23066   }
23067
23068   return SDValue();
23069 }
23070
23071 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23072 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23073                                   TargetLowering::DAGCombinerInfo &DCI,
23074                                   const X86Subtarget *Subtarget) {
23075   SDLoc DL(N);
23076
23077   // If the flag operand isn't dead, don't touch this CMOV.
23078   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23079     return SDValue();
23080
23081   SDValue FalseOp = N->getOperand(0);
23082   SDValue TrueOp = N->getOperand(1);
23083   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23084   SDValue Cond = N->getOperand(3);
23085
23086   if (CC == X86::COND_E || CC == X86::COND_NE) {
23087     switch (Cond.getOpcode()) {
23088     default: break;
23089     case X86ISD::BSR:
23090     case X86ISD::BSF:
23091       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23092       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23093         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23094     }
23095   }
23096
23097   SDValue Flags;
23098
23099   Flags = checkBoolTestSetCCCombine(Cond, CC);
23100   if (Flags.getNode() &&
23101       // Extra check as FCMOV only supports a subset of X86 cond.
23102       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23103     SDValue Ops[] = { FalseOp, TrueOp,
23104                       DAG.getConstant(CC, MVT::i8), Flags };
23105     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23106   }
23107
23108   // If this is a select between two integer constants, try to do some
23109   // optimizations.  Note that the operands are ordered the opposite of SELECT
23110   // operands.
23111   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23112     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23113       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23114       // larger than FalseC (the false value).
23115       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23116         CC = X86::GetOppositeBranchCondition(CC);
23117         std::swap(TrueC, FalseC);
23118         std::swap(TrueOp, FalseOp);
23119       }
23120
23121       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23122       // This is efficient for any integer data type (including i8/i16) and
23123       // shift amount.
23124       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23125         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23126                            DAG.getConstant(CC, MVT::i8), Cond);
23127
23128         // Zero extend the condition if needed.
23129         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23130
23131         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23132         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23133                            DAG.getConstant(ShAmt, MVT::i8));
23134         if (N->getNumValues() == 2)  // Dead flag value?
23135           return DCI.CombineTo(N, Cond, SDValue());
23136         return Cond;
23137       }
23138
23139       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23140       // for any integer data type, including i8/i16.
23141       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23142         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23143                            DAG.getConstant(CC, MVT::i8), Cond);
23144
23145         // Zero extend the condition if needed.
23146         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23147                            FalseC->getValueType(0), Cond);
23148         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23149                            SDValue(FalseC, 0));
23150
23151         if (N->getNumValues() == 2)  // Dead flag value?
23152           return DCI.CombineTo(N, Cond, SDValue());
23153         return Cond;
23154       }
23155
23156       // Optimize cases that will turn into an LEA instruction.  This requires
23157       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23158       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23159         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23160         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23161
23162         bool isFastMultiplier = false;
23163         if (Diff < 10) {
23164           switch ((unsigned char)Diff) {
23165           default: break;
23166           case 1:  // result = add base, cond
23167           case 2:  // result = lea base(    , cond*2)
23168           case 3:  // result = lea base(cond, cond*2)
23169           case 4:  // result = lea base(    , cond*4)
23170           case 5:  // result = lea base(cond, cond*4)
23171           case 8:  // result = lea base(    , cond*8)
23172           case 9:  // result = lea base(cond, cond*8)
23173             isFastMultiplier = true;
23174             break;
23175           }
23176         }
23177
23178         if (isFastMultiplier) {
23179           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23180           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23181                              DAG.getConstant(CC, MVT::i8), Cond);
23182           // Zero extend the condition if needed.
23183           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23184                              Cond);
23185           // Scale the condition by the difference.
23186           if (Diff != 1)
23187             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23188                                DAG.getConstant(Diff, Cond.getValueType()));
23189
23190           // Add the base if non-zero.
23191           if (FalseC->getAPIntValue() != 0)
23192             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23193                                SDValue(FalseC, 0));
23194           if (N->getNumValues() == 2)  // Dead flag value?
23195             return DCI.CombineTo(N, Cond, SDValue());
23196           return Cond;
23197         }
23198       }
23199     }
23200   }
23201
23202   // Handle these cases:
23203   //   (select (x != c), e, c) -> select (x != c), e, x),
23204   //   (select (x == c), c, e) -> select (x == c), x, e)
23205   // where the c is an integer constant, and the "select" is the combination
23206   // of CMOV and CMP.
23207   //
23208   // The rationale for this change is that the conditional-move from a constant
23209   // needs two instructions, however, conditional-move from a register needs
23210   // only one instruction.
23211   //
23212   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23213   //  some instruction-combining opportunities. This opt needs to be
23214   //  postponed as late as possible.
23215   //
23216   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23217     // the DCI.xxxx conditions are provided to postpone the optimization as
23218     // late as possible.
23219
23220     ConstantSDNode *CmpAgainst = nullptr;
23221     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23222         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23223         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23224
23225       if (CC == X86::COND_NE &&
23226           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23227         CC = X86::GetOppositeBranchCondition(CC);
23228         std::swap(TrueOp, FalseOp);
23229       }
23230
23231       if (CC == X86::COND_E &&
23232           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23233         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23234                           DAG.getConstant(CC, MVT::i8), Cond };
23235         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23236       }
23237     }
23238   }
23239
23240   return SDValue();
23241 }
23242
23243 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23244                                                 const X86Subtarget *Subtarget) {
23245   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23246   switch (IntNo) {
23247   default: return SDValue();
23248   // SSE/AVX/AVX2 blend intrinsics.
23249   case Intrinsic::x86_avx2_pblendvb:
23250   case Intrinsic::x86_avx2_pblendw:
23251   case Intrinsic::x86_avx2_pblendd_128:
23252   case Intrinsic::x86_avx2_pblendd_256:
23253     // Don't try to simplify this intrinsic if we don't have AVX2.
23254     if (!Subtarget->hasAVX2())
23255       return SDValue();
23256     // FALL-THROUGH
23257   case Intrinsic::x86_avx_blend_pd_256:
23258   case Intrinsic::x86_avx_blend_ps_256:
23259   case Intrinsic::x86_avx_blendv_pd_256:
23260   case Intrinsic::x86_avx_blendv_ps_256:
23261     // Don't try to simplify this intrinsic if we don't have AVX.
23262     if (!Subtarget->hasAVX())
23263       return SDValue();
23264     // FALL-THROUGH
23265   case Intrinsic::x86_sse41_pblendw:
23266   case Intrinsic::x86_sse41_blendpd:
23267   case Intrinsic::x86_sse41_blendps:
23268   case Intrinsic::x86_sse41_blendvps:
23269   case Intrinsic::x86_sse41_blendvpd:
23270   case Intrinsic::x86_sse41_pblendvb: {
23271     SDValue Op0 = N->getOperand(1);
23272     SDValue Op1 = N->getOperand(2);
23273     SDValue Mask = N->getOperand(3);
23274
23275     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23276     if (!Subtarget->hasSSE41())
23277       return SDValue();
23278
23279     // fold (blend A, A, Mask) -> A
23280     if (Op0 == Op1)
23281       return Op0;
23282     // fold (blend A, B, allZeros) -> A
23283     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23284       return Op0;
23285     // fold (blend A, B, allOnes) -> B
23286     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23287       return Op1;
23288     
23289     // Simplify the case where the mask is a constant i32 value.
23290     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23291       if (C->isNullValue())
23292         return Op0;
23293       if (C->isAllOnesValue())
23294         return Op1;
23295     }
23296
23297     return SDValue();
23298   }
23299
23300   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23301   case Intrinsic::x86_sse2_psrai_w:
23302   case Intrinsic::x86_sse2_psrai_d:
23303   case Intrinsic::x86_avx2_psrai_w:
23304   case Intrinsic::x86_avx2_psrai_d:
23305   case Intrinsic::x86_sse2_psra_w:
23306   case Intrinsic::x86_sse2_psra_d:
23307   case Intrinsic::x86_avx2_psra_w:
23308   case Intrinsic::x86_avx2_psra_d: {
23309     SDValue Op0 = N->getOperand(1);
23310     SDValue Op1 = N->getOperand(2);
23311     EVT VT = Op0.getValueType();
23312     assert(VT.isVector() && "Expected a vector type!");
23313
23314     if (isa<BuildVectorSDNode>(Op1))
23315       Op1 = Op1.getOperand(0);
23316
23317     if (!isa<ConstantSDNode>(Op1))
23318       return SDValue();
23319
23320     EVT SVT = VT.getVectorElementType();
23321     unsigned SVTBits = SVT.getSizeInBits();
23322
23323     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23324     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23325     uint64_t ShAmt = C.getZExtValue();
23326
23327     // Don't try to convert this shift into a ISD::SRA if the shift
23328     // count is bigger than or equal to the element size.
23329     if (ShAmt >= SVTBits)
23330       return SDValue();
23331
23332     // Trivial case: if the shift count is zero, then fold this
23333     // into the first operand.
23334     if (ShAmt == 0)
23335       return Op0;
23336
23337     // Replace this packed shift intrinsic with a target independent
23338     // shift dag node.
23339     SDValue Splat = DAG.getConstant(C, VT);
23340     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
23341   }
23342   }
23343 }
23344
23345 /// PerformMulCombine - Optimize a single multiply with constant into two
23346 /// in order to implement it with two cheaper instructions, e.g.
23347 /// LEA + SHL, LEA + LEA.
23348 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23349                                  TargetLowering::DAGCombinerInfo &DCI) {
23350   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23351     return SDValue();
23352
23353   EVT VT = N->getValueType(0);
23354   if (VT != MVT::i64)
23355     return SDValue();
23356
23357   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23358   if (!C)
23359     return SDValue();
23360   uint64_t MulAmt = C->getZExtValue();
23361   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23362     return SDValue();
23363
23364   uint64_t MulAmt1 = 0;
23365   uint64_t MulAmt2 = 0;
23366   if ((MulAmt % 9) == 0) {
23367     MulAmt1 = 9;
23368     MulAmt2 = MulAmt / 9;
23369   } else if ((MulAmt % 5) == 0) {
23370     MulAmt1 = 5;
23371     MulAmt2 = MulAmt / 5;
23372   } else if ((MulAmt % 3) == 0) {
23373     MulAmt1 = 3;
23374     MulAmt2 = MulAmt / 3;
23375   }
23376   if (MulAmt2 &&
23377       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23378     SDLoc DL(N);
23379
23380     if (isPowerOf2_64(MulAmt2) &&
23381         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23382       // If second multiplifer is pow2, issue it first. We want the multiply by
23383       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23384       // is an add.
23385       std::swap(MulAmt1, MulAmt2);
23386
23387     SDValue NewMul;
23388     if (isPowerOf2_64(MulAmt1))
23389       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23390                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
23391     else
23392       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23393                            DAG.getConstant(MulAmt1, VT));
23394
23395     if (isPowerOf2_64(MulAmt2))
23396       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23397                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
23398     else
23399       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23400                            DAG.getConstant(MulAmt2, VT));
23401
23402     // Do not add new nodes to DAG combiner worklist.
23403     DCI.CombineTo(N, NewMul, false);
23404   }
23405   return SDValue();
23406 }
23407
23408 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23409   SDValue N0 = N->getOperand(0);
23410   SDValue N1 = N->getOperand(1);
23411   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23412   EVT VT = N0.getValueType();
23413
23414   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23415   // since the result of setcc_c is all zero's or all ones.
23416   if (VT.isInteger() && !VT.isVector() &&
23417       N1C && N0.getOpcode() == ISD::AND &&
23418       N0.getOperand(1).getOpcode() == ISD::Constant) {
23419     SDValue N00 = N0.getOperand(0);
23420     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23421         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23422           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23423          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23424       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23425       APInt ShAmt = N1C->getAPIntValue();
23426       Mask = Mask.shl(ShAmt);
23427       if (Mask != 0)
23428         return DAG.getNode(ISD::AND, SDLoc(N), VT,
23429                            N00, DAG.getConstant(Mask, VT));
23430     }
23431   }
23432
23433   // Hardware support for vector shifts is sparse which makes us scalarize the
23434   // vector operations in many cases. Also, on sandybridge ADD is faster than
23435   // shl.
23436   // (shl V, 1) -> add V,V
23437   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23438     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23439       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23440       // We shift all of the values by one. In many cases we do not have
23441       // hardware support for this operation. This is better expressed as an ADD
23442       // of two values.
23443       if (N1SplatC->getZExtValue() == 1)
23444         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23445     }
23446
23447   return SDValue();
23448 }
23449
23450 /// \brief Returns a vector of 0s if the node in input is a vector logical
23451 /// shift by a constant amount which is known to be bigger than or equal
23452 /// to the vector element size in bits.
23453 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23454                                       const X86Subtarget *Subtarget) {
23455   EVT VT = N->getValueType(0);
23456
23457   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23458       (!Subtarget->hasInt256() ||
23459        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23460     return SDValue();
23461
23462   SDValue Amt = N->getOperand(1);
23463   SDLoc DL(N);
23464   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23465     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23466       APInt ShiftAmt = AmtSplat->getAPIntValue();
23467       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23468
23469       // SSE2/AVX2 logical shifts always return a vector of 0s
23470       // if the shift amount is bigger than or equal to
23471       // the element size. The constant shift amount will be
23472       // encoded as a 8-bit immediate.
23473       if (ShiftAmt.trunc(8).uge(MaxAmount))
23474         return getZeroVector(VT, Subtarget, DAG, DL);
23475     }
23476
23477   return SDValue();
23478 }
23479
23480 /// PerformShiftCombine - Combine shifts.
23481 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23482                                    TargetLowering::DAGCombinerInfo &DCI,
23483                                    const X86Subtarget *Subtarget) {
23484   if (N->getOpcode() == ISD::SHL) {
23485     SDValue V = PerformSHLCombine(N, DAG);
23486     if (V.getNode()) return V;
23487   }
23488
23489   if (N->getOpcode() != ISD::SRA) {
23490     // Try to fold this logical shift into a zero vector.
23491     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
23492     if (V.getNode()) return V;
23493   }
23494
23495   return SDValue();
23496 }
23497
23498 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23499 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23500 // and friends.  Likewise for OR -> CMPNEQSS.
23501 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23502                             TargetLowering::DAGCombinerInfo &DCI,
23503                             const X86Subtarget *Subtarget) {
23504   unsigned opcode;
23505
23506   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23507   // we're requiring SSE2 for both.
23508   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23509     SDValue N0 = N->getOperand(0);
23510     SDValue N1 = N->getOperand(1);
23511     SDValue CMP0 = N0->getOperand(1);
23512     SDValue CMP1 = N1->getOperand(1);
23513     SDLoc DL(N);
23514
23515     // The SETCCs should both refer to the same CMP.
23516     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23517       return SDValue();
23518
23519     SDValue CMP00 = CMP0->getOperand(0);
23520     SDValue CMP01 = CMP0->getOperand(1);
23521     EVT     VT    = CMP00.getValueType();
23522
23523     if (VT == MVT::f32 || VT == MVT::f64) {
23524       bool ExpectingFlags = false;
23525       // Check for any users that want flags:
23526       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23527            !ExpectingFlags && UI != UE; ++UI)
23528         switch (UI->getOpcode()) {
23529         default:
23530         case ISD::BR_CC:
23531         case ISD::BRCOND:
23532         case ISD::SELECT:
23533           ExpectingFlags = true;
23534           break;
23535         case ISD::CopyToReg:
23536         case ISD::SIGN_EXTEND:
23537         case ISD::ZERO_EXTEND:
23538         case ISD::ANY_EXTEND:
23539           break;
23540         }
23541
23542       if (!ExpectingFlags) {
23543         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23544         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23545
23546         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23547           X86::CondCode tmp = cc0;
23548           cc0 = cc1;
23549           cc1 = tmp;
23550         }
23551
23552         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23553             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23554           // FIXME: need symbolic constants for these magic numbers.
23555           // See X86ATTInstPrinter.cpp:printSSECC().
23556           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23557           if (Subtarget->hasAVX512()) {
23558             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23559                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
23560             if (N->getValueType(0) != MVT::i1)
23561               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23562                                  FSetCC);
23563             return FSetCC;
23564           }
23565           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23566                                               CMP00.getValueType(), CMP00, CMP01,
23567                                               DAG.getConstant(x86cc, MVT::i8));
23568
23569           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23570           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23571
23572           if (is64BitFP && !Subtarget->is64Bit()) {
23573             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23574             // 64-bit integer, since that's not a legal type. Since
23575             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23576             // bits, but can do this little dance to extract the lowest 32 bits
23577             // and work with those going forward.
23578             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23579                                            OnesOrZeroesF);
23580             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
23581                                            Vector64);
23582             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23583                                         Vector32, DAG.getIntPtrConstant(0));
23584             IntVT = MVT::i32;
23585           }
23586
23587           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
23588           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23589                                       DAG.getConstant(1, IntVT));
23590           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
23591           return OneBitOfTruth;
23592         }
23593       }
23594     }
23595   }
23596   return SDValue();
23597 }
23598
23599 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23600 /// so it can be folded inside ANDNP.
23601 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23602   EVT VT = N->getValueType(0);
23603
23604   // Match direct AllOnes for 128 and 256-bit vectors
23605   if (ISD::isBuildVectorAllOnes(N))
23606     return true;
23607
23608   // Look through a bit convert.
23609   if (N->getOpcode() == ISD::BITCAST)
23610     N = N->getOperand(0).getNode();
23611
23612   // Sometimes the operand may come from a insert_subvector building a 256-bit
23613   // allones vector
23614   if (VT.is256BitVector() &&
23615       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23616     SDValue V1 = N->getOperand(0);
23617     SDValue V2 = N->getOperand(1);
23618
23619     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23620         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23621         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23622         ISD::isBuildVectorAllOnes(V2.getNode()))
23623       return true;
23624   }
23625
23626   return false;
23627 }
23628
23629 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23630 // register. In most cases we actually compare or select YMM-sized registers
23631 // and mixing the two types creates horrible code. This method optimizes
23632 // some of the transition sequences.
23633 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23634                                  TargetLowering::DAGCombinerInfo &DCI,
23635                                  const X86Subtarget *Subtarget) {
23636   EVT VT = N->getValueType(0);
23637   if (!VT.is256BitVector())
23638     return SDValue();
23639
23640   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23641           N->getOpcode() == ISD::ZERO_EXTEND ||
23642           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23643
23644   SDValue Narrow = N->getOperand(0);
23645   EVT NarrowVT = Narrow->getValueType(0);
23646   if (!NarrowVT.is128BitVector())
23647     return SDValue();
23648
23649   if (Narrow->getOpcode() != ISD::XOR &&
23650       Narrow->getOpcode() != ISD::AND &&
23651       Narrow->getOpcode() != ISD::OR)
23652     return SDValue();
23653
23654   SDValue N0  = Narrow->getOperand(0);
23655   SDValue N1  = Narrow->getOperand(1);
23656   SDLoc DL(Narrow);
23657
23658   // The Left side has to be a trunc.
23659   if (N0.getOpcode() != ISD::TRUNCATE)
23660     return SDValue();
23661
23662   // The type of the truncated inputs.
23663   EVT WideVT = N0->getOperand(0)->getValueType(0);
23664   if (WideVT != VT)
23665     return SDValue();
23666
23667   // The right side has to be a 'trunc' or a constant vector.
23668   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23669   ConstantSDNode *RHSConstSplat = nullptr;
23670   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23671     RHSConstSplat = RHSBV->getConstantSplatNode();
23672   if (!RHSTrunc && !RHSConstSplat)
23673     return SDValue();
23674
23675   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23676
23677   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23678     return SDValue();
23679
23680   // Set N0 and N1 to hold the inputs to the new wide operation.
23681   N0 = N0->getOperand(0);
23682   if (RHSConstSplat) {
23683     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23684                      SDValue(RHSConstSplat, 0));
23685     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23686     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23687   } else if (RHSTrunc) {
23688     N1 = N1->getOperand(0);
23689   }
23690
23691   // Generate the wide operation.
23692   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23693   unsigned Opcode = N->getOpcode();
23694   switch (Opcode) {
23695   case ISD::ANY_EXTEND:
23696     return Op;
23697   case ISD::ZERO_EXTEND: {
23698     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23699     APInt Mask = APInt::getAllOnesValue(InBits);
23700     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23701     return DAG.getNode(ISD::AND, DL, VT,
23702                        Op, DAG.getConstant(Mask, VT));
23703   }
23704   case ISD::SIGN_EXTEND:
23705     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23706                        Op, DAG.getValueType(NarrowVT));
23707   default:
23708     llvm_unreachable("Unexpected opcode");
23709   }
23710 }
23711
23712 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23713                                  TargetLowering::DAGCombinerInfo &DCI,
23714                                  const X86Subtarget *Subtarget) {
23715   EVT VT = N->getValueType(0);
23716   if (DCI.isBeforeLegalizeOps())
23717     return SDValue();
23718
23719   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
23720   if (R.getNode())
23721     return R;
23722
23723   // Create BEXTR instructions
23724   // BEXTR is ((X >> imm) & (2**size-1))
23725   if (VT == MVT::i32 || VT == MVT::i64) {
23726     SDValue N0 = N->getOperand(0);
23727     SDValue N1 = N->getOperand(1);
23728     SDLoc DL(N);
23729
23730     // Check for BEXTR.
23731     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23732         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23733       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23734       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23735       if (MaskNode && ShiftNode) {
23736         uint64_t Mask = MaskNode->getZExtValue();
23737         uint64_t Shift = ShiftNode->getZExtValue();
23738         if (isMask_64(Mask)) {
23739           uint64_t MaskSize = CountPopulation_64(Mask);
23740           if (Shift + MaskSize <= VT.getSizeInBits())
23741             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23742                                DAG.getConstant(Shift | (MaskSize << 8), VT));
23743         }
23744       }
23745     } // BEXTR
23746
23747     return SDValue();
23748   }
23749
23750   // Want to form ANDNP nodes:
23751   // 1) In the hopes of then easily combining them with OR and AND nodes
23752   //    to form PBLEND/PSIGN.
23753   // 2) To match ANDN packed intrinsics
23754   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23755     return SDValue();
23756
23757   SDValue N0 = N->getOperand(0);
23758   SDValue N1 = N->getOperand(1);
23759   SDLoc DL(N);
23760
23761   // Check LHS for vnot
23762   if (N0.getOpcode() == ISD::XOR &&
23763       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23764       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23765     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23766
23767   // Check RHS for vnot
23768   if (N1.getOpcode() == ISD::XOR &&
23769       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23770       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23771     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23772
23773   return SDValue();
23774 }
23775
23776 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23777                                 TargetLowering::DAGCombinerInfo &DCI,
23778                                 const X86Subtarget *Subtarget) {
23779   if (DCI.isBeforeLegalizeOps())
23780     return SDValue();
23781
23782   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
23783   if (R.getNode())
23784     return R;
23785
23786   SDValue N0 = N->getOperand(0);
23787   SDValue N1 = N->getOperand(1);
23788   EVT VT = N->getValueType(0);
23789
23790   // look for psign/blend
23791   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23792     if (!Subtarget->hasSSSE3() ||
23793         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23794       return SDValue();
23795
23796     // Canonicalize pandn to RHS
23797     if (N0.getOpcode() == X86ISD::ANDNP)
23798       std::swap(N0, N1);
23799     // or (and (m, y), (pandn m, x))
23800     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23801       SDValue Mask = N1.getOperand(0);
23802       SDValue X    = N1.getOperand(1);
23803       SDValue Y;
23804       if (N0.getOperand(0) == Mask)
23805         Y = N0.getOperand(1);
23806       if (N0.getOperand(1) == Mask)
23807         Y = N0.getOperand(0);
23808
23809       // Check to see if the mask appeared in both the AND and ANDNP and
23810       if (!Y.getNode())
23811         return SDValue();
23812
23813       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23814       // Look through mask bitcast.
23815       if (Mask.getOpcode() == ISD::BITCAST)
23816         Mask = Mask.getOperand(0);
23817       if (X.getOpcode() == ISD::BITCAST)
23818         X = X.getOperand(0);
23819       if (Y.getOpcode() == ISD::BITCAST)
23820         Y = Y.getOperand(0);
23821
23822       EVT MaskVT = Mask.getValueType();
23823
23824       // Validate that the Mask operand is a vector sra node.
23825       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23826       // there is no psrai.b
23827       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23828       unsigned SraAmt = ~0;
23829       if (Mask.getOpcode() == ISD::SRA) {
23830         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23831           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23832             SraAmt = AmtConst->getZExtValue();
23833       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23834         SDValue SraC = Mask.getOperand(1);
23835         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23836       }
23837       if ((SraAmt + 1) != EltBits)
23838         return SDValue();
23839
23840       SDLoc DL(N);
23841
23842       // Now we know we at least have a plendvb with the mask val.  See if
23843       // we can form a psignb/w/d.
23844       // psign = x.type == y.type == mask.type && y = sub(0, x);
23845       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23846           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23847           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23848         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23849                "Unsupported VT for PSIGN");
23850         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23851         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
23852       }
23853       // PBLENDVB only available on SSE 4.1
23854       if (!Subtarget->hasSSE41())
23855         return SDValue();
23856
23857       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23858
23859       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
23860       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
23861       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
23862       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23863       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
23864     }
23865   }
23866
23867   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23868     return SDValue();
23869
23870   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23871   MachineFunction &MF = DAG.getMachineFunction();
23872   bool OptForSize = MF.getFunction()->getAttributes().
23873     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
23874
23875   // SHLD/SHRD instructions have lower register pressure, but on some
23876   // platforms they have higher latency than the equivalent
23877   // series of shifts/or that would otherwise be generated.
23878   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23879   // have higher latencies and we are not optimizing for size.
23880   if (!OptForSize && Subtarget->isSHLDSlow())
23881     return SDValue();
23882
23883   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23884     std::swap(N0, N1);
23885   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23886     return SDValue();
23887   if (!N0.hasOneUse() || !N1.hasOneUse())
23888     return SDValue();
23889
23890   SDValue ShAmt0 = N0.getOperand(1);
23891   if (ShAmt0.getValueType() != MVT::i8)
23892     return SDValue();
23893   SDValue ShAmt1 = N1.getOperand(1);
23894   if (ShAmt1.getValueType() != MVT::i8)
23895     return SDValue();
23896   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23897     ShAmt0 = ShAmt0.getOperand(0);
23898   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23899     ShAmt1 = ShAmt1.getOperand(0);
23900
23901   SDLoc DL(N);
23902   unsigned Opc = X86ISD::SHLD;
23903   SDValue Op0 = N0.getOperand(0);
23904   SDValue Op1 = N1.getOperand(0);
23905   if (ShAmt0.getOpcode() == ISD::SUB) {
23906     Opc = X86ISD::SHRD;
23907     std::swap(Op0, Op1);
23908     std::swap(ShAmt0, ShAmt1);
23909   }
23910
23911   unsigned Bits = VT.getSizeInBits();
23912   if (ShAmt1.getOpcode() == ISD::SUB) {
23913     SDValue Sum = ShAmt1.getOperand(0);
23914     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23915       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23916       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23917         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23918       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23919         return DAG.getNode(Opc, DL, VT,
23920                            Op0, Op1,
23921                            DAG.getNode(ISD::TRUNCATE, DL,
23922                                        MVT::i8, ShAmt0));
23923     }
23924   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23925     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23926     if (ShAmt0C &&
23927         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23928       return DAG.getNode(Opc, DL, VT,
23929                          N0.getOperand(0), N1.getOperand(0),
23930                          DAG.getNode(ISD::TRUNCATE, DL,
23931                                        MVT::i8, ShAmt0));
23932   }
23933
23934   return SDValue();
23935 }
23936
23937 // Generate NEG and CMOV for integer abs.
23938 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23939   EVT VT = N->getValueType(0);
23940
23941   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23942   // 8-bit integer abs to NEG and CMOV.
23943   if (VT.isInteger() && VT.getSizeInBits() == 8)
23944     return SDValue();
23945
23946   SDValue N0 = N->getOperand(0);
23947   SDValue N1 = N->getOperand(1);
23948   SDLoc DL(N);
23949
23950   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23951   // and change it to SUB and CMOV.
23952   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23953       N0.getOpcode() == ISD::ADD &&
23954       N0.getOperand(1) == N1 &&
23955       N1.getOpcode() == ISD::SRA &&
23956       N1.getOperand(0) == N0.getOperand(0))
23957     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23958       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23959         // Generate SUB & CMOV.
23960         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23961                                   DAG.getConstant(0, VT), N0.getOperand(0));
23962
23963         SDValue Ops[] = { N0.getOperand(0), Neg,
23964                           DAG.getConstant(X86::COND_GE, MVT::i8),
23965                           SDValue(Neg.getNode(), 1) };
23966         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23967       }
23968   return SDValue();
23969 }
23970
23971 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23972 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23973                                  TargetLowering::DAGCombinerInfo &DCI,
23974                                  const X86Subtarget *Subtarget) {
23975   if (DCI.isBeforeLegalizeOps())
23976     return SDValue();
23977
23978   if (Subtarget->hasCMov()) {
23979     SDValue RV = performIntegerAbsCombine(N, DAG);
23980     if (RV.getNode())
23981       return RV;
23982   }
23983
23984   return SDValue();
23985 }
23986
23987 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23988 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23989                                   TargetLowering::DAGCombinerInfo &DCI,
23990                                   const X86Subtarget *Subtarget) {
23991   LoadSDNode *Ld = cast<LoadSDNode>(N);
23992   EVT RegVT = Ld->getValueType(0);
23993   EVT MemVT = Ld->getMemoryVT();
23994   SDLoc dl(Ld);
23995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23996
23997   // On Sandybridge unaligned 256bit loads are inefficient.
23998   ISD::LoadExtType Ext = Ld->getExtensionType();
23999   unsigned Alignment = Ld->getAlignment();
24000   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24001   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
24002       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24003     unsigned NumElems = RegVT.getVectorNumElements();
24004     if (NumElems < 2)
24005       return SDValue();
24006
24007     SDValue Ptr = Ld->getBasePtr();
24008     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
24009
24010     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24011                                   NumElems/2);
24012     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24013                                 Ld->getPointerInfo(), Ld->isVolatile(),
24014                                 Ld->isNonTemporal(), Ld->isInvariant(),
24015                                 Alignment);
24016     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24017     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24018                                 Ld->getPointerInfo(), Ld->isVolatile(),
24019                                 Ld->isNonTemporal(), Ld->isInvariant(),
24020                                 std::min(16U, Alignment));
24021     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24022                              Load1.getValue(1),
24023                              Load2.getValue(1));
24024
24025     SDValue NewVec = DAG.getUNDEF(RegVT);
24026     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24027     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24028     return DCI.CombineTo(N, NewVec, TF, true);
24029   }
24030
24031   return SDValue();
24032 }
24033
24034 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24035 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24036                                    const X86Subtarget *Subtarget) {
24037   StoreSDNode *St = cast<StoreSDNode>(N);
24038   EVT VT = St->getValue().getValueType();
24039   EVT StVT = St->getMemoryVT();
24040   SDLoc dl(St);
24041   SDValue StoredVal = St->getOperand(1);
24042   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24043
24044   // If we are saving a concatenation of two XMM registers, perform two stores.
24045   // On Sandy Bridge, 256-bit memory operations are executed by two
24046   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
24047   // memory  operation.
24048   unsigned Alignment = St->getAlignment();
24049   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24050   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
24051       StVT == VT && !IsAligned) {
24052     unsigned NumElems = VT.getVectorNumElements();
24053     if (NumElems < 2)
24054       return SDValue();
24055
24056     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24057     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24058
24059     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
24060     SDValue Ptr0 = St->getBasePtr();
24061     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24062
24063     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24064                                 St->getPointerInfo(), St->isVolatile(),
24065                                 St->isNonTemporal(), Alignment);
24066     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24067                                 St->getPointerInfo(), St->isVolatile(),
24068                                 St->isNonTemporal(),
24069                                 std::min(16U, Alignment));
24070     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24071   }
24072
24073   // Optimize trunc store (of multiple scalars) to shuffle and store.
24074   // First, pack all of the elements in one place. Next, store to memory
24075   // in fewer chunks.
24076   if (St->isTruncatingStore() && VT.isVector()) {
24077     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24078     unsigned NumElems = VT.getVectorNumElements();
24079     assert(StVT != VT && "Cannot truncate to the same type");
24080     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24081     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24082
24083     // From, To sizes and ElemCount must be pow of two
24084     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24085     // We are going to use the original vector elt for storing.
24086     // Accumulated smaller vector elements must be a multiple of the store size.
24087     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24088
24089     unsigned SizeRatio  = FromSz / ToSz;
24090
24091     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24092
24093     // Create a type on which we perform the shuffle
24094     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24095             StVT.getScalarType(), NumElems*SizeRatio);
24096
24097     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24098
24099     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
24100     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24101     for (unsigned i = 0; i != NumElems; ++i)
24102       ShuffleVec[i] = i * SizeRatio;
24103
24104     // Can't shuffle using an illegal type.
24105     if (!TLI.isTypeLegal(WideVecVT))
24106       return SDValue();
24107
24108     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24109                                          DAG.getUNDEF(WideVecVT),
24110                                          &ShuffleVec[0]);
24111     // At this point all of the data is stored at the bottom of the
24112     // register. We now need to save it to mem.
24113
24114     // Find the largest store unit
24115     MVT StoreType = MVT::i8;
24116     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
24117          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
24118       MVT Tp = (MVT::SimpleValueType)tp;
24119       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24120         StoreType = Tp;
24121     }
24122
24123     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24124     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24125         (64 <= NumElems * ToSz))
24126       StoreType = MVT::f64;
24127
24128     // Bitcast the original vector into a vector of store-size units
24129     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24130             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24131     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24132     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
24133     SmallVector<SDValue, 8> Chains;
24134     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
24135                                         TLI.getPointerTy());
24136     SDValue Ptr = St->getBasePtr();
24137
24138     // Perform one or more big stores into memory.
24139     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24140       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24141                                    StoreType, ShuffWide,
24142                                    DAG.getIntPtrConstant(i));
24143       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24144                                 St->getPointerInfo(), St->isVolatile(),
24145                                 St->isNonTemporal(), St->getAlignment());
24146       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24147       Chains.push_back(Ch);
24148     }
24149
24150     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24151   }
24152
24153   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24154   // the FP state in cases where an emms may be missing.
24155   // A preferable solution to the general problem is to figure out the right
24156   // places to insert EMMS.  This qualifies as a quick hack.
24157
24158   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24159   if (VT.getSizeInBits() != 64)
24160     return SDValue();
24161
24162   const Function *F = DAG.getMachineFunction().getFunction();
24163   bool NoImplicitFloatOps = F->getAttributes().
24164     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
24165   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
24166                      && Subtarget->hasSSE2();
24167   if ((VT.isVector() ||
24168        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24169       isa<LoadSDNode>(St->getValue()) &&
24170       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24171       St->getChain().hasOneUse() && !St->isVolatile()) {
24172     SDNode* LdVal = St->getValue().getNode();
24173     LoadSDNode *Ld = nullptr;
24174     int TokenFactorIndex = -1;
24175     SmallVector<SDValue, 8> Ops;
24176     SDNode* ChainVal = St->getChain().getNode();
24177     // Must be a store of a load.  We currently handle two cases:  the load
24178     // is a direct child, and it's under an intervening TokenFactor.  It is
24179     // possible to dig deeper under nested TokenFactors.
24180     if (ChainVal == LdVal)
24181       Ld = cast<LoadSDNode>(St->getChain());
24182     else if (St->getValue().hasOneUse() &&
24183              ChainVal->getOpcode() == ISD::TokenFactor) {
24184       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24185         if (ChainVal->getOperand(i).getNode() == LdVal) {
24186           TokenFactorIndex = i;
24187           Ld = cast<LoadSDNode>(St->getValue());
24188         } else
24189           Ops.push_back(ChainVal->getOperand(i));
24190       }
24191     }
24192
24193     if (!Ld || !ISD::isNormalLoad(Ld))
24194       return SDValue();
24195
24196     // If this is not the MMX case, i.e. we are just turning i64 load/store
24197     // into f64 load/store, avoid the transformation if there are multiple
24198     // uses of the loaded value.
24199     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24200       return SDValue();
24201
24202     SDLoc LdDL(Ld);
24203     SDLoc StDL(N);
24204     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24205     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24206     // pair instead.
24207     if (Subtarget->is64Bit() || F64IsLegal) {
24208       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24209       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24210                                   Ld->getPointerInfo(), Ld->isVolatile(),
24211                                   Ld->isNonTemporal(), Ld->isInvariant(),
24212                                   Ld->getAlignment());
24213       SDValue NewChain = NewLd.getValue(1);
24214       if (TokenFactorIndex != -1) {
24215         Ops.push_back(NewChain);
24216         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24217       }
24218       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24219                           St->getPointerInfo(),
24220                           St->isVolatile(), St->isNonTemporal(),
24221                           St->getAlignment());
24222     }
24223
24224     // Otherwise, lower to two pairs of 32-bit loads / stores.
24225     SDValue LoAddr = Ld->getBasePtr();
24226     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24227                                  DAG.getConstant(4, MVT::i32));
24228
24229     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24230                                Ld->getPointerInfo(),
24231                                Ld->isVolatile(), Ld->isNonTemporal(),
24232                                Ld->isInvariant(), Ld->getAlignment());
24233     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24234                                Ld->getPointerInfo().getWithOffset(4),
24235                                Ld->isVolatile(), Ld->isNonTemporal(),
24236                                Ld->isInvariant(),
24237                                MinAlign(Ld->getAlignment(), 4));
24238
24239     SDValue NewChain = LoLd.getValue(1);
24240     if (TokenFactorIndex != -1) {
24241       Ops.push_back(LoLd);
24242       Ops.push_back(HiLd);
24243       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24244     }
24245
24246     LoAddr = St->getBasePtr();
24247     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24248                          DAG.getConstant(4, MVT::i32));
24249
24250     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24251                                 St->getPointerInfo(),
24252                                 St->isVolatile(), St->isNonTemporal(),
24253                                 St->getAlignment());
24254     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24255                                 St->getPointerInfo().getWithOffset(4),
24256                                 St->isVolatile(),
24257                                 St->isNonTemporal(),
24258                                 MinAlign(St->getAlignment(), 4));
24259     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24260   }
24261   return SDValue();
24262 }
24263
24264 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
24265 /// and return the operands for the horizontal operation in LHS and RHS.  A
24266 /// horizontal operation performs the binary operation on successive elements
24267 /// of its first operand, then on successive elements of its second operand,
24268 /// returning the resulting values in a vector.  For example, if
24269 ///   A = < float a0, float a1, float a2, float a3 >
24270 /// and
24271 ///   B = < float b0, float b1, float b2, float b3 >
24272 /// then the result of doing a horizontal operation on A and B is
24273 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24274 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24275 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24276 /// set to A, RHS to B, and the routine returns 'true'.
24277 /// Note that the binary operation should have the property that if one of the
24278 /// operands is UNDEF then the result is UNDEF.
24279 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24280   // Look for the following pattern: if
24281   //   A = < float a0, float a1, float a2, float a3 >
24282   //   B = < float b0, float b1, float b2, float b3 >
24283   // and
24284   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24285   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24286   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24287   // which is A horizontal-op B.
24288
24289   // At least one of the operands should be a vector shuffle.
24290   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24291       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24292     return false;
24293
24294   MVT VT = LHS.getSimpleValueType();
24295
24296   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24297          "Unsupported vector type for horizontal add/sub");
24298
24299   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24300   // operate independently on 128-bit lanes.
24301   unsigned NumElts = VT.getVectorNumElements();
24302   unsigned NumLanes = VT.getSizeInBits()/128;
24303   unsigned NumLaneElts = NumElts / NumLanes;
24304   assert((NumLaneElts % 2 == 0) &&
24305          "Vector type should have an even number of elements in each lane");
24306   unsigned HalfLaneElts = NumLaneElts/2;
24307
24308   // View LHS in the form
24309   //   LHS = VECTOR_SHUFFLE A, B, LMask
24310   // If LHS is not a shuffle then pretend it is the shuffle
24311   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24312   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24313   // type VT.
24314   SDValue A, B;
24315   SmallVector<int, 16> LMask(NumElts);
24316   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24317     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24318       A = LHS.getOperand(0);
24319     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24320       B = LHS.getOperand(1);
24321     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24322     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24323   } else {
24324     if (LHS.getOpcode() != ISD::UNDEF)
24325       A = LHS;
24326     for (unsigned i = 0; i != NumElts; ++i)
24327       LMask[i] = i;
24328   }
24329
24330   // Likewise, view RHS in the form
24331   //   RHS = VECTOR_SHUFFLE C, D, RMask
24332   SDValue C, D;
24333   SmallVector<int, 16> RMask(NumElts);
24334   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24335     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24336       C = RHS.getOperand(0);
24337     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24338       D = RHS.getOperand(1);
24339     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24340     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24341   } else {
24342     if (RHS.getOpcode() != ISD::UNDEF)
24343       C = RHS;
24344     for (unsigned i = 0; i != NumElts; ++i)
24345       RMask[i] = i;
24346   }
24347
24348   // Check that the shuffles are both shuffling the same vectors.
24349   if (!(A == C && B == D) && !(A == D && B == C))
24350     return false;
24351
24352   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24353   if (!A.getNode() && !B.getNode())
24354     return false;
24355
24356   // If A and B occur in reverse order in RHS, then "swap" them (which means
24357   // rewriting the mask).
24358   if (A != C)
24359     CommuteVectorShuffleMask(RMask, NumElts);
24360
24361   // At this point LHS and RHS are equivalent to
24362   //   LHS = VECTOR_SHUFFLE A, B, LMask
24363   //   RHS = VECTOR_SHUFFLE A, B, RMask
24364   // Check that the masks correspond to performing a horizontal operation.
24365   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24366     for (unsigned i = 0; i != NumLaneElts; ++i) {
24367       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24368
24369       // Ignore any UNDEF components.
24370       if (LIdx < 0 || RIdx < 0 ||
24371           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24372           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24373         continue;
24374
24375       // Check that successive elements are being operated on.  If not, this is
24376       // not a horizontal operation.
24377       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24378       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24379       if (!(LIdx == Index && RIdx == Index + 1) &&
24380           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24381         return false;
24382     }
24383   }
24384
24385   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24386   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24387   return true;
24388 }
24389
24390 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
24391 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24392                                   const X86Subtarget *Subtarget) {
24393   EVT VT = N->getValueType(0);
24394   SDValue LHS = N->getOperand(0);
24395   SDValue RHS = N->getOperand(1);
24396
24397   // Try to synthesize horizontal adds from adds of shuffles.
24398   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24399        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24400       isHorizontalBinOp(LHS, RHS, true))
24401     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24402   return SDValue();
24403 }
24404
24405 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
24406 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24407                                   const X86Subtarget *Subtarget) {
24408   EVT VT = N->getValueType(0);
24409   SDValue LHS = N->getOperand(0);
24410   SDValue RHS = N->getOperand(1);
24411
24412   // Try to synthesize horizontal subs from subs of shuffles.
24413   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24414        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24415       isHorizontalBinOp(LHS, RHS, false))
24416     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24417   return SDValue();
24418 }
24419
24420 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
24421 /// X86ISD::FXOR nodes.
24422 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24423   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24424   // F[X]OR(0.0, x) -> x
24425   // F[X]OR(x, 0.0) -> x
24426   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24427     if (C->getValueAPF().isPosZero())
24428       return N->getOperand(1);
24429   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24430     if (C->getValueAPF().isPosZero())
24431       return N->getOperand(0);
24432   return SDValue();
24433 }
24434
24435 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
24436 /// X86ISD::FMAX nodes.
24437 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24438   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24439
24440   // Only perform optimizations if UnsafeMath is used.
24441   if (!DAG.getTarget().Options.UnsafeFPMath)
24442     return SDValue();
24443
24444   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24445   // into FMINC and FMAXC, which are Commutative operations.
24446   unsigned NewOp = 0;
24447   switch (N->getOpcode()) {
24448     default: llvm_unreachable("unknown opcode");
24449     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24450     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24451   }
24452
24453   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24454                      N->getOperand(0), N->getOperand(1));
24455 }
24456
24457 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
24458 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24459   // FAND(0.0, x) -> 0.0
24460   // FAND(x, 0.0) -> 0.0
24461   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24462     if (C->getValueAPF().isPosZero())
24463       return N->getOperand(0);
24464   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24465     if (C->getValueAPF().isPosZero())
24466       return N->getOperand(1);
24467   return SDValue();
24468 }
24469
24470 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
24471 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24472   // FANDN(x, 0.0) -> 0.0
24473   // FANDN(0.0, x) -> x
24474   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24475     if (C->getValueAPF().isPosZero())
24476       return N->getOperand(1);
24477   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24478     if (C->getValueAPF().isPosZero())
24479       return N->getOperand(1);
24480   return SDValue();
24481 }
24482
24483 static SDValue PerformBTCombine(SDNode *N,
24484                                 SelectionDAG &DAG,
24485                                 TargetLowering::DAGCombinerInfo &DCI) {
24486   // BT ignores high bits in the bit index operand.
24487   SDValue Op1 = N->getOperand(1);
24488   if (Op1.hasOneUse()) {
24489     unsigned BitWidth = Op1.getValueSizeInBits();
24490     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24491     APInt KnownZero, KnownOne;
24492     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24493                                           !DCI.isBeforeLegalizeOps());
24494     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24495     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24496         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24497       DCI.CommitTargetLoweringOpt(TLO);
24498   }
24499   return SDValue();
24500 }
24501
24502 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24503   SDValue Op = N->getOperand(0);
24504   if (Op.getOpcode() == ISD::BITCAST)
24505     Op = Op.getOperand(0);
24506   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24507   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24508       VT.getVectorElementType().getSizeInBits() ==
24509       OpVT.getVectorElementType().getSizeInBits()) {
24510     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24511   }
24512   return SDValue();
24513 }
24514
24515 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24516                                                const X86Subtarget *Subtarget) {
24517   EVT VT = N->getValueType(0);
24518   if (!VT.isVector())
24519     return SDValue();
24520
24521   SDValue N0 = N->getOperand(0);
24522   SDValue N1 = N->getOperand(1);
24523   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24524   SDLoc dl(N);
24525
24526   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24527   // both SSE and AVX2 since there is no sign-extended shift right
24528   // operation on a vector with 64-bit elements.
24529   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24530   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24531   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24532       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24533     SDValue N00 = N0.getOperand(0);
24534
24535     // EXTLOAD has a better solution on AVX2,
24536     // it may be replaced with X86ISD::VSEXT node.
24537     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24538       if (!ISD::isNormalLoad(N00.getNode()))
24539         return SDValue();
24540
24541     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24542         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24543                                   N00, N1);
24544       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24545     }
24546   }
24547   return SDValue();
24548 }
24549
24550 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24551                                   TargetLowering::DAGCombinerInfo &DCI,
24552                                   const X86Subtarget *Subtarget) {
24553   SDValue N0 = N->getOperand(0);
24554   EVT VT = N->getValueType(0);
24555
24556   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24557   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24558   // This exposes the sext to the sdivrem lowering, so that it directly extends
24559   // from AH (which we otherwise need to do contortions to access).
24560   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24561       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
24562     SDLoc dl(N);
24563     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24564     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
24565                             N0.getOperand(0), N0.getOperand(1));
24566     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24567     return R.getValue(1);
24568   }
24569
24570   if (!DCI.isBeforeLegalizeOps())
24571     return SDValue();
24572
24573   if (!Subtarget->hasFp256())
24574     return SDValue();
24575
24576   if (VT.isVector() && VT.getSizeInBits() == 256) {
24577     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
24578     if (R.getNode())
24579       return R;
24580   }
24581
24582   return SDValue();
24583 }
24584
24585 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24586                                  const X86Subtarget* Subtarget) {
24587   SDLoc dl(N);
24588   EVT VT = N->getValueType(0);
24589
24590   // Let legalize expand this if it isn't a legal type yet.
24591   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24592     return SDValue();
24593
24594   EVT ScalarVT = VT.getScalarType();
24595   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24596       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
24597     return SDValue();
24598
24599   SDValue A = N->getOperand(0);
24600   SDValue B = N->getOperand(1);
24601   SDValue C = N->getOperand(2);
24602
24603   bool NegA = (A.getOpcode() == ISD::FNEG);
24604   bool NegB = (B.getOpcode() == ISD::FNEG);
24605   bool NegC = (C.getOpcode() == ISD::FNEG);
24606
24607   // Negative multiplication when NegA xor NegB
24608   bool NegMul = (NegA != NegB);
24609   if (NegA)
24610     A = A.getOperand(0);
24611   if (NegB)
24612     B = B.getOperand(0);
24613   if (NegC)
24614     C = C.getOperand(0);
24615
24616   unsigned Opcode;
24617   if (!NegMul)
24618     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24619   else
24620     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24621
24622   return DAG.getNode(Opcode, dl, VT, A, B, C);
24623 }
24624
24625 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24626                                   TargetLowering::DAGCombinerInfo &DCI,
24627                                   const X86Subtarget *Subtarget) {
24628   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24629   //           (and (i32 x86isd::setcc_carry), 1)
24630   // This eliminates the zext. This transformation is necessary because
24631   // ISD::SETCC is always legalized to i8.
24632   SDLoc dl(N);
24633   SDValue N0 = N->getOperand(0);
24634   EVT VT = N->getValueType(0);
24635
24636   if (N0.getOpcode() == ISD::AND &&
24637       N0.hasOneUse() &&
24638       N0.getOperand(0).hasOneUse()) {
24639     SDValue N00 = N0.getOperand(0);
24640     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24641       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24642       if (!C || C->getZExtValue() != 1)
24643         return SDValue();
24644       return DAG.getNode(ISD::AND, dl, VT,
24645                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24646                                      N00.getOperand(0), N00.getOperand(1)),
24647                          DAG.getConstant(1, VT));
24648     }
24649   }
24650
24651   if (N0.getOpcode() == ISD::TRUNCATE &&
24652       N0.hasOneUse() &&
24653       N0.getOperand(0).hasOneUse()) {
24654     SDValue N00 = N0.getOperand(0);
24655     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24656       return DAG.getNode(ISD::AND, dl, VT,
24657                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24658                                      N00.getOperand(0), N00.getOperand(1)),
24659                          DAG.getConstant(1, VT));
24660     }
24661   }
24662   if (VT.is256BitVector()) {
24663     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
24664     if (R.getNode())
24665       return R;
24666   }
24667
24668   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24669   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24670   // This exposes the zext to the udivrem lowering, so that it directly extends
24671   // from AH (which we otherwise need to do contortions to access).
24672   if (N0.getOpcode() == ISD::UDIVREM &&
24673       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24674       (VT == MVT::i32 || VT == MVT::i64)) {
24675     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24676     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24677                             N0.getOperand(0), N0.getOperand(1));
24678     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24679     return R.getValue(1);
24680   }
24681
24682   return SDValue();
24683 }
24684
24685 // Optimize x == -y --> x+y == 0
24686 //          x != -y --> x+y != 0
24687 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24688                                       const X86Subtarget* Subtarget) {
24689   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24690   SDValue LHS = N->getOperand(0);
24691   SDValue RHS = N->getOperand(1);
24692   EVT VT = N->getValueType(0);
24693   SDLoc DL(N);
24694
24695   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24696     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24697       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24698         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
24699                                    LHS.getValueType(), RHS, LHS.getOperand(1));
24700         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
24701                             addV, DAG.getConstant(0, addV.getValueType()), CC);
24702       }
24703   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24704     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24705       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24706         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
24707                                    RHS.getValueType(), LHS, RHS.getOperand(1));
24708         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
24709                             addV, DAG.getConstant(0, addV.getValueType()), CC);
24710       }
24711
24712   if (VT.getScalarType() == MVT::i1) {
24713     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24714       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
24715     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
24716     if (!IsSEXT0 && !IsVZero0)
24717       return SDValue();
24718     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
24719       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
24720     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24721
24722     if (!IsSEXT1 && !IsVZero1)
24723       return SDValue();
24724
24725     if (IsSEXT0 && IsVZero1) {
24726       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
24727       if (CC == ISD::SETEQ)
24728         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24729       return LHS.getOperand(0);
24730     }
24731     if (IsSEXT1 && IsVZero0) {
24732       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
24733       if (CC == ISD::SETEQ)
24734         return DAG.getNOT(DL, RHS.getOperand(0), VT);
24735       return RHS.getOperand(0);
24736     }
24737   }
24738
24739   return SDValue();
24740 }
24741
24742 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24743                                       const X86Subtarget *Subtarget) {
24744   SDLoc dl(N);
24745   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24746   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24747          "X86insertps is only defined for v4x32");
24748
24749   SDValue Ld = N->getOperand(1);
24750   if (MayFoldLoad(Ld)) {
24751     // Extract the countS bits from the immediate so we can get the proper
24752     // address when narrowing the vector load to a specific element.
24753     // When the second source op is a memory address, interps doesn't use
24754     // countS and just gets an f32 from that address.
24755     unsigned DestIndex =
24756         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24757     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24758   } else
24759     return SDValue();
24760
24761   // Create this as a scalar to vector to match the instruction pattern.
24762   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24763   // countS bits are ignored when loading from memory on insertps, which
24764   // means we don't need to explicitly set them to 0.
24765   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24766                      LoadScalarToVector, N->getOperand(2));
24767 }
24768
24769 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24770 // as "sbb reg,reg", since it can be extended without zext and produces
24771 // an all-ones bit which is more useful than 0/1 in some cases.
24772 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24773                                MVT VT) {
24774   if (VT == MVT::i8)
24775     return DAG.getNode(ISD::AND, DL, VT,
24776                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24777                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
24778                        DAG.getConstant(1, VT));
24779   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24780   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24781                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24782                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
24783 }
24784
24785 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24786 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24787                                    TargetLowering::DAGCombinerInfo &DCI,
24788                                    const X86Subtarget *Subtarget) {
24789   SDLoc DL(N);
24790   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24791   SDValue EFLAGS = N->getOperand(1);
24792
24793   if (CC == X86::COND_A) {
24794     // Try to convert COND_A into COND_B in an attempt to facilitate
24795     // materializing "setb reg".
24796     //
24797     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24798     // cannot take an immediate as its first operand.
24799     //
24800     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24801         EFLAGS.getValueType().isInteger() &&
24802         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24803       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24804                                    EFLAGS.getNode()->getVTList(),
24805                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24806       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24807       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24808     }
24809   }
24810
24811   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24812   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24813   // cases.
24814   if (CC == X86::COND_B)
24815     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24816
24817   SDValue Flags;
24818
24819   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24820   if (Flags.getNode()) {
24821     SDValue Cond = DAG.getConstant(CC, MVT::i8);
24822     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24823   }
24824
24825   return SDValue();
24826 }
24827
24828 // Optimize branch condition evaluation.
24829 //
24830 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24831                                     TargetLowering::DAGCombinerInfo &DCI,
24832                                     const X86Subtarget *Subtarget) {
24833   SDLoc DL(N);
24834   SDValue Chain = N->getOperand(0);
24835   SDValue Dest = N->getOperand(1);
24836   SDValue EFLAGS = N->getOperand(3);
24837   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24838
24839   SDValue Flags;
24840
24841   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24842   if (Flags.getNode()) {
24843     SDValue Cond = DAG.getConstant(CC, MVT::i8);
24844     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24845                        Flags);
24846   }
24847
24848   return SDValue();
24849 }
24850
24851 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24852                                                          SelectionDAG &DAG) {
24853   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24854   // optimize away operation when it's from a constant.
24855   //
24856   // The general transformation is:
24857   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24858   //       AND(VECTOR_CMP(x,y), constant2)
24859   //    constant2 = UNARYOP(constant)
24860
24861   // Early exit if this isn't a vector operation, the operand of the
24862   // unary operation isn't a bitwise AND, or if the sizes of the operations
24863   // aren't the same.
24864   EVT VT = N->getValueType(0);
24865   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24866       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24867       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24868     return SDValue();
24869
24870   // Now check that the other operand of the AND is a constant. We could
24871   // make the transformation for non-constant splats as well, but it's unclear
24872   // that would be a benefit as it would not eliminate any operations, just
24873   // perform one more step in scalar code before moving to the vector unit.
24874   if (BuildVectorSDNode *BV =
24875           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24876     // Bail out if the vector isn't a constant.
24877     if (!BV->isConstant())
24878       return SDValue();
24879
24880     // Everything checks out. Build up the new and improved node.
24881     SDLoc DL(N);
24882     EVT IntVT = BV->getValueType(0);
24883     // Create a new constant of the appropriate type for the transformed
24884     // DAG.
24885     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24886     // The AND node needs bitcasts to/from an integer vector type around it.
24887     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24888     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24889                                  N->getOperand(0)->getOperand(0), MaskConst);
24890     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24891     return Res;
24892   }
24893
24894   return SDValue();
24895 }
24896
24897 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24898                                         const X86TargetLowering *XTLI) {
24899   // First try to optimize away the conversion entirely when it's
24900   // conditionally from a constant. Vectors only.
24901   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24902   if (Res != SDValue())
24903     return Res;
24904
24905   // Now move on to more general possibilities.
24906   SDValue Op0 = N->getOperand(0);
24907   EVT InVT = Op0->getValueType(0);
24908
24909   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24910   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24911     SDLoc dl(N);
24912     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24913     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24914     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24915   }
24916
24917   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24918   // a 32-bit target where SSE doesn't support i64->FP operations.
24919   if (Op0.getOpcode() == ISD::LOAD) {
24920     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24921     EVT VT = Ld->getValueType(0);
24922     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24923         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24924         !XTLI->getSubtarget()->is64Bit() &&
24925         VT == MVT::i64) {
24926       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
24927                                           Ld->getChain(), Op0, DAG);
24928       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24929       return FILDChain;
24930     }
24931   }
24932   return SDValue();
24933 }
24934
24935 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24936 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24937                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24938   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24939   // the result is either zero or one (depending on the input carry bit).
24940   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24941   if (X86::isZeroNode(N->getOperand(0)) &&
24942       X86::isZeroNode(N->getOperand(1)) &&
24943       // We don't have a good way to replace an EFLAGS use, so only do this when
24944       // dead right now.
24945       SDValue(N, 1).use_empty()) {
24946     SDLoc DL(N);
24947     EVT VT = N->getValueType(0);
24948     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
24949     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24950                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24951                                            DAG.getConstant(X86::COND_B,MVT::i8),
24952                                            N->getOperand(2)),
24953                                DAG.getConstant(1, VT));
24954     return DCI.CombineTo(N, Res1, CarryOut);
24955   }
24956
24957   return SDValue();
24958 }
24959
24960 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24961 //      (add Y, (setne X, 0)) -> sbb -1, Y
24962 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24963 //      (sub (setne X, 0), Y) -> adc -1, Y
24964 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24965   SDLoc DL(N);
24966
24967   // Look through ZExts.
24968   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24969   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24970     return SDValue();
24971
24972   SDValue SetCC = Ext.getOperand(0);
24973   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24974     return SDValue();
24975
24976   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24977   if (CC != X86::COND_E && CC != X86::COND_NE)
24978     return SDValue();
24979
24980   SDValue Cmp = SetCC.getOperand(1);
24981   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24982       !X86::isZeroNode(Cmp.getOperand(1)) ||
24983       !Cmp.getOperand(0).getValueType().isInteger())
24984     return SDValue();
24985
24986   SDValue CmpOp0 = Cmp.getOperand(0);
24987   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24988                                DAG.getConstant(1, CmpOp0.getValueType()));
24989
24990   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24991   if (CC == X86::COND_NE)
24992     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24993                        DL, OtherVal.getValueType(), OtherVal,
24994                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
24995   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24996                      DL, OtherVal.getValueType(), OtherVal,
24997                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
24998 }
24999
25000 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25001 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25002                                  const X86Subtarget *Subtarget) {
25003   EVT VT = N->getValueType(0);
25004   SDValue Op0 = N->getOperand(0);
25005   SDValue Op1 = N->getOperand(1);
25006
25007   // Try to synthesize horizontal adds from adds of shuffles.
25008   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25009        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25010       isHorizontalBinOp(Op0, Op1, true))
25011     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25012
25013   return OptimizeConditionalInDecrement(N, DAG);
25014 }
25015
25016 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25017                                  const X86Subtarget *Subtarget) {
25018   SDValue Op0 = N->getOperand(0);
25019   SDValue Op1 = N->getOperand(1);
25020
25021   // X86 can't encode an immediate LHS of a sub. See if we can push the
25022   // negation into a preceding instruction.
25023   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25024     // If the RHS of the sub is a XOR with one use and a constant, invert the
25025     // immediate. Then add one to the LHS of the sub so we can turn
25026     // X-Y -> X+~Y+1, saving one register.
25027     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25028         isa<ConstantSDNode>(Op1.getOperand(1))) {
25029       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25030       EVT VT = Op0.getValueType();
25031       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25032                                    Op1.getOperand(0),
25033                                    DAG.getConstant(~XorC, VT));
25034       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25035                          DAG.getConstant(C->getAPIntValue()+1, VT));
25036     }
25037   }
25038
25039   // Try to synthesize horizontal adds from adds of shuffles.
25040   EVT VT = N->getValueType(0);
25041   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25042        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25043       isHorizontalBinOp(Op0, Op1, true))
25044     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25045
25046   return OptimizeConditionalInDecrement(N, DAG);
25047 }
25048
25049 /// performVZEXTCombine - Performs build vector combines
25050 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25051                                    TargetLowering::DAGCombinerInfo &DCI,
25052                                    const X86Subtarget *Subtarget) {
25053   SDLoc DL(N);
25054   MVT VT = N->getSimpleValueType(0);
25055   SDValue Op = N->getOperand(0);
25056   MVT OpVT = Op.getSimpleValueType();
25057   MVT OpEltVT = OpVT.getVectorElementType();
25058   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25059
25060   // (vzext (bitcast (vzext (x)) -> (vzext x)
25061   SDValue V = Op;
25062   while (V.getOpcode() == ISD::BITCAST)
25063     V = V.getOperand(0);
25064
25065   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25066     MVT InnerVT = V.getSimpleValueType();
25067     MVT InnerEltVT = InnerVT.getVectorElementType();
25068
25069     // If the element sizes match exactly, we can just do one larger vzext. This
25070     // is always an exact type match as vzext operates on integer types.
25071     if (OpEltVT == InnerEltVT) {
25072       assert(OpVT == InnerVT && "Types must match for vzext!");
25073       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25074     }
25075
25076     // The only other way we can combine them is if only a single element of the
25077     // inner vzext is used in the input to the outer vzext.
25078     if (InnerEltVT.getSizeInBits() < InputBits)
25079       return SDValue();
25080
25081     // In this case, the inner vzext is completely dead because we're going to
25082     // only look at bits inside of the low element. Just do the outer vzext on
25083     // a bitcast of the input to the inner.
25084     return DAG.getNode(X86ISD::VZEXT, DL, VT,
25085                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
25086   }
25087
25088   // Check if we can bypass extracting and re-inserting an element of an input
25089   // vector. Essentialy:
25090   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25091   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25092       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25093       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25094     SDValue ExtractedV = V.getOperand(0);
25095     SDValue OrigV = ExtractedV.getOperand(0);
25096     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25097       if (ExtractIdx->getZExtValue() == 0) {
25098         MVT OrigVT = OrigV.getSimpleValueType();
25099         // Extract a subvector if necessary...
25100         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25101           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25102           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25103                                     OrigVT.getVectorNumElements() / Ratio);
25104           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25105                               DAG.getIntPtrConstant(0));
25106         }
25107         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
25108         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25109       }
25110   }
25111
25112   return SDValue();
25113 }
25114
25115 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25116                                              DAGCombinerInfo &DCI) const {
25117   SelectionDAG &DAG = DCI.DAG;
25118   switch (N->getOpcode()) {
25119   default: break;
25120   case ISD::EXTRACT_VECTOR_ELT:
25121     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25122   case ISD::VSELECT:
25123   case ISD::SELECT:
25124   case X86ISD::SHRUNKBLEND:
25125     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25126   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25127   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25128   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25129   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25130   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25131   case ISD::SHL:
25132   case ISD::SRA:
25133   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25134   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25135   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25136   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25137   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25138   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25139   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
25140   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25141   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25142   case X86ISD::FXOR:
25143   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25144   case X86ISD::FMIN:
25145   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25146   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25147   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25148   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25149   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25150   case ISD::ANY_EXTEND:
25151   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25152   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25153   case ISD::SIGN_EXTEND_INREG:
25154     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25155   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
25156   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25157   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25158   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25159   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25160   case X86ISD::SHUFP:       // Handle all target specific shuffles
25161   case X86ISD::PALIGNR:
25162   case X86ISD::UNPCKH:
25163   case X86ISD::UNPCKL:
25164   case X86ISD::MOVHLPS:
25165   case X86ISD::MOVLHPS:
25166   case X86ISD::PSHUFB:
25167   case X86ISD::PSHUFD:
25168   case X86ISD::PSHUFHW:
25169   case X86ISD::PSHUFLW:
25170   case X86ISD::MOVSS:
25171   case X86ISD::MOVSD:
25172   case X86ISD::VPERMILPI:
25173   case X86ISD::VPERM2X128:
25174   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25175   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25176   case ISD::INTRINSIC_WO_CHAIN:
25177     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25178   case X86ISD::INSERTPS:
25179     return PerformINSERTPSCombine(N, DAG, Subtarget);
25180   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
25181   }
25182
25183   return SDValue();
25184 }
25185
25186 /// isTypeDesirableForOp - Return true if the target has native support for
25187 /// the specified value type and it is 'desirable' to use the type for the
25188 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25189 /// instruction encodings are longer and some i16 instructions are slow.
25190 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25191   if (!isTypeLegal(VT))
25192     return false;
25193   if (VT != MVT::i16)
25194     return true;
25195
25196   switch (Opc) {
25197   default:
25198     return true;
25199   case ISD::LOAD:
25200   case ISD::SIGN_EXTEND:
25201   case ISD::ZERO_EXTEND:
25202   case ISD::ANY_EXTEND:
25203   case ISD::SHL:
25204   case ISD::SRL:
25205   case ISD::SUB:
25206   case ISD::ADD:
25207   case ISD::MUL:
25208   case ISD::AND:
25209   case ISD::OR:
25210   case ISD::XOR:
25211     return false;
25212   }
25213 }
25214
25215 /// IsDesirableToPromoteOp - This method query the target whether it is
25216 /// beneficial for dag combiner to promote the specified node. If true, it
25217 /// should return the desired promotion type by reference.
25218 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25219   EVT VT = Op.getValueType();
25220   if (VT != MVT::i16)
25221     return false;
25222
25223   bool Promote = false;
25224   bool Commute = false;
25225   switch (Op.getOpcode()) {
25226   default: break;
25227   case ISD::LOAD: {
25228     LoadSDNode *LD = cast<LoadSDNode>(Op);
25229     // If the non-extending load has a single use and it's not live out, then it
25230     // might be folded.
25231     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25232                                                      Op.hasOneUse()*/) {
25233       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25234              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25235         // The only case where we'd want to promote LOAD (rather then it being
25236         // promoted as an operand is when it's only use is liveout.
25237         if (UI->getOpcode() != ISD::CopyToReg)
25238           return false;
25239       }
25240     }
25241     Promote = true;
25242     break;
25243   }
25244   case ISD::SIGN_EXTEND:
25245   case ISD::ZERO_EXTEND:
25246   case ISD::ANY_EXTEND:
25247     Promote = true;
25248     break;
25249   case ISD::SHL:
25250   case ISD::SRL: {
25251     SDValue N0 = Op.getOperand(0);
25252     // Look out for (store (shl (load), x)).
25253     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25254       return false;
25255     Promote = true;
25256     break;
25257   }
25258   case ISD::ADD:
25259   case ISD::MUL:
25260   case ISD::AND:
25261   case ISD::OR:
25262   case ISD::XOR:
25263     Commute = true;
25264     // fallthrough
25265   case ISD::SUB: {
25266     SDValue N0 = Op.getOperand(0);
25267     SDValue N1 = Op.getOperand(1);
25268     if (!Commute && MayFoldLoad(N1))
25269       return false;
25270     // Avoid disabling potential load folding opportunities.
25271     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25272       return false;
25273     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25274       return false;
25275     Promote = true;
25276   }
25277   }
25278
25279   PVT = MVT::i32;
25280   return Promote;
25281 }
25282
25283 //===----------------------------------------------------------------------===//
25284 //                           X86 Inline Assembly Support
25285 //===----------------------------------------------------------------------===//
25286
25287 namespace {
25288   // Helper to match a string separated by whitespace.
25289   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
25290     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
25291
25292     for (unsigned i = 0, e = args.size(); i != e; ++i) {
25293       StringRef piece(*args[i]);
25294       if (!s.startswith(piece)) // Check if the piece matches.
25295         return false;
25296
25297       s = s.substr(piece.size());
25298       StringRef::size_type pos = s.find_first_not_of(" \t");
25299       if (pos == 0) // We matched a prefix.
25300         return false;
25301
25302       s = s.substr(pos);
25303     }
25304
25305     return s.empty();
25306   }
25307   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
25308 }
25309
25310 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25311
25312   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25313     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25314         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25315         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25316
25317       if (AsmPieces.size() == 3)
25318         return true;
25319       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25320         return true;
25321     }
25322   }
25323   return false;
25324 }
25325
25326 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25327   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25328
25329   std::string AsmStr = IA->getAsmString();
25330
25331   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25332   if (!Ty || Ty->getBitWidth() % 16 != 0)
25333     return false;
25334
25335   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25336   SmallVector<StringRef, 4> AsmPieces;
25337   SplitString(AsmStr, AsmPieces, ";\n");
25338
25339   switch (AsmPieces.size()) {
25340   default: return false;
25341   case 1:
25342     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25343     // we will turn this bswap into something that will be lowered to logical
25344     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25345     // lower so don't worry about this.
25346     // bswap $0
25347     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
25348         matchAsm(AsmPieces[0], "bswapl", "$0") ||
25349         matchAsm(AsmPieces[0], "bswapq", "$0") ||
25350         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
25351         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
25352         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
25353       // No need to check constraints, nothing other than the equivalent of
25354       // "=r,0" would be valid here.
25355       return IntrinsicLowering::LowerToByteSwap(CI);
25356     }
25357
25358     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25359     if (CI->getType()->isIntegerTy(16) &&
25360         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25361         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
25362          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
25363       AsmPieces.clear();
25364       const std::string &ConstraintsStr = IA->getConstraintString();
25365       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25366       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25367       if (clobbersFlagRegisters(AsmPieces))
25368         return IntrinsicLowering::LowerToByteSwap(CI);
25369     }
25370     break;
25371   case 3:
25372     if (CI->getType()->isIntegerTy(32) &&
25373         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25374         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
25375         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
25376         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
25377       AsmPieces.clear();
25378       const std::string &ConstraintsStr = IA->getConstraintString();
25379       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25380       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25381       if (clobbersFlagRegisters(AsmPieces))
25382         return IntrinsicLowering::LowerToByteSwap(CI);
25383     }
25384
25385     if (CI->getType()->isIntegerTy(64)) {
25386       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25387       if (Constraints.size() >= 2 &&
25388           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25389           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25390         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25391         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
25392             matchAsm(AsmPieces[1], "bswap", "%edx") &&
25393             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
25394           return IntrinsicLowering::LowerToByteSwap(CI);
25395       }
25396     }
25397     break;
25398   }
25399   return false;
25400 }
25401
25402 /// getConstraintType - Given a constraint letter, return the type of
25403 /// constraint it is for this target.
25404 X86TargetLowering::ConstraintType
25405 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
25406   if (Constraint.size() == 1) {
25407     switch (Constraint[0]) {
25408     case 'R':
25409     case 'q':
25410     case 'Q':
25411     case 'f':
25412     case 't':
25413     case 'u':
25414     case 'y':
25415     case 'x':
25416     case 'Y':
25417     case 'l':
25418       return C_RegisterClass;
25419     case 'a':
25420     case 'b':
25421     case 'c':
25422     case 'd':
25423     case 'S':
25424     case 'D':
25425     case 'A':
25426       return C_Register;
25427     case 'I':
25428     case 'J':
25429     case 'K':
25430     case 'L':
25431     case 'M':
25432     case 'N':
25433     case 'G':
25434     case 'C':
25435     case 'e':
25436     case 'Z':
25437       return C_Other;
25438     default:
25439       break;
25440     }
25441   }
25442   return TargetLowering::getConstraintType(Constraint);
25443 }
25444
25445 /// Examine constraint type and operand type and determine a weight value.
25446 /// This object must already have been set up with the operand type
25447 /// and the current alternative constraint selected.
25448 TargetLowering::ConstraintWeight
25449   X86TargetLowering::getSingleConstraintMatchWeight(
25450     AsmOperandInfo &info, const char *constraint) const {
25451   ConstraintWeight weight = CW_Invalid;
25452   Value *CallOperandVal = info.CallOperandVal;
25453     // If we don't have a value, we can't do a match,
25454     // but allow it at the lowest weight.
25455   if (!CallOperandVal)
25456     return CW_Default;
25457   Type *type = CallOperandVal->getType();
25458   // Look at the constraint type.
25459   switch (*constraint) {
25460   default:
25461     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25462   case 'R':
25463   case 'q':
25464   case 'Q':
25465   case 'a':
25466   case 'b':
25467   case 'c':
25468   case 'd':
25469   case 'S':
25470   case 'D':
25471   case 'A':
25472     if (CallOperandVal->getType()->isIntegerTy())
25473       weight = CW_SpecificReg;
25474     break;
25475   case 'f':
25476   case 't':
25477   case 'u':
25478     if (type->isFloatingPointTy())
25479       weight = CW_SpecificReg;
25480     break;
25481   case 'y':
25482     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25483       weight = CW_SpecificReg;
25484     break;
25485   case 'x':
25486   case 'Y':
25487     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25488         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25489       weight = CW_Register;
25490     break;
25491   case 'I':
25492     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25493       if (C->getZExtValue() <= 31)
25494         weight = CW_Constant;
25495     }
25496     break;
25497   case 'J':
25498     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25499       if (C->getZExtValue() <= 63)
25500         weight = CW_Constant;
25501     }
25502     break;
25503   case 'K':
25504     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25505       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25506         weight = CW_Constant;
25507     }
25508     break;
25509   case 'L':
25510     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25511       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25512         weight = CW_Constant;
25513     }
25514     break;
25515   case 'M':
25516     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25517       if (C->getZExtValue() <= 3)
25518         weight = CW_Constant;
25519     }
25520     break;
25521   case 'N':
25522     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25523       if (C->getZExtValue() <= 0xff)
25524         weight = CW_Constant;
25525     }
25526     break;
25527   case 'G':
25528   case 'C':
25529     if (dyn_cast<ConstantFP>(CallOperandVal)) {
25530       weight = CW_Constant;
25531     }
25532     break;
25533   case 'e':
25534     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25535       if ((C->getSExtValue() >= -0x80000000LL) &&
25536           (C->getSExtValue() <= 0x7fffffffLL))
25537         weight = CW_Constant;
25538     }
25539     break;
25540   case 'Z':
25541     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25542       if (C->getZExtValue() <= 0xffffffff)
25543         weight = CW_Constant;
25544     }
25545     break;
25546   }
25547   return weight;
25548 }
25549
25550 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25551 /// with another that has more specific requirements based on the type of the
25552 /// corresponding operand.
25553 const char *X86TargetLowering::
25554 LowerXConstraint(EVT ConstraintVT) const {
25555   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25556   // 'f' like normal targets.
25557   if (ConstraintVT.isFloatingPoint()) {
25558     if (Subtarget->hasSSE2())
25559       return "Y";
25560     if (Subtarget->hasSSE1())
25561       return "x";
25562   }
25563
25564   return TargetLowering::LowerXConstraint(ConstraintVT);
25565 }
25566
25567 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25568 /// vector.  If it is invalid, don't add anything to Ops.
25569 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25570                                                      std::string &Constraint,
25571                                                      std::vector<SDValue>&Ops,
25572                                                      SelectionDAG &DAG) const {
25573   SDValue Result;
25574
25575   // Only support length 1 constraints for now.
25576   if (Constraint.length() > 1) return;
25577
25578   char ConstraintLetter = Constraint[0];
25579   switch (ConstraintLetter) {
25580   default: break;
25581   case 'I':
25582     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25583       if (C->getZExtValue() <= 31) {
25584         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25585         break;
25586       }
25587     }
25588     return;
25589   case 'J':
25590     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25591       if (C->getZExtValue() <= 63) {
25592         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25593         break;
25594       }
25595     }
25596     return;
25597   case 'K':
25598     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25599       if (isInt<8>(C->getSExtValue())) {
25600         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25601         break;
25602       }
25603     }
25604     return;
25605   case 'N':
25606     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25607       if (C->getZExtValue() <= 255) {
25608         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25609         break;
25610       }
25611     }
25612     return;
25613   case 'e': {
25614     // 32-bit signed value
25615     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25616       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25617                                            C->getSExtValue())) {
25618         // Widen to 64 bits here to get it sign extended.
25619         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
25620         break;
25621       }
25622     // FIXME gcc accepts some relocatable values here too, but only in certain
25623     // memory models; it's complicated.
25624     }
25625     return;
25626   }
25627   case 'Z': {
25628     // 32-bit unsigned value
25629     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25630       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25631                                            C->getZExtValue())) {
25632         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25633         break;
25634       }
25635     }
25636     // FIXME gcc accepts some relocatable values here too, but only in certain
25637     // memory models; it's complicated.
25638     return;
25639   }
25640   case 'i': {
25641     // Literal immediates are always ok.
25642     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25643       // Widen to 64 bits here to get it sign extended.
25644       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
25645       break;
25646     }
25647
25648     // In any sort of PIC mode addresses need to be computed at runtime by
25649     // adding in a register or some sort of table lookup.  These can't
25650     // be used as immediates.
25651     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25652       return;
25653
25654     // If we are in non-pic codegen mode, we allow the address of a global (with
25655     // an optional displacement) to be used with 'i'.
25656     GlobalAddressSDNode *GA = nullptr;
25657     int64_t Offset = 0;
25658
25659     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25660     while (1) {
25661       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25662         Offset += GA->getOffset();
25663         break;
25664       } else if (Op.getOpcode() == ISD::ADD) {
25665         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25666           Offset += C->getZExtValue();
25667           Op = Op.getOperand(0);
25668           continue;
25669         }
25670       } else if (Op.getOpcode() == ISD::SUB) {
25671         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25672           Offset += -C->getZExtValue();
25673           Op = Op.getOperand(0);
25674           continue;
25675         }
25676       }
25677
25678       // Otherwise, this isn't something we can handle, reject it.
25679       return;
25680     }
25681
25682     const GlobalValue *GV = GA->getGlobal();
25683     // If we require an extra load to get this address, as in PIC mode, we
25684     // can't accept it.
25685     if (isGlobalStubReference(
25686             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25687       return;
25688
25689     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25690                                         GA->getValueType(0), Offset);
25691     break;
25692   }
25693   }
25694
25695   if (Result.getNode()) {
25696     Ops.push_back(Result);
25697     return;
25698   }
25699   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25700 }
25701
25702 std::pair<unsigned, const TargetRegisterClass*>
25703 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
25704                                                 MVT VT) const {
25705   // First, see if this is a constraint that directly corresponds to an LLVM
25706   // register class.
25707   if (Constraint.size() == 1) {
25708     // GCC Constraint Letters
25709     switch (Constraint[0]) {
25710     default: break;
25711       // TODO: Slight differences here in allocation order and leaving
25712       // RIP in the class. Do they matter any more here than they do
25713       // in the normal allocation?
25714     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25715       if (Subtarget->is64Bit()) {
25716         if (VT == MVT::i32 || VT == MVT::f32)
25717           return std::make_pair(0U, &X86::GR32RegClass);
25718         if (VT == MVT::i16)
25719           return std::make_pair(0U, &X86::GR16RegClass);
25720         if (VT == MVT::i8 || VT == MVT::i1)
25721           return std::make_pair(0U, &X86::GR8RegClass);
25722         if (VT == MVT::i64 || VT == MVT::f64)
25723           return std::make_pair(0U, &X86::GR64RegClass);
25724         break;
25725       }
25726       // 32-bit fallthrough
25727     case 'Q':   // Q_REGS
25728       if (VT == MVT::i32 || VT == MVT::f32)
25729         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25730       if (VT == MVT::i16)
25731         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25732       if (VT == MVT::i8 || VT == MVT::i1)
25733         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25734       if (VT == MVT::i64)
25735         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25736       break;
25737     case 'r':   // GENERAL_REGS
25738     case 'l':   // INDEX_REGS
25739       if (VT == MVT::i8 || VT == MVT::i1)
25740         return std::make_pair(0U, &X86::GR8RegClass);
25741       if (VT == MVT::i16)
25742         return std::make_pair(0U, &X86::GR16RegClass);
25743       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25744         return std::make_pair(0U, &X86::GR32RegClass);
25745       return std::make_pair(0U, &X86::GR64RegClass);
25746     case 'R':   // LEGACY_REGS
25747       if (VT == MVT::i8 || VT == MVT::i1)
25748         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25749       if (VT == MVT::i16)
25750         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25751       if (VT == MVT::i32 || !Subtarget->is64Bit())
25752         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25753       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25754     case 'f':  // FP Stack registers.
25755       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25756       // value to the correct fpstack register class.
25757       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25758         return std::make_pair(0U, &X86::RFP32RegClass);
25759       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25760         return std::make_pair(0U, &X86::RFP64RegClass);
25761       return std::make_pair(0U, &X86::RFP80RegClass);
25762     case 'y':   // MMX_REGS if MMX allowed.
25763       if (!Subtarget->hasMMX()) break;
25764       return std::make_pair(0U, &X86::VR64RegClass);
25765     case 'Y':   // SSE_REGS if SSE2 allowed
25766       if (!Subtarget->hasSSE2()) break;
25767       // FALL THROUGH.
25768     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25769       if (!Subtarget->hasSSE1()) break;
25770
25771       switch (VT.SimpleTy) {
25772       default: break;
25773       // Scalar SSE types.
25774       case MVT::f32:
25775       case MVT::i32:
25776         return std::make_pair(0U, &X86::FR32RegClass);
25777       case MVT::f64:
25778       case MVT::i64:
25779         return std::make_pair(0U, &X86::FR64RegClass);
25780       // Vector types.
25781       case MVT::v16i8:
25782       case MVT::v8i16:
25783       case MVT::v4i32:
25784       case MVT::v2i64:
25785       case MVT::v4f32:
25786       case MVT::v2f64:
25787         return std::make_pair(0U, &X86::VR128RegClass);
25788       // AVX types.
25789       case MVT::v32i8:
25790       case MVT::v16i16:
25791       case MVT::v8i32:
25792       case MVT::v4i64:
25793       case MVT::v8f32:
25794       case MVT::v4f64:
25795         return std::make_pair(0U, &X86::VR256RegClass);
25796       case MVT::v8f64:
25797       case MVT::v16f32:
25798       case MVT::v16i32:
25799       case MVT::v8i64:
25800         return std::make_pair(0U, &X86::VR512RegClass);
25801       }
25802       break;
25803     }
25804   }
25805
25806   // Use the default implementation in TargetLowering to convert the register
25807   // constraint into a member of a register class.
25808   std::pair<unsigned, const TargetRegisterClass*> Res;
25809   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
25810
25811   // Not found as a standard register?
25812   if (!Res.second) {
25813     // Map st(0) -> st(7) -> ST0
25814     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25815         tolower(Constraint[1]) == 's' &&
25816         tolower(Constraint[2]) == 't' &&
25817         Constraint[3] == '(' &&
25818         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25819         Constraint[5] == ')' &&
25820         Constraint[6] == '}') {
25821
25822       Res.first = X86::FP0+Constraint[4]-'0';
25823       Res.second = &X86::RFP80RegClass;
25824       return Res;
25825     }
25826
25827     // GCC allows "st(0)" to be called just plain "st".
25828     if (StringRef("{st}").equals_lower(Constraint)) {
25829       Res.first = X86::FP0;
25830       Res.second = &X86::RFP80RegClass;
25831       return Res;
25832     }
25833
25834     // flags -> EFLAGS
25835     if (StringRef("{flags}").equals_lower(Constraint)) {
25836       Res.first = X86::EFLAGS;
25837       Res.second = &X86::CCRRegClass;
25838       return Res;
25839     }
25840
25841     // 'A' means EAX + EDX.
25842     if (Constraint == "A") {
25843       Res.first = X86::EAX;
25844       Res.second = &X86::GR32_ADRegClass;
25845       return Res;
25846     }
25847     return Res;
25848   }
25849
25850   // Otherwise, check to see if this is a register class of the wrong value
25851   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25852   // turn into {ax},{dx}.
25853   if (Res.second->hasType(VT))
25854     return Res;   // Correct type already, nothing to do.
25855
25856   // All of the single-register GCC register classes map their values onto
25857   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25858   // really want an 8-bit or 32-bit register, map to the appropriate register
25859   // class and return the appropriate register.
25860   if (Res.second == &X86::GR16RegClass) {
25861     if (VT == MVT::i8 || VT == MVT::i1) {
25862       unsigned DestReg = 0;
25863       switch (Res.first) {
25864       default: break;
25865       case X86::AX: DestReg = X86::AL; break;
25866       case X86::DX: DestReg = X86::DL; break;
25867       case X86::CX: DestReg = X86::CL; break;
25868       case X86::BX: DestReg = X86::BL; break;
25869       }
25870       if (DestReg) {
25871         Res.first = DestReg;
25872         Res.second = &X86::GR8RegClass;
25873       }
25874     } else if (VT == MVT::i32 || VT == MVT::f32) {
25875       unsigned DestReg = 0;
25876       switch (Res.first) {
25877       default: break;
25878       case X86::AX: DestReg = X86::EAX; break;
25879       case X86::DX: DestReg = X86::EDX; break;
25880       case X86::CX: DestReg = X86::ECX; break;
25881       case X86::BX: DestReg = X86::EBX; break;
25882       case X86::SI: DestReg = X86::ESI; break;
25883       case X86::DI: DestReg = X86::EDI; break;
25884       case X86::BP: DestReg = X86::EBP; break;
25885       case X86::SP: DestReg = X86::ESP; break;
25886       }
25887       if (DestReg) {
25888         Res.first = DestReg;
25889         Res.second = &X86::GR32RegClass;
25890       }
25891     } else if (VT == MVT::i64 || VT == MVT::f64) {
25892       unsigned DestReg = 0;
25893       switch (Res.first) {
25894       default: break;
25895       case X86::AX: DestReg = X86::RAX; break;
25896       case X86::DX: DestReg = X86::RDX; break;
25897       case X86::CX: DestReg = X86::RCX; break;
25898       case X86::BX: DestReg = X86::RBX; break;
25899       case X86::SI: DestReg = X86::RSI; break;
25900       case X86::DI: DestReg = X86::RDI; break;
25901       case X86::BP: DestReg = X86::RBP; break;
25902       case X86::SP: DestReg = X86::RSP; break;
25903       }
25904       if (DestReg) {
25905         Res.first = DestReg;
25906         Res.second = &X86::GR64RegClass;
25907       }
25908     }
25909   } else if (Res.second == &X86::FR32RegClass ||
25910              Res.second == &X86::FR64RegClass ||
25911              Res.second == &X86::VR128RegClass ||
25912              Res.second == &X86::VR256RegClass ||
25913              Res.second == &X86::FR32XRegClass ||
25914              Res.second == &X86::FR64XRegClass ||
25915              Res.second == &X86::VR128XRegClass ||
25916              Res.second == &X86::VR256XRegClass ||
25917              Res.second == &X86::VR512RegClass) {
25918     // Handle references to XMM physical registers that got mapped into the
25919     // wrong class.  This can happen with constraints like {xmm0} where the
25920     // target independent register mapper will just pick the first match it can
25921     // find, ignoring the required type.
25922
25923     if (VT == MVT::f32 || VT == MVT::i32)
25924       Res.second = &X86::FR32RegClass;
25925     else if (VT == MVT::f64 || VT == MVT::i64)
25926       Res.second = &X86::FR64RegClass;
25927     else if (X86::VR128RegClass.hasType(VT))
25928       Res.second = &X86::VR128RegClass;
25929     else if (X86::VR256RegClass.hasType(VT))
25930       Res.second = &X86::VR256RegClass;
25931     else if (X86::VR512RegClass.hasType(VT))
25932       Res.second = &X86::VR512RegClass;
25933   }
25934
25935   return Res;
25936 }
25937
25938 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25939                                             Type *Ty) const {
25940   // Scaling factors are not free at all.
25941   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25942   // will take 2 allocations in the out of order engine instead of 1
25943   // for plain addressing mode, i.e. inst (reg1).
25944   // E.g.,
25945   // vaddps (%rsi,%drx), %ymm0, %ymm1
25946   // Requires two allocations (one for the load, one for the computation)
25947   // whereas:
25948   // vaddps (%rsi), %ymm0, %ymm1
25949   // Requires just 1 allocation, i.e., freeing allocations for other operations
25950   // and having less micro operations to execute.
25951   //
25952   // For some X86 architectures, this is even worse because for instance for
25953   // stores, the complex addressing mode forces the instruction to use the
25954   // "load" ports instead of the dedicated "store" port.
25955   // E.g., on Haswell:
25956   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25957   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
25958   if (isLegalAddressingMode(AM, Ty))
25959     // Scale represents reg2 * scale, thus account for 1
25960     // as soon as we use a second register.
25961     return AM.Scale != 0;
25962   return -1;
25963 }
25964
25965 bool X86TargetLowering::isTargetFTOL() const {
25966   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25967 }