R600/SI: Try to keep i32 mul on SALU
[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/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "X86IntrinsicsInfo.h"
53 #include <bitset>
54 #include <numeric>
55 #include <cctype>
56 using namespace llvm;
57
58 #define DEBUG_TYPE "x86-isel"
59
60 STATISTIC(NumTailCalls, "Number of tail calls");
61
62 static cl::opt<bool> ExperimentalVectorWideningLegalization(
63     "x86-experimental-vector-widening-legalization", cl::init(false),
64     cl::desc("Enable an experimental vector type legalization through widening "
65              "rather than promotion."),
66     cl::Hidden);
67
68 static cl::opt<bool> ExperimentalVectorShuffleLowering(
69     "x86-experimental-vector-shuffle-lowering", cl::init(false),
70     cl::desc("Enable an experimental vector shuffle lowering code path."),
71     cl::Hidden);
72
73 // Forward declarations.
74 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
75                        SDValue V2);
76
77 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
78                                 SelectionDAG &DAG, SDLoc dl,
79                                 unsigned vectorWidth) {
80   assert((vectorWidth == 128 || vectorWidth == 256) &&
81          "Unsupported vector width");
82   EVT VT = Vec.getValueType();
83   EVT ElVT = VT.getVectorElementType();
84   unsigned Factor = VT.getSizeInBits()/vectorWidth;
85   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
86                                   VT.getVectorNumElements()/Factor);
87
88   // Extract from UNDEF is UNDEF.
89   if (Vec.getOpcode() == ISD::UNDEF)
90     return DAG.getUNDEF(ResultVT);
91
92   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
93   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94
95   // This is the index of the first element of the vectorWidth-bit chunk
96   // we want.
97   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
98                                * ElemsPerChunk);
99
100   // If the input is a buildvector just emit a smaller one.
101   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
102     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
103                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
104                                     ElemsPerChunk));
105
106   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
107   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                VecIdx);
109
110   return Result;
111
112 }
113 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
114 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
115 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
116 /// instructions or a simple subregister reference. Idx is an index in the
117 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
118 /// lowering EXTRACT_VECTOR_ELT operations easier.
119 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
120                                    SelectionDAG &DAG, SDLoc dl) {
121   assert((Vec.getValueType().is256BitVector() ||
122           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
123   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
124 }
125
126 /// Generate a DAG to grab 256-bits from a 512-bit vector.
127 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
128                                    SelectionDAG &DAG, SDLoc dl) {
129   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
130   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
131 }
132
133 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
134                                unsigned IdxVal, SelectionDAG &DAG,
135                                SDLoc dl, unsigned vectorWidth) {
136   assert((vectorWidth == 128 || vectorWidth == 256) &&
137          "Unsupported vector width");
138   // Inserting UNDEF is Result
139   if (Vec.getOpcode() == ISD::UNDEF)
140     return Result;
141   EVT VT = Vec.getValueType();
142   EVT ElVT = VT.getVectorElementType();
143   EVT ResultVT = Result.getValueType();
144
145   // Insert the relevant vectorWidth bits.
146   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147
148   // This is the index of the first element of the vectorWidth-bit chunk
149   // we want.
150   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
151                                * ElemsPerChunk);
152
153   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
154   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                      VecIdx);
156 }
157 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
158 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
159 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
160 /// simple superregister reference.  Idx is an index in the 128 bits
161 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
162 /// lowering INSERT_VECTOR_ELT operations easier.
163 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
164                                   unsigned IdxVal, SelectionDAG &DAG,
165                                   SDLoc dl) {
166   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
167   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
168 }
169
170 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
171                                   unsigned IdxVal, SelectionDAG &DAG,
172                                   SDLoc dl) {
173   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
174   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
175 }
176
177 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
178 /// instructions. This is used because creating CONCAT_VECTOR nodes of
179 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
180 /// large BUILD_VECTORS.
181 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
182                                    unsigned NumElems, SelectionDAG &DAG,
183                                    SDLoc dl) {
184   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
185   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
186 }
187
188 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
189                                    unsigned NumElems, SelectionDAG &DAG,
190                                    SDLoc dl) {
191   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
192   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
193 }
194
195 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
196   if (TT.isOSBinFormatMachO()) {
197     if (TT.getArch() == Triple::x86_64)
198       return new X86_64MachoTargetObjectFile();
199     return new TargetLoweringObjectFileMachO();
200   }
201
202   if (TT.isOSLinux())
203     return new X86LinuxTargetObjectFile();
204   if (TT.isOSBinFormatELF())
205     return new TargetLoweringObjectFileELF();
206   if (TT.isKnownWindowsMSVCEnvironment())
207     return new X86WindowsTargetObjectFile();
208   if (TT.isOSBinFormatCOFF())
209     return new TargetLoweringObjectFileCOFF();
210   llvm_unreachable("unknown subtarget type");
211 }
212
213 // FIXME: This should stop caching the target machine as soon as
214 // we can remove resetOperationActions et al.
215 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
216   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
217   Subtarget = &TM.getSubtarget<X86Subtarget>();
218   X86ScalarSSEf64 = Subtarget->hasSSE2();
219   X86ScalarSSEf32 = Subtarget->hasSSE1();
220   TD = getDataLayout();
221
222   resetOperationActions();
223 }
224
225 void X86TargetLowering::resetOperationActions() {
226   const TargetMachine &TM = getTargetMachine();
227   static bool FirstTimeThrough = true;
228
229   // If none of the target options have changed, then we don't need to reset the
230   // operation actions.
231   if (!FirstTimeThrough && TO == TM.Options) return;
232
233   if (!FirstTimeThrough) {
234     // Reinitialize the actions.
235     initActions();
236     FirstTimeThrough = false;
237   }
238
239   TO = TM.Options;
240
241   // Set up the TargetLowering object.
242   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243
244   // X86 is weird, it always uses i8 for shift amounts and setcc results.
245   setBooleanContents(ZeroOrOneBooleanContent);
246   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
247   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248
249   // For 64-bit since we have so many registers use the ILP scheduler, for
250   // 32-bit code use the register pressure specific scheduling.
251   // For Atom, always use ILP scheduling.
252   if (Subtarget->isAtom())
253     setSchedulingPreference(Sched::ILP);
254   else if (Subtarget->is64Bit())
255     setSchedulingPreference(Sched::ILP);
256   else
257     setSchedulingPreference(Sched::RegPressure);
258   const X86RegisterInfo *RegInfo =
259       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
260   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261
262   // Bypass expensive divides on Atom when compiling with O2
263   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
264     addBypassSlowDiv(32, 8);
265     if (Subtarget->is64Bit())
266       addBypassSlowDiv(64, 16);
267   }
268
269   if (Subtarget->isTargetKnownWindowsMSVC()) {
270     // Setup Windows compiler runtime calls.
271     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
272     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
273     setLibcallName(RTLIB::SREM_I64, "_allrem");
274     setLibcallName(RTLIB::UREM_I64, "_aullrem");
275     setLibcallName(RTLIB::MUL_I64, "_allmul");
276     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
280     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281
282     // The _ftol2 runtime function has an unusual calling conv, which
283     // is modeled by a special pseudo-instruction.
284     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
287     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
288   }
289
290   if (Subtarget->isTargetDarwin()) {
291     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
292     setUseUnderscoreSetJmp(false);
293     setUseUnderscoreLongJmp(false);
294   } else if (Subtarget->isTargetWindowsGNU()) {
295     // MS runtime is weird: it exports _setjmp, but longjmp!
296     setUseUnderscoreSetJmp(true);
297     setUseUnderscoreLongJmp(false);
298   } else {
299     setUseUnderscoreSetJmp(true);
300     setUseUnderscoreLongJmp(true);
301   }
302
303   // Set up the register classes.
304   addRegisterClass(MVT::i8, &X86::GR8RegClass);
305   addRegisterClass(MVT::i16, &X86::GR16RegClass);
306   addRegisterClass(MVT::i32, &X86::GR32RegClass);
307   if (Subtarget->is64Bit())
308     addRegisterClass(MVT::i64, &X86::GR64RegClass);
309
310   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311
312   // We don't accept any truncstore of integer registers.
313   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
315   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
316   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
317   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
318   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
319
320   // SETOEQ and SETUNE require checking two conditions.
321   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
323   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
326   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
327
328   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
329   // operation.
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
332   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
333
334   if (Subtarget->is64Bit()) {
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
336     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
337   } else if (!TM.Options.UseSoftFloat) {
338     // We have an algorithm for SSE2->double, and we turn this into a
339     // 64-bit FILD followed by conditional FADD for other targets.
340     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
341     // We have an algorithm for SSE2, and we turn this into a 64-bit
342     // FILD for other targets.
343     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
344   }
345
346   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
347   // this operation.
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
349   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
350
351   if (!TM.Options.UseSoftFloat) {
352     // SSE has no i16 to fp conversion, only i32
353     if (X86ScalarSSEf32) {
354       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
355       // f32 and f64 cases are Legal, f80 case is not
356       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
357     } else {
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
359       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
360     }
361   } else {
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
363     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
364   }
365
366   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
367   // are Legal, f80 is custom lowered.
368   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
369   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
370
371   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
372   // this operation.
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
374   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
375
376   if (X86ScalarSSEf32) {
377     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
378     // f32 and f64 cases are Legal, f80 case is not
379     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
380   } else {
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
382     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
383   }
384
385   // Handle FP_TO_UINT by promoting the destination to a larger signed
386   // conversion.
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
389   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
390
391   if (Subtarget->is64Bit()) {
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
393     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
394   } else if (!TM.Options.UseSoftFloat) {
395     // Since AVX is a superset of SSE3, only check for SSE here.
396     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
397       // Expand FP_TO_UINT into a select.
398       // FIXME: We would like to use a Custom expander here eventually to do
399       // the optimal thing for SSE vs. the default expansion in the legalizer.
400       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
401     else
402       // With SSE3 we can use fisttpll to convert to a signed i64; without
403       // SSE, we're stuck with a fistpll.
404       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
405   }
406
407   if (isTargetFTOL()) {
408     // Use the _ftol2 runtime function, which has a pseudo-instruction
409     // to handle its weird calling convention.
410     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
411   }
412
413   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
414   if (!X86ScalarSSEf64) {
415     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
416     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
417     if (Subtarget->is64Bit()) {
418       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
419       // Without SSE, i64->f64 goes through memory.
420       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
421     }
422   }
423
424   // Scalar integer divide and remainder are lowered to use operations that
425   // produce two results, to match the available instructions. This exposes
426   // the two-result form to trivial CSE, which is able to combine x/y and x%y
427   // into a single instruction.
428   //
429   // Scalar integer multiply-high is also lowered to use two-result
430   // operations, to match the available instructions. However, plain multiply
431   // (low) operations are left as Legal, as there are single-result
432   // instructions for this in x86. Using the two-result multiply instructions
433   // when both high and low results are needed must be arranged by dagcombine.
434   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
435     MVT VT = IntVTs[i];
436     setOperationAction(ISD::MULHS, VT, Expand);
437     setOperationAction(ISD::MULHU, VT, Expand);
438     setOperationAction(ISD::SDIV, VT, Expand);
439     setOperationAction(ISD::UDIV, VT, Expand);
440     setOperationAction(ISD::SREM, VT, Expand);
441     setOperationAction(ISD::UREM, VT, Expand);
442
443     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
444     setOperationAction(ISD::ADDC, VT, Custom);
445     setOperationAction(ISD::ADDE, VT, Custom);
446     setOperationAction(ISD::SUBC, VT, Custom);
447     setOperationAction(ISD::SUBE, VT, Custom);
448   }
449
450   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
451   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
452   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
458   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
465   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
466   if (Subtarget->is64Bit())
467     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
470   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
471   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
474   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
475   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
476
477   // Promote the i8 variants and force them on up to i32 which has a shorter
478   // encoding.
479   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
480   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
481   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
482   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
483   if (Subtarget->hasBMI()) {
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
485     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
486     if (Subtarget->is64Bit())
487       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
488   } else {
489     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
490     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
491     if (Subtarget->is64Bit())
492       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
493   }
494
495   if (Subtarget->hasLZCNT()) {
496     // When promoting the i8 variants, force them to i32 for a shorter
497     // encoding.
498     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
499     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
500     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
501     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
503     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
504     if (Subtarget->is64Bit())
505       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
506   } else {
507     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
509     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
512     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
513     if (Subtarget->is64Bit()) {
514       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
515       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
516     }
517   }
518
519   // Special handling for half-precision floating point conversions.
520   // If we don't have F16C support, then lower half float conversions
521   // into library calls.
522   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
523     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
524     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
525   }
526
527   // There's never any support for operations beyond MVT::f32.
528   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
529   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
531   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
532
533   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
536   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
537
538   if (Subtarget->hasPOPCNT()) {
539     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
540   } else {
541     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
543     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
544     if (Subtarget->is64Bit())
545       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
546   }
547
548   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
549
550   if (!Subtarget->hasMOVBE())
551     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
552
553   // These should be promoted to a larger select which is supported.
554   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
555   // X86 wants to expand cmov itself.
556   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
561   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
567   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
568   if (Subtarget->is64Bit()) {
569     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
570     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
571   }
572   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
573   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
574   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
575   // support continuation, user-level threading, and etc.. As a result, no
576   // other SjLj exception interfaces are implemented and please don't build
577   // your own exception handling based on them.
578   // LLVM/Clang supports zero-cost DWARF exception handling.
579   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
580   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
581
582   // Darwin ABI issue.
583   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
584   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
586   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
587   if (Subtarget->is64Bit())
588     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
589   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
590   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
591   if (Subtarget->is64Bit()) {
592     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
593     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
594     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
595     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
596     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
597   }
598   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
599   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
601   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
602   if (Subtarget->is64Bit()) {
603     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
605     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
606   }
607
608   if (Subtarget->hasSSE1())
609     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
610
611   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
612
613   // Expand certain atomics
614   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
615     MVT VT = IntVTs[i];
616     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
617     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
618     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
619   }
620
621   if (Subtarget->hasCmpxchg16b()) {
622     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
623   }
624
625   // FIXME - use subtarget debug flags
626   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
627       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
628     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
629   }
630
631   if (Subtarget->is64Bit()) {
632     setExceptionPointerRegister(X86::RAX);
633     setExceptionSelectorRegister(X86::RDX);
634   } else {
635     setExceptionPointerRegister(X86::EAX);
636     setExceptionSelectorRegister(X86::EDX);
637   }
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
639   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
640
641   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
642   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
643
644   setOperationAction(ISD::TRAP, MVT::Other, Legal);
645   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
646
647   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
648   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
649   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
650   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
651     // TargetInfo::X86_64ABIBuiltinVaList
652     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
653     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
654   } else {
655     // TargetInfo::CharPtrBuiltinVaList
656     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
657     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
658   }
659
660   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
661   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
662
663   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
664
665   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666     // f32 and f64 use SSE.
667     // Set up the FP register classes.
668     addRegisterClass(MVT::f32, &X86::FR32RegClass);
669     addRegisterClass(MVT::f64, &X86::FR64RegClass);
670
671     // Use ANDPD to simulate FABS.
672     setOperationAction(ISD::FABS , MVT::f64, Custom);
673     setOperationAction(ISD::FABS , MVT::f32, Custom);
674
675     // Use XORP to simulate FNEG.
676     setOperationAction(ISD::FNEG , MVT::f64, Custom);
677     setOperationAction(ISD::FNEG , MVT::f32, Custom);
678
679     // Use ANDPD and ORPD to simulate FCOPYSIGN.
680     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682
683     // Lower this to FGETSIGNx86 plus an AND.
684     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686
687     // We don't support sin/cos/fmod
688     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
689     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694
695     // Expand FP immediates into loads from the stack, except for the special
696     // cases we handle.
697     addLegalFPImmediate(APFloat(+0.0)); // xorpd
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700     // Use SSE for f32, x87 for f64.
701     // Set up the FP register classes.
702     addRegisterClass(MVT::f32, &X86::FR32RegClass);
703     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704
705     // Use ANDPS to simulate FABS.
706     setOperationAction(ISD::FABS , MVT::f32, Custom);
707
708     // Use XORP to simulate FNEG.
709     setOperationAction(ISD::FNEG , MVT::f32, Custom);
710
711     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
712
713     // Use ANDPS and ORPS to simulate FCOPYSIGN.
714     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716
717     // We don't support sin/cos/fmod
718     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
719     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
720     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721
722     // Special cases we handle for FP constants.
723     addLegalFPImmediate(APFloat(+0.0f)); // xorps
724     addLegalFPImmediate(APFloat(+0.0)); // FLD0
725     addLegalFPImmediate(APFloat(+1.0)); // FLD1
726     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733     }
734   } else if (!TM.Options.UseSoftFloat) {
735     // f32 and f64 in x87.
736     // Set up the FP register classes.
737     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739
740     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
741     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744
745     if (!TM.Options.UnsafeFPMath) {
746       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
747       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
749       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752     }
753     addLegalFPImmediate(APFloat(+0.0)); // FLD0
754     addLegalFPImmediate(APFloat(+1.0)); // FLD1
755     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
761   }
762
763   // We don't support FMA.
764   setOperationAction(ISD::FMA, MVT::f64, Expand);
765   setOperationAction(ISD::FMA, MVT::f32, Expand);
766
767   // Long double always uses X87.
768   if (!TM.Options.UseSoftFloat) {
769     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
771     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772     {
773       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774       addLegalFPImmediate(TmpFlt);  // FLD0
775       TmpFlt.changeSign();
776       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
777
778       bool ignored;
779       APFloat TmpFlt2(+1.0);
780       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781                       &ignored);
782       addLegalFPImmediate(TmpFlt2);  // FLD1
783       TmpFlt2.changeSign();
784       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
785     }
786
787     if (!TM.Options.UnsafeFPMath) {
788       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
789       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
790       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
791     }
792
793     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
795     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
797     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798     setOperationAction(ISD::FMA, MVT::f80, Expand);
799   }
800
801   // Always use a library call for pow.
802   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
804   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
805
806   setOperationAction(ISD::FLOG, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP, MVT::f80, Expand);
810   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811
812   // First set operation action for all vector types to either promote
813   // (for widening) or expand (for scalarization). Then we will selectively
814   // turn on ones that can be effectively codegen'd.
815   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817     MVT VT = (MVT::SimpleValueType)i;
818     setOperationAction(ISD::ADD , VT, Expand);
819     setOperationAction(ISD::SUB , VT, Expand);
820     setOperationAction(ISD::FADD, VT, Expand);
821     setOperationAction(ISD::FNEG, VT, Expand);
822     setOperationAction(ISD::FSUB, VT, Expand);
823     setOperationAction(ISD::MUL , VT, Expand);
824     setOperationAction(ISD::FMUL, VT, Expand);
825     setOperationAction(ISD::SDIV, VT, Expand);
826     setOperationAction(ISD::UDIV, VT, Expand);
827     setOperationAction(ISD::FDIV, VT, Expand);
828     setOperationAction(ISD::SREM, VT, Expand);
829     setOperationAction(ISD::UREM, VT, Expand);
830     setOperationAction(ISD::LOAD, VT, Expand);
831     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836     setOperationAction(ISD::FABS, VT, Expand);
837     setOperationAction(ISD::FSIN, VT, Expand);
838     setOperationAction(ISD::FSINCOS, VT, Expand);
839     setOperationAction(ISD::FCOS, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FREM, VT, Expand);
842     setOperationAction(ISD::FMA,  VT, Expand);
843     setOperationAction(ISD::FPOWI, VT, Expand);
844     setOperationAction(ISD::FSQRT, VT, Expand);
845     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846     setOperationAction(ISD::FFLOOR, VT, Expand);
847     setOperationAction(ISD::FCEIL, VT, Expand);
848     setOperationAction(ISD::FTRUNC, VT, Expand);
849     setOperationAction(ISD::FRINT, VT, Expand);
850     setOperationAction(ISD::FNEARBYINT, VT, Expand);
851     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852     setOperationAction(ISD::MULHS, VT, Expand);
853     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHU, VT, Expand);
855     setOperationAction(ISD::SDIVREM, VT, Expand);
856     setOperationAction(ISD::UDIVREM, VT, Expand);
857     setOperationAction(ISD::FPOW, VT, Expand);
858     setOperationAction(ISD::CTPOP, VT, Expand);
859     setOperationAction(ISD::CTTZ, VT, Expand);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861     setOperationAction(ISD::CTLZ, VT, Expand);
862     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::SHL, VT, Expand);
864     setOperationAction(ISD::SRA, VT, Expand);
865     setOperationAction(ISD::SRL, VT, Expand);
866     setOperationAction(ISD::ROTL, VT, Expand);
867     setOperationAction(ISD::ROTR, VT, Expand);
868     setOperationAction(ISD::BSWAP, VT, Expand);
869     setOperationAction(ISD::SETCC, VT, Expand);
870     setOperationAction(ISD::FLOG, VT, Expand);
871     setOperationAction(ISD::FLOG2, VT, Expand);
872     setOperationAction(ISD::FLOG10, VT, Expand);
873     setOperationAction(ISD::FEXP, VT, Expand);
874     setOperationAction(ISD::FEXP2, VT, Expand);
875     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880     setOperationAction(ISD::TRUNCATE, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884     setOperationAction(ISD::VSELECT, VT, Expand);
885     setOperationAction(ISD::SELECT_CC, VT, Expand);
886     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888       setTruncStoreAction(VT,
889                           (MVT::SimpleValueType)InnerVT, Expand);
890     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892
893     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894     // we have to deal with them whether we ask for Expansion or not. Setting
895     // Expand causes its own optimisation problems though, so leave them legal.
896     if (VT.getVectorElementType() == MVT::i1)
897       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
898   }
899
900   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901   // with -msoft-float, disable use of MMX as well.
902   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904     // No operations on x86mmx supported, everything uses intrinsics.
905   }
906
907   // MMX-sized vectors (other than x86mmx) are expected to be expanded
908   // into smaller operations.
909   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
910   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
912   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
913   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
914   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
915   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
916   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
917   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
918   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
919   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
920   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
921   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
922   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
923   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
924   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
929   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
930   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
931   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
938
939   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941
942     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
947     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
948     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
949     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
950     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
951     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
954   }
955
956   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958
959     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
960     // registers cannot be used even for integer operations.
961     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965
966     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
967     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
968     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
969     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
971     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
972     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
974     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
975     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
976     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
977     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
978     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
979     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
980     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
981     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
986     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
987     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
988
989     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
992     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
993
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
995     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002       MVT VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-power-of-2 vectors
1004       if (!isPowerOf2_32(VT.getVectorNumElements()))
1005         continue;
1006       // Do not attempt to custom lower non-128-bit vectors
1007       if (!VT.is128BitVector())
1008         continue;
1009       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1010       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012     }
1013
1014     // We support custom legalizing of sext and anyext loads for specific
1015     // memory vector types which we can load as a scalar (or sequence of
1016     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017     // loads these must work with a single scalar load.
1018     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1020     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1021     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1022     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1027
1028     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1029     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1030     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1031     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1032     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1033     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1034
1035     if (Subtarget->is64Bit()) {
1036       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1037       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1038     }
1039
1040     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1041     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1042       MVT VT = (MVT::SimpleValueType)i;
1043
1044       // Do not attempt to promote non-128-bit vectors
1045       if (!VT.is128BitVector())
1046         continue;
1047
1048       setOperationAction(ISD::AND,    VT, Promote);
1049       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1050       setOperationAction(ISD::OR,     VT, Promote);
1051       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1052       setOperationAction(ISD::XOR,    VT, Promote);
1053       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1054       setOperationAction(ISD::LOAD,   VT, Promote);
1055       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1056       setOperationAction(ISD::SELECT, VT, Promote);
1057       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1058     }
1059
1060     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1061
1062     // Custom lower v2i64 and v2f64 selects.
1063     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1064     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1065     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1066     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1067
1068     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1069     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1070
1071     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1073     // As there is no 64-bit GPR available, we need build a special custom
1074     // sequence to convert from v2i32 to v2f32.
1075     if (!Subtarget->is64Bit())
1076       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1077
1078     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1079     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1080
1081     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1082
1083     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1084     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1085     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1086   }
1087
1088   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1089     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1090     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1091     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1094     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1095     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1096     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1099
1100     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1101     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1102     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1105     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1106     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1107     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1110
1111     // FIXME: Do we need to handle scalar-to-vector here?
1112     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1113
1114     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1115     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1116     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1119     // There is no BLENDI for byte vectors. We don't need to custom lower
1120     // some vselects for now.
1121     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1122
1123     // SSE41 brings specific instructions for doing vector sign extend even in
1124     // cases where we don't have SRA.
1125     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1126     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1128
1129     // i8 and i16 vectors are custom because the source register and source
1130     // source memory operand types are not the same width.  f32 vectors are
1131     // custom since the immediate controlling the insert encodes additional
1132     // information.
1133     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1134     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1137
1138     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1139     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1142
1143     // FIXME: these should be Legal, but that's only for the case where
1144     // the index is constant.  For now custom expand to deal with that.
1145     if (Subtarget->is64Bit()) {
1146       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1147       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1148     }
1149   }
1150
1151   if (Subtarget->hasSSE2()) {
1152     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1153     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1154
1155     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1156     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1157
1158     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1159     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1160
1161     // In the customized shift lowering, the legal cases in AVX2 will be
1162     // recognized.
1163     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1164     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1165
1166     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1167     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1168
1169     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1170   }
1171
1172   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1173     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1174     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1175     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1177     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1179
1180     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1181     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1182     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1183
1184     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1185     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1186     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1189     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1190     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1194     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1195     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1196
1197     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1198     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1199     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1202     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1203     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1207     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1208     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1209
1210     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1211     // even though v8i16 is a legal type.
1212     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1213     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1215
1216     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1217     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1218     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1219
1220     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1221     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1222
1223     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1224
1225     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1226     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1227
1228     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1229     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1230
1231     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1232     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1233
1234     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1235     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1236     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1238
1239     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1240     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1241     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1242
1243     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1244     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1245     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1247
1248     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1249     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1251     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1252     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1254     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1255     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1257     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1258     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1260
1261     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1262       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1263       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1264       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1268     }
1269
1270     if (Subtarget->hasInt256()) {
1271       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1272       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1273       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1275
1276       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1277       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1278       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1280
1281       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1282       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1283       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1284       // Don't lower v32i8 because there is no 128-bit byte mul
1285
1286       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1287       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1288       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1289       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1290
1291       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1292       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1293     } else {
1294       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1295       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1296       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1298
1299       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1300       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1301       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1303
1304       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1305       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1306       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1307       // Don't lower v32i8 because there is no 128-bit byte mul
1308     }
1309
1310     // In the customized shift lowering, the legal cases in AVX2 will be
1311     // recognized.
1312     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1313     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1314
1315     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1316     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1317
1318     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1319
1320     // Custom lower several nodes for 256-bit types.
1321     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1322              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1323       MVT VT = (MVT::SimpleValueType)i;
1324
1325       // Extract subvector is special because the value type
1326       // (result) is 128-bit but the source is 256-bit wide.
1327       if (VT.is128BitVector())
1328         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1329
1330       // Do not attempt to custom lower other non-256-bit vectors
1331       if (!VT.is256BitVector())
1332         continue;
1333
1334       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1335       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1336       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1337       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1338       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1339       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1340       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1341     }
1342
1343     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1344     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1345       MVT VT = (MVT::SimpleValueType)i;
1346
1347       // Do not attempt to promote non-256-bit vectors
1348       if (!VT.is256BitVector())
1349         continue;
1350
1351       setOperationAction(ISD::AND,    VT, Promote);
1352       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1353       setOperationAction(ISD::OR,     VT, Promote);
1354       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1355       setOperationAction(ISD::XOR,    VT, Promote);
1356       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1357       setOperationAction(ISD::LOAD,   VT, Promote);
1358       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1359       setOperationAction(ISD::SELECT, VT, Promote);
1360       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1361     }
1362   }
1363
1364   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1365     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1366     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1369
1370     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1371     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1372     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1373
1374     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1375     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1376     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1377     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1378     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1379     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1380     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1385
1386     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1387     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1391     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1392
1393     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1394     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1398     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1399     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1400     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1401
1402     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1403     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1405     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1406     if (Subtarget->is64Bit()) {
1407       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1408       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1410       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1411     }
1412     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1413     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1416     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1417     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1418     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1420     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1421     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1422
1423     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1424     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1425     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1429     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1431     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1436
1437     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1443
1444     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1445     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1446
1447     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1448
1449     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1451     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1453     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1455     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1458
1459     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1460     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1461
1462     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1463     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1464
1465     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1468     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1469
1470     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1471     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1472
1473     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1474     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1475
1476     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1477     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1478     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1480     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1481     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1482
1483     if (Subtarget->hasCDI()) {
1484       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1485       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1486     }
1487
1488     // Custom lower several nodes.
1489     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1490              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1491       MVT VT = (MVT::SimpleValueType)i;
1492
1493       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1494       // Extract subvector is special because the value type
1495       // (result) is 256/128-bit but the source is 512-bit wide.
1496       if (VT.is128BitVector() || VT.is256BitVector())
1497         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1498
1499       if (VT.getVectorElementType() == MVT::i1)
1500         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1501
1502       // Do not attempt to custom lower other non-512-bit vectors
1503       if (!VT.is512BitVector())
1504         continue;
1505
1506       if ( EltSize >= 32) {
1507         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1508         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1509         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1510         setOperationAction(ISD::VSELECT,             VT, Legal);
1511         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1512         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1513         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1514       }
1515     }
1516     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1517       MVT VT = (MVT::SimpleValueType)i;
1518
1519       // Do not attempt to promote non-256-bit vectors
1520       if (!VT.is512BitVector())
1521         continue;
1522
1523       setOperationAction(ISD::SELECT, VT, Promote);
1524       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1525     }
1526   }// has  AVX-512
1527
1528   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1529     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1530     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1531
1532     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1533     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1534
1535     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1536     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1537     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1538     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1539
1540     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1541       const MVT VT = (MVT::SimpleValueType)i;
1542
1543       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1544
1545       // Do not attempt to promote non-256-bit vectors
1546       if (!VT.is512BitVector())
1547         continue;
1548
1549       if ( EltSize < 32) {
1550         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1551         setOperationAction(ISD::VSELECT,             VT, Legal);
1552       }
1553     }
1554   }
1555
1556   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1557     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1558     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1559
1560     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1561     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1562   }
1563
1564   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1565   // of this type with custom code.
1566   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1567            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1568     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1569                        Custom);
1570   }
1571
1572   // We want to custom lower some of our intrinsics.
1573   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1574   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1575   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1576   if (!Subtarget->is64Bit())
1577     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1578
1579   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1580   // handle type legalization for these operations here.
1581   //
1582   // FIXME: We really should do custom legalization for addition and
1583   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1584   // than generic legalization for 64-bit multiplication-with-overflow, though.
1585   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1586     // Add/Sub/Mul with overflow operations are custom lowered.
1587     MVT VT = IntVTs[i];
1588     setOperationAction(ISD::SADDO, VT, Custom);
1589     setOperationAction(ISD::UADDO, VT, Custom);
1590     setOperationAction(ISD::SSUBO, VT, Custom);
1591     setOperationAction(ISD::USUBO, VT, Custom);
1592     setOperationAction(ISD::SMULO, VT, Custom);
1593     setOperationAction(ISD::UMULO, VT, Custom);
1594   }
1595
1596   // There are no 8-bit 3-address imul/mul instructions
1597   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1598   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1599
1600   if (!Subtarget->is64Bit()) {
1601     // These libcalls are not available in 32-bit.
1602     setLibcallName(RTLIB::SHL_I128, nullptr);
1603     setLibcallName(RTLIB::SRL_I128, nullptr);
1604     setLibcallName(RTLIB::SRA_I128, nullptr);
1605   }
1606
1607   // Combine sin / cos into one node or libcall if possible.
1608   if (Subtarget->hasSinCos()) {
1609     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1610     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1611     if (Subtarget->isTargetDarwin()) {
1612       // For MacOSX, we don't want to the normal expansion of a libcall to
1613       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1614       // traffic.
1615       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1616       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1617     }
1618   }
1619
1620   if (Subtarget->isTargetWin64()) {
1621     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1622     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1623     setOperationAction(ISD::SREM, MVT::i128, Custom);
1624     setOperationAction(ISD::UREM, MVT::i128, Custom);
1625     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1626     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1627   }
1628
1629   // We have target-specific dag combine patterns for the following nodes:
1630   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1631   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1632   setTargetDAGCombine(ISD::VSELECT);
1633   setTargetDAGCombine(ISD::SELECT);
1634   setTargetDAGCombine(ISD::SHL);
1635   setTargetDAGCombine(ISD::SRA);
1636   setTargetDAGCombine(ISD::SRL);
1637   setTargetDAGCombine(ISD::OR);
1638   setTargetDAGCombine(ISD::AND);
1639   setTargetDAGCombine(ISD::ADD);
1640   setTargetDAGCombine(ISD::FADD);
1641   setTargetDAGCombine(ISD::FSUB);
1642   setTargetDAGCombine(ISD::FMA);
1643   setTargetDAGCombine(ISD::SUB);
1644   setTargetDAGCombine(ISD::LOAD);
1645   setTargetDAGCombine(ISD::STORE);
1646   setTargetDAGCombine(ISD::ZERO_EXTEND);
1647   setTargetDAGCombine(ISD::ANY_EXTEND);
1648   setTargetDAGCombine(ISD::SIGN_EXTEND);
1649   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1650   setTargetDAGCombine(ISD::TRUNCATE);
1651   setTargetDAGCombine(ISD::SINT_TO_FP);
1652   setTargetDAGCombine(ISD::SETCC);
1653   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1654   setTargetDAGCombine(ISD::BUILD_VECTOR);
1655   if (Subtarget->is64Bit())
1656     setTargetDAGCombine(ISD::MUL);
1657   setTargetDAGCombine(ISD::XOR);
1658
1659   computeRegisterProperties();
1660
1661   // On Darwin, -Os means optimize for size without hurting performance,
1662   // do not reduce the limit.
1663   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1664   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1665   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1666   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1667   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1668   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1669   setPrefLoopAlignment(4); // 2^4 bytes.
1670
1671   // Predictable cmov don't hurt on atom because it's in-order.
1672   PredictableSelectIsExpensive = !Subtarget->isAtom();
1673
1674   setPrefFunctionAlignment(4); // 2^4 bytes.
1675
1676   InitIntrinsicTables();
1677 }
1678
1679 // This has so far only been implemented for 64-bit MachO.
1680 bool X86TargetLowering::useLoadStackGuardNode() const {
1681   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1682          Subtarget->is64Bit();
1683 }
1684
1685 TargetLoweringBase::LegalizeTypeAction
1686 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1687   if (ExperimentalVectorWideningLegalization &&
1688       VT.getVectorNumElements() != 1 &&
1689       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1690     return TypeWidenVector;
1691
1692   return TargetLoweringBase::getPreferredVectorAction(VT);
1693 }
1694
1695 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1696   if (!VT.isVector())
1697     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1698
1699   const unsigned NumElts = VT.getVectorNumElements();
1700   const EVT EltVT = VT.getVectorElementType();
1701   if (VT.is512BitVector()) {
1702     if (Subtarget->hasAVX512())
1703       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1704           EltVT == MVT::f32 || EltVT == MVT::f64)
1705         switch(NumElts) {
1706         case  8: return MVT::v8i1;
1707         case 16: return MVT::v16i1;
1708       }
1709     if (Subtarget->hasBWI())
1710       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1711         switch(NumElts) {
1712         case 32: return MVT::v32i1;
1713         case 64: return MVT::v64i1;
1714       }
1715   }
1716
1717   if (VT.is256BitVector() || VT.is128BitVector()) {
1718     if (Subtarget->hasVLX())
1719       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1720           EltVT == MVT::f32 || EltVT == MVT::f64)
1721         switch(NumElts) {
1722         case 2: return MVT::v2i1;
1723         case 4: return MVT::v4i1;
1724         case 8: return MVT::v8i1;
1725       }
1726     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1727       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1728         switch(NumElts) {
1729         case  8: return MVT::v8i1;
1730         case 16: return MVT::v16i1;
1731         case 32: return MVT::v32i1;
1732       }
1733   }
1734
1735   return VT.changeVectorElementTypeToInteger();
1736 }
1737
1738 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1739 /// the desired ByVal argument alignment.
1740 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1741   if (MaxAlign == 16)
1742     return;
1743   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1744     if (VTy->getBitWidth() == 128)
1745       MaxAlign = 16;
1746   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1747     unsigned EltAlign = 0;
1748     getMaxByValAlign(ATy->getElementType(), EltAlign);
1749     if (EltAlign > MaxAlign)
1750       MaxAlign = EltAlign;
1751   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1752     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1753       unsigned EltAlign = 0;
1754       getMaxByValAlign(STy->getElementType(i), EltAlign);
1755       if (EltAlign > MaxAlign)
1756         MaxAlign = EltAlign;
1757       if (MaxAlign == 16)
1758         break;
1759     }
1760   }
1761 }
1762
1763 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1764 /// function arguments in the caller parameter area. For X86, aggregates
1765 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1766 /// are at 4-byte boundaries.
1767 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1768   if (Subtarget->is64Bit()) {
1769     // Max of 8 and alignment of type.
1770     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1771     if (TyAlign > 8)
1772       return TyAlign;
1773     return 8;
1774   }
1775
1776   unsigned Align = 4;
1777   if (Subtarget->hasSSE1())
1778     getMaxByValAlign(Ty, Align);
1779   return Align;
1780 }
1781
1782 /// getOptimalMemOpType - Returns the target specific optimal type for load
1783 /// and store operations as a result of memset, memcpy, and memmove
1784 /// lowering. If DstAlign is zero that means it's safe to destination
1785 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1786 /// means there isn't a need to check it against alignment requirement,
1787 /// probably because the source does not need to be loaded. If 'IsMemset' is
1788 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1789 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1790 /// source is constant so it does not need to be loaded.
1791 /// It returns EVT::Other if the type should be determined using generic
1792 /// target-independent logic.
1793 EVT
1794 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1795                                        unsigned DstAlign, unsigned SrcAlign,
1796                                        bool IsMemset, bool ZeroMemset,
1797                                        bool MemcpyStrSrc,
1798                                        MachineFunction &MF) const {
1799   const Function *F = MF.getFunction();
1800   if ((!IsMemset || ZeroMemset) &&
1801       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1802                                        Attribute::NoImplicitFloat)) {
1803     if (Size >= 16 &&
1804         (Subtarget->isUnalignedMemAccessFast() ||
1805          ((DstAlign == 0 || DstAlign >= 16) &&
1806           (SrcAlign == 0 || SrcAlign >= 16)))) {
1807       if (Size >= 32) {
1808         if (Subtarget->hasInt256())
1809           return MVT::v8i32;
1810         if (Subtarget->hasFp256())
1811           return MVT::v8f32;
1812       }
1813       if (Subtarget->hasSSE2())
1814         return MVT::v4i32;
1815       if (Subtarget->hasSSE1())
1816         return MVT::v4f32;
1817     } else if (!MemcpyStrSrc && Size >= 8 &&
1818                !Subtarget->is64Bit() &&
1819                Subtarget->hasSSE2()) {
1820       // Do not use f64 to lower memcpy if source is string constant. It's
1821       // better to use i32 to avoid the loads.
1822       return MVT::f64;
1823     }
1824   }
1825   if (Subtarget->is64Bit() && Size >= 8)
1826     return MVT::i64;
1827   return MVT::i32;
1828 }
1829
1830 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1831   if (VT == MVT::f32)
1832     return X86ScalarSSEf32;
1833   else if (VT == MVT::f64)
1834     return X86ScalarSSEf64;
1835   return true;
1836 }
1837
1838 bool
1839 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1840                                                   unsigned,
1841                                                   unsigned,
1842                                                   bool *Fast) const {
1843   if (Fast)
1844     *Fast = Subtarget->isUnalignedMemAccessFast();
1845   return true;
1846 }
1847
1848 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1849 /// current function.  The returned value is a member of the
1850 /// MachineJumpTableInfo::JTEntryKind enum.
1851 unsigned X86TargetLowering::getJumpTableEncoding() const {
1852   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1853   // symbol.
1854   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1855       Subtarget->isPICStyleGOT())
1856     return MachineJumpTableInfo::EK_Custom32;
1857
1858   // Otherwise, use the normal jump table encoding heuristics.
1859   return TargetLowering::getJumpTableEncoding();
1860 }
1861
1862 const MCExpr *
1863 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1864                                              const MachineBasicBlock *MBB,
1865                                              unsigned uid,MCContext &Ctx) const{
1866   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1867          Subtarget->isPICStyleGOT());
1868   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1869   // entries.
1870   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1871                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1872 }
1873
1874 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1875 /// jumptable.
1876 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1877                                                     SelectionDAG &DAG) const {
1878   if (!Subtarget->is64Bit())
1879     // This doesn't have SDLoc associated with it, but is not really the
1880     // same as a Register.
1881     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1882   return Table;
1883 }
1884
1885 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1886 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1887 /// MCExpr.
1888 const MCExpr *X86TargetLowering::
1889 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1890                              MCContext &Ctx) const {
1891   // X86-64 uses RIP relative addressing based on the jump table label.
1892   if (Subtarget->isPICStyleRIPRel())
1893     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1894
1895   // Otherwise, the reference is relative to the PIC base.
1896   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1897 }
1898
1899 // FIXME: Why this routine is here? Move to RegInfo!
1900 std::pair<const TargetRegisterClass*, uint8_t>
1901 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1902   const TargetRegisterClass *RRC = nullptr;
1903   uint8_t Cost = 1;
1904   switch (VT.SimpleTy) {
1905   default:
1906     return TargetLowering::findRepresentativeClass(VT);
1907   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1908     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1909     break;
1910   case MVT::x86mmx:
1911     RRC = &X86::VR64RegClass;
1912     break;
1913   case MVT::f32: case MVT::f64:
1914   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1915   case MVT::v4f32: case MVT::v2f64:
1916   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1917   case MVT::v4f64:
1918     RRC = &X86::VR128RegClass;
1919     break;
1920   }
1921   return std::make_pair(RRC, Cost);
1922 }
1923
1924 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1925                                                unsigned &Offset) const {
1926   if (!Subtarget->isTargetLinux())
1927     return false;
1928
1929   if (Subtarget->is64Bit()) {
1930     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1931     Offset = 0x28;
1932     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1933       AddressSpace = 256;
1934     else
1935       AddressSpace = 257;
1936   } else {
1937     // %gs:0x14 on i386
1938     Offset = 0x14;
1939     AddressSpace = 256;
1940   }
1941   return true;
1942 }
1943
1944 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1945                                             unsigned DestAS) const {
1946   assert(SrcAS != DestAS && "Expected different address spaces!");
1947
1948   return SrcAS < 256 && DestAS < 256;
1949 }
1950
1951 //===----------------------------------------------------------------------===//
1952 //               Return Value Calling Convention Implementation
1953 //===----------------------------------------------------------------------===//
1954
1955 #include "X86GenCallingConv.inc"
1956
1957 bool
1958 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1959                                   MachineFunction &MF, bool isVarArg,
1960                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1961                         LLVMContext &Context) const {
1962   SmallVector<CCValAssign, 16> RVLocs;
1963   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1964   return CCInfo.CheckReturn(Outs, RetCC_X86);
1965 }
1966
1967 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1968   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1969   return ScratchRegs;
1970 }
1971
1972 SDValue
1973 X86TargetLowering::LowerReturn(SDValue Chain,
1974                                CallingConv::ID CallConv, bool isVarArg,
1975                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1976                                const SmallVectorImpl<SDValue> &OutVals,
1977                                SDLoc dl, SelectionDAG &DAG) const {
1978   MachineFunction &MF = DAG.getMachineFunction();
1979   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1980
1981   SmallVector<CCValAssign, 16> RVLocs;
1982   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1983   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1984
1985   SDValue Flag;
1986   SmallVector<SDValue, 6> RetOps;
1987   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1988   // Operand #1 = Bytes To Pop
1989   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1990                    MVT::i16));
1991
1992   // Copy the result values into the output registers.
1993   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1994     CCValAssign &VA = RVLocs[i];
1995     assert(VA.isRegLoc() && "Can only return in registers!");
1996     SDValue ValToCopy = OutVals[i];
1997     EVT ValVT = ValToCopy.getValueType();
1998
1999     // Promote values to the appropriate types
2000     if (VA.getLocInfo() == CCValAssign::SExt)
2001       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2002     else if (VA.getLocInfo() == CCValAssign::ZExt)
2003       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2004     else if (VA.getLocInfo() == CCValAssign::AExt)
2005       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2006     else if (VA.getLocInfo() == CCValAssign::BCvt)
2007       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2008
2009     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2010            "Unexpected FP-extend for return value.");  
2011
2012     // If this is x86-64, and we disabled SSE, we can't return FP values,
2013     // or SSE or MMX vectors.
2014     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2015          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2016           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2017       report_fatal_error("SSE register return with SSE disabled");
2018     }
2019     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2020     // llvm-gcc has never done it right and no one has noticed, so this
2021     // should be OK for now.
2022     if (ValVT == MVT::f64 &&
2023         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2024       report_fatal_error("SSE2 register return with SSE2 disabled");
2025
2026     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2027     // the RET instruction and handled by the FP Stackifier.
2028     if (VA.getLocReg() == X86::FP0 ||
2029         VA.getLocReg() == X86::FP1) {
2030       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2031       // change the value to the FP stack register class.
2032       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2033         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2034       RetOps.push_back(ValToCopy);
2035       // Don't emit a copytoreg.
2036       continue;
2037     }
2038
2039     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2040     // which is returned in RAX / RDX.
2041     if (Subtarget->is64Bit()) {
2042       if (ValVT == MVT::x86mmx) {
2043         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2044           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2045           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2046                                   ValToCopy);
2047           // If we don't have SSE2 available, convert to v4f32 so the generated
2048           // register is legal.
2049           if (!Subtarget->hasSSE2())
2050             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2051         }
2052       }
2053     }
2054
2055     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2056     Flag = Chain.getValue(1);
2057     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2058   }
2059
2060   // The x86-64 ABIs require that for returning structs by value we copy
2061   // the sret argument into %rax/%eax (depending on ABI) for the return.
2062   // Win32 requires us to put the sret argument to %eax as well.
2063   // We saved the argument into a virtual register in the entry block,
2064   // so now we copy the value out and into %rax/%eax.
2065   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2066       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2067     MachineFunction &MF = DAG.getMachineFunction();
2068     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2069     unsigned Reg = FuncInfo->getSRetReturnReg();
2070     assert(Reg &&
2071            "SRetReturnReg should have been set in LowerFormalArguments().");
2072     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2073
2074     unsigned RetValReg
2075         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2076           X86::RAX : X86::EAX;
2077     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2078     Flag = Chain.getValue(1);
2079
2080     // RAX/EAX now acts like a return value.
2081     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2082   }
2083
2084   RetOps[0] = Chain;  // Update chain.
2085
2086   // Add the flag if we have it.
2087   if (Flag.getNode())
2088     RetOps.push_back(Flag);
2089
2090   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2091 }
2092
2093 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2094   if (N->getNumValues() != 1)
2095     return false;
2096   if (!N->hasNUsesOfValue(1, 0))
2097     return false;
2098
2099   SDValue TCChain = Chain;
2100   SDNode *Copy = *N->use_begin();
2101   if (Copy->getOpcode() == ISD::CopyToReg) {
2102     // If the copy has a glue operand, we conservatively assume it isn't safe to
2103     // perform a tail call.
2104     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2105       return false;
2106     TCChain = Copy->getOperand(0);
2107   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2108     return false;
2109
2110   bool HasRet = false;
2111   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2112        UI != UE; ++UI) {
2113     if (UI->getOpcode() != X86ISD::RET_FLAG)
2114       return false;
2115     // If we are returning more than one value, we can definitely
2116     // not make a tail call see PR19530
2117     if (UI->getNumOperands() > 4)
2118       return false;
2119     if (UI->getNumOperands() == 4 &&
2120         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2121       return false;
2122     HasRet = true;
2123   }
2124
2125   if (!HasRet)
2126     return false;
2127
2128   Chain = TCChain;
2129   return true;
2130 }
2131
2132 EVT
2133 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2134                                             ISD::NodeType ExtendKind) const {
2135   MVT ReturnMVT;
2136   // TODO: Is this also valid on 32-bit?
2137   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2138     ReturnMVT = MVT::i8;
2139   else
2140     ReturnMVT = MVT::i32;
2141
2142   EVT MinVT = getRegisterType(Context, ReturnMVT);
2143   return VT.bitsLT(MinVT) ? MinVT : VT;
2144 }
2145
2146 /// LowerCallResult - Lower the result values of a call into the
2147 /// appropriate copies out of appropriate physical registers.
2148 ///
2149 SDValue
2150 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2151                                    CallingConv::ID CallConv, bool isVarArg,
2152                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2153                                    SDLoc dl, SelectionDAG &DAG,
2154                                    SmallVectorImpl<SDValue> &InVals) const {
2155
2156   // Assign locations to each value returned by this call.
2157   SmallVector<CCValAssign, 16> RVLocs;
2158   bool Is64Bit = Subtarget->is64Bit();
2159   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2160                  *DAG.getContext());
2161   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2162
2163   // Copy all of the result registers out of their specified physreg.
2164   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2165     CCValAssign &VA = RVLocs[i];
2166     EVT CopyVT = VA.getValVT();
2167
2168     // If this is x86-64, and we disabled SSE, we can't return FP values
2169     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2170         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2171       report_fatal_error("SSE register return with SSE disabled");
2172     }
2173
2174     // If we prefer to use the value in xmm registers, copy it out as f80 and
2175     // use a truncate to move it from fp stack reg to xmm reg.
2176     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2177         isScalarFPTypeInSSEReg(VA.getValVT()))
2178       CopyVT = MVT::f80;
2179
2180     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2181                                CopyVT, InFlag).getValue(1);
2182     SDValue Val = Chain.getValue(0);
2183
2184     if (CopyVT != VA.getValVT())
2185       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2186                         // This truncation won't change the value.
2187                         DAG.getIntPtrConstant(1));
2188
2189     InFlag = Chain.getValue(2);
2190     InVals.push_back(Val);
2191   }
2192
2193   return Chain;
2194 }
2195
2196 //===----------------------------------------------------------------------===//
2197 //                C & StdCall & Fast Calling Convention implementation
2198 //===----------------------------------------------------------------------===//
2199 //  StdCall calling convention seems to be standard for many Windows' API
2200 //  routines and around. It differs from C calling convention just a little:
2201 //  callee should clean up the stack, not caller. Symbols should be also
2202 //  decorated in some fancy way :) It doesn't support any vector arguments.
2203 //  For info on fast calling convention see Fast Calling Convention (tail call)
2204 //  implementation LowerX86_32FastCCCallTo.
2205
2206 /// CallIsStructReturn - Determines whether a call uses struct return
2207 /// semantics.
2208 enum StructReturnType {
2209   NotStructReturn,
2210   RegStructReturn,
2211   StackStructReturn
2212 };
2213 static StructReturnType
2214 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2215   if (Outs.empty())
2216     return NotStructReturn;
2217
2218   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2219   if (!Flags.isSRet())
2220     return NotStructReturn;
2221   if (Flags.isInReg())
2222     return RegStructReturn;
2223   return StackStructReturn;
2224 }
2225
2226 /// ArgsAreStructReturn - Determines whether a function uses struct
2227 /// return semantics.
2228 static StructReturnType
2229 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2230   if (Ins.empty())
2231     return NotStructReturn;
2232
2233   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2234   if (!Flags.isSRet())
2235     return NotStructReturn;
2236   if (Flags.isInReg())
2237     return RegStructReturn;
2238   return StackStructReturn;
2239 }
2240
2241 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2242 /// by "Src" to address "Dst" with size and alignment information specified by
2243 /// the specific parameter attribute. The copy will be passed as a byval
2244 /// function parameter.
2245 static SDValue
2246 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2247                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2248                           SDLoc dl) {
2249   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2250
2251   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2252                        /*isVolatile*/false, /*AlwaysInline=*/true,
2253                        MachinePointerInfo(), MachinePointerInfo());
2254 }
2255
2256 /// IsTailCallConvention - Return true if the calling convention is one that
2257 /// supports tail call optimization.
2258 static bool IsTailCallConvention(CallingConv::ID CC) {
2259   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2260           CC == CallingConv::HiPE);
2261 }
2262
2263 /// \brief Return true if the calling convention is a C calling convention.
2264 static bool IsCCallConvention(CallingConv::ID CC) {
2265   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2266           CC == CallingConv::X86_64_SysV);
2267 }
2268
2269 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2270   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2271     return false;
2272
2273   CallSite CS(CI);
2274   CallingConv::ID CalleeCC = CS.getCallingConv();
2275   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2276     return false;
2277
2278   return true;
2279 }
2280
2281 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2282 /// a tailcall target by changing its ABI.
2283 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2284                                    bool GuaranteedTailCallOpt) {
2285   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2286 }
2287
2288 SDValue
2289 X86TargetLowering::LowerMemArgument(SDValue Chain,
2290                                     CallingConv::ID CallConv,
2291                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2292                                     SDLoc dl, SelectionDAG &DAG,
2293                                     const CCValAssign &VA,
2294                                     MachineFrameInfo *MFI,
2295                                     unsigned i) const {
2296   // Create the nodes corresponding to a load from this parameter slot.
2297   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2298   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2299       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2300   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2301   EVT ValVT;
2302
2303   // If value is passed by pointer we have address passed instead of the value
2304   // itself.
2305   if (VA.getLocInfo() == CCValAssign::Indirect)
2306     ValVT = VA.getLocVT();
2307   else
2308     ValVT = VA.getValVT();
2309
2310   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2311   // changed with more analysis.
2312   // In case of tail call optimization mark all arguments mutable. Since they
2313   // could be overwritten by lowering of arguments in case of a tail call.
2314   if (Flags.isByVal()) {
2315     unsigned Bytes = Flags.getByValSize();
2316     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2317     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2318     return DAG.getFrameIndex(FI, getPointerTy());
2319   } else {
2320     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2321                                     VA.getLocMemOffset(), isImmutable);
2322     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2323     return DAG.getLoad(ValVT, dl, Chain, FIN,
2324                        MachinePointerInfo::getFixedStack(FI),
2325                        false, false, false, 0);
2326   }
2327 }
2328
2329 // FIXME: Get this from tablegen.
2330 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2331                                                 const X86Subtarget *Subtarget) {
2332   assert(Subtarget->is64Bit());
2333
2334   if (Subtarget->isCallingConvWin64(CallConv)) {
2335     static const MCPhysReg GPR64ArgRegsWin64[] = {
2336       X86::RCX, X86::RDX, X86::R8,  X86::R9
2337     };
2338     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2339   }
2340
2341   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2342     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2343   };
2344   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2345 }
2346
2347 // FIXME: Get this from tablegen.
2348 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2349                                                 CallingConv::ID CallConv,
2350                                                 const X86Subtarget *Subtarget) {
2351   assert(Subtarget->is64Bit());
2352   if (Subtarget->isCallingConvWin64(CallConv)) {
2353     // The XMM registers which might contain var arg parameters are shadowed
2354     // in their paired GPR.  So we only need to save the GPR to their home
2355     // slots.
2356     // TODO: __vectorcall will change this.
2357     return None;
2358   }
2359
2360   const Function *Fn = MF.getFunction();
2361   bool NoImplicitFloatOps = Fn->getAttributes().
2362       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2363   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2364          "SSE register cannot be used when SSE is disabled!");
2365   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2366       !Subtarget->hasSSE1())
2367     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2368     // registers.
2369     return None;
2370
2371   static const MCPhysReg XMMArgRegs64Bit[] = {
2372     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2373     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2374   };
2375   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2376 }
2377
2378 SDValue
2379 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2380                                         CallingConv::ID CallConv,
2381                                         bool isVarArg,
2382                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2383                                         SDLoc dl,
2384                                         SelectionDAG &DAG,
2385                                         SmallVectorImpl<SDValue> &InVals)
2386                                           const {
2387   MachineFunction &MF = DAG.getMachineFunction();
2388   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2389
2390   const Function* Fn = MF.getFunction();
2391   if (Fn->hasExternalLinkage() &&
2392       Subtarget->isTargetCygMing() &&
2393       Fn->getName() == "main")
2394     FuncInfo->setForceFramePointer(true);
2395
2396   MachineFrameInfo *MFI = MF.getFrameInfo();
2397   bool Is64Bit = Subtarget->is64Bit();
2398   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2399
2400   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2401          "Var args not supported with calling convention fastcc, ghc or hipe");
2402
2403   // Assign locations to all of the incoming arguments.
2404   SmallVector<CCValAssign, 16> ArgLocs;
2405   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2406
2407   // Allocate shadow area for Win64
2408   if (IsWin64)
2409     CCInfo.AllocateStack(32, 8);
2410
2411   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2412
2413   unsigned LastVal = ~0U;
2414   SDValue ArgValue;
2415   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416     CCValAssign &VA = ArgLocs[i];
2417     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2418     // places.
2419     assert(VA.getValNo() != LastVal &&
2420            "Don't support value assigned to multiple locs yet");
2421     (void)LastVal;
2422     LastVal = VA.getValNo();
2423
2424     if (VA.isRegLoc()) {
2425       EVT RegVT = VA.getLocVT();
2426       const TargetRegisterClass *RC;
2427       if (RegVT == MVT::i32)
2428         RC = &X86::GR32RegClass;
2429       else if (Is64Bit && RegVT == MVT::i64)
2430         RC = &X86::GR64RegClass;
2431       else if (RegVT == MVT::f32)
2432         RC = &X86::FR32RegClass;
2433       else if (RegVT == MVT::f64)
2434         RC = &X86::FR64RegClass;
2435       else if (RegVT.is512BitVector())
2436         RC = &X86::VR512RegClass;
2437       else if (RegVT.is256BitVector())
2438         RC = &X86::VR256RegClass;
2439       else if (RegVT.is128BitVector())
2440         RC = &X86::VR128RegClass;
2441       else if (RegVT == MVT::x86mmx)
2442         RC = &X86::VR64RegClass;
2443       else if (RegVT == MVT::i1)
2444         RC = &X86::VK1RegClass;
2445       else if (RegVT == MVT::v8i1)
2446         RC = &X86::VK8RegClass;
2447       else if (RegVT == MVT::v16i1)
2448         RC = &X86::VK16RegClass;
2449       else if (RegVT == MVT::v32i1)
2450         RC = &X86::VK32RegClass;
2451       else if (RegVT == MVT::v64i1)
2452         RC = &X86::VK64RegClass;
2453       else
2454         llvm_unreachable("Unknown argument type!");
2455
2456       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2457       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2458
2459       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2460       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2461       // right size.
2462       if (VA.getLocInfo() == CCValAssign::SExt)
2463         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2464                                DAG.getValueType(VA.getValVT()));
2465       else if (VA.getLocInfo() == CCValAssign::ZExt)
2466         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2467                                DAG.getValueType(VA.getValVT()));
2468       else if (VA.getLocInfo() == CCValAssign::BCvt)
2469         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2470
2471       if (VA.isExtInLoc()) {
2472         // Handle MMX values passed in XMM regs.
2473         if (RegVT.isVector())
2474           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2475         else
2476           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2477       }
2478     } else {
2479       assert(VA.isMemLoc());
2480       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2481     }
2482
2483     // If value is passed via pointer - do a load.
2484     if (VA.getLocInfo() == CCValAssign::Indirect)
2485       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2486                              MachinePointerInfo(), false, false, false, 0);
2487
2488     InVals.push_back(ArgValue);
2489   }
2490
2491   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2492     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2493       // The x86-64 ABIs require that for returning structs by value we copy
2494       // the sret argument into %rax/%eax (depending on ABI) for the return.
2495       // Win32 requires us to put the sret argument to %eax as well.
2496       // Save the argument into a virtual register so that we can access it
2497       // from the return points.
2498       if (Ins[i].Flags.isSRet()) {
2499         unsigned Reg = FuncInfo->getSRetReturnReg();
2500         if (!Reg) {
2501           MVT PtrTy = getPointerTy();
2502           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2503           FuncInfo->setSRetReturnReg(Reg);
2504         }
2505         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2506         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2507         break;
2508       }
2509     }
2510   }
2511
2512   unsigned StackSize = CCInfo.getNextStackOffset();
2513   // Align stack specially for tail calls.
2514   if (FuncIsMadeTailCallSafe(CallConv,
2515                              MF.getTarget().Options.GuaranteedTailCallOpt))
2516     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2517
2518   // If the function takes variable number of arguments, make a frame index for
2519   // the start of the first vararg value... for expansion of llvm.va_start. We
2520   // can skip this if there are no va_start calls.
2521   if (MFI->hasVAStart() &&
2522       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2523                    CallConv != CallingConv::X86_ThisCall))) {
2524     FuncInfo->setVarArgsFrameIndex(
2525         MFI->CreateFixedObject(1, StackSize, true));
2526   }
2527
2528   // 64-bit calling conventions support varargs and register parameters, so we
2529   // have to do extra work to spill them in the prologue or forward them to
2530   // musttail calls.
2531   if (Is64Bit && isVarArg &&
2532       (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2533     // Find the first unallocated argument registers.
2534     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2535     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2536     unsigned NumIntRegs =
2537         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2538     unsigned NumXMMRegs =
2539         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2540     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2541            "SSE register cannot be used when SSE is disabled!");
2542
2543     // Gather all the live in physical registers.
2544     SmallVector<SDValue, 6> LiveGPRs;
2545     SmallVector<SDValue, 8> LiveXMMRegs;
2546     SDValue ALVal;
2547     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2548       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2549       LiveGPRs.push_back(
2550           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2551     }
2552     if (!ArgXMMs.empty()) {
2553       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2554       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2555       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2556         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2557         LiveXMMRegs.push_back(
2558             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2559       }
2560     }
2561
2562     // Store them to the va_list returned by va_start.
2563     if (MFI->hasVAStart()) {
2564       if (IsWin64) {
2565         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2566         // Get to the caller-allocated home save location.  Add 8 to account
2567         // for the return address.
2568         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2569         FuncInfo->setRegSaveFrameIndex(
2570           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2571         // Fixup to set vararg frame on shadow area (4 x i64).
2572         if (NumIntRegs < 4)
2573           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2574       } else {
2575         // For X86-64, if there are vararg parameters that are passed via
2576         // registers, then we must store them to their spots on the stack so
2577         // they may be loaded by deferencing the result of va_next.
2578         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2579         FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2580         FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2581             ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2582       }
2583
2584       // Store the integer parameter registers.
2585       SmallVector<SDValue, 8> MemOps;
2586       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2587                                         getPointerTy());
2588       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2589       for (SDValue Val : LiveGPRs) {
2590         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2591                                   DAG.getIntPtrConstant(Offset));
2592         SDValue Store =
2593           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2594                        MachinePointerInfo::getFixedStack(
2595                          FuncInfo->getRegSaveFrameIndex(), Offset),
2596                        false, false, 0);
2597         MemOps.push_back(Store);
2598         Offset += 8;
2599       }
2600
2601       if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2602         // Now store the XMM (fp + vector) parameter registers.
2603         SmallVector<SDValue, 12> SaveXMMOps;
2604         SaveXMMOps.push_back(Chain);
2605         SaveXMMOps.push_back(ALVal);
2606         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2607                                FuncInfo->getRegSaveFrameIndex()));
2608         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2609                                FuncInfo->getVarArgsFPOffset()));
2610         SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2611                           LiveXMMRegs.end());
2612         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2613                                      MVT::Other, SaveXMMOps));
2614       }
2615
2616       if (!MemOps.empty())
2617         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2618     } else {
2619       // Add all GPRs, al, and XMMs to the list of forwards.  We will add then
2620       // to the liveout set on a musttail call.
2621       assert(MFI->hasMustTailInVarArgFunc());
2622       auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2623       typedef X86MachineFunctionInfo::Forward Forward;
2624
2625       for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2626         unsigned VReg =
2627             MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2628         Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2629         Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2630       }
2631
2632       if (!ArgXMMs.empty()) {
2633         unsigned ALVReg =
2634             MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2635         Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2636         Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2637
2638         for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2639           unsigned VReg =
2640               MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2641           Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2642           Forwards.push_back(
2643               Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2644         }
2645       }
2646     }
2647   }
2648
2649   // Some CCs need callee pop.
2650   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2651                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2652     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2653   } else {
2654     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2655     // If this is an sret function, the return should pop the hidden pointer.
2656     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2657         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2658         argsAreStructReturn(Ins) == StackStructReturn)
2659       FuncInfo->setBytesToPopOnReturn(4);
2660   }
2661
2662   if (!Is64Bit) {
2663     // RegSaveFrameIndex is X86-64 only.
2664     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2665     if (CallConv == CallingConv::X86_FastCall ||
2666         CallConv == CallingConv::X86_ThisCall)
2667       // fastcc functions can't have varargs.
2668       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2669   }
2670
2671   FuncInfo->setArgumentStackSize(StackSize);
2672
2673   return Chain;
2674 }
2675
2676 SDValue
2677 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2678                                     SDValue StackPtr, SDValue Arg,
2679                                     SDLoc dl, SelectionDAG &DAG,
2680                                     const CCValAssign &VA,
2681                                     ISD::ArgFlagsTy Flags) const {
2682   unsigned LocMemOffset = VA.getLocMemOffset();
2683   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2684   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2685   if (Flags.isByVal())
2686     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2687
2688   return DAG.getStore(Chain, dl, Arg, PtrOff,
2689                       MachinePointerInfo::getStack(LocMemOffset),
2690                       false, false, 0);
2691 }
2692
2693 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2694 /// optimization is performed and it is required.
2695 SDValue
2696 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2697                                            SDValue &OutRetAddr, SDValue Chain,
2698                                            bool IsTailCall, bool Is64Bit,
2699                                            int FPDiff, SDLoc dl) const {
2700   // Adjust the Return address stack slot.
2701   EVT VT = getPointerTy();
2702   OutRetAddr = getReturnAddressFrameIndex(DAG);
2703
2704   // Load the "old" Return address.
2705   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2706                            false, false, false, 0);
2707   return SDValue(OutRetAddr.getNode(), 1);
2708 }
2709
2710 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2711 /// optimization is performed and it is required (FPDiff!=0).
2712 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2713                                         SDValue Chain, SDValue RetAddrFrIdx,
2714                                         EVT PtrVT, unsigned SlotSize,
2715                                         int FPDiff, SDLoc dl) {
2716   // Store the return address to the appropriate stack slot.
2717   if (!FPDiff) return Chain;
2718   // Calculate the new stack slot for the return address.
2719   int NewReturnAddrFI =
2720     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2721                                          false);
2722   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2723   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2724                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2725                        false, false, 0);
2726   return Chain;
2727 }
2728
2729 SDValue
2730 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2731                              SmallVectorImpl<SDValue> &InVals) const {
2732   SelectionDAG &DAG                     = CLI.DAG;
2733   SDLoc &dl                             = CLI.DL;
2734   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2735   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2736   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2737   SDValue Chain                         = CLI.Chain;
2738   SDValue Callee                        = CLI.Callee;
2739   CallingConv::ID CallConv              = CLI.CallConv;
2740   bool &isTailCall                      = CLI.IsTailCall;
2741   bool isVarArg                         = CLI.IsVarArg;
2742
2743   MachineFunction &MF = DAG.getMachineFunction();
2744   bool Is64Bit        = Subtarget->is64Bit();
2745   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2746   StructReturnType SR = callIsStructReturn(Outs);
2747   bool IsSibcall      = false;
2748   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2749
2750   if (MF.getTarget().Options.DisableTailCalls)
2751     isTailCall = false;
2752
2753   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2754   if (IsMustTail) {
2755     // Force this to be a tail call.  The verifier rules are enough to ensure
2756     // that we can lower this successfully without moving the return address
2757     // around.
2758     isTailCall = true;
2759   } else if (isTailCall) {
2760     // Check if it's really possible to do a tail call.
2761     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2762                     isVarArg, SR != NotStructReturn,
2763                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2764                     Outs, OutVals, Ins, DAG);
2765
2766     // Sibcalls are automatically detected tailcalls which do not require
2767     // ABI changes.
2768     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2769       IsSibcall = true;
2770
2771     if (isTailCall)
2772       ++NumTailCalls;
2773   }
2774
2775   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2776          "Var args not supported with calling convention fastcc, ghc or hipe");
2777
2778   // Analyze operands of the call, assigning locations to each operand.
2779   SmallVector<CCValAssign, 16> ArgLocs;
2780   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2781
2782   // Allocate shadow area for Win64
2783   if (IsWin64)
2784     CCInfo.AllocateStack(32, 8);
2785
2786   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2787
2788   // Get a count of how many bytes are to be pushed on the stack.
2789   unsigned NumBytes = CCInfo.getNextStackOffset();
2790   if (IsSibcall)
2791     // This is a sibcall. The memory operands are available in caller's
2792     // own caller's stack.
2793     NumBytes = 0;
2794   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2795            IsTailCallConvention(CallConv))
2796     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2797
2798   int FPDiff = 0;
2799   if (isTailCall && !IsSibcall && !IsMustTail) {
2800     // Lower arguments at fp - stackoffset + fpdiff.
2801     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2802
2803     FPDiff = NumBytesCallerPushed - NumBytes;
2804
2805     // Set the delta of movement of the returnaddr stackslot.
2806     // But only set if delta is greater than previous delta.
2807     if (FPDiff < X86Info->getTCReturnAddrDelta())
2808       X86Info->setTCReturnAddrDelta(FPDiff);
2809   }
2810
2811   unsigned NumBytesToPush = NumBytes;
2812   unsigned NumBytesToPop = NumBytes;
2813
2814   // If we have an inalloca argument, all stack space has already been allocated
2815   // for us and be right at the top of the stack.  We don't support multiple
2816   // arguments passed in memory when using inalloca.
2817   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2818     NumBytesToPush = 0;
2819     if (!ArgLocs.back().isMemLoc())
2820       report_fatal_error("cannot use inalloca attribute on a register "
2821                          "parameter");
2822     if (ArgLocs.back().getLocMemOffset() != 0)
2823       report_fatal_error("any parameter with the inalloca attribute must be "
2824                          "the only memory argument");
2825   }
2826
2827   if (!IsSibcall)
2828     Chain = DAG.getCALLSEQ_START(
2829         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2830
2831   SDValue RetAddrFrIdx;
2832   // Load return address for tail calls.
2833   if (isTailCall && FPDiff)
2834     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2835                                     Is64Bit, FPDiff, dl);
2836
2837   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2838   SmallVector<SDValue, 8> MemOpChains;
2839   SDValue StackPtr;
2840
2841   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2842   // of tail call optimization arguments are handle later.
2843   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2844       DAG.getSubtarget().getRegisterInfo());
2845   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2846     // Skip inalloca arguments, they have already been written.
2847     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2848     if (Flags.isInAlloca())
2849       continue;
2850
2851     CCValAssign &VA = ArgLocs[i];
2852     EVT RegVT = VA.getLocVT();
2853     SDValue Arg = OutVals[i];
2854     bool isByVal = Flags.isByVal();
2855
2856     // Promote the value if needed.
2857     switch (VA.getLocInfo()) {
2858     default: llvm_unreachable("Unknown loc info!");
2859     case CCValAssign::Full: break;
2860     case CCValAssign::SExt:
2861       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2862       break;
2863     case CCValAssign::ZExt:
2864       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2865       break;
2866     case CCValAssign::AExt:
2867       if (RegVT.is128BitVector()) {
2868         // Special case: passing MMX values in XMM registers.
2869         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2870         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2871         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2872       } else
2873         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2874       break;
2875     case CCValAssign::BCvt:
2876       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2877       break;
2878     case CCValAssign::Indirect: {
2879       // Store the argument.
2880       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2881       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2882       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2883                            MachinePointerInfo::getFixedStack(FI),
2884                            false, false, 0);
2885       Arg = SpillSlot;
2886       break;
2887     }
2888     }
2889
2890     if (VA.isRegLoc()) {
2891       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2892       if (isVarArg && IsWin64) {
2893         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2894         // shadow reg if callee is a varargs function.
2895         unsigned ShadowReg = 0;
2896         switch (VA.getLocReg()) {
2897         case X86::XMM0: ShadowReg = X86::RCX; break;
2898         case X86::XMM1: ShadowReg = X86::RDX; break;
2899         case X86::XMM2: ShadowReg = X86::R8; break;
2900         case X86::XMM3: ShadowReg = X86::R9; break;
2901         }
2902         if (ShadowReg)
2903           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2904       }
2905     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2906       assert(VA.isMemLoc());
2907       if (!StackPtr.getNode())
2908         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2909                                       getPointerTy());
2910       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2911                                              dl, DAG, VA, Flags));
2912     }
2913   }
2914
2915   if (!MemOpChains.empty())
2916     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2917
2918   if (Subtarget->isPICStyleGOT()) {
2919     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2920     // GOT pointer.
2921     if (!isTailCall) {
2922       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2923                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2924     } else {
2925       // If we are tail calling and generating PIC/GOT style code load the
2926       // address of the callee into ECX. The value in ecx is used as target of
2927       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2928       // for tail calls on PIC/GOT architectures. Normally we would just put the
2929       // address of GOT into ebx and then call target@PLT. But for tail calls
2930       // ebx would be restored (since ebx is callee saved) before jumping to the
2931       // target@PLT.
2932
2933       // Note: The actual moving to ECX is done further down.
2934       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2935       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2936           !G->getGlobal()->hasProtectedVisibility())
2937         Callee = LowerGlobalAddress(Callee, DAG);
2938       else if (isa<ExternalSymbolSDNode>(Callee))
2939         Callee = LowerExternalSymbol(Callee, DAG);
2940     }
2941   }
2942
2943   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2944     // From AMD64 ABI document:
2945     // For calls that may call functions that use varargs or stdargs
2946     // (prototype-less calls or calls to functions containing ellipsis (...) in
2947     // the declaration) %al is used as hidden argument to specify the number
2948     // of SSE registers used. The contents of %al do not need to match exactly
2949     // the number of registers, but must be an ubound on the number of SSE
2950     // registers used and is in the range 0 - 8 inclusive.
2951
2952     // Count the number of XMM registers allocated.
2953     static const MCPhysReg XMMArgRegs[] = {
2954       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2955       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2956     };
2957     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2958     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2959            && "SSE registers cannot be used when SSE is disabled");
2960
2961     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2962                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2963   }
2964
2965   if (Is64Bit && isVarArg && IsMustTail) {
2966     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2967     for (const auto &F : Forwards) {
2968       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2969       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2970     }
2971   }
2972
2973   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2974   // don't need this because the eligibility check rejects calls that require
2975   // shuffling arguments passed in memory.
2976   if (!IsSibcall && isTailCall) {
2977     // Force all the incoming stack arguments to be loaded from the stack
2978     // before any new outgoing arguments are stored to the stack, because the
2979     // outgoing stack slots may alias the incoming argument stack slots, and
2980     // the alias isn't otherwise explicit. This is slightly more conservative
2981     // than necessary, because it means that each store effectively depends
2982     // on every argument instead of just those arguments it would clobber.
2983     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2984
2985     SmallVector<SDValue, 8> MemOpChains2;
2986     SDValue FIN;
2987     int FI = 0;
2988     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2989       CCValAssign &VA = ArgLocs[i];
2990       if (VA.isRegLoc())
2991         continue;
2992       assert(VA.isMemLoc());
2993       SDValue Arg = OutVals[i];
2994       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2995       // Skip inalloca arguments.  They don't require any work.
2996       if (Flags.isInAlloca())
2997         continue;
2998       // Create frame index.
2999       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3000       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3001       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3002       FIN = DAG.getFrameIndex(FI, getPointerTy());
3003
3004       if (Flags.isByVal()) {
3005         // Copy relative to framepointer.
3006         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3007         if (!StackPtr.getNode())
3008           StackPtr = DAG.getCopyFromReg(Chain, dl,
3009                                         RegInfo->getStackRegister(),
3010                                         getPointerTy());
3011         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3012
3013         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3014                                                          ArgChain,
3015                                                          Flags, DAG, dl));
3016       } else {
3017         // Store relative to framepointer.
3018         MemOpChains2.push_back(
3019           DAG.getStore(ArgChain, dl, Arg, FIN,
3020                        MachinePointerInfo::getFixedStack(FI),
3021                        false, false, 0));
3022       }
3023     }
3024
3025     if (!MemOpChains2.empty())
3026       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3027
3028     // Store the return address to the appropriate stack slot.
3029     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3030                                      getPointerTy(), RegInfo->getSlotSize(),
3031                                      FPDiff, dl);
3032   }
3033
3034   // Build a sequence of copy-to-reg nodes chained together with token chain
3035   // and flag operands which copy the outgoing args into registers.
3036   SDValue InFlag;
3037   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3038     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3039                              RegsToPass[i].second, InFlag);
3040     InFlag = Chain.getValue(1);
3041   }
3042
3043   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3044     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3045     // In the 64-bit large code model, we have to make all calls
3046     // through a register, since the call instruction's 32-bit
3047     // pc-relative offset may not be large enough to hold the whole
3048     // address.
3049   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3050     // If the callee is a GlobalAddress node (quite common, every direct call
3051     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3052     // it.
3053
3054     // We should use extra load for direct calls to dllimported functions in
3055     // non-JIT mode.
3056     const GlobalValue *GV = G->getGlobal();
3057     if (!GV->hasDLLImportStorageClass()) {
3058       unsigned char OpFlags = 0;
3059       bool ExtraLoad = false;
3060       unsigned WrapperKind = ISD::DELETED_NODE;
3061
3062       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3063       // external symbols most go through the PLT in PIC mode.  If the symbol
3064       // has hidden or protected visibility, or if it is static or local, then
3065       // we don't need to use the PLT - we can directly call it.
3066       if (Subtarget->isTargetELF() &&
3067           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3068           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3069         OpFlags = X86II::MO_PLT;
3070       } else if (Subtarget->isPICStyleStubAny() &&
3071                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3072                  (!Subtarget->getTargetTriple().isMacOSX() ||
3073                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3074         // PC-relative references to external symbols should go through $stub,
3075         // unless we're building with the leopard linker or later, which
3076         // automatically synthesizes these stubs.
3077         OpFlags = X86II::MO_DARWIN_STUB;
3078       } else if (Subtarget->isPICStyleRIPRel() &&
3079                  isa<Function>(GV) &&
3080                  cast<Function>(GV)->getAttributes().
3081                    hasAttribute(AttributeSet::FunctionIndex,
3082                                 Attribute::NonLazyBind)) {
3083         // If the function is marked as non-lazy, generate an indirect call
3084         // which loads from the GOT directly. This avoids runtime overhead
3085         // at the cost of eager binding (and one extra byte of encoding).
3086         OpFlags = X86II::MO_GOTPCREL;
3087         WrapperKind = X86ISD::WrapperRIP;
3088         ExtraLoad = true;
3089       }
3090
3091       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3092                                           G->getOffset(), OpFlags);
3093
3094       // Add a wrapper if needed.
3095       if (WrapperKind != ISD::DELETED_NODE)
3096         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3097       // Add extra indirection if needed.
3098       if (ExtraLoad)
3099         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3100                              MachinePointerInfo::getGOT(),
3101                              false, false, false, 0);
3102     }
3103   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3104     unsigned char OpFlags = 0;
3105
3106     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3107     // external symbols should go through the PLT.
3108     if (Subtarget->isTargetELF() &&
3109         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3110       OpFlags = X86II::MO_PLT;
3111     } else if (Subtarget->isPICStyleStubAny() &&
3112                (!Subtarget->getTargetTriple().isMacOSX() ||
3113                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3114       // PC-relative references to external symbols should go through $stub,
3115       // unless we're building with the leopard linker or later, which
3116       // automatically synthesizes these stubs.
3117       OpFlags = X86II::MO_DARWIN_STUB;
3118     }
3119
3120     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3121                                          OpFlags);
3122   }
3123
3124   // Returns a chain & a flag for retval copy to use.
3125   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3126   SmallVector<SDValue, 8> Ops;
3127
3128   if (!IsSibcall && isTailCall) {
3129     Chain = DAG.getCALLSEQ_END(Chain,
3130                                DAG.getIntPtrConstant(NumBytesToPop, true),
3131                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3132     InFlag = Chain.getValue(1);
3133   }
3134
3135   Ops.push_back(Chain);
3136   Ops.push_back(Callee);
3137
3138   if (isTailCall)
3139     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3140
3141   // Add argument registers to the end of the list so that they are known live
3142   // into the call.
3143   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3144     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3145                                   RegsToPass[i].second.getValueType()));
3146
3147   // Add a register mask operand representing the call-preserved registers.
3148   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3149   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3150   assert(Mask && "Missing call preserved mask for calling convention");
3151   Ops.push_back(DAG.getRegisterMask(Mask));
3152
3153   if (InFlag.getNode())
3154     Ops.push_back(InFlag);
3155
3156   if (isTailCall) {
3157     // We used to do:
3158     //// If this is the first return lowered for this function, add the regs
3159     //// to the liveout set for the function.
3160     // This isn't right, although it's probably harmless on x86; liveouts
3161     // should be computed from returns not tail calls.  Consider a void
3162     // function making a tail call to a function returning int.
3163     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3164   }
3165
3166   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3167   InFlag = Chain.getValue(1);
3168
3169   // Create the CALLSEQ_END node.
3170   unsigned NumBytesForCalleeToPop;
3171   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3172                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3173     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3174   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3175            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3176            SR == StackStructReturn)
3177     // If this is a call to a struct-return function, the callee
3178     // pops the hidden struct pointer, so we have to push it back.
3179     // This is common for Darwin/X86, Linux & Mingw32 targets.
3180     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3181     NumBytesForCalleeToPop = 4;
3182   else
3183     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3184
3185   // Returns a flag for retval copy to use.
3186   if (!IsSibcall) {
3187     Chain = DAG.getCALLSEQ_END(Chain,
3188                                DAG.getIntPtrConstant(NumBytesToPop, true),
3189                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3190                                                      true),
3191                                InFlag, dl);
3192     InFlag = Chain.getValue(1);
3193   }
3194
3195   // Handle result values, copying them out of physregs into vregs that we
3196   // return.
3197   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3198                          Ins, dl, DAG, InVals);
3199 }
3200
3201 //===----------------------------------------------------------------------===//
3202 //                Fast Calling Convention (tail call) implementation
3203 //===----------------------------------------------------------------------===//
3204
3205 //  Like std call, callee cleans arguments, convention except that ECX is
3206 //  reserved for storing the tail called function address. Only 2 registers are
3207 //  free for argument passing (inreg). Tail call optimization is performed
3208 //  provided:
3209 //                * tailcallopt is enabled
3210 //                * caller/callee are fastcc
3211 //  On X86_64 architecture with GOT-style position independent code only local
3212 //  (within module) calls are supported at the moment.
3213 //  To keep the stack aligned according to platform abi the function
3214 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3215 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3216 //  If a tail called function callee has more arguments than the caller the
3217 //  caller needs to make sure that there is room to move the RETADDR to. This is
3218 //  achieved by reserving an area the size of the argument delta right after the
3219 //  original RETADDR, but before the saved framepointer or the spilled registers
3220 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3221 //  stack layout:
3222 //    arg1
3223 //    arg2
3224 //    RETADDR
3225 //    [ new RETADDR
3226 //      move area ]
3227 //    (possible EBP)
3228 //    ESI
3229 //    EDI
3230 //    local1 ..
3231
3232 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3233 /// for a 16 byte align requirement.
3234 unsigned
3235 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3236                                                SelectionDAG& DAG) const {
3237   MachineFunction &MF = DAG.getMachineFunction();
3238   const TargetMachine &TM = MF.getTarget();
3239   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3240       TM.getSubtargetImpl()->getRegisterInfo());
3241   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3242   unsigned StackAlignment = TFI.getStackAlignment();
3243   uint64_t AlignMask = StackAlignment - 1;
3244   int64_t Offset = StackSize;
3245   unsigned SlotSize = RegInfo->getSlotSize();
3246   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3247     // Number smaller than 12 so just add the difference.
3248     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3249   } else {
3250     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3251     Offset = ((~AlignMask) & Offset) + StackAlignment +
3252       (StackAlignment-SlotSize);
3253   }
3254   return Offset;
3255 }
3256
3257 /// MatchingStackOffset - Return true if the given stack call argument is
3258 /// already available in the same position (relatively) of the caller's
3259 /// incoming argument stack.
3260 static
3261 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3262                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3263                          const X86InstrInfo *TII) {
3264   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3265   int FI = INT_MAX;
3266   if (Arg.getOpcode() == ISD::CopyFromReg) {
3267     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3268     if (!TargetRegisterInfo::isVirtualRegister(VR))
3269       return false;
3270     MachineInstr *Def = MRI->getVRegDef(VR);
3271     if (!Def)
3272       return false;
3273     if (!Flags.isByVal()) {
3274       if (!TII->isLoadFromStackSlot(Def, FI))
3275         return false;
3276     } else {
3277       unsigned Opcode = Def->getOpcode();
3278       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3279           Def->getOperand(1).isFI()) {
3280         FI = Def->getOperand(1).getIndex();
3281         Bytes = Flags.getByValSize();
3282       } else
3283         return false;
3284     }
3285   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3286     if (Flags.isByVal())
3287       // ByVal argument is passed in as a pointer but it's now being
3288       // dereferenced. e.g.
3289       // define @foo(%struct.X* %A) {
3290       //   tail call @bar(%struct.X* byval %A)
3291       // }
3292       return false;
3293     SDValue Ptr = Ld->getBasePtr();
3294     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3295     if (!FINode)
3296       return false;
3297     FI = FINode->getIndex();
3298   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3299     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3300     FI = FINode->getIndex();
3301     Bytes = Flags.getByValSize();
3302   } else
3303     return false;
3304
3305   assert(FI != INT_MAX);
3306   if (!MFI->isFixedObjectIndex(FI))
3307     return false;
3308   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3309 }
3310
3311 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3312 /// for tail call optimization. Targets which want to do tail call
3313 /// optimization should implement this function.
3314 bool
3315 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3316                                                      CallingConv::ID CalleeCC,
3317                                                      bool isVarArg,
3318                                                      bool isCalleeStructRet,
3319                                                      bool isCallerStructRet,
3320                                                      Type *RetTy,
3321                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3322                                     const SmallVectorImpl<SDValue> &OutVals,
3323                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3324                                                      SelectionDAG &DAG) const {
3325   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3326     return false;
3327
3328   // If -tailcallopt is specified, make fastcc functions tail-callable.
3329   const MachineFunction &MF = DAG.getMachineFunction();
3330   const Function *CallerF = MF.getFunction();
3331
3332   // If the function return type is x86_fp80 and the callee return type is not,
3333   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3334   // perform a tailcall optimization here.
3335   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3336     return false;
3337
3338   CallingConv::ID CallerCC = CallerF->getCallingConv();
3339   bool CCMatch = CallerCC == CalleeCC;
3340   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3341   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3342
3343   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3344     if (IsTailCallConvention(CalleeCC) && CCMatch)
3345       return true;
3346     return false;
3347   }
3348
3349   // Look for obvious safe cases to perform tail call optimization that do not
3350   // require ABI changes. This is what gcc calls sibcall.
3351
3352   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3353   // emit a special epilogue.
3354   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3355       DAG.getSubtarget().getRegisterInfo());
3356   if (RegInfo->needsStackRealignment(MF))
3357     return false;
3358
3359   // Also avoid sibcall optimization if either caller or callee uses struct
3360   // return semantics.
3361   if (isCalleeStructRet || isCallerStructRet)
3362     return false;
3363
3364   // An stdcall/thiscall caller is expected to clean up its arguments; the
3365   // callee isn't going to do that.
3366   // FIXME: this is more restrictive than needed. We could produce a tailcall
3367   // when the stack adjustment matches. For example, with a thiscall that takes
3368   // only one argument.
3369   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3370                    CallerCC == CallingConv::X86_ThisCall))
3371     return false;
3372
3373   // Do not sibcall optimize vararg calls unless all arguments are passed via
3374   // registers.
3375   if (isVarArg && !Outs.empty()) {
3376
3377     // Optimizing for varargs on Win64 is unlikely to be safe without
3378     // additional testing.
3379     if (IsCalleeWin64 || IsCallerWin64)
3380       return false;
3381
3382     SmallVector<CCValAssign, 16> ArgLocs;
3383     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3384                    *DAG.getContext());
3385
3386     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3387     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3388       if (!ArgLocs[i].isRegLoc())
3389         return false;
3390   }
3391
3392   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3393   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3394   // this into a sibcall.
3395   bool Unused = false;
3396   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3397     if (!Ins[i].Used) {
3398       Unused = true;
3399       break;
3400     }
3401   }
3402   if (Unused) {
3403     SmallVector<CCValAssign, 16> RVLocs;
3404     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3405                    *DAG.getContext());
3406     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3407     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3408       CCValAssign &VA = RVLocs[i];
3409       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3410         return false;
3411     }
3412   }
3413
3414   // If the calling conventions do not match, then we'd better make sure the
3415   // results are returned in the same way as what the caller expects.
3416   if (!CCMatch) {
3417     SmallVector<CCValAssign, 16> RVLocs1;
3418     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3419                     *DAG.getContext());
3420     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3421
3422     SmallVector<CCValAssign, 16> RVLocs2;
3423     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3424                     *DAG.getContext());
3425     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3426
3427     if (RVLocs1.size() != RVLocs2.size())
3428       return false;
3429     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3430       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3431         return false;
3432       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3433         return false;
3434       if (RVLocs1[i].isRegLoc()) {
3435         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3436           return false;
3437       } else {
3438         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3439           return false;
3440       }
3441     }
3442   }
3443
3444   // If the callee takes no arguments then go on to check the results of the
3445   // call.
3446   if (!Outs.empty()) {
3447     // Check if stack adjustment is needed. For now, do not do this if any
3448     // argument is passed on the stack.
3449     SmallVector<CCValAssign, 16> ArgLocs;
3450     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3451                    *DAG.getContext());
3452
3453     // Allocate shadow area for Win64
3454     if (IsCalleeWin64)
3455       CCInfo.AllocateStack(32, 8);
3456
3457     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3458     if (CCInfo.getNextStackOffset()) {
3459       MachineFunction &MF = DAG.getMachineFunction();
3460       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3461         return false;
3462
3463       // Check if the arguments are already laid out in the right way as
3464       // the caller's fixed stack objects.
3465       MachineFrameInfo *MFI = MF.getFrameInfo();
3466       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3467       const X86InstrInfo *TII =
3468           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3469       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3470         CCValAssign &VA = ArgLocs[i];
3471         SDValue Arg = OutVals[i];
3472         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3473         if (VA.getLocInfo() == CCValAssign::Indirect)
3474           return false;
3475         if (!VA.isRegLoc()) {
3476           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3477                                    MFI, MRI, TII))
3478             return false;
3479         }
3480       }
3481     }
3482
3483     // If the tailcall address may be in a register, then make sure it's
3484     // possible to register allocate for it. In 32-bit, the call address can
3485     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3486     // callee-saved registers are restored. These happen to be the same
3487     // registers used to pass 'inreg' arguments so watch out for those.
3488     if (!Subtarget->is64Bit() &&
3489         ((!isa<GlobalAddressSDNode>(Callee) &&
3490           !isa<ExternalSymbolSDNode>(Callee)) ||
3491          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3492       unsigned NumInRegs = 0;
3493       // In PIC we need an extra register to formulate the address computation
3494       // for the callee.
3495       unsigned MaxInRegs =
3496         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3497
3498       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3499         CCValAssign &VA = ArgLocs[i];
3500         if (!VA.isRegLoc())
3501           continue;
3502         unsigned Reg = VA.getLocReg();
3503         switch (Reg) {
3504         default: break;
3505         case X86::EAX: case X86::EDX: case X86::ECX:
3506           if (++NumInRegs == MaxInRegs)
3507             return false;
3508           break;
3509         }
3510       }
3511     }
3512   }
3513
3514   return true;
3515 }
3516
3517 FastISel *
3518 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3519                                   const TargetLibraryInfo *libInfo) const {
3520   return X86::createFastISel(funcInfo, libInfo);
3521 }
3522
3523 //===----------------------------------------------------------------------===//
3524 //                           Other Lowering Hooks
3525 //===----------------------------------------------------------------------===//
3526
3527 static bool MayFoldLoad(SDValue Op) {
3528   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3529 }
3530
3531 static bool MayFoldIntoStore(SDValue Op) {
3532   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3533 }
3534
3535 static bool isTargetShuffle(unsigned Opcode) {
3536   switch(Opcode) {
3537   default: return false;
3538   case X86ISD::PSHUFB:
3539   case X86ISD::PSHUFD:
3540   case X86ISD::PSHUFHW:
3541   case X86ISD::PSHUFLW:
3542   case X86ISD::SHUFP:
3543   case X86ISD::PALIGNR:
3544   case X86ISD::MOVLHPS:
3545   case X86ISD::MOVLHPD:
3546   case X86ISD::MOVHLPS:
3547   case X86ISD::MOVLPS:
3548   case X86ISD::MOVLPD:
3549   case X86ISD::MOVSHDUP:
3550   case X86ISD::MOVSLDUP:
3551   case X86ISD::MOVDDUP:
3552   case X86ISD::MOVSS:
3553   case X86ISD::MOVSD:
3554   case X86ISD::UNPCKL:
3555   case X86ISD::UNPCKH:
3556   case X86ISD::VPERMILP:
3557   case X86ISD::VPERM2X128:
3558   case X86ISD::VPERMI:
3559     return true;
3560   }
3561 }
3562
3563 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3564                                     SDValue V1, SelectionDAG &DAG) {
3565   switch(Opc) {
3566   default: llvm_unreachable("Unknown x86 shuffle node");
3567   case X86ISD::MOVSHDUP:
3568   case X86ISD::MOVSLDUP:
3569   case X86ISD::MOVDDUP:
3570     return DAG.getNode(Opc, dl, VT, V1);
3571   }
3572 }
3573
3574 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3575                                     SDValue V1, unsigned TargetMask,
3576                                     SelectionDAG &DAG) {
3577   switch(Opc) {
3578   default: llvm_unreachable("Unknown x86 shuffle node");
3579   case X86ISD::PSHUFD:
3580   case X86ISD::PSHUFHW:
3581   case X86ISD::PSHUFLW:
3582   case X86ISD::VPERMILP:
3583   case X86ISD::VPERMI:
3584     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3585   }
3586 }
3587
3588 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3589                                     SDValue V1, SDValue V2, unsigned TargetMask,
3590                                     SelectionDAG &DAG) {
3591   switch(Opc) {
3592   default: llvm_unreachable("Unknown x86 shuffle node");
3593   case X86ISD::PALIGNR:
3594   case X86ISD::VALIGN:
3595   case X86ISD::SHUFP:
3596   case X86ISD::VPERM2X128:
3597     return DAG.getNode(Opc, dl, VT, V1, V2,
3598                        DAG.getConstant(TargetMask, MVT::i8));
3599   }
3600 }
3601
3602 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3603                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3604   switch(Opc) {
3605   default: llvm_unreachable("Unknown x86 shuffle node");
3606   case X86ISD::MOVLHPS:
3607   case X86ISD::MOVLHPD:
3608   case X86ISD::MOVHLPS:
3609   case X86ISD::MOVLPS:
3610   case X86ISD::MOVLPD:
3611   case X86ISD::MOVSS:
3612   case X86ISD::MOVSD:
3613   case X86ISD::UNPCKL:
3614   case X86ISD::UNPCKH:
3615     return DAG.getNode(Opc, dl, VT, V1, V2);
3616   }
3617 }
3618
3619 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3620   MachineFunction &MF = DAG.getMachineFunction();
3621   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3622       DAG.getSubtarget().getRegisterInfo());
3623   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3624   int ReturnAddrIndex = FuncInfo->getRAIndex();
3625
3626   if (ReturnAddrIndex == 0) {
3627     // Set up a frame object for the return address.
3628     unsigned SlotSize = RegInfo->getSlotSize();
3629     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3630                                                            -(int64_t)SlotSize,
3631                                                            false);
3632     FuncInfo->setRAIndex(ReturnAddrIndex);
3633   }
3634
3635   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3636 }
3637
3638 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3639                                        bool hasSymbolicDisplacement) {
3640   // Offset should fit into 32 bit immediate field.
3641   if (!isInt<32>(Offset))
3642     return false;
3643
3644   // If we don't have a symbolic displacement - we don't have any extra
3645   // restrictions.
3646   if (!hasSymbolicDisplacement)
3647     return true;
3648
3649   // FIXME: Some tweaks might be needed for medium code model.
3650   if (M != CodeModel::Small && M != CodeModel::Kernel)
3651     return false;
3652
3653   // For small code model we assume that latest object is 16MB before end of 31
3654   // bits boundary. We may also accept pretty large negative constants knowing
3655   // that all objects are in the positive half of address space.
3656   if (M == CodeModel::Small && Offset < 16*1024*1024)
3657     return true;
3658
3659   // For kernel code model we know that all object resist in the negative half
3660   // of 32bits address space. We may not accept negative offsets, since they may
3661   // be just off and we may accept pretty large positive ones.
3662   if (M == CodeModel::Kernel && Offset > 0)
3663     return true;
3664
3665   return false;
3666 }
3667
3668 /// isCalleePop - Determines whether the callee is required to pop its
3669 /// own arguments. Callee pop is necessary to support tail calls.
3670 bool X86::isCalleePop(CallingConv::ID CallingConv,
3671                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3672   switch (CallingConv) {
3673   default:
3674     return false;
3675   case CallingConv::X86_StdCall:
3676   case CallingConv::X86_FastCall:
3677   case CallingConv::X86_ThisCall:
3678     return !is64Bit;
3679   case CallingConv::Fast:
3680   case CallingConv::GHC:
3681   case CallingConv::HiPE:
3682     if (IsVarArg)
3683       return false;
3684     return TailCallOpt;
3685   }
3686 }
3687
3688 /// \brief Return true if the condition is an unsigned comparison operation.
3689 static bool isX86CCUnsigned(unsigned X86CC) {
3690   switch (X86CC) {
3691   default: llvm_unreachable("Invalid integer condition!");
3692   case X86::COND_E:     return true;
3693   case X86::COND_G:     return false;
3694   case X86::COND_GE:    return false;
3695   case X86::COND_L:     return false;
3696   case X86::COND_LE:    return false;
3697   case X86::COND_NE:    return true;
3698   case X86::COND_B:     return true;
3699   case X86::COND_A:     return true;
3700   case X86::COND_BE:    return true;
3701   case X86::COND_AE:    return true;
3702   }
3703   llvm_unreachable("covered switch fell through?!");
3704 }
3705
3706 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3707 /// specific condition code, returning the condition code and the LHS/RHS of the
3708 /// comparison to make.
3709 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3710                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3711   if (!isFP) {
3712     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3713       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3714         // X > -1   -> X == 0, jump !sign.
3715         RHS = DAG.getConstant(0, RHS.getValueType());
3716         return X86::COND_NS;
3717       }
3718       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3719         // X < 0   -> X == 0, jump on sign.
3720         return X86::COND_S;
3721       }
3722       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3723         // X < 1   -> X <= 0
3724         RHS = DAG.getConstant(0, RHS.getValueType());
3725         return X86::COND_LE;
3726       }
3727     }
3728
3729     switch (SetCCOpcode) {
3730     default: llvm_unreachable("Invalid integer condition!");
3731     case ISD::SETEQ:  return X86::COND_E;
3732     case ISD::SETGT:  return X86::COND_G;
3733     case ISD::SETGE:  return X86::COND_GE;
3734     case ISD::SETLT:  return X86::COND_L;
3735     case ISD::SETLE:  return X86::COND_LE;
3736     case ISD::SETNE:  return X86::COND_NE;
3737     case ISD::SETULT: return X86::COND_B;
3738     case ISD::SETUGT: return X86::COND_A;
3739     case ISD::SETULE: return X86::COND_BE;
3740     case ISD::SETUGE: return X86::COND_AE;
3741     }
3742   }
3743
3744   // First determine if it is required or is profitable to flip the operands.
3745
3746   // If LHS is a foldable load, but RHS is not, flip the condition.
3747   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3748       !ISD::isNON_EXTLoad(RHS.getNode())) {
3749     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3750     std::swap(LHS, RHS);
3751   }
3752
3753   switch (SetCCOpcode) {
3754   default: break;
3755   case ISD::SETOLT:
3756   case ISD::SETOLE:
3757   case ISD::SETUGT:
3758   case ISD::SETUGE:
3759     std::swap(LHS, RHS);
3760     break;
3761   }
3762
3763   // On a floating point condition, the flags are set as follows:
3764   // ZF  PF  CF   op
3765   //  0 | 0 | 0 | X > Y
3766   //  0 | 0 | 1 | X < Y
3767   //  1 | 0 | 0 | X == Y
3768   //  1 | 1 | 1 | unordered
3769   switch (SetCCOpcode) {
3770   default: llvm_unreachable("Condcode should be pre-legalized away");
3771   case ISD::SETUEQ:
3772   case ISD::SETEQ:   return X86::COND_E;
3773   case ISD::SETOLT:              // flipped
3774   case ISD::SETOGT:
3775   case ISD::SETGT:   return X86::COND_A;
3776   case ISD::SETOLE:              // flipped
3777   case ISD::SETOGE:
3778   case ISD::SETGE:   return X86::COND_AE;
3779   case ISD::SETUGT:              // flipped
3780   case ISD::SETULT:
3781   case ISD::SETLT:   return X86::COND_B;
3782   case ISD::SETUGE:              // flipped
3783   case ISD::SETULE:
3784   case ISD::SETLE:   return X86::COND_BE;
3785   case ISD::SETONE:
3786   case ISD::SETNE:   return X86::COND_NE;
3787   case ISD::SETUO:   return X86::COND_P;
3788   case ISD::SETO:    return X86::COND_NP;
3789   case ISD::SETOEQ:
3790   case ISD::SETUNE:  return X86::COND_INVALID;
3791   }
3792 }
3793
3794 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3795 /// code. Current x86 isa includes the following FP cmov instructions:
3796 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3797 static bool hasFPCMov(unsigned X86CC) {
3798   switch (X86CC) {
3799   default:
3800     return false;
3801   case X86::COND_B:
3802   case X86::COND_BE:
3803   case X86::COND_E:
3804   case X86::COND_P:
3805   case X86::COND_A:
3806   case X86::COND_AE:
3807   case X86::COND_NE:
3808   case X86::COND_NP:
3809     return true;
3810   }
3811 }
3812
3813 /// isFPImmLegal - Returns true if the target can instruction select the
3814 /// specified FP immediate natively. If false, the legalizer will
3815 /// materialize the FP immediate as a load from a constant pool.
3816 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3817   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3818     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3819       return true;
3820   }
3821   return false;
3822 }
3823
3824 /// \brief Returns true if it is beneficial to convert a load of a constant
3825 /// to just the constant itself.
3826 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3827                                                           Type *Ty) const {
3828   assert(Ty->isIntegerTy());
3829
3830   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3831   if (BitSize == 0 || BitSize > 64)
3832     return false;
3833   return true;
3834 }
3835
3836 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3837 /// the specified range (L, H].
3838 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3839   return (Val < 0) || (Val >= Low && Val < Hi);
3840 }
3841
3842 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3843 /// specified value.
3844 static bool isUndefOrEqual(int Val, int CmpVal) {
3845   return (Val < 0 || Val == CmpVal);
3846 }
3847
3848 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3849 /// from position Pos and ending in Pos+Size, falls within the specified
3850 /// sequential range (L, L+Pos]. or is undef.
3851 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3852                                        unsigned Pos, unsigned Size, int Low) {
3853   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3854     if (!isUndefOrEqual(Mask[i], Low))
3855       return false;
3856   return true;
3857 }
3858
3859 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3860 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3861 /// the second operand.
3862 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3863   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3864     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3865   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3866     return (Mask[0] < 2 && Mask[1] < 2);
3867   return false;
3868 }
3869
3870 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3871 /// is suitable for input to PSHUFHW.
3872 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3873   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3874     return false;
3875
3876   // Lower quadword copied in order or undef.
3877   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3878     return false;
3879
3880   // Upper quadword shuffled.
3881   for (unsigned i = 4; i != 8; ++i)
3882     if (!isUndefOrInRange(Mask[i], 4, 8))
3883       return false;
3884
3885   if (VT == MVT::v16i16) {
3886     // Lower quadword copied in order or undef.
3887     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3888       return false;
3889
3890     // Upper quadword shuffled.
3891     for (unsigned i = 12; i != 16; ++i)
3892       if (!isUndefOrInRange(Mask[i], 12, 16))
3893         return false;
3894   }
3895
3896   return true;
3897 }
3898
3899 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3900 /// is suitable for input to PSHUFLW.
3901 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3902   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3903     return false;
3904
3905   // Upper quadword copied in order.
3906   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3907     return false;
3908
3909   // Lower quadword shuffled.
3910   for (unsigned i = 0; i != 4; ++i)
3911     if (!isUndefOrInRange(Mask[i], 0, 4))
3912       return false;
3913
3914   if (VT == MVT::v16i16) {
3915     // Upper quadword copied in order.
3916     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3917       return false;
3918
3919     // Lower quadword shuffled.
3920     for (unsigned i = 8; i != 12; ++i)
3921       if (!isUndefOrInRange(Mask[i], 8, 12))
3922         return false;
3923   }
3924
3925   return true;
3926 }
3927
3928 /// \brief Return true if the mask specifies a shuffle of elements that is
3929 /// suitable for input to intralane (palignr) or interlane (valign) vector
3930 /// right-shift.
3931 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3932   unsigned NumElts = VT.getVectorNumElements();
3933   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3934   unsigned NumLaneElts = NumElts/NumLanes;
3935
3936   // Do not handle 64-bit element shuffles with palignr.
3937   if (NumLaneElts == 2)
3938     return false;
3939
3940   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3941     unsigned i;
3942     for (i = 0; i != NumLaneElts; ++i) {
3943       if (Mask[i+l] >= 0)
3944         break;
3945     }
3946
3947     // Lane is all undef, go to next lane
3948     if (i == NumLaneElts)
3949       continue;
3950
3951     int Start = Mask[i+l];
3952
3953     // Make sure its in this lane in one of the sources
3954     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3955         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3956       return false;
3957
3958     // If not lane 0, then we must match lane 0
3959     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3960       return false;
3961
3962     // Correct second source to be contiguous with first source
3963     if (Start >= (int)NumElts)
3964       Start -= NumElts - NumLaneElts;
3965
3966     // Make sure we're shifting in the right direction.
3967     if (Start <= (int)(i+l))
3968       return false;
3969
3970     Start -= i;
3971
3972     // Check the rest of the elements to see if they are consecutive.
3973     for (++i; i != NumLaneElts; ++i) {
3974       int Idx = Mask[i+l];
3975
3976       // Make sure its in this lane
3977       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3978           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3979         return false;
3980
3981       // If not lane 0, then we must match lane 0
3982       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3983         return false;
3984
3985       if (Idx >= (int)NumElts)
3986         Idx -= NumElts - NumLaneElts;
3987
3988       if (!isUndefOrEqual(Idx, Start+i))
3989         return false;
3990
3991     }
3992   }
3993
3994   return true;
3995 }
3996
3997 /// \brief Return true if the node specifies a shuffle of elements that is
3998 /// suitable for input to PALIGNR.
3999 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4000                           const X86Subtarget *Subtarget) {
4001   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4002       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4003       VT.is512BitVector())
4004     // FIXME: Add AVX512BW.
4005     return false;
4006
4007   return isAlignrMask(Mask, VT, false);
4008 }
4009
4010 /// \brief Return true if the node specifies a shuffle of elements that is
4011 /// suitable for input to VALIGN.
4012 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4013                           const X86Subtarget *Subtarget) {
4014   // FIXME: Add AVX512VL.
4015   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4016     return false;
4017   return isAlignrMask(Mask, VT, true);
4018 }
4019
4020 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4021 /// the two vector operands have swapped position.
4022 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4023                                      unsigned NumElems) {
4024   for (unsigned i = 0; i != NumElems; ++i) {
4025     int idx = Mask[i];
4026     if (idx < 0)
4027       continue;
4028     else if (idx < (int)NumElems)
4029       Mask[i] = idx + NumElems;
4030     else
4031       Mask[i] = idx - NumElems;
4032   }
4033 }
4034
4035 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4036 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4037 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4038 /// reverse of what x86 shuffles want.
4039 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4040
4041   unsigned NumElems = VT.getVectorNumElements();
4042   unsigned NumLanes = VT.getSizeInBits()/128;
4043   unsigned NumLaneElems = NumElems/NumLanes;
4044
4045   if (NumLaneElems != 2 && NumLaneElems != 4)
4046     return false;
4047
4048   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4049   bool symetricMaskRequired =
4050     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4051
4052   // VSHUFPSY divides the resulting vector into 4 chunks.
4053   // The sources are also splitted into 4 chunks, and each destination
4054   // chunk must come from a different source chunk.
4055   //
4056   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4057   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4058   //
4059   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4060   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4061   //
4062   // VSHUFPDY divides the resulting vector into 4 chunks.
4063   // The sources are also splitted into 4 chunks, and each destination
4064   // chunk must come from a different source chunk.
4065   //
4066   //  SRC1 =>      X3       X2       X1       X0
4067   //  SRC2 =>      Y3       Y2       Y1       Y0
4068   //
4069   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4070   //
4071   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4072   unsigned HalfLaneElems = NumLaneElems/2;
4073   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4074     for (unsigned i = 0; i != NumLaneElems; ++i) {
4075       int Idx = Mask[i+l];
4076       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4077       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4078         return false;
4079       // For VSHUFPSY, the mask of the second half must be the same as the
4080       // first but with the appropriate offsets. This works in the same way as
4081       // VPERMILPS works with masks.
4082       if (!symetricMaskRequired || Idx < 0)
4083         continue;
4084       if (MaskVal[i] < 0) {
4085         MaskVal[i] = Idx - l;
4086         continue;
4087       }
4088       if ((signed)(Idx - l) != MaskVal[i])
4089         return false;
4090     }
4091   }
4092
4093   return true;
4094 }
4095
4096 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4097 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4098 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4099   if (!VT.is128BitVector())
4100     return false;
4101
4102   unsigned NumElems = VT.getVectorNumElements();
4103
4104   if (NumElems != 4)
4105     return false;
4106
4107   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4108   return isUndefOrEqual(Mask[0], 6) &&
4109          isUndefOrEqual(Mask[1], 7) &&
4110          isUndefOrEqual(Mask[2], 2) &&
4111          isUndefOrEqual(Mask[3], 3);
4112 }
4113
4114 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4115 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4116 /// <2, 3, 2, 3>
4117 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4118   if (!VT.is128BitVector())
4119     return false;
4120
4121   unsigned NumElems = VT.getVectorNumElements();
4122
4123   if (NumElems != 4)
4124     return false;
4125
4126   return isUndefOrEqual(Mask[0], 2) &&
4127          isUndefOrEqual(Mask[1], 3) &&
4128          isUndefOrEqual(Mask[2], 2) &&
4129          isUndefOrEqual(Mask[3], 3);
4130 }
4131
4132 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4133 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4134 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4135   if (!VT.is128BitVector())
4136     return false;
4137
4138   unsigned NumElems = VT.getVectorNumElements();
4139
4140   if (NumElems != 2 && NumElems != 4)
4141     return false;
4142
4143   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4144     if (!isUndefOrEqual(Mask[i], i + NumElems))
4145       return false;
4146
4147   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4148     if (!isUndefOrEqual(Mask[i], i))
4149       return false;
4150
4151   return true;
4152 }
4153
4154 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4155 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4156 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4157   if (!VT.is128BitVector())
4158     return false;
4159
4160   unsigned NumElems = VT.getVectorNumElements();
4161
4162   if (NumElems != 2 && NumElems != 4)
4163     return false;
4164
4165   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4166     if (!isUndefOrEqual(Mask[i], i))
4167       return false;
4168
4169   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4170     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4171       return false;
4172
4173   return true;
4174 }
4175
4176 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4177 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4178 /// i. e: If all but one element come from the same vector.
4179 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4180   // TODO: Deal with AVX's VINSERTPS
4181   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4182     return false;
4183
4184   unsigned CorrectPosV1 = 0;
4185   unsigned CorrectPosV2 = 0;
4186   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4187     if (Mask[i] == -1) {
4188       ++CorrectPosV1;
4189       ++CorrectPosV2;
4190       continue;
4191     }
4192
4193     if (Mask[i] == i)
4194       ++CorrectPosV1;
4195     else if (Mask[i] == i + 4)
4196       ++CorrectPosV2;
4197   }
4198
4199   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4200     // We have 3 elements (undefs count as elements from any vector) from one
4201     // vector, and one from another.
4202     return true;
4203
4204   return false;
4205 }
4206
4207 //
4208 // Some special combinations that can be optimized.
4209 //
4210 static
4211 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4212                                SelectionDAG &DAG) {
4213   MVT VT = SVOp->getSimpleValueType(0);
4214   SDLoc dl(SVOp);
4215
4216   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4217     return SDValue();
4218
4219   ArrayRef<int> Mask = SVOp->getMask();
4220
4221   // These are the special masks that may be optimized.
4222   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4223   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4224   bool MatchEvenMask = true;
4225   bool MatchOddMask  = true;
4226   for (int i=0; i<8; ++i) {
4227     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4228       MatchEvenMask = false;
4229     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4230       MatchOddMask = false;
4231   }
4232
4233   if (!MatchEvenMask && !MatchOddMask)
4234     return SDValue();
4235
4236   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4237
4238   SDValue Op0 = SVOp->getOperand(0);
4239   SDValue Op1 = SVOp->getOperand(1);
4240
4241   if (MatchEvenMask) {
4242     // Shift the second operand right to 32 bits.
4243     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4244     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4245   } else {
4246     // Shift the first operand left to 32 bits.
4247     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4248     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4249   }
4250   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4251   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4252 }
4253
4254 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4255 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4256 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4257                          bool HasInt256, bool V2IsSplat = false) {
4258
4259   assert(VT.getSizeInBits() >= 128 &&
4260          "Unsupported vector type for unpckl");
4261
4262   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4263   unsigned NumLanes;
4264   unsigned NumOf256BitLanes;
4265   unsigned NumElts = VT.getVectorNumElements();
4266   if (VT.is256BitVector()) {
4267     if (NumElts != 4 && NumElts != 8 &&
4268         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4269     return false;
4270     NumLanes = 2;
4271     NumOf256BitLanes = 1;
4272   } else if (VT.is512BitVector()) {
4273     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4274            "Unsupported vector type for unpckh");
4275     NumLanes = 2;
4276     NumOf256BitLanes = 2;
4277   } else {
4278     NumLanes = 1;
4279     NumOf256BitLanes = 1;
4280   }
4281
4282   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4283   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4284
4285   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4286     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4287       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4288         int BitI  = Mask[l256*NumEltsInStride+l+i];
4289         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4290         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4291           return false;
4292         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4293           return false;
4294         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4295           return false;
4296       }
4297     }
4298   }
4299   return true;
4300 }
4301
4302 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4303 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4304 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4305                          bool HasInt256, bool V2IsSplat = false) {
4306   assert(VT.getSizeInBits() >= 128 &&
4307          "Unsupported vector type for unpckh");
4308
4309   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4310   unsigned NumLanes;
4311   unsigned NumOf256BitLanes;
4312   unsigned NumElts = VT.getVectorNumElements();
4313   if (VT.is256BitVector()) {
4314     if (NumElts != 4 && NumElts != 8 &&
4315         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4316     return false;
4317     NumLanes = 2;
4318     NumOf256BitLanes = 1;
4319   } else if (VT.is512BitVector()) {
4320     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4321            "Unsupported vector type for unpckh");
4322     NumLanes = 2;
4323     NumOf256BitLanes = 2;
4324   } else {
4325     NumLanes = 1;
4326     NumOf256BitLanes = 1;
4327   }
4328
4329   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4330   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4331
4332   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4333     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4334       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4335         int BitI  = Mask[l256*NumEltsInStride+l+i];
4336         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4337         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4338           return false;
4339         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4340           return false;
4341         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4342           return false;
4343       }
4344     }
4345   }
4346   return true;
4347 }
4348
4349 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4350 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4351 /// <0, 0, 1, 1>
4352 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4353   unsigned NumElts = VT.getVectorNumElements();
4354   bool Is256BitVec = VT.is256BitVector();
4355
4356   if (VT.is512BitVector())
4357     return false;
4358   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4359          "Unsupported vector type for unpckh");
4360
4361   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4362       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4363     return false;
4364
4365   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4366   // FIXME: Need a better way to get rid of this, there's no latency difference
4367   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4368   // the former later. We should also remove the "_undef" special mask.
4369   if (NumElts == 4 && Is256BitVec)
4370     return false;
4371
4372   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4373   // independently on 128-bit lanes.
4374   unsigned NumLanes = VT.getSizeInBits()/128;
4375   unsigned NumLaneElts = NumElts/NumLanes;
4376
4377   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4378     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4379       int BitI  = Mask[l+i];
4380       int BitI1 = Mask[l+i+1];
4381
4382       if (!isUndefOrEqual(BitI, j))
4383         return false;
4384       if (!isUndefOrEqual(BitI1, j))
4385         return false;
4386     }
4387   }
4388
4389   return true;
4390 }
4391
4392 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4393 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4394 /// <2, 2, 3, 3>
4395 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4396   unsigned NumElts = VT.getVectorNumElements();
4397
4398   if (VT.is512BitVector())
4399     return false;
4400
4401   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4402          "Unsupported vector type for unpckh");
4403
4404   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4405       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4406     return false;
4407
4408   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4409   // independently on 128-bit lanes.
4410   unsigned NumLanes = VT.getSizeInBits()/128;
4411   unsigned NumLaneElts = NumElts/NumLanes;
4412
4413   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4414     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4415       int BitI  = Mask[l+i];
4416       int BitI1 = Mask[l+i+1];
4417       if (!isUndefOrEqual(BitI, j))
4418         return false;
4419       if (!isUndefOrEqual(BitI1, j))
4420         return false;
4421     }
4422   }
4423   return true;
4424 }
4425
4426 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4427 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4428 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4429   if (!VT.is512BitVector())
4430     return false;
4431
4432   unsigned NumElts = VT.getVectorNumElements();
4433   unsigned HalfSize = NumElts/2;
4434   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4435     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4436       *Imm = 1;
4437       return true;
4438     }
4439   }
4440   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4441     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4442       *Imm = 0;
4443       return true;
4444     }
4445   }
4446   return false;
4447 }
4448
4449 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4450 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4451 /// MOVSD, and MOVD, i.e. setting the lowest element.
4452 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4453   if (VT.getVectorElementType().getSizeInBits() < 32)
4454     return false;
4455   if (!VT.is128BitVector())
4456     return false;
4457
4458   unsigned NumElts = VT.getVectorNumElements();
4459
4460   if (!isUndefOrEqual(Mask[0], NumElts))
4461     return false;
4462
4463   for (unsigned i = 1; i != NumElts; ++i)
4464     if (!isUndefOrEqual(Mask[i], i))
4465       return false;
4466
4467   return true;
4468 }
4469
4470 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4471 /// as permutations between 128-bit chunks or halves. As an example: this
4472 /// shuffle bellow:
4473 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4474 /// The first half comes from the second half of V1 and the second half from the
4475 /// the second half of V2.
4476 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4477   if (!HasFp256 || !VT.is256BitVector())
4478     return false;
4479
4480   // The shuffle result is divided into half A and half B. In total the two
4481   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4482   // B must come from C, D, E or F.
4483   unsigned HalfSize = VT.getVectorNumElements()/2;
4484   bool MatchA = false, MatchB = false;
4485
4486   // Check if A comes from one of C, D, E, F.
4487   for (unsigned Half = 0; Half != 4; ++Half) {
4488     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4489       MatchA = true;
4490       break;
4491     }
4492   }
4493
4494   // Check if B comes from one of C, D, E, F.
4495   for (unsigned Half = 0; Half != 4; ++Half) {
4496     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4497       MatchB = true;
4498       break;
4499     }
4500   }
4501
4502   return MatchA && MatchB;
4503 }
4504
4505 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4506 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4507 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4508   MVT VT = SVOp->getSimpleValueType(0);
4509
4510   unsigned HalfSize = VT.getVectorNumElements()/2;
4511
4512   unsigned FstHalf = 0, SndHalf = 0;
4513   for (unsigned i = 0; i < HalfSize; ++i) {
4514     if (SVOp->getMaskElt(i) > 0) {
4515       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4516       break;
4517     }
4518   }
4519   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4520     if (SVOp->getMaskElt(i) > 0) {
4521       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4522       break;
4523     }
4524   }
4525
4526   return (FstHalf | (SndHalf << 4));
4527 }
4528
4529 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4530 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4531   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4532   if (EltSize < 32)
4533     return false;
4534
4535   unsigned NumElts = VT.getVectorNumElements();
4536   Imm8 = 0;
4537   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4538     for (unsigned i = 0; i != NumElts; ++i) {
4539       if (Mask[i] < 0)
4540         continue;
4541       Imm8 |= Mask[i] << (i*2);
4542     }
4543     return true;
4544   }
4545
4546   unsigned LaneSize = 4;
4547   SmallVector<int, 4> MaskVal(LaneSize, -1);
4548
4549   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4550     for (unsigned i = 0; i != LaneSize; ++i) {
4551       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4552         return false;
4553       if (Mask[i+l] < 0)
4554         continue;
4555       if (MaskVal[i] < 0) {
4556         MaskVal[i] = Mask[i+l] - l;
4557         Imm8 |= MaskVal[i] << (i*2);
4558         continue;
4559       }
4560       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4561         return false;
4562     }
4563   }
4564   return true;
4565 }
4566
4567 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4568 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4569 /// Note that VPERMIL mask matching is different depending whether theunderlying
4570 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4571 /// to the same elements of the low, but to the higher half of the source.
4572 /// In VPERMILPD the two lanes could be shuffled independently of each other
4573 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4574 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4575   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4576   if (VT.getSizeInBits() < 256 || EltSize < 32)
4577     return false;
4578   bool symetricMaskRequired = (EltSize == 32);
4579   unsigned NumElts = VT.getVectorNumElements();
4580
4581   unsigned NumLanes = VT.getSizeInBits()/128;
4582   unsigned LaneSize = NumElts/NumLanes;
4583   // 2 or 4 elements in one lane
4584
4585   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4586   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4587     for (unsigned i = 0; i != LaneSize; ++i) {
4588       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4589         return false;
4590       if (symetricMaskRequired) {
4591         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4592           ExpectedMaskVal[i] = Mask[i+l] - l;
4593           continue;
4594         }
4595         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4596           return false;
4597       }
4598     }
4599   }
4600   return true;
4601 }
4602
4603 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4604 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4605 /// element of vector 2 and the other elements to come from vector 1 in order.
4606 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4607                                bool V2IsSplat = false, bool V2IsUndef = false) {
4608   if (!VT.is128BitVector())
4609     return false;
4610
4611   unsigned NumOps = VT.getVectorNumElements();
4612   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4613     return false;
4614
4615   if (!isUndefOrEqual(Mask[0], 0))
4616     return false;
4617
4618   for (unsigned i = 1; i != NumOps; ++i)
4619     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4620           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4621           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4622       return false;
4623
4624   return true;
4625 }
4626
4627 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4628 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4629 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4630 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4631                            const X86Subtarget *Subtarget) {
4632   if (!Subtarget->hasSSE3())
4633     return false;
4634
4635   unsigned NumElems = VT.getVectorNumElements();
4636
4637   if ((VT.is128BitVector() && NumElems != 4) ||
4638       (VT.is256BitVector() && NumElems != 8) ||
4639       (VT.is512BitVector() && NumElems != 16))
4640     return false;
4641
4642   // "i+1" is the value the indexed mask element must have
4643   for (unsigned i = 0; i != NumElems; i += 2)
4644     if (!isUndefOrEqual(Mask[i], i+1) ||
4645         !isUndefOrEqual(Mask[i+1], i+1))
4646       return false;
4647
4648   return true;
4649 }
4650
4651 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4652 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4653 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4654 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4655                            const X86Subtarget *Subtarget) {
4656   if (!Subtarget->hasSSE3())
4657     return false;
4658
4659   unsigned NumElems = VT.getVectorNumElements();
4660
4661   if ((VT.is128BitVector() && NumElems != 4) ||
4662       (VT.is256BitVector() && NumElems != 8) ||
4663       (VT.is512BitVector() && NumElems != 16))
4664     return false;
4665
4666   // "i" is the value the indexed mask element must have
4667   for (unsigned i = 0; i != NumElems; i += 2)
4668     if (!isUndefOrEqual(Mask[i], i) ||
4669         !isUndefOrEqual(Mask[i+1], i))
4670       return false;
4671
4672   return true;
4673 }
4674
4675 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4676 /// specifies a shuffle of elements that is suitable for input to 256-bit
4677 /// version of MOVDDUP.
4678 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4679   if (!HasFp256 || !VT.is256BitVector())
4680     return false;
4681
4682   unsigned NumElts = VT.getVectorNumElements();
4683   if (NumElts != 4)
4684     return false;
4685
4686   for (unsigned i = 0; i != NumElts/2; ++i)
4687     if (!isUndefOrEqual(Mask[i], 0))
4688       return false;
4689   for (unsigned i = NumElts/2; i != NumElts; ++i)
4690     if (!isUndefOrEqual(Mask[i], NumElts/2))
4691       return false;
4692   return true;
4693 }
4694
4695 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4696 /// specifies a shuffle of elements that is suitable for input to 128-bit
4697 /// version of MOVDDUP.
4698 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4699   if (!VT.is128BitVector())
4700     return false;
4701
4702   unsigned e = VT.getVectorNumElements() / 2;
4703   for (unsigned i = 0; i != e; ++i)
4704     if (!isUndefOrEqual(Mask[i], i))
4705       return false;
4706   for (unsigned i = 0; i != e; ++i)
4707     if (!isUndefOrEqual(Mask[e+i], i))
4708       return false;
4709   return true;
4710 }
4711
4712 /// isVEXTRACTIndex - Return true if the specified
4713 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4714 /// suitable for instruction that extract 128 or 256 bit vectors
4715 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4716   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4717   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4718     return false;
4719
4720   // The index should be aligned on a vecWidth-bit boundary.
4721   uint64_t Index =
4722     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4723
4724   MVT VT = N->getSimpleValueType(0);
4725   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4726   bool Result = (Index * ElSize) % vecWidth == 0;
4727
4728   return Result;
4729 }
4730
4731 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4732 /// operand specifies a subvector insert that is suitable for input to
4733 /// insertion of 128 or 256-bit subvectors
4734 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4735   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4736   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4737     return false;
4738   // The index should be aligned on a vecWidth-bit boundary.
4739   uint64_t Index =
4740     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4741
4742   MVT VT = N->getSimpleValueType(0);
4743   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4744   bool Result = (Index * ElSize) % vecWidth == 0;
4745
4746   return Result;
4747 }
4748
4749 bool X86::isVINSERT128Index(SDNode *N) {
4750   return isVINSERTIndex(N, 128);
4751 }
4752
4753 bool X86::isVINSERT256Index(SDNode *N) {
4754   return isVINSERTIndex(N, 256);
4755 }
4756
4757 bool X86::isVEXTRACT128Index(SDNode *N) {
4758   return isVEXTRACTIndex(N, 128);
4759 }
4760
4761 bool X86::isVEXTRACT256Index(SDNode *N) {
4762   return isVEXTRACTIndex(N, 256);
4763 }
4764
4765 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4766 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4767 /// Handles 128-bit and 256-bit.
4768 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4769   MVT VT = N->getSimpleValueType(0);
4770
4771   assert((VT.getSizeInBits() >= 128) &&
4772          "Unsupported vector type for PSHUF/SHUFP");
4773
4774   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4775   // independently on 128-bit lanes.
4776   unsigned NumElts = VT.getVectorNumElements();
4777   unsigned NumLanes = VT.getSizeInBits()/128;
4778   unsigned NumLaneElts = NumElts/NumLanes;
4779
4780   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4781          "Only supports 2, 4 or 8 elements per lane");
4782
4783   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4784   unsigned Mask = 0;
4785   for (unsigned i = 0; i != NumElts; ++i) {
4786     int Elt = N->getMaskElt(i);
4787     if (Elt < 0) continue;
4788     Elt &= NumLaneElts - 1;
4789     unsigned ShAmt = (i << Shift) % 8;
4790     Mask |= Elt << ShAmt;
4791   }
4792
4793   return Mask;
4794 }
4795
4796 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4797 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4798 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4799   MVT VT = N->getSimpleValueType(0);
4800
4801   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4802          "Unsupported vector type for PSHUFHW");
4803
4804   unsigned NumElts = VT.getVectorNumElements();
4805
4806   unsigned Mask = 0;
4807   for (unsigned l = 0; l != NumElts; l += 8) {
4808     // 8 nodes per lane, but we only care about the last 4.
4809     for (unsigned i = 0; i < 4; ++i) {
4810       int Elt = N->getMaskElt(l+i+4);
4811       if (Elt < 0) continue;
4812       Elt &= 0x3; // only 2-bits.
4813       Mask |= Elt << (i * 2);
4814     }
4815   }
4816
4817   return Mask;
4818 }
4819
4820 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4821 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4822 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4823   MVT VT = N->getSimpleValueType(0);
4824
4825   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4826          "Unsupported vector type for PSHUFHW");
4827
4828   unsigned NumElts = VT.getVectorNumElements();
4829
4830   unsigned Mask = 0;
4831   for (unsigned l = 0; l != NumElts; l += 8) {
4832     // 8 nodes per lane, but we only care about the first 4.
4833     for (unsigned i = 0; i < 4; ++i) {
4834       int Elt = N->getMaskElt(l+i);
4835       if (Elt < 0) continue;
4836       Elt &= 0x3; // only 2-bits
4837       Mask |= Elt << (i * 2);
4838     }
4839   }
4840
4841   return Mask;
4842 }
4843
4844 /// \brief Return the appropriate immediate to shuffle the specified
4845 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4846 /// VALIGN (if Interlane is true) instructions.
4847 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4848                                            bool InterLane) {
4849   MVT VT = SVOp->getSimpleValueType(0);
4850   unsigned EltSize = InterLane ? 1 :
4851     VT.getVectorElementType().getSizeInBits() >> 3;
4852
4853   unsigned NumElts = VT.getVectorNumElements();
4854   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4855   unsigned NumLaneElts = NumElts/NumLanes;
4856
4857   int Val = 0;
4858   unsigned i;
4859   for (i = 0; i != NumElts; ++i) {
4860     Val = SVOp->getMaskElt(i);
4861     if (Val >= 0)
4862       break;
4863   }
4864   if (Val >= (int)NumElts)
4865     Val -= NumElts - NumLaneElts;
4866
4867   assert(Val - i > 0 && "PALIGNR imm should be positive");
4868   return (Val - i) * EltSize;
4869 }
4870
4871 /// \brief Return the appropriate immediate to shuffle the specified
4872 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4873 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4874   return getShuffleAlignrImmediate(SVOp, false);
4875 }
4876
4877 /// \brief Return the appropriate immediate to shuffle the specified
4878 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4879 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4880   return getShuffleAlignrImmediate(SVOp, true);
4881 }
4882
4883
4884 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4885   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4886   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4887     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4888
4889   uint64_t Index =
4890     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4891
4892   MVT VecVT = N->getOperand(0).getSimpleValueType();
4893   MVT ElVT = VecVT.getVectorElementType();
4894
4895   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4896   return Index / NumElemsPerChunk;
4897 }
4898
4899 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4900   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4901   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4902     llvm_unreachable("Illegal insert subvector for VINSERT");
4903
4904   uint64_t Index =
4905     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4906
4907   MVT VecVT = N->getSimpleValueType(0);
4908   MVT ElVT = VecVT.getVectorElementType();
4909
4910   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4911   return Index / NumElemsPerChunk;
4912 }
4913
4914 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4915 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4916 /// and VINSERTI128 instructions.
4917 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4918   return getExtractVEXTRACTImmediate(N, 128);
4919 }
4920
4921 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4922 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4923 /// and VINSERTI64x4 instructions.
4924 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4925   return getExtractVEXTRACTImmediate(N, 256);
4926 }
4927
4928 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4929 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4930 /// and VINSERTI128 instructions.
4931 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4932   return getInsertVINSERTImmediate(N, 128);
4933 }
4934
4935 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4936 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4937 /// and VINSERTI64x4 instructions.
4938 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4939   return getInsertVINSERTImmediate(N, 256);
4940 }
4941
4942 /// isZero - Returns true if Elt is a constant integer zero
4943 static bool isZero(SDValue V) {
4944   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4945   return C && C->isNullValue();
4946 }
4947
4948 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4949 /// constant +0.0.
4950 bool X86::isZeroNode(SDValue Elt) {
4951   if (isZero(Elt))
4952     return true;
4953   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4954     return CFP->getValueAPF().isPosZero();
4955   return false;
4956 }
4957
4958 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4959 /// match movhlps. The lower half elements should come from upper half of
4960 /// V1 (and in order), and the upper half elements should come from the upper
4961 /// half of V2 (and in order).
4962 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4963   if (!VT.is128BitVector())
4964     return false;
4965   if (VT.getVectorNumElements() != 4)
4966     return false;
4967   for (unsigned i = 0, e = 2; i != e; ++i)
4968     if (!isUndefOrEqual(Mask[i], i+2))
4969       return false;
4970   for (unsigned i = 2; i != 4; ++i)
4971     if (!isUndefOrEqual(Mask[i], i+4))
4972       return false;
4973   return true;
4974 }
4975
4976 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4977 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4978 /// required.
4979 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4980   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4981     return false;
4982   N = N->getOperand(0).getNode();
4983   if (!ISD::isNON_EXTLoad(N))
4984     return false;
4985   if (LD)
4986     *LD = cast<LoadSDNode>(N);
4987   return true;
4988 }
4989
4990 // Test whether the given value is a vector value which will be legalized
4991 // into a load.
4992 static bool WillBeConstantPoolLoad(SDNode *N) {
4993   if (N->getOpcode() != ISD::BUILD_VECTOR)
4994     return false;
4995
4996   // Check for any non-constant elements.
4997   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4998     switch (N->getOperand(i).getNode()->getOpcode()) {
4999     case ISD::UNDEF:
5000     case ISD::ConstantFP:
5001     case ISD::Constant:
5002       break;
5003     default:
5004       return false;
5005     }
5006
5007   // Vectors of all-zeros and all-ones are materialized with special
5008   // instructions rather than being loaded.
5009   return !ISD::isBuildVectorAllZeros(N) &&
5010          !ISD::isBuildVectorAllOnes(N);
5011 }
5012
5013 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5014 /// match movlp{s|d}. The lower half elements should come from lower half of
5015 /// V1 (and in order), and the upper half elements should come from the upper
5016 /// half of V2 (and in order). And since V1 will become the source of the
5017 /// MOVLP, it must be either a vector load or a scalar load to vector.
5018 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5019                                ArrayRef<int> Mask, MVT VT) {
5020   if (!VT.is128BitVector())
5021     return false;
5022
5023   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5024     return false;
5025   // Is V2 is a vector load, don't do this transformation. We will try to use
5026   // load folding shufps op.
5027   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5028     return false;
5029
5030   unsigned NumElems = VT.getVectorNumElements();
5031
5032   if (NumElems != 2 && NumElems != 4)
5033     return false;
5034   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5035     if (!isUndefOrEqual(Mask[i], i))
5036       return false;
5037   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5038     if (!isUndefOrEqual(Mask[i], i+NumElems))
5039       return false;
5040   return true;
5041 }
5042
5043 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5044 /// to an zero vector.
5045 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5046 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5047   SDValue V1 = N->getOperand(0);
5048   SDValue V2 = N->getOperand(1);
5049   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5050   for (unsigned i = 0; i != NumElems; ++i) {
5051     int Idx = N->getMaskElt(i);
5052     if (Idx >= (int)NumElems) {
5053       unsigned Opc = V2.getOpcode();
5054       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5055         continue;
5056       if (Opc != ISD::BUILD_VECTOR ||
5057           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5058         return false;
5059     } else if (Idx >= 0) {
5060       unsigned Opc = V1.getOpcode();
5061       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5062         continue;
5063       if (Opc != ISD::BUILD_VECTOR ||
5064           !X86::isZeroNode(V1.getOperand(Idx)))
5065         return false;
5066     }
5067   }
5068   return true;
5069 }
5070
5071 /// getZeroVector - Returns a vector of specified type with all zero elements.
5072 ///
5073 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5074                              SelectionDAG &DAG, SDLoc dl) {
5075   assert(VT.isVector() && "Expected a vector type");
5076
5077   // Always build SSE zero vectors as <4 x i32> bitcasted
5078   // to their dest type. This ensures they get CSE'd.
5079   SDValue Vec;
5080   if (VT.is128BitVector()) {  // SSE
5081     if (Subtarget->hasSSE2()) {  // SSE2
5082       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5083       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5084     } else { // SSE1
5085       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5086       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5087     }
5088   } else if (VT.is256BitVector()) { // AVX
5089     if (Subtarget->hasInt256()) { // AVX2
5090       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5091       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5092       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5093     } else {
5094       // 256-bit logic and arithmetic instructions in AVX are all
5095       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5096       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5097       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5098       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5099     }
5100   } else if (VT.is512BitVector()) { // AVX-512
5101       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5102       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5103                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5104       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5105   } else if (VT.getScalarType() == MVT::i1) {
5106     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5107     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5108     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5109     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5110   } else
5111     llvm_unreachable("Unexpected vector type");
5112
5113   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5114 }
5115
5116 /// getOnesVector - Returns a vector of specified type with all bits set.
5117 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5118 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5119 /// Then bitcast to their original type, ensuring they get CSE'd.
5120 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5121                              SDLoc dl) {
5122   assert(VT.isVector() && "Expected a vector type");
5123
5124   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5125   SDValue Vec;
5126   if (VT.is256BitVector()) {
5127     if (HasInt256) { // AVX2
5128       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5129       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5130     } else { // AVX
5131       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5132       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5133     }
5134   } else if (VT.is128BitVector()) {
5135     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5136   } else
5137     llvm_unreachable("Unexpected vector type");
5138
5139   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5140 }
5141
5142 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5143 /// that point to V2 points to its first element.
5144 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5145   for (unsigned i = 0; i != NumElems; ++i) {
5146     if (Mask[i] > (int)NumElems) {
5147       Mask[i] = NumElems;
5148     }
5149   }
5150 }
5151
5152 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5153 /// operation of specified width.
5154 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5155                        SDValue V2) {
5156   unsigned NumElems = VT.getVectorNumElements();
5157   SmallVector<int, 8> Mask;
5158   Mask.push_back(NumElems);
5159   for (unsigned i = 1; i != NumElems; ++i)
5160     Mask.push_back(i);
5161   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5162 }
5163
5164 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5165 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5166                           SDValue V2) {
5167   unsigned NumElems = VT.getVectorNumElements();
5168   SmallVector<int, 8> Mask;
5169   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5170     Mask.push_back(i);
5171     Mask.push_back(i + NumElems);
5172   }
5173   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5174 }
5175
5176 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5177 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5178                           SDValue V2) {
5179   unsigned NumElems = VT.getVectorNumElements();
5180   SmallVector<int, 8> Mask;
5181   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5182     Mask.push_back(i + Half);
5183     Mask.push_back(i + NumElems + Half);
5184   }
5185   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5186 }
5187
5188 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5189 // a generic shuffle instruction because the target has no such instructions.
5190 // Generate shuffles which repeat i16 and i8 several times until they can be
5191 // represented by v4f32 and then be manipulated by target suported shuffles.
5192 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5193   MVT VT = V.getSimpleValueType();
5194   int NumElems = VT.getVectorNumElements();
5195   SDLoc dl(V);
5196
5197   while (NumElems > 4) {
5198     if (EltNo < NumElems/2) {
5199       V = getUnpackl(DAG, dl, VT, V, V);
5200     } else {
5201       V = getUnpackh(DAG, dl, VT, V, V);
5202       EltNo -= NumElems/2;
5203     }
5204     NumElems >>= 1;
5205   }
5206   return V;
5207 }
5208
5209 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5210 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5211   MVT VT = V.getSimpleValueType();
5212   SDLoc dl(V);
5213
5214   if (VT.is128BitVector()) {
5215     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5216     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5217     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5218                              &SplatMask[0]);
5219   } else if (VT.is256BitVector()) {
5220     // To use VPERMILPS to splat scalars, the second half of indicies must
5221     // refer to the higher part, which is a duplication of the lower one,
5222     // because VPERMILPS can only handle in-lane permutations.
5223     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5224                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5225
5226     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5227     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5228                              &SplatMask[0]);
5229   } else
5230     llvm_unreachable("Vector size not supported");
5231
5232   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5233 }
5234
5235 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5236 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5237   MVT SrcVT = SV->getSimpleValueType(0);
5238   SDValue V1 = SV->getOperand(0);
5239   SDLoc dl(SV);
5240
5241   int EltNo = SV->getSplatIndex();
5242   int NumElems = SrcVT.getVectorNumElements();
5243   bool Is256BitVec = SrcVT.is256BitVector();
5244
5245   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5246          "Unknown how to promote splat for type");
5247
5248   // Extract the 128-bit part containing the splat element and update
5249   // the splat element index when it refers to the higher register.
5250   if (Is256BitVec) {
5251     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5252     if (EltNo >= NumElems/2)
5253       EltNo -= NumElems/2;
5254   }
5255
5256   // All i16 and i8 vector types can't be used directly by a generic shuffle
5257   // instruction because the target has no such instruction. Generate shuffles
5258   // which repeat i16 and i8 several times until they fit in i32, and then can
5259   // be manipulated by target suported shuffles.
5260   MVT EltVT = SrcVT.getVectorElementType();
5261   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5262     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5263
5264   // Recreate the 256-bit vector and place the same 128-bit vector
5265   // into the low and high part. This is necessary because we want
5266   // to use VPERM* to shuffle the vectors
5267   if (Is256BitVec) {
5268     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5269   }
5270
5271   return getLegalSplat(DAG, V1, EltNo);
5272 }
5273
5274 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5275 /// vector of zero or undef vector.  This produces a shuffle where the low
5276 /// element of V2 is swizzled into the zero/undef vector, landing at element
5277 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5278 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5279                                            bool IsZero,
5280                                            const X86Subtarget *Subtarget,
5281                                            SelectionDAG &DAG) {
5282   MVT VT = V2.getSimpleValueType();
5283   SDValue V1 = IsZero
5284     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5285   unsigned NumElems = VT.getVectorNumElements();
5286   SmallVector<int, 16> MaskVec;
5287   for (unsigned i = 0; i != NumElems; ++i)
5288     // If this is the insertion idx, put the low elt of V2 here.
5289     MaskVec.push_back(i == Idx ? NumElems : i);
5290   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5291 }
5292
5293 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5294 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5295 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5296 /// shuffles which use a single input multiple times, and in those cases it will
5297 /// adjust the mask to only have indices within that single input.
5298 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5299                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5300   unsigned NumElems = VT.getVectorNumElements();
5301   SDValue ImmN;
5302
5303   IsUnary = false;
5304   bool IsFakeUnary = false;
5305   switch(N->getOpcode()) {
5306   case X86ISD::SHUFP:
5307     ImmN = N->getOperand(N->getNumOperands()-1);
5308     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5309     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5310     break;
5311   case X86ISD::UNPCKH:
5312     DecodeUNPCKHMask(VT, Mask);
5313     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5314     break;
5315   case X86ISD::UNPCKL:
5316     DecodeUNPCKLMask(VT, Mask);
5317     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5318     break;
5319   case X86ISD::MOVHLPS:
5320     DecodeMOVHLPSMask(NumElems, Mask);
5321     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5322     break;
5323   case X86ISD::MOVLHPS:
5324     DecodeMOVLHPSMask(NumElems, Mask);
5325     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5326     break;
5327   case X86ISD::PALIGNR:
5328     ImmN = N->getOperand(N->getNumOperands()-1);
5329     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5330     break;
5331   case X86ISD::PSHUFD:
5332   case X86ISD::VPERMILP:
5333     ImmN = N->getOperand(N->getNumOperands()-1);
5334     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5335     IsUnary = true;
5336     break;
5337   case X86ISD::PSHUFHW:
5338     ImmN = N->getOperand(N->getNumOperands()-1);
5339     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5340     IsUnary = true;
5341     break;
5342   case X86ISD::PSHUFLW:
5343     ImmN = N->getOperand(N->getNumOperands()-1);
5344     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5345     IsUnary = true;
5346     break;
5347   case X86ISD::PSHUFB: {
5348     IsUnary = true;
5349     SDValue MaskNode = N->getOperand(1);
5350     while (MaskNode->getOpcode() == ISD::BITCAST)
5351       MaskNode = MaskNode->getOperand(0);
5352
5353     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5354       // If we have a build-vector, then things are easy.
5355       EVT VT = MaskNode.getValueType();
5356       assert(VT.isVector() &&
5357              "Can't produce a non-vector with a build_vector!");
5358       if (!VT.isInteger())
5359         return false;
5360
5361       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5362
5363       SmallVector<uint64_t, 32> RawMask;
5364       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5365         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5366         if (!CN)
5367           return false;
5368         APInt MaskElement = CN->getAPIntValue();
5369
5370         // We now have to decode the element which could be any integer size and
5371         // extract each byte of it.
5372         for (int j = 0; j < NumBytesPerElement; ++j) {
5373           // Note that this is x86 and so always little endian: the low byte is
5374           // the first byte of the mask.
5375           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5376           MaskElement = MaskElement.lshr(8);
5377         }
5378       }
5379       DecodePSHUFBMask(RawMask, Mask);
5380       break;
5381     }
5382
5383     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5384     if (!MaskLoad)
5385       return false;
5386
5387     SDValue Ptr = MaskLoad->getBasePtr();
5388     if (Ptr->getOpcode() == X86ISD::Wrapper)
5389       Ptr = Ptr->getOperand(0);
5390
5391     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5392     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5393       return false;
5394
5395     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5396       // FIXME: Support AVX-512 here.
5397       if (!C->getType()->isVectorTy() ||
5398           (C->getNumElements() != 16 && C->getNumElements() != 32))
5399         return false;
5400
5401       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5402       DecodePSHUFBMask(C, Mask);
5403       break;
5404     }
5405
5406     return false;
5407   }
5408   case X86ISD::VPERMI:
5409     ImmN = N->getOperand(N->getNumOperands()-1);
5410     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5411     IsUnary = true;
5412     break;
5413   case X86ISD::MOVSS:
5414   case X86ISD::MOVSD: {
5415     // The index 0 always comes from the first element of the second source,
5416     // this is why MOVSS and MOVSD are used in the first place. The other
5417     // elements come from the other positions of the first source vector
5418     Mask.push_back(NumElems);
5419     for (unsigned i = 1; i != NumElems; ++i) {
5420       Mask.push_back(i);
5421     }
5422     break;
5423   }
5424   case X86ISD::VPERM2X128:
5425     ImmN = N->getOperand(N->getNumOperands()-1);
5426     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5427     if (Mask.empty()) return false;
5428     break;
5429   case X86ISD::MOVDDUP:
5430   case X86ISD::MOVLHPD:
5431   case X86ISD::MOVLPD:
5432   case X86ISD::MOVLPS:
5433   case X86ISD::MOVSHDUP:
5434   case X86ISD::MOVSLDUP:
5435     // Not yet implemented
5436     return false;
5437   default: llvm_unreachable("unknown target shuffle node");
5438   }
5439
5440   // If we have a fake unary shuffle, the shuffle mask is spread across two
5441   // inputs that are actually the same node. Re-map the mask to always point
5442   // into the first input.
5443   if (IsFakeUnary)
5444     for (int &M : Mask)
5445       if (M >= (int)Mask.size())
5446         M -= Mask.size();
5447
5448   return true;
5449 }
5450
5451 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5452 /// element of the result of the vector shuffle.
5453 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5454                                    unsigned Depth) {
5455   if (Depth == 6)
5456     return SDValue();  // Limit search depth.
5457
5458   SDValue V = SDValue(N, 0);
5459   EVT VT = V.getValueType();
5460   unsigned Opcode = V.getOpcode();
5461
5462   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5463   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5464     int Elt = SV->getMaskElt(Index);
5465
5466     if (Elt < 0)
5467       return DAG.getUNDEF(VT.getVectorElementType());
5468
5469     unsigned NumElems = VT.getVectorNumElements();
5470     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5471                                          : SV->getOperand(1);
5472     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5473   }
5474
5475   // Recurse into target specific vector shuffles to find scalars.
5476   if (isTargetShuffle(Opcode)) {
5477     MVT ShufVT = V.getSimpleValueType();
5478     unsigned NumElems = ShufVT.getVectorNumElements();
5479     SmallVector<int, 16> ShuffleMask;
5480     bool IsUnary;
5481
5482     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5483       return SDValue();
5484
5485     int Elt = ShuffleMask[Index];
5486     if (Elt < 0)
5487       return DAG.getUNDEF(ShufVT.getVectorElementType());
5488
5489     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5490                                          : N->getOperand(1);
5491     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5492                                Depth+1);
5493   }
5494
5495   // Actual nodes that may contain scalar elements
5496   if (Opcode == ISD::BITCAST) {
5497     V = V.getOperand(0);
5498     EVT SrcVT = V.getValueType();
5499     unsigned NumElems = VT.getVectorNumElements();
5500
5501     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5502       return SDValue();
5503   }
5504
5505   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5506     return (Index == 0) ? V.getOperand(0)
5507                         : DAG.getUNDEF(VT.getVectorElementType());
5508
5509   if (V.getOpcode() == ISD::BUILD_VECTOR)
5510     return V.getOperand(Index);
5511
5512   return SDValue();
5513 }
5514
5515 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5516 /// shuffle operation which come from a consecutively from a zero. The
5517 /// search can start in two different directions, from left or right.
5518 /// We count undefs as zeros until PreferredNum is reached.
5519 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5520                                          unsigned NumElems, bool ZerosFromLeft,
5521                                          SelectionDAG &DAG,
5522                                          unsigned PreferredNum = -1U) {
5523   unsigned NumZeros = 0;
5524   for (unsigned i = 0; i != NumElems; ++i) {
5525     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5526     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5527     if (!Elt.getNode())
5528       break;
5529
5530     if (X86::isZeroNode(Elt))
5531       ++NumZeros;
5532     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5533       NumZeros = std::min(NumZeros + 1, PreferredNum);
5534     else
5535       break;
5536   }
5537
5538   return NumZeros;
5539 }
5540
5541 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5542 /// correspond consecutively to elements from one of the vector operands,
5543 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5544 static
5545 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5546                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5547                               unsigned NumElems, unsigned &OpNum) {
5548   bool SeenV1 = false;
5549   bool SeenV2 = false;
5550
5551   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5552     int Idx = SVOp->getMaskElt(i);
5553     // Ignore undef indicies
5554     if (Idx < 0)
5555       continue;
5556
5557     if (Idx < (int)NumElems)
5558       SeenV1 = true;
5559     else
5560       SeenV2 = true;
5561
5562     // Only accept consecutive elements from the same vector
5563     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5564       return false;
5565   }
5566
5567   OpNum = SeenV1 ? 0 : 1;
5568   return true;
5569 }
5570
5571 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5572 /// logical left shift of a vector.
5573 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5574                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5575   unsigned NumElems =
5576     SVOp->getSimpleValueType(0).getVectorNumElements();
5577   unsigned NumZeros = getNumOfConsecutiveZeros(
5578       SVOp, NumElems, false /* check zeros from right */, DAG,
5579       SVOp->getMaskElt(0));
5580   unsigned OpSrc;
5581
5582   if (!NumZeros)
5583     return false;
5584
5585   // Considering the elements in the mask that are not consecutive zeros,
5586   // check if they consecutively come from only one of the source vectors.
5587   //
5588   //               V1 = {X, A, B, C}     0
5589   //                         \  \  \    /
5590   //   vector_shuffle V1, V2 <1, 2, 3, X>
5591   //
5592   if (!isShuffleMaskConsecutive(SVOp,
5593             0,                   // Mask Start Index
5594             NumElems-NumZeros,   // Mask End Index(exclusive)
5595             NumZeros,            // Where to start looking in the src vector
5596             NumElems,            // Number of elements in vector
5597             OpSrc))              // Which source operand ?
5598     return false;
5599
5600   isLeft = false;
5601   ShAmt = NumZeros;
5602   ShVal = SVOp->getOperand(OpSrc);
5603   return true;
5604 }
5605
5606 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5607 /// logical left shift of a vector.
5608 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5609                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5610   unsigned NumElems =
5611     SVOp->getSimpleValueType(0).getVectorNumElements();
5612   unsigned NumZeros = getNumOfConsecutiveZeros(
5613       SVOp, NumElems, true /* check zeros from left */, DAG,
5614       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5615   unsigned OpSrc;
5616
5617   if (!NumZeros)
5618     return false;
5619
5620   // Considering the elements in the mask that are not consecutive zeros,
5621   // check if they consecutively come from only one of the source vectors.
5622   //
5623   //                           0    { A, B, X, X } = V2
5624   //                          / \    /  /
5625   //   vector_shuffle V1, V2 <X, X, 4, 5>
5626   //
5627   if (!isShuffleMaskConsecutive(SVOp,
5628             NumZeros,     // Mask Start Index
5629             NumElems,     // Mask End Index(exclusive)
5630             0,            // Where to start looking in the src vector
5631             NumElems,     // Number of elements in vector
5632             OpSrc))       // Which source operand ?
5633     return false;
5634
5635   isLeft = true;
5636   ShAmt = NumZeros;
5637   ShVal = SVOp->getOperand(OpSrc);
5638   return true;
5639 }
5640
5641 /// isVectorShift - Returns true if the shuffle can be implemented as a
5642 /// logical left or right shift of a vector.
5643 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5644                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5645   // Although the logic below support any bitwidth size, there are no
5646   // shift instructions which handle more than 128-bit vectors.
5647   if (!SVOp->getSimpleValueType(0).is128BitVector())
5648     return false;
5649
5650   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5651       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5652     return true;
5653
5654   return false;
5655 }
5656
5657 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5658 ///
5659 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5660                                        unsigned NumNonZero, unsigned NumZero,
5661                                        SelectionDAG &DAG,
5662                                        const X86Subtarget* Subtarget,
5663                                        const TargetLowering &TLI) {
5664   if (NumNonZero > 8)
5665     return SDValue();
5666
5667   SDLoc dl(Op);
5668   SDValue V;
5669   bool First = true;
5670   for (unsigned i = 0; i < 16; ++i) {
5671     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5672     if (ThisIsNonZero && First) {
5673       if (NumZero)
5674         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5675       else
5676         V = DAG.getUNDEF(MVT::v8i16);
5677       First = false;
5678     }
5679
5680     if ((i & 1) != 0) {
5681       SDValue ThisElt, LastElt;
5682       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5683       if (LastIsNonZero) {
5684         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5685                               MVT::i16, Op.getOperand(i-1));
5686       }
5687       if (ThisIsNonZero) {
5688         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5689         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5690                               ThisElt, DAG.getConstant(8, MVT::i8));
5691         if (LastIsNonZero)
5692           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5693       } else
5694         ThisElt = LastElt;
5695
5696       if (ThisElt.getNode())
5697         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5698                         DAG.getIntPtrConstant(i/2));
5699     }
5700   }
5701
5702   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5703 }
5704
5705 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5706 ///
5707 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5708                                      unsigned NumNonZero, unsigned NumZero,
5709                                      SelectionDAG &DAG,
5710                                      const X86Subtarget* Subtarget,
5711                                      const TargetLowering &TLI) {
5712   if (NumNonZero > 4)
5713     return SDValue();
5714
5715   SDLoc dl(Op);
5716   SDValue V;
5717   bool First = true;
5718   for (unsigned i = 0; i < 8; ++i) {
5719     bool isNonZero = (NonZeros & (1 << i)) != 0;
5720     if (isNonZero) {
5721       if (First) {
5722         if (NumZero)
5723           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5724         else
5725           V = DAG.getUNDEF(MVT::v8i16);
5726         First = false;
5727       }
5728       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5729                       MVT::v8i16, V, Op.getOperand(i),
5730                       DAG.getIntPtrConstant(i));
5731     }
5732   }
5733
5734   return V;
5735 }
5736
5737 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5738 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5739                                      unsigned NonZeros, unsigned NumNonZero,
5740                                      unsigned NumZero, SelectionDAG &DAG,
5741                                      const X86Subtarget *Subtarget,
5742                                      const TargetLowering &TLI) {
5743   // We know there's at least one non-zero element
5744   unsigned FirstNonZeroIdx = 0;
5745   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5746   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5747          X86::isZeroNode(FirstNonZero)) {
5748     ++FirstNonZeroIdx;
5749     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5750   }
5751
5752   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5753       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5754     return SDValue();
5755
5756   SDValue V = FirstNonZero.getOperand(0);
5757   MVT VVT = V.getSimpleValueType();
5758   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5759     return SDValue();
5760
5761   unsigned FirstNonZeroDst =
5762       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5763   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5764   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5765   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5766
5767   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5768     SDValue Elem = Op.getOperand(Idx);
5769     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5770       continue;
5771
5772     // TODO: What else can be here? Deal with it.
5773     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5774       return SDValue();
5775
5776     // TODO: Some optimizations are still possible here
5777     // ex: Getting one element from a vector, and the rest from another.
5778     if (Elem.getOperand(0) != V)
5779       return SDValue();
5780
5781     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5782     if (Dst == Idx)
5783       ++CorrectIdx;
5784     else if (IncorrectIdx == -1U) {
5785       IncorrectIdx = Idx;
5786       IncorrectDst = Dst;
5787     } else
5788       // There was already one element with an incorrect index.
5789       // We can't optimize this case to an insertps.
5790       return SDValue();
5791   }
5792
5793   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5794     SDLoc dl(Op);
5795     EVT VT = Op.getSimpleValueType();
5796     unsigned ElementMoveMask = 0;
5797     if (IncorrectIdx == -1U)
5798       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5799     else
5800       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5801
5802     SDValue InsertpsMask =
5803         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5804     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5805   }
5806
5807   return SDValue();
5808 }
5809
5810 /// getVShift - Return a vector logical shift node.
5811 ///
5812 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5813                          unsigned NumBits, SelectionDAG &DAG,
5814                          const TargetLowering &TLI, SDLoc dl) {
5815   assert(VT.is128BitVector() && "Unknown type for VShift");
5816   EVT ShVT = MVT::v2i64;
5817   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5818   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5819   return DAG.getNode(ISD::BITCAST, dl, VT,
5820                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5821                              DAG.getConstant(NumBits,
5822                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5823 }
5824
5825 static SDValue
5826 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5827
5828   // Check if the scalar load can be widened into a vector load. And if
5829   // the address is "base + cst" see if the cst can be "absorbed" into
5830   // the shuffle mask.
5831   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5832     SDValue Ptr = LD->getBasePtr();
5833     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5834       return SDValue();
5835     EVT PVT = LD->getValueType(0);
5836     if (PVT != MVT::i32 && PVT != MVT::f32)
5837       return SDValue();
5838
5839     int FI = -1;
5840     int64_t Offset = 0;
5841     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5842       FI = FINode->getIndex();
5843       Offset = 0;
5844     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5845                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5846       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5847       Offset = Ptr.getConstantOperandVal(1);
5848       Ptr = Ptr.getOperand(0);
5849     } else {
5850       return SDValue();
5851     }
5852
5853     // FIXME: 256-bit vector instructions don't require a strict alignment,
5854     // improve this code to support it better.
5855     unsigned RequiredAlign = VT.getSizeInBits()/8;
5856     SDValue Chain = LD->getChain();
5857     // Make sure the stack object alignment is at least 16 or 32.
5858     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5859     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5860       if (MFI->isFixedObjectIndex(FI)) {
5861         // Can't change the alignment. FIXME: It's possible to compute
5862         // the exact stack offset and reference FI + adjust offset instead.
5863         // If someone *really* cares about this. That's the way to implement it.
5864         return SDValue();
5865       } else {
5866         MFI->setObjectAlignment(FI, RequiredAlign);
5867       }
5868     }
5869
5870     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5871     // Ptr + (Offset & ~15).
5872     if (Offset < 0)
5873       return SDValue();
5874     if ((Offset % RequiredAlign) & 3)
5875       return SDValue();
5876     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5877     if (StartOffset)
5878       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5879                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5880
5881     int EltNo = (Offset - StartOffset) >> 2;
5882     unsigned NumElems = VT.getVectorNumElements();
5883
5884     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5885     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5886                              LD->getPointerInfo().getWithOffset(StartOffset),
5887                              false, false, false, 0);
5888
5889     SmallVector<int, 8> Mask;
5890     for (unsigned i = 0; i != NumElems; ++i)
5891       Mask.push_back(EltNo);
5892
5893     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5894   }
5895
5896   return SDValue();
5897 }
5898
5899 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5900 /// vector of type 'VT', see if the elements can be replaced by a single large
5901 /// load which has the same value as a build_vector whose operands are 'elts'.
5902 ///
5903 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5904 ///
5905 /// FIXME: we'd also like to handle the case where the last elements are zero
5906 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5907 /// There's even a handy isZeroNode for that purpose.
5908 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5909                                         SDLoc &DL, SelectionDAG &DAG,
5910                                         bool isAfterLegalize) {
5911   EVT EltVT = VT.getVectorElementType();
5912   unsigned NumElems = Elts.size();
5913
5914   LoadSDNode *LDBase = nullptr;
5915   unsigned LastLoadedElt = -1U;
5916
5917   // For each element in the initializer, see if we've found a load or an undef.
5918   // If we don't find an initial load element, or later load elements are
5919   // non-consecutive, bail out.
5920   for (unsigned i = 0; i < NumElems; ++i) {
5921     SDValue Elt = Elts[i];
5922
5923     if (!Elt.getNode() ||
5924         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5925       return SDValue();
5926     if (!LDBase) {
5927       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5928         return SDValue();
5929       LDBase = cast<LoadSDNode>(Elt.getNode());
5930       LastLoadedElt = i;
5931       continue;
5932     }
5933     if (Elt.getOpcode() == ISD::UNDEF)
5934       continue;
5935
5936     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5937     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5938       return SDValue();
5939     LastLoadedElt = i;
5940   }
5941
5942   // If we have found an entire vector of loads and undefs, then return a large
5943   // load of the entire vector width starting at the base pointer.  If we found
5944   // consecutive loads for the low half, generate a vzext_load node.
5945   if (LastLoadedElt == NumElems - 1) {
5946
5947     if (isAfterLegalize &&
5948         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5949       return SDValue();
5950
5951     SDValue NewLd = SDValue();
5952
5953     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5954       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5955                           LDBase->getPointerInfo(),
5956                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5957                           LDBase->isInvariant(), 0);
5958     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5959                         LDBase->getPointerInfo(),
5960                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5961                         LDBase->isInvariant(), LDBase->getAlignment());
5962
5963     if (LDBase->hasAnyUseOfValue(1)) {
5964       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5965                                      SDValue(LDBase, 1),
5966                                      SDValue(NewLd.getNode(), 1));
5967       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5968       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5969                              SDValue(NewLd.getNode(), 1));
5970     }
5971
5972     return NewLd;
5973   }
5974   if (NumElems == 4 && LastLoadedElt == 1 &&
5975       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5976     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5977     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5978     SDValue ResNode =
5979         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5980                                 LDBase->getPointerInfo(),
5981                                 LDBase->getAlignment(),
5982                                 false/*isVolatile*/, true/*ReadMem*/,
5983                                 false/*WriteMem*/);
5984
5985     // Make sure the newly-created LOAD is in the same position as LDBase in
5986     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5987     // update uses of LDBase's output chain to use the TokenFactor.
5988     if (LDBase->hasAnyUseOfValue(1)) {
5989       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5990                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5991       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5992       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5993                              SDValue(ResNode.getNode(), 1));
5994     }
5995
5996     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5997   }
5998   return SDValue();
5999 }
6000
6001 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6002 /// to generate a splat value for the following cases:
6003 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6004 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6005 /// a scalar load, or a constant.
6006 /// The VBROADCAST node is returned when a pattern is found,
6007 /// or SDValue() otherwise.
6008 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6009                                     SelectionDAG &DAG) {
6010   if (!Subtarget->hasFp256())
6011     return SDValue();
6012
6013   MVT VT = Op.getSimpleValueType();
6014   SDLoc dl(Op);
6015
6016   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6017          "Unsupported vector type for broadcast.");
6018
6019   SDValue Ld;
6020   bool ConstSplatVal;
6021
6022   switch (Op.getOpcode()) {
6023     default:
6024       // Unknown pattern found.
6025       return SDValue();
6026
6027     case ISD::BUILD_VECTOR: {
6028       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6029       BitVector UndefElements;
6030       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6031
6032       // We need a splat of a single value to use broadcast, and it doesn't
6033       // make any sense if the value is only in one element of the vector.
6034       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6035         return SDValue();
6036
6037       Ld = Splat;
6038       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6039                        Ld.getOpcode() == ISD::ConstantFP);
6040
6041       // Make sure that all of the users of a non-constant load are from the
6042       // BUILD_VECTOR node.
6043       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6044         return SDValue();
6045       break;
6046     }
6047
6048     case ISD::VECTOR_SHUFFLE: {
6049       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6050
6051       // Shuffles must have a splat mask where the first element is
6052       // broadcasted.
6053       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6054         return SDValue();
6055
6056       SDValue Sc = Op.getOperand(0);
6057       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6058           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6059
6060         if (!Subtarget->hasInt256())
6061           return SDValue();
6062
6063         // Use the register form of the broadcast instruction available on AVX2.
6064         if (VT.getSizeInBits() >= 256)
6065           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6066         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6067       }
6068
6069       Ld = Sc.getOperand(0);
6070       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6071                        Ld.getOpcode() == ISD::ConstantFP);
6072
6073       // The scalar_to_vector node and the suspected
6074       // load node must have exactly one user.
6075       // Constants may have multiple users.
6076
6077       // AVX-512 has register version of the broadcast
6078       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6079         Ld.getValueType().getSizeInBits() >= 32;
6080       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6081           !hasRegVer))
6082         return SDValue();
6083       break;
6084     }
6085   }
6086
6087   bool IsGE256 = (VT.getSizeInBits() >= 256);
6088
6089   // Handle the broadcasting a single constant scalar from the constant pool
6090   // into a vector. On Sandybridge it is still better to load a constant vector
6091   // from the constant pool and not to broadcast it from a scalar.
6092   if (ConstSplatVal && Subtarget->hasInt256()) {
6093     EVT CVT = Ld.getValueType();
6094     assert(!CVT.isVector() && "Must not broadcast a vector type");
6095     unsigned ScalarSize = CVT.getSizeInBits();
6096
6097     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
6098       const Constant *C = nullptr;
6099       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6100         C = CI->getConstantIntValue();
6101       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6102         C = CF->getConstantFPValue();
6103
6104       assert(C && "Invalid constant type");
6105
6106       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6107       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6108       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6109       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6110                        MachinePointerInfo::getConstantPool(),
6111                        false, false, false, Alignment);
6112
6113       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6114     }
6115   }
6116
6117   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6118   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6119
6120   // Handle AVX2 in-register broadcasts.
6121   if (!IsLoad && Subtarget->hasInt256() &&
6122       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6123     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6124
6125   // The scalar source must be a normal load.
6126   if (!IsLoad)
6127     return SDValue();
6128
6129   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6130     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6131
6132   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6133   // double since there is no vbroadcastsd xmm
6134   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6135     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6136       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6137   }
6138
6139   // Unsupported broadcast.
6140   return SDValue();
6141 }
6142
6143 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6144 /// underlying vector and index.
6145 ///
6146 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6147 /// index.
6148 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6149                                          SDValue ExtIdx) {
6150   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6151   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6152     return Idx;
6153
6154   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6155   // lowered this:
6156   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6157   // to:
6158   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6159   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6160   //                           undef)
6161   //                       Constant<0>)
6162   // In this case the vector is the extract_subvector expression and the index
6163   // is 2, as specified by the shuffle.
6164   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6165   SDValue ShuffleVec = SVOp->getOperand(0);
6166   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6167   assert(ShuffleVecVT.getVectorElementType() ==
6168          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6169
6170   int ShuffleIdx = SVOp->getMaskElt(Idx);
6171   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6172     ExtractedFromVec = ShuffleVec;
6173     return ShuffleIdx;
6174   }
6175   return Idx;
6176 }
6177
6178 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6179   MVT VT = Op.getSimpleValueType();
6180
6181   // Skip if insert_vec_elt is not supported.
6182   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6183   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6184     return SDValue();
6185
6186   SDLoc DL(Op);
6187   unsigned NumElems = Op.getNumOperands();
6188
6189   SDValue VecIn1;
6190   SDValue VecIn2;
6191   SmallVector<unsigned, 4> InsertIndices;
6192   SmallVector<int, 8> Mask(NumElems, -1);
6193
6194   for (unsigned i = 0; i != NumElems; ++i) {
6195     unsigned Opc = Op.getOperand(i).getOpcode();
6196
6197     if (Opc == ISD::UNDEF)
6198       continue;
6199
6200     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6201       // Quit if more than 1 elements need inserting.
6202       if (InsertIndices.size() > 1)
6203         return SDValue();
6204
6205       InsertIndices.push_back(i);
6206       continue;
6207     }
6208
6209     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6210     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6211     // Quit if non-constant index.
6212     if (!isa<ConstantSDNode>(ExtIdx))
6213       return SDValue();
6214     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6215
6216     // Quit if extracted from vector of different type.
6217     if (ExtractedFromVec.getValueType() != VT)
6218       return SDValue();
6219
6220     if (!VecIn1.getNode())
6221       VecIn1 = ExtractedFromVec;
6222     else if (VecIn1 != ExtractedFromVec) {
6223       if (!VecIn2.getNode())
6224         VecIn2 = ExtractedFromVec;
6225       else if (VecIn2 != ExtractedFromVec)
6226         // Quit if more than 2 vectors to shuffle
6227         return SDValue();
6228     }
6229
6230     if (ExtractedFromVec == VecIn1)
6231       Mask[i] = Idx;
6232     else if (ExtractedFromVec == VecIn2)
6233       Mask[i] = Idx + NumElems;
6234   }
6235
6236   if (!VecIn1.getNode())
6237     return SDValue();
6238
6239   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6240   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6241   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6242     unsigned Idx = InsertIndices[i];
6243     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6244                      DAG.getIntPtrConstant(Idx));
6245   }
6246
6247   return NV;
6248 }
6249
6250 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6251 SDValue
6252 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6253
6254   MVT VT = Op.getSimpleValueType();
6255   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6256          "Unexpected type in LowerBUILD_VECTORvXi1!");
6257
6258   SDLoc dl(Op);
6259   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6260     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6261     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6262     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6263   }
6264
6265   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6266     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6267     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6268     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6269   }
6270
6271   bool AllContants = true;
6272   uint64_t Immediate = 0;
6273   int NonConstIdx = -1;
6274   bool IsSplat = true;
6275   unsigned NumNonConsts = 0;
6276   unsigned NumConsts = 0;
6277   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6278     SDValue In = Op.getOperand(idx);
6279     if (In.getOpcode() == ISD::UNDEF)
6280       continue;
6281     if (!isa<ConstantSDNode>(In)) {
6282       AllContants = false;
6283       NonConstIdx = idx;
6284       NumNonConsts++;
6285     }
6286     else {
6287       NumConsts++;
6288       if (cast<ConstantSDNode>(In)->getZExtValue())
6289       Immediate |= (1ULL << idx);
6290     }
6291     if (In != Op.getOperand(0))
6292       IsSplat = false;
6293   }
6294
6295   if (AllContants) {
6296     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6297       DAG.getConstant(Immediate, MVT::i16));
6298     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6299                        DAG.getIntPtrConstant(0));
6300   }
6301
6302   if (NumNonConsts == 1 && NonConstIdx != 0) {
6303     SDValue DstVec;
6304     if (NumConsts) {
6305       SDValue VecAsImm = DAG.getConstant(Immediate,
6306                                          MVT::getIntegerVT(VT.getSizeInBits()));
6307       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6308     }
6309     else 
6310       DstVec = DAG.getUNDEF(VT);
6311     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6312                        Op.getOperand(NonConstIdx),
6313                        DAG.getIntPtrConstant(NonConstIdx));
6314   }
6315   if (!IsSplat && (NonConstIdx != 0))
6316     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6317   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6318   SDValue Select;
6319   if (IsSplat)
6320     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6321                           DAG.getConstant(-1, SelectVT),
6322                           DAG.getConstant(0, SelectVT));
6323   else
6324     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6325                          DAG.getConstant((Immediate | 1), SelectVT),
6326                          DAG.getConstant(Immediate, SelectVT));
6327   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6328 }
6329
6330 /// \brief Return true if \p N implements a horizontal binop and return the
6331 /// operands for the horizontal binop into V0 and V1.
6332 /// 
6333 /// This is a helper function of PerformBUILD_VECTORCombine.
6334 /// This function checks that the build_vector \p N in input implements a
6335 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6336 /// operation to match.
6337 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6338 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6339 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6340 /// arithmetic sub.
6341 ///
6342 /// This function only analyzes elements of \p N whose indices are
6343 /// in range [BaseIdx, LastIdx).
6344 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6345                               SelectionDAG &DAG,
6346                               unsigned BaseIdx, unsigned LastIdx,
6347                               SDValue &V0, SDValue &V1) {
6348   EVT VT = N->getValueType(0);
6349
6350   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6351   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6352          "Invalid Vector in input!");
6353   
6354   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6355   bool CanFold = true;
6356   unsigned ExpectedVExtractIdx = BaseIdx;
6357   unsigned NumElts = LastIdx - BaseIdx;
6358   V0 = DAG.getUNDEF(VT);
6359   V1 = DAG.getUNDEF(VT);
6360
6361   // Check if N implements a horizontal binop.
6362   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6363     SDValue Op = N->getOperand(i + BaseIdx);
6364
6365     // Skip UNDEFs.
6366     if (Op->getOpcode() == ISD::UNDEF) {
6367       // Update the expected vector extract index.
6368       if (i * 2 == NumElts)
6369         ExpectedVExtractIdx = BaseIdx;
6370       ExpectedVExtractIdx += 2;
6371       continue;
6372     }
6373
6374     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6375
6376     if (!CanFold)
6377       break;
6378
6379     SDValue Op0 = Op.getOperand(0);
6380     SDValue Op1 = Op.getOperand(1);
6381
6382     // Try to match the following pattern:
6383     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6384     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6385         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6386         Op0.getOperand(0) == Op1.getOperand(0) &&
6387         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6388         isa<ConstantSDNode>(Op1.getOperand(1)));
6389     if (!CanFold)
6390       break;
6391
6392     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6393     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6394
6395     if (i * 2 < NumElts) {
6396       if (V0.getOpcode() == ISD::UNDEF)
6397         V0 = Op0.getOperand(0);
6398     } else {
6399       if (V1.getOpcode() == ISD::UNDEF)
6400         V1 = Op0.getOperand(0);
6401       if (i * 2 == NumElts)
6402         ExpectedVExtractIdx = BaseIdx;
6403     }
6404
6405     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6406     if (I0 == ExpectedVExtractIdx)
6407       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6408     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6409       // Try to match the following dag sequence:
6410       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6411       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6412     } else
6413       CanFold = false;
6414
6415     ExpectedVExtractIdx += 2;
6416   }
6417
6418   return CanFold;
6419 }
6420
6421 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6422 /// a concat_vector. 
6423 ///
6424 /// This is a helper function of PerformBUILD_VECTORCombine.
6425 /// This function expects two 256-bit vectors called V0 and V1.
6426 /// At first, each vector is split into two separate 128-bit vectors.
6427 /// Then, the resulting 128-bit vectors are used to implement two
6428 /// horizontal binary operations. 
6429 ///
6430 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6431 ///
6432 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6433 /// the two new horizontal binop.
6434 /// When Mode is set, the first horizontal binop dag node would take as input
6435 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6436 /// horizontal binop dag node would take as input the lower 128-bit of V1
6437 /// and the upper 128-bit of V1.
6438 ///   Example:
6439 ///     HADD V0_LO, V0_HI
6440 ///     HADD V1_LO, V1_HI
6441 ///
6442 /// Otherwise, the first horizontal binop dag node takes as input the lower
6443 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6444 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6445 ///   Example:
6446 ///     HADD V0_LO, V1_LO
6447 ///     HADD V0_HI, V1_HI
6448 ///
6449 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6450 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6451 /// the upper 128-bits of the result.
6452 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6453                                      SDLoc DL, SelectionDAG &DAG,
6454                                      unsigned X86Opcode, bool Mode,
6455                                      bool isUndefLO, bool isUndefHI) {
6456   EVT VT = V0.getValueType();
6457   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6458          "Invalid nodes in input!");
6459
6460   unsigned NumElts = VT.getVectorNumElements();
6461   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6462   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6463   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6464   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6465   EVT NewVT = V0_LO.getValueType();
6466
6467   SDValue LO = DAG.getUNDEF(NewVT);
6468   SDValue HI = DAG.getUNDEF(NewVT);
6469
6470   if (Mode) {
6471     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6472     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6473       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6474     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6475       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6476   } else {
6477     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6478     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6479                        V1_LO->getOpcode() != ISD::UNDEF))
6480       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6481
6482     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6483                        V1_HI->getOpcode() != ISD::UNDEF))
6484       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6485   }
6486
6487   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6488 }
6489
6490 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6491 /// sequence of 'vadd + vsub + blendi'.
6492 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6493                            const X86Subtarget *Subtarget) {
6494   SDLoc DL(BV);
6495   EVT VT = BV->getValueType(0);
6496   unsigned NumElts = VT.getVectorNumElements();
6497   SDValue InVec0 = DAG.getUNDEF(VT);
6498   SDValue InVec1 = DAG.getUNDEF(VT);
6499
6500   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6501           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6502
6503   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6504   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6505   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6506     return SDValue();
6507
6508   // Odd-numbered elements in the input build vector are obtained from
6509   // adding two integer/float elements.
6510   // Even-numbered elements in the input build vector are obtained from
6511   // subtracting two integer/float elements.
6512   unsigned ExpectedOpcode = ISD::FSUB;
6513   unsigned NextExpectedOpcode = ISD::FADD;
6514   bool AddFound = false;
6515   bool SubFound = false;
6516
6517   for (unsigned i = 0, e = NumElts; i != e; i++) {
6518     SDValue Op = BV->getOperand(i);
6519       
6520     // Skip 'undef' values.
6521     unsigned Opcode = Op.getOpcode();
6522     if (Opcode == ISD::UNDEF) {
6523       std::swap(ExpectedOpcode, NextExpectedOpcode);
6524       continue;
6525     }
6526       
6527     // Early exit if we found an unexpected opcode.
6528     if (Opcode != ExpectedOpcode)
6529       return SDValue();
6530
6531     SDValue Op0 = Op.getOperand(0);
6532     SDValue Op1 = Op.getOperand(1);
6533
6534     // Try to match the following pattern:
6535     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6536     // Early exit if we cannot match that sequence.
6537     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6538         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6539         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6540         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6541         Op0.getOperand(1) != Op1.getOperand(1))
6542       return SDValue();
6543
6544     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6545     if (I0 != i)
6546       return SDValue();
6547
6548     // We found a valid add/sub node. Update the information accordingly.
6549     if (i & 1)
6550       AddFound = true;
6551     else
6552       SubFound = true;
6553
6554     // Update InVec0 and InVec1.
6555     if (InVec0.getOpcode() == ISD::UNDEF)
6556       InVec0 = Op0.getOperand(0);
6557     if (InVec1.getOpcode() == ISD::UNDEF)
6558       InVec1 = Op1.getOperand(0);
6559
6560     // Make sure that operands in input to each add/sub node always
6561     // come from a same pair of vectors.
6562     if (InVec0 != Op0.getOperand(0)) {
6563       if (ExpectedOpcode == ISD::FSUB)
6564         return SDValue();
6565
6566       // FADD is commutable. Try to commute the operands
6567       // and then test again.
6568       std::swap(Op0, Op1);
6569       if (InVec0 != Op0.getOperand(0))
6570         return SDValue();
6571     }
6572
6573     if (InVec1 != Op1.getOperand(0))
6574       return SDValue();
6575
6576     // Update the pair of expected opcodes.
6577     std::swap(ExpectedOpcode, NextExpectedOpcode);
6578   }
6579
6580   // Don't try to fold this build_vector into a VSELECT if it has
6581   // too many UNDEF operands.
6582   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6583       InVec1.getOpcode() != ISD::UNDEF) {
6584     // Emit a sequence of vector add and sub followed by a VSELECT.
6585     // The new VSELECT will be lowered into a BLENDI.
6586     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6587     // and emit a single ADDSUB instruction.
6588     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6589     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6590
6591     // Construct the VSELECT mask.
6592     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6593     EVT SVT = MaskVT.getVectorElementType();
6594     unsigned SVTBits = SVT.getSizeInBits();
6595     SmallVector<SDValue, 8> Ops;
6596
6597     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6598       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6599                             APInt::getAllOnesValue(SVTBits);
6600       SDValue Constant = DAG.getConstant(Value, SVT);
6601       Ops.push_back(Constant);
6602     }
6603
6604     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6605     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6606   }
6607   
6608   return SDValue();
6609 }
6610
6611 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6612                                           const X86Subtarget *Subtarget) {
6613   SDLoc DL(N);
6614   EVT VT = N->getValueType(0);
6615   unsigned NumElts = VT.getVectorNumElements();
6616   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6617   SDValue InVec0, InVec1;
6618
6619   // Try to match an ADDSUB.
6620   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6621       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6622     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6623     if (Value.getNode())
6624       return Value;
6625   }
6626
6627   // Try to match horizontal ADD/SUB.
6628   unsigned NumUndefsLO = 0;
6629   unsigned NumUndefsHI = 0;
6630   unsigned Half = NumElts/2;
6631
6632   // Count the number of UNDEF operands in the build_vector in input.
6633   for (unsigned i = 0, e = Half; i != e; ++i)
6634     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6635       NumUndefsLO++;
6636
6637   for (unsigned i = Half, e = NumElts; i != e; ++i)
6638     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6639       NumUndefsHI++;
6640
6641   // Early exit if this is either a build_vector of all UNDEFs or all the
6642   // operands but one are UNDEF.
6643   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6644     return SDValue();
6645
6646   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6647     // Try to match an SSE3 float HADD/HSUB.
6648     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6649       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6650     
6651     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6652       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6653   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6654     // Try to match an SSSE3 integer HADD/HSUB.
6655     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6656       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6657     
6658     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6659       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6660   }
6661   
6662   if (!Subtarget->hasAVX())
6663     return SDValue();
6664
6665   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6666     // Try to match an AVX horizontal add/sub of packed single/double
6667     // precision floating point values from 256-bit vectors.
6668     SDValue InVec2, InVec3;
6669     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6670         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6671         ((InVec0.getOpcode() == ISD::UNDEF ||
6672           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6673         ((InVec1.getOpcode() == ISD::UNDEF ||
6674           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6675       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6676
6677     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6678         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6679         ((InVec0.getOpcode() == ISD::UNDEF ||
6680           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6681         ((InVec1.getOpcode() == ISD::UNDEF ||
6682           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6683       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6684   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6685     // Try to match an AVX2 horizontal add/sub of signed integers.
6686     SDValue InVec2, InVec3;
6687     unsigned X86Opcode;
6688     bool CanFold = true;
6689
6690     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6691         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6692         ((InVec0.getOpcode() == ISD::UNDEF ||
6693           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6694         ((InVec1.getOpcode() == ISD::UNDEF ||
6695           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6696       X86Opcode = X86ISD::HADD;
6697     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6698         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6699         ((InVec0.getOpcode() == ISD::UNDEF ||
6700           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6701         ((InVec1.getOpcode() == ISD::UNDEF ||
6702           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6703       X86Opcode = X86ISD::HSUB;
6704     else
6705       CanFold = false;
6706
6707     if (CanFold) {
6708       // Fold this build_vector into a single horizontal add/sub.
6709       // Do this only if the target has AVX2.
6710       if (Subtarget->hasAVX2())
6711         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6712  
6713       // Do not try to expand this build_vector into a pair of horizontal
6714       // add/sub if we can emit a pair of scalar add/sub.
6715       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6716         return SDValue();
6717
6718       // Convert this build_vector into a pair of horizontal binop followed by
6719       // a concat vector.
6720       bool isUndefLO = NumUndefsLO == Half;
6721       bool isUndefHI = NumUndefsHI == Half;
6722       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6723                                    isUndefLO, isUndefHI);
6724     }
6725   }
6726
6727   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6728        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6729     unsigned X86Opcode;
6730     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6731       X86Opcode = X86ISD::HADD;
6732     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6733       X86Opcode = X86ISD::HSUB;
6734     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6735       X86Opcode = X86ISD::FHADD;
6736     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6737       X86Opcode = X86ISD::FHSUB;
6738     else
6739       return SDValue();
6740
6741     // Don't try to expand this build_vector into a pair of horizontal add/sub
6742     // if we can simply emit a pair of scalar add/sub.
6743     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6744       return SDValue();
6745
6746     // Convert this build_vector into two horizontal add/sub followed by
6747     // a concat vector.
6748     bool isUndefLO = NumUndefsLO == Half;
6749     bool isUndefHI = NumUndefsHI == Half;
6750     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6751                                  isUndefLO, isUndefHI);
6752   }
6753
6754   return SDValue();
6755 }
6756
6757 SDValue
6758 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6759   SDLoc dl(Op);
6760
6761   MVT VT = Op.getSimpleValueType();
6762   MVT ExtVT = VT.getVectorElementType();
6763   unsigned NumElems = Op.getNumOperands();
6764
6765   // Generate vectors for predicate vectors.
6766   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6767     return LowerBUILD_VECTORvXi1(Op, DAG);
6768
6769   // Vectors containing all zeros can be matched by pxor and xorps later
6770   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6771     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6772     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6773     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6774       return Op;
6775
6776     return getZeroVector(VT, Subtarget, DAG, dl);
6777   }
6778
6779   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6780   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6781   // vpcmpeqd on 256-bit vectors.
6782   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6783     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6784       return Op;
6785
6786     if (!VT.is512BitVector())
6787       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6788   }
6789
6790   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6791   if (Broadcast.getNode())
6792     return Broadcast;
6793
6794   unsigned EVTBits = ExtVT.getSizeInBits();
6795
6796   unsigned NumZero  = 0;
6797   unsigned NumNonZero = 0;
6798   unsigned NonZeros = 0;
6799   bool IsAllConstants = true;
6800   SmallSet<SDValue, 8> Values;
6801   for (unsigned i = 0; i < NumElems; ++i) {
6802     SDValue Elt = Op.getOperand(i);
6803     if (Elt.getOpcode() == ISD::UNDEF)
6804       continue;
6805     Values.insert(Elt);
6806     if (Elt.getOpcode() != ISD::Constant &&
6807         Elt.getOpcode() != ISD::ConstantFP)
6808       IsAllConstants = false;
6809     if (X86::isZeroNode(Elt))
6810       NumZero++;
6811     else {
6812       NonZeros |= (1 << i);
6813       NumNonZero++;
6814     }
6815   }
6816
6817   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6818   if (NumNonZero == 0)
6819     return DAG.getUNDEF(VT);
6820
6821   // Special case for single non-zero, non-undef, element.
6822   if (NumNonZero == 1) {
6823     unsigned Idx = countTrailingZeros(NonZeros);
6824     SDValue Item = Op.getOperand(Idx);
6825
6826     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6827     // the value are obviously zero, truncate the value to i32 and do the
6828     // insertion that way.  Only do this if the value is non-constant or if the
6829     // value is a constant being inserted into element 0.  It is cheaper to do
6830     // a constant pool load than it is to do a movd + shuffle.
6831     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6832         (!IsAllConstants || Idx == 0)) {
6833       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6834         // Handle SSE only.
6835         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6836         EVT VecVT = MVT::v4i32;
6837         unsigned VecElts = 4;
6838
6839         // Truncate the value (which may itself be a constant) to i32, and
6840         // convert it to a vector with movd (S2V+shuffle to zero extend).
6841         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6842         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6843         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6844
6845         // Now we have our 32-bit value zero extended in the low element of
6846         // a vector.  If Idx != 0, swizzle it into place.
6847         if (Idx != 0) {
6848           SmallVector<int, 4> Mask;
6849           Mask.push_back(Idx);
6850           for (unsigned i = 1; i != VecElts; ++i)
6851             Mask.push_back(i);
6852           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6853                                       &Mask[0]);
6854         }
6855         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6856       }
6857     }
6858
6859     // If we have a constant or non-constant insertion into the low element of
6860     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6861     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6862     // depending on what the source datatype is.
6863     if (Idx == 0) {
6864       if (NumZero == 0)
6865         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6866
6867       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6868           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6869         if (VT.is256BitVector() || VT.is512BitVector()) {
6870           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6871           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6872                              Item, DAG.getIntPtrConstant(0));
6873         }
6874         assert(VT.is128BitVector() && "Expected an SSE value type!");
6875         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6876         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6877         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6878       }
6879
6880       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6881         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6882         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6883         if (VT.is256BitVector()) {
6884           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6885           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6886         } else {
6887           assert(VT.is128BitVector() && "Expected an SSE value type!");
6888           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6889         }
6890         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6891       }
6892     }
6893
6894     // Is it a vector logical left shift?
6895     if (NumElems == 2 && Idx == 1 &&
6896         X86::isZeroNode(Op.getOperand(0)) &&
6897         !X86::isZeroNode(Op.getOperand(1))) {
6898       unsigned NumBits = VT.getSizeInBits();
6899       return getVShift(true, VT,
6900                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6901                                    VT, Op.getOperand(1)),
6902                        NumBits/2, DAG, *this, dl);
6903     }
6904
6905     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6906       return SDValue();
6907
6908     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6909     // is a non-constant being inserted into an element other than the low one,
6910     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6911     // movd/movss) to move this into the low element, then shuffle it into
6912     // place.
6913     if (EVTBits == 32) {
6914       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6915
6916       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6917       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6918       SmallVector<int, 8> MaskVec;
6919       for (unsigned i = 0; i != NumElems; ++i)
6920         MaskVec.push_back(i == Idx ? 0 : 1);
6921       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6922     }
6923   }
6924
6925   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6926   if (Values.size() == 1) {
6927     if (EVTBits == 32) {
6928       // Instead of a shuffle like this:
6929       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6930       // Check if it's possible to issue this instead.
6931       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6932       unsigned Idx = countTrailingZeros(NonZeros);
6933       SDValue Item = Op.getOperand(Idx);
6934       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6935         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6936     }
6937     return SDValue();
6938   }
6939
6940   // A vector full of immediates; various special cases are already
6941   // handled, so this is best done with a single constant-pool load.
6942   if (IsAllConstants)
6943     return SDValue();
6944
6945   // For AVX-length vectors, build the individual 128-bit pieces and use
6946   // shuffles to put them in place.
6947   if (VT.is256BitVector() || VT.is512BitVector()) {
6948     SmallVector<SDValue, 64> V;
6949     for (unsigned i = 0; i != NumElems; ++i)
6950       V.push_back(Op.getOperand(i));
6951
6952     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6953
6954     // Build both the lower and upper subvector.
6955     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6956                                 makeArrayRef(&V[0], NumElems/2));
6957     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6958                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6959
6960     // Recreate the wider vector with the lower and upper part.
6961     if (VT.is256BitVector())
6962       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6963     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6964   }
6965
6966   // Let legalizer expand 2-wide build_vectors.
6967   if (EVTBits == 64) {
6968     if (NumNonZero == 1) {
6969       // One half is zero or undef.
6970       unsigned Idx = countTrailingZeros(NonZeros);
6971       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6972                                  Op.getOperand(Idx));
6973       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6974     }
6975     return SDValue();
6976   }
6977
6978   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6979   if (EVTBits == 8 && NumElems == 16) {
6980     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6981                                         Subtarget, *this);
6982     if (V.getNode()) return V;
6983   }
6984
6985   if (EVTBits == 16 && NumElems == 8) {
6986     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6987                                       Subtarget, *this);
6988     if (V.getNode()) return V;
6989   }
6990
6991   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6992   if (EVTBits == 32 && NumElems == 4) {
6993     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6994                                       NumZero, DAG, Subtarget, *this);
6995     if (V.getNode())
6996       return V;
6997   }
6998
6999   // If element VT is == 32 bits, turn it into a number of shuffles.
7000   SmallVector<SDValue, 8> V(NumElems);
7001   if (NumElems == 4 && NumZero > 0) {
7002     for (unsigned i = 0; i < 4; ++i) {
7003       bool isZero = !(NonZeros & (1 << i));
7004       if (isZero)
7005         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7006       else
7007         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7008     }
7009
7010     for (unsigned i = 0; i < 2; ++i) {
7011       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7012         default: break;
7013         case 0:
7014           V[i] = V[i*2];  // Must be a zero vector.
7015           break;
7016         case 1:
7017           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7018           break;
7019         case 2:
7020           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7021           break;
7022         case 3:
7023           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7024           break;
7025       }
7026     }
7027
7028     bool Reverse1 = (NonZeros & 0x3) == 2;
7029     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7030     int MaskVec[] = {
7031       Reverse1 ? 1 : 0,
7032       Reverse1 ? 0 : 1,
7033       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7034       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7035     };
7036     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7037   }
7038
7039   if (Values.size() > 1 && VT.is128BitVector()) {
7040     // Check for a build vector of consecutive loads.
7041     for (unsigned i = 0; i < NumElems; ++i)
7042       V[i] = Op.getOperand(i);
7043
7044     // Check for elements which are consecutive loads.
7045     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7046     if (LD.getNode())
7047       return LD;
7048
7049     // Check for a build vector from mostly shuffle plus few inserting.
7050     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7051     if (Sh.getNode())
7052       return Sh;
7053
7054     // For SSE 4.1, use insertps to put the high elements into the low element.
7055     if (getSubtarget()->hasSSE41()) {
7056       SDValue Result;
7057       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7058         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7059       else
7060         Result = DAG.getUNDEF(VT);
7061
7062       for (unsigned i = 1; i < NumElems; ++i) {
7063         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7064         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7065                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7066       }
7067       return Result;
7068     }
7069
7070     // Otherwise, expand into a number of unpckl*, start by extending each of
7071     // our (non-undef) elements to the full vector width with the element in the
7072     // bottom slot of the vector (which generates no code for SSE).
7073     for (unsigned i = 0; i < NumElems; ++i) {
7074       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7075         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7076       else
7077         V[i] = DAG.getUNDEF(VT);
7078     }
7079
7080     // Next, we iteratively mix elements, e.g. for v4f32:
7081     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7082     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7083     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7084     unsigned EltStride = NumElems >> 1;
7085     while (EltStride != 0) {
7086       for (unsigned i = 0; i < EltStride; ++i) {
7087         // If V[i+EltStride] is undef and this is the first round of mixing,
7088         // then it is safe to just drop this shuffle: V[i] is already in the
7089         // right place, the one element (since it's the first round) being
7090         // inserted as undef can be dropped.  This isn't safe for successive
7091         // rounds because they will permute elements within both vectors.
7092         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7093             EltStride == NumElems/2)
7094           continue;
7095
7096         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7097       }
7098       EltStride >>= 1;
7099     }
7100     return V[0];
7101   }
7102   return SDValue();
7103 }
7104
7105 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7106 // to create 256-bit vectors from two other 128-bit ones.
7107 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7108   SDLoc dl(Op);
7109   MVT ResVT = Op.getSimpleValueType();
7110
7111   assert((ResVT.is256BitVector() ||
7112           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7113
7114   SDValue V1 = Op.getOperand(0);
7115   SDValue V2 = Op.getOperand(1);
7116   unsigned NumElems = ResVT.getVectorNumElements();
7117   if(ResVT.is256BitVector())
7118     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7119
7120   if (Op.getNumOperands() == 4) {
7121     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7122                                 ResVT.getVectorNumElements()/2);
7123     SDValue V3 = Op.getOperand(2);
7124     SDValue V4 = Op.getOperand(3);
7125     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7126       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7127   }
7128   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7129 }
7130
7131 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7132   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7133   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7134          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7135           Op.getNumOperands() == 4)));
7136
7137   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7138   // from two other 128-bit ones.
7139
7140   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7141   return LowerAVXCONCAT_VECTORS(Op, DAG);
7142 }
7143
7144
7145 //===----------------------------------------------------------------------===//
7146 // Vector shuffle lowering
7147 //
7148 // This is an experimental code path for lowering vector shuffles on x86. It is
7149 // designed to handle arbitrary vector shuffles and blends, gracefully
7150 // degrading performance as necessary. It works hard to recognize idiomatic
7151 // shuffles and lower them to optimal instruction patterns without leaving
7152 // a framework that allows reasonably efficient handling of all vector shuffle
7153 // patterns.
7154 //===----------------------------------------------------------------------===//
7155
7156 /// \brief Tiny helper function to identify a no-op mask.
7157 ///
7158 /// This is a somewhat boring predicate function. It checks whether the mask
7159 /// array input, which is assumed to be a single-input shuffle mask of the kind
7160 /// used by the X86 shuffle instructions (not a fully general
7161 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7162 /// in-place shuffle are 'no-op's.
7163 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7164   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7165     if (Mask[i] != -1 && Mask[i] != i)
7166       return false;
7167   return true;
7168 }
7169
7170 /// \brief Helper function to classify a mask as a single-input mask.
7171 ///
7172 /// This isn't a generic single-input test because in the vector shuffle
7173 /// lowering we canonicalize single inputs to be the first input operand. This
7174 /// means we can more quickly test for a single input by only checking whether
7175 /// an input from the second operand exists. We also assume that the size of
7176 /// mask corresponds to the size of the input vectors which isn't true in the
7177 /// fully general case.
7178 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7179   for (int M : Mask)
7180     if (M >= (int)Mask.size())
7181       return false;
7182   return true;
7183 }
7184
7185 /// \brief Check wether all of one set of inputs to a shuffle mask are in place.
7186 ///
7187 /// Mask entries pointing at the other input or undef will be skipped.
7188 static bool isShuffleMaskInputInPlace(ArrayRef<int> Mask, bool LoInput = true) {
7189   int Size = Mask.size();
7190   for (int i = 0; i < Size; ++i) {
7191     int M = Mask[i];
7192     if (M == -1 || (LoInput && M >= 4) || (!LoInput && M < 4))
7193       continue;
7194     if (M - (LoInput ? 0 : Size) != i)
7195       return false;
7196   }
7197   return true;
7198 }
7199
7200 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7201 // 2013 will allow us to use it as a non-type template parameter.
7202 namespace {
7203
7204 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7205 ///
7206 /// See its documentation for details.
7207 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7208   if (Mask.size() != Args.size())
7209     return false;
7210   for (int i = 0, e = Mask.size(); i < e; ++i) {
7211     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7212     assert(*Args[i] < (int)Args.size() * 2 &&
7213            "Argument outside the range of possible shuffle inputs!");
7214     if (Mask[i] != -1 && Mask[i] != *Args[i])
7215       return false;
7216   }
7217   return true;
7218 }
7219
7220 } // namespace
7221
7222 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7223 /// arguments.
7224 ///
7225 /// This is a fast way to test a shuffle mask against a fixed pattern:
7226 ///
7227 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7228 ///
7229 /// It returns true if the mask is exactly as wide as the argument list, and
7230 /// each element of the mask is either -1 (signifying undef) or the value given
7231 /// in the argument.
7232 static const VariadicFunction1<
7233     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7234
7235 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7236 ///
7237 /// This helper function produces an 8-bit shuffle immediate corresponding to
7238 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7239 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7240 /// example.
7241 ///
7242 /// NB: We rely heavily on "undef" masks preserving the input lane.
7243 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7244                                           SelectionDAG &DAG) {
7245   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7246   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7247   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7248   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7249   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7250
7251   unsigned Imm = 0;
7252   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7253   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7254   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7255   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7256   return DAG.getConstant(Imm, MVT::i8);
7257 }
7258
7259 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7260 ///
7261 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7262 /// support for floating point shuffles but not integer shuffles. These
7263 /// instructions will incur a domain crossing penalty on some chips though so
7264 /// it is better to avoid lowering through this for integer vectors where
7265 /// possible.
7266 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7267                                        const X86Subtarget *Subtarget,
7268                                        SelectionDAG &DAG) {
7269   SDLoc DL(Op);
7270   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7271   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7272   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7273   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7274   ArrayRef<int> Mask = SVOp->getMask();
7275   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7276
7277   if (isSingleInputShuffleMask(Mask)) {
7278     // Straight shuffle of a single input vector. Simulate this by using the
7279     // single input as both of the "inputs" to this instruction..
7280     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7281     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7282                        DAG.getConstant(SHUFPDMask, MVT::i8));
7283   }
7284   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7285   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7286
7287   // Use dedicated unpack instructions for masks that match their pattern.
7288   if (isShuffleEquivalent(Mask, 0, 2))
7289     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7290   if (isShuffleEquivalent(Mask, 1, 3))
7291     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7292
7293   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7294   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7295                      DAG.getConstant(SHUFPDMask, MVT::i8));
7296 }
7297
7298 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7299 ///
7300 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7301 /// the integer unit to minimize domain crossing penalties. However, for blends
7302 /// it falls back to the floating point shuffle operation with appropriate bit
7303 /// casting.
7304 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7305                                        const X86Subtarget *Subtarget,
7306                                        SelectionDAG &DAG) {
7307   SDLoc DL(Op);
7308   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7309   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7310   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7311   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7312   ArrayRef<int> Mask = SVOp->getMask();
7313   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7314
7315   if (isSingleInputShuffleMask(Mask)) {
7316     // Straight shuffle of a single input vector. For everything from SSE2
7317     // onward this has a single fast instruction with no scary immediates.
7318     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7319     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7320     int WidenedMask[4] = {
7321         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7322         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7323     return DAG.getNode(
7324         ISD::BITCAST, DL, MVT::v2i64,
7325         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7326                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7327   }
7328
7329   // Use dedicated unpack instructions for masks that match their pattern.
7330   if (isShuffleEquivalent(Mask, 0, 2))
7331     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7332   if (isShuffleEquivalent(Mask, 1, 3))
7333     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7334
7335   // We implement this with SHUFPD which is pretty lame because it will likely
7336   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7337   // However, all the alternatives are still more cycles and newer chips don't
7338   // have this problem. It would be really nice if x86 had better shuffles here.
7339   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7340   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7341   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7342                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7343 }
7344
7345 /// \brief Lower 4-lane 32-bit floating point shuffles.
7346 ///
7347 /// Uses instructions exclusively from the floating point unit to minimize
7348 /// domain crossing penalties, as these are sufficient to implement all v4f32
7349 /// shuffles.
7350 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7351                                        const X86Subtarget *Subtarget,
7352                                        SelectionDAG &DAG) {
7353   SDLoc DL(Op);
7354   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7355   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7356   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7357   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7358   ArrayRef<int> Mask = SVOp->getMask();
7359   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7360
7361   SDValue LowV = V1, HighV = V2;
7362   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7363
7364   int NumV2Elements =
7365       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7366
7367   if (NumV2Elements == 0)
7368     // Straight shuffle of a single input vector. We pass the input vector to
7369     // both operands to simulate this with a SHUFPS.
7370     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7371                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7372
7373   // Use dedicated unpack instructions for masks that match their pattern.
7374   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7375     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7376   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7377     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7378
7379   if (NumV2Elements == 1) {
7380     int V2Index =
7381         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7382         Mask.begin();
7383
7384     // Check for whether we can use INSERTPS to perform the blend. We only use
7385     // INSERTPS when the V1 elements are already in the correct locations
7386     // because otherwise we can just always use two SHUFPS instructions which
7387     // are much smaller to encode than a SHUFPS and an INSERTPS.
7388     if (Subtarget->hasSSE41() &&
7389         isShuffleMaskInputInPlace(Mask, /*LoInput*/ true)) {
7390       // Insert the V2 element into the desired position.
7391       SDValue InsertPSMask =
7392           DAG.getIntPtrConstant(Mask[V2Index] << 6 | V2Index << 4);
7393       return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7394                          InsertPSMask);
7395     }
7396
7397     // Compute the index adjacent to V2Index and in the same half by toggling
7398     // the low bit.
7399     int V2AdjIndex = V2Index ^ 1;
7400
7401     if (Mask[V2AdjIndex] == -1) {
7402       // Handles all the cases where we have a single V2 element and an undef.
7403       // This will only ever happen in the high lanes because we commute the
7404       // vector otherwise.
7405       if (V2Index < 2)
7406         std::swap(LowV, HighV);
7407       NewMask[V2Index] -= 4;
7408     } else {
7409       // Handle the case where the V2 element ends up adjacent to a V1 element.
7410       // To make this work, blend them together as the first step.
7411       int V1Index = V2AdjIndex;
7412       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7413       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7414                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7415
7416       // Now proceed to reconstruct the final blend as we have the necessary
7417       // high or low half formed.
7418       if (V2Index < 2) {
7419         LowV = V2;
7420         HighV = V1;
7421       } else {
7422         HighV = V2;
7423       }
7424       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7425       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7426     }
7427   } else if (NumV2Elements == 2) {
7428     if (Mask[0] < 4 && Mask[1] < 4) {
7429       // Handle the easy case where we have V1 in the low lanes and V2 in the
7430       // high lanes. We never see this reversed because we sort the shuffle.
7431       NewMask[2] -= 4;
7432       NewMask[3] -= 4;
7433     } else {
7434       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7435       // trying to place elements directly, just blend them and set up the final
7436       // shuffle to place them.
7437
7438       // The first two blend mask elements are for V1, the second two are for
7439       // V2.
7440       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7441                           Mask[2] < 4 ? Mask[2] : Mask[3],
7442                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7443                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7444       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7445                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7446
7447       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7448       // a blend.
7449       LowV = HighV = V1;
7450       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7451       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7452       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7453       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7454     }
7455   }
7456   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7457                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7458 }
7459
7460 /// \brief Lower 4-lane i32 vector shuffles.
7461 ///
7462 /// We try to handle these with integer-domain shuffles where we can, but for
7463 /// blends we use the floating point domain blend instructions.
7464 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7465                                        const X86Subtarget *Subtarget,
7466                                        SelectionDAG &DAG) {
7467   SDLoc DL(Op);
7468   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7469   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7470   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7471   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7472   ArrayRef<int> Mask = SVOp->getMask();
7473   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7474
7475   if (isSingleInputShuffleMask(Mask))
7476     // Straight shuffle of a single input vector. For everything from SSE2
7477     // onward this has a single fast instruction with no scary immediates.
7478     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7479                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7480
7481   // Use dedicated unpack instructions for masks that match their pattern.
7482   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7483     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7484   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7485     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7486
7487   // We implement this with SHUFPS because it can blend from two vectors.
7488   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7489   // up the inputs, bypassing domain shift penalties that we would encur if we
7490   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7491   // relevant.
7492   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7493                      DAG.getVectorShuffle(
7494                          MVT::v4f32, DL,
7495                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7496                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7497 }
7498
7499 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7500 /// shuffle lowering, and the most complex part.
7501 ///
7502 /// The lowering strategy is to try to form pairs of input lanes which are
7503 /// targeted at the same half of the final vector, and then use a dword shuffle
7504 /// to place them onto the right half, and finally unpack the paired lanes into
7505 /// their final position.
7506 ///
7507 /// The exact breakdown of how to form these dword pairs and align them on the
7508 /// correct sides is really tricky. See the comments within the function for
7509 /// more of the details.
7510 static SDValue lowerV8I16SingleInputVectorShuffle(
7511     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7512     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7513   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7514   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7515   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7516
7517   SmallVector<int, 4> LoInputs;
7518   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7519                [](int M) { return M >= 0; });
7520   std::sort(LoInputs.begin(), LoInputs.end());
7521   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7522   SmallVector<int, 4> HiInputs;
7523   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7524                [](int M) { return M >= 0; });
7525   std::sort(HiInputs.begin(), HiInputs.end());
7526   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7527   int NumLToL =
7528       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7529   int NumHToL = LoInputs.size() - NumLToL;
7530   int NumLToH =
7531       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7532   int NumHToH = HiInputs.size() - NumLToH;
7533   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7534   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7535   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7536   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7537
7538   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7539   // such inputs we can swap two of the dwords across the half mark and end up
7540   // with <=2 inputs to each half in each half. Once there, we can fall through
7541   // to the generic code below. For example:
7542   //
7543   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7544   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7545   //
7546   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7547   // and an existing 2-into-2 on the other half. In this case we may have to
7548   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7549   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7550   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7551   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7552   // half than the one we target for fixing) will be fixed when we re-enter this
7553   // path. We will also combine away any sequence of PSHUFD instructions that
7554   // result into a single instruction. Here is an example of the tricky case:
7555   //
7556   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7557   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7558   //
7559   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7560   //
7561   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7562   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7563   //
7564   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7565   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7566   //
7567   // The result is fine to be handled by the generic logic.
7568   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7569                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7570                           int AOffset, int BOffset) {
7571     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7572            "Must call this with A having 3 or 1 inputs from the A half.");
7573     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7574            "Must call this with B having 1 or 3 inputs from the B half.");
7575     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7576            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7577
7578     // Compute the index of dword with only one word among the three inputs in
7579     // a half by taking the sum of the half with three inputs and subtracting
7580     // the sum of the actual three inputs. The difference is the remaining
7581     // slot.
7582     int ADWord, BDWord;
7583     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7584     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7585     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7586     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7587     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7588     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7589     int TripleNonInputIdx =
7590         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7591     TripleDWord = TripleNonInputIdx / 2;
7592
7593     // We use xor with one to compute the adjacent DWord to whichever one the
7594     // OneInput is in.
7595     OneInputDWord = (OneInput / 2) ^ 1;
7596
7597     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7598     // and BToA inputs. If there is also such a problem with the BToB and AToB
7599     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7600     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7601     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7602     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7603       // Compute how many inputs will be flipped by swapping these DWords. We
7604       // need
7605       // to balance this to ensure we don't form a 3-1 shuffle in the other
7606       // half.
7607       int NumFlippedAToBInputs =
7608           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7609           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7610       int NumFlippedBToBInputs =
7611           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7612           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7613       if ((NumFlippedAToBInputs == 1 &&
7614            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7615           (NumFlippedBToBInputs == 1 &&
7616            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7617         // We choose whether to fix the A half or B half based on whether that
7618         // half has zero flipped inputs. At zero, we may not be able to fix it
7619         // with that half. We also bias towards fixing the B half because that
7620         // will more commonly be the high half, and we have to bias one way.
7621         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7622                                                        ArrayRef<int> Inputs) {
7623           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7624           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7625                                          PinnedIdx ^ 1) != Inputs.end();
7626           // Determine whether the free index is in the flipped dword or the
7627           // unflipped dword based on where the pinned index is. We use this bit
7628           // in an xor to conditionally select the adjacent dword.
7629           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7630           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7631                                              FixFreeIdx) != Inputs.end();
7632           if (IsFixIdxInput == IsFixFreeIdxInput)
7633             FixFreeIdx += 1;
7634           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7635                                         FixFreeIdx) != Inputs.end();
7636           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7637                  "We need to be changing the number of flipped inputs!");
7638           int PSHUFHalfMask[] = {0, 1, 2, 3};
7639           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7640           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7641                           MVT::v8i16, V,
7642                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7643
7644           for (int &M : Mask)
7645             if (M != -1 && M == FixIdx)
7646               M = FixFreeIdx;
7647             else if (M != -1 && M == FixFreeIdx)
7648               M = FixIdx;
7649         };
7650         if (NumFlippedBToBInputs != 0) {
7651           int BPinnedIdx =
7652               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7653           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7654         } else {
7655           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7656           int APinnedIdx =
7657               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7658           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7659         }
7660       }
7661     }
7662
7663     int PSHUFDMask[] = {0, 1, 2, 3};
7664     PSHUFDMask[ADWord] = BDWord;
7665     PSHUFDMask[BDWord] = ADWord;
7666     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7667                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7668                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7669                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7670
7671     // Adjust the mask to match the new locations of A and B.
7672     for (int &M : Mask)
7673       if (M != -1 && M/2 == ADWord)
7674         M = 2 * BDWord + M % 2;
7675       else if (M != -1 && M/2 == BDWord)
7676         M = 2 * ADWord + M % 2;
7677
7678     // Recurse back into this routine to re-compute state now that this isn't
7679     // a 3 and 1 problem.
7680     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7681                                 Mask);
7682   };
7683   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7684     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7685   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7686     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7687
7688   // At this point there are at most two inputs to the low and high halves from
7689   // each half. That means the inputs can always be grouped into dwords and
7690   // those dwords can then be moved to the correct half with a dword shuffle.
7691   // We use at most one low and one high word shuffle to collect these paired
7692   // inputs into dwords, and finally a dword shuffle to place them.
7693   int PSHUFLMask[4] = {-1, -1, -1, -1};
7694   int PSHUFHMask[4] = {-1, -1, -1, -1};
7695   int PSHUFDMask[4] = {-1, -1, -1, -1};
7696
7697   // First fix the masks for all the inputs that are staying in their
7698   // original halves. This will then dictate the targets of the cross-half
7699   // shuffles.
7700   auto fixInPlaceInputs =
7701       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7702                     MutableArrayRef<int> SourceHalfMask,
7703                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7704     if (InPlaceInputs.empty())
7705       return;
7706     if (InPlaceInputs.size() == 1) {
7707       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7708           InPlaceInputs[0] - HalfOffset;
7709       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7710       return;
7711     }
7712     if (IncomingInputs.empty()) {
7713       // Just fix all of the in place inputs.
7714       for (int Input : InPlaceInputs) {
7715         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7716         PSHUFDMask[Input / 2] = Input / 2;
7717       }
7718       return;
7719     }
7720
7721     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7722     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7723         InPlaceInputs[0] - HalfOffset;
7724     // Put the second input next to the first so that they are packed into
7725     // a dword. We find the adjacent index by toggling the low bit.
7726     int AdjIndex = InPlaceInputs[0] ^ 1;
7727     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7728     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7729     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7730   };
7731   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7732   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7733
7734   // Now gather the cross-half inputs and place them into a free dword of
7735   // their target half.
7736   // FIXME: This operation could almost certainly be simplified dramatically to
7737   // look more like the 3-1 fixing operation.
7738   auto moveInputsToRightHalf = [&PSHUFDMask](
7739       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7740       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7741       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7742       int DestOffset) {
7743     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7744       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7745     };
7746     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7747                                                int Word) {
7748       int LowWord = Word & ~1;
7749       int HighWord = Word | 1;
7750       return isWordClobbered(SourceHalfMask, LowWord) ||
7751              isWordClobbered(SourceHalfMask, HighWord);
7752     };
7753
7754     if (IncomingInputs.empty())
7755       return;
7756
7757     if (ExistingInputs.empty()) {
7758       // Map any dwords with inputs from them into the right half.
7759       for (int Input : IncomingInputs) {
7760         // If the source half mask maps over the inputs, turn those into
7761         // swaps and use the swapped lane.
7762         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7763           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7764             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7765                 Input - SourceOffset;
7766             // We have to swap the uses in our half mask in one sweep.
7767             for (int &M : HalfMask)
7768               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7769                 M = Input;
7770               else if (M == Input)
7771                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7772           } else {
7773             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7774                        Input - SourceOffset &&
7775                    "Previous placement doesn't match!");
7776           }
7777           // Note that this correctly re-maps both when we do a swap and when
7778           // we observe the other side of the swap above. We rely on that to
7779           // avoid swapping the members of the input list directly.
7780           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7781         }
7782
7783         // Map the input's dword into the correct half.
7784         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7785           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7786         else
7787           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7788                      Input / 2 &&
7789                  "Previous placement doesn't match!");
7790       }
7791
7792       // And just directly shift any other-half mask elements to be same-half
7793       // as we will have mirrored the dword containing the element into the
7794       // same position within that half.
7795       for (int &M : HalfMask)
7796         if (M >= SourceOffset && M < SourceOffset + 4) {
7797           M = M - SourceOffset + DestOffset;
7798           assert(M >= 0 && "This should never wrap below zero!");
7799         }
7800       return;
7801     }
7802
7803     // Ensure we have the input in a viable dword of its current half. This
7804     // is particularly tricky because the original position may be clobbered
7805     // by inputs being moved and *staying* in that half.
7806     if (IncomingInputs.size() == 1) {
7807       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7808         int InputFixed = std::find(std::begin(SourceHalfMask),
7809                                    std::end(SourceHalfMask), -1) -
7810                          std::begin(SourceHalfMask) + SourceOffset;
7811         SourceHalfMask[InputFixed - SourceOffset] =
7812             IncomingInputs[0] - SourceOffset;
7813         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7814                      InputFixed);
7815         IncomingInputs[0] = InputFixed;
7816       }
7817     } else if (IncomingInputs.size() == 2) {
7818       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7819           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7820         // We have two non-adjacent or clobbered inputs we need to extract from
7821         // the source half. To do this, we need to map them into some adjacent
7822         // dword slot in the source mask.
7823         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7824                               IncomingInputs[1] - SourceOffset};
7825
7826         // If there is a free slot in the source half mask adjacent to one of
7827         // the inputs, place the other input in it. We use (Index XOR 1) to
7828         // compute an adjacent index.
7829         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7830             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7831           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7832           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7833           InputsFixed[1] = InputsFixed[0] ^ 1;
7834         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7835                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7836           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7837           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7838           InputsFixed[0] = InputsFixed[1] ^ 1;
7839         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7840                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7841           // The two inputs are in the same DWord but it is clobbered and the
7842           // adjacent DWord isn't used at all. Move both inputs to the free
7843           // slot.
7844           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7845           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7846           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7847           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7848         } else {
7849           // The only way we hit this point is if there is no clobbering
7850           // (because there are no off-half inputs to this half) and there is no
7851           // free slot adjacent to one of the inputs. In this case, we have to
7852           // swap an input with a non-input.
7853           for (int i = 0; i < 4; ++i)
7854             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7855                    "We can't handle any clobbers here!");
7856           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7857                  "Cannot have adjacent inputs here!");
7858
7859           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7860           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7861
7862           // We also have to update the final source mask in this case because
7863           // it may need to undo the above swap.
7864           for (int &M : FinalSourceHalfMask)
7865             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7866               M = InputsFixed[1] + SourceOffset;
7867             else if (M == InputsFixed[1] + SourceOffset)
7868               M = (InputsFixed[0] ^ 1) + SourceOffset;
7869
7870           InputsFixed[1] = InputsFixed[0] ^ 1;
7871         }
7872
7873         // Point everything at the fixed inputs.
7874         for (int &M : HalfMask)
7875           if (M == IncomingInputs[0])
7876             M = InputsFixed[0] + SourceOffset;
7877           else if (M == IncomingInputs[1])
7878             M = InputsFixed[1] + SourceOffset;
7879
7880         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7881         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7882       }
7883     } else {
7884       llvm_unreachable("Unhandled input size!");
7885     }
7886
7887     // Now hoist the DWord down to the right half.
7888     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7889     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7890     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7891     for (int &M : HalfMask)
7892       for (int Input : IncomingInputs)
7893         if (M == Input)
7894           M = FreeDWord * 2 + Input % 2;
7895   };
7896   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7897                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7898   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7899                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7900
7901   // Now enact all the shuffles we've computed to move the inputs into their
7902   // target half.
7903   if (!isNoopShuffleMask(PSHUFLMask))
7904     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7905                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7906   if (!isNoopShuffleMask(PSHUFHMask))
7907     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7908                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7909   if (!isNoopShuffleMask(PSHUFDMask))
7910     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7911                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7912                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7913                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7914
7915   // At this point, each half should contain all its inputs, and we can then
7916   // just shuffle them into their final position.
7917   assert(std::count_if(LoMask.begin(), LoMask.end(),
7918                        [](int M) { return M >= 4; }) == 0 &&
7919          "Failed to lift all the high half inputs to the low mask!");
7920   assert(std::count_if(HiMask.begin(), HiMask.end(),
7921                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7922          "Failed to lift all the low half inputs to the high mask!");
7923
7924   // Do a half shuffle for the low mask.
7925   if (!isNoopShuffleMask(LoMask))
7926     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7927                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7928
7929   // Do a half shuffle with the high mask after shifting its values down.
7930   for (int &M : HiMask)
7931     if (M >= 0)
7932       M -= 4;
7933   if (!isNoopShuffleMask(HiMask))
7934     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7935                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7936
7937   return V;
7938 }
7939
7940 /// \brief Detect whether the mask pattern should be lowered through
7941 /// interleaving.
7942 ///
7943 /// This essentially tests whether viewing the mask as an interleaving of two
7944 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7945 /// lowering it through interleaving is a significantly better strategy.
7946 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7947   int NumEvenInputs[2] = {0, 0};
7948   int NumOddInputs[2] = {0, 0};
7949   int NumLoInputs[2] = {0, 0};
7950   int NumHiInputs[2] = {0, 0};
7951   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7952     if (Mask[i] < 0)
7953       continue;
7954
7955     int InputIdx = Mask[i] >= Size;
7956
7957     if (i < Size / 2)
7958       ++NumLoInputs[InputIdx];
7959     else
7960       ++NumHiInputs[InputIdx];
7961
7962     if ((i % 2) == 0)
7963       ++NumEvenInputs[InputIdx];
7964     else
7965       ++NumOddInputs[InputIdx];
7966   }
7967
7968   // The minimum number of cross-input results for both the interleaved and
7969   // split cases. If interleaving results in fewer cross-input results, return
7970   // true.
7971   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7972                                     NumEvenInputs[0] + NumOddInputs[1]);
7973   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7974                               NumLoInputs[0] + NumHiInputs[1]);
7975   return InterleavedCrosses < SplitCrosses;
7976 }
7977
7978 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7979 ///
7980 /// This strategy only works when the inputs from each vector fit into a single
7981 /// half of that vector, and generally there are not so many inputs as to leave
7982 /// the in-place shuffles required highly constrained (and thus expensive). It
7983 /// shifts all the inputs into a single side of both input vectors and then
7984 /// uses an unpack to interleave these inputs in a single vector. At that
7985 /// point, we will fall back on the generic single input shuffle lowering.
7986 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7987                                                  SDValue V2,
7988                                                  MutableArrayRef<int> Mask,
7989                                                  const X86Subtarget *Subtarget,
7990                                                  SelectionDAG &DAG) {
7991   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7992   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7993   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7994   for (int i = 0; i < 8; ++i)
7995     if (Mask[i] >= 0 && Mask[i] < 4)
7996       LoV1Inputs.push_back(i);
7997     else if (Mask[i] >= 4 && Mask[i] < 8)
7998       HiV1Inputs.push_back(i);
7999     else if (Mask[i] >= 8 && Mask[i] < 12)
8000       LoV2Inputs.push_back(i);
8001     else if (Mask[i] >= 12)
8002       HiV2Inputs.push_back(i);
8003
8004   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
8005   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
8006   (void)NumV1Inputs;
8007   (void)NumV2Inputs;
8008   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
8009   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
8010   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
8011
8012   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
8013                      HiV1Inputs.size() + HiV2Inputs.size();
8014
8015   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
8016                               ArrayRef<int> HiInputs, bool MoveToLo,
8017                               int MaskOffset) {
8018     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
8019     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
8020     if (BadInputs.empty())
8021       return V;
8022
8023     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8024     int MoveOffset = MoveToLo ? 0 : 4;
8025
8026     if (GoodInputs.empty()) {
8027       for (int BadInput : BadInputs) {
8028         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
8029         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
8030       }
8031     } else {
8032       if (GoodInputs.size() == 2) {
8033         // If the low inputs are spread across two dwords, pack them into
8034         // a single dword.
8035         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
8036         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
8037         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
8038         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
8039       } else {
8040         // Otherwise pin the good inputs.
8041         for (int GoodInput : GoodInputs)
8042           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
8043       }
8044
8045       if (BadInputs.size() == 2) {
8046         // If we have two bad inputs then there may be either one or two good
8047         // inputs fixed in place. Find a fixed input, and then find the *other*
8048         // two adjacent indices by using modular arithmetic.
8049         int GoodMaskIdx =
8050             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
8051                          [](int M) { return M >= 0; }) -
8052             std::begin(MoveMask);
8053         int MoveMaskIdx =
8054             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
8055         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
8056         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
8057         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8058         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
8059         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8060         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
8061       } else {
8062         assert(BadInputs.size() == 1 && "All sizes handled");
8063         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
8064                                     std::end(MoveMask), -1) -
8065                           std::begin(MoveMask);
8066         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8067         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8068       }
8069     }
8070
8071     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8072                                 MoveMask);
8073   };
8074   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
8075                         /*MaskOffset*/ 0);
8076   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
8077                         /*MaskOffset*/ 8);
8078
8079   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
8080   // cross-half traffic in the final shuffle.
8081
8082   // Munge the mask to be a single-input mask after the unpack merges the
8083   // results.
8084   for (int &M : Mask)
8085     if (M != -1)
8086       M = 2 * (M % 4) + (M / 8);
8087
8088   return DAG.getVectorShuffle(
8089       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
8090                                   DL, MVT::v8i16, V1, V2),
8091       DAG.getUNDEF(MVT::v8i16), Mask);
8092 }
8093
8094 /// \brief Generic lowering of 8-lane i16 shuffles.
8095 ///
8096 /// This handles both single-input shuffles and combined shuffle/blends with
8097 /// two inputs. The single input shuffles are immediately delegated to
8098 /// a dedicated lowering routine.
8099 ///
8100 /// The blends are lowered in one of three fundamental ways. If there are few
8101 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8102 /// of the input is significantly cheaper when lowered as an interleaving of
8103 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8104 /// halves of the inputs separately (making them have relatively few inputs)
8105 /// and then concatenate them.
8106 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8107                                        const X86Subtarget *Subtarget,
8108                                        SelectionDAG &DAG) {
8109   SDLoc DL(Op);
8110   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8111   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8112   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8113   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8114   ArrayRef<int> OrigMask = SVOp->getMask();
8115   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8116                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8117   MutableArrayRef<int> Mask(MaskStorage);
8118
8119   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8120
8121   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8122   auto isV2 = [](int M) { return M >= 8; };
8123
8124   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
8125   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8126
8127   if (NumV2Inputs == 0)
8128     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
8129
8130   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
8131                             "to be V1-input shuffles.");
8132
8133   if (NumV1Inputs + NumV2Inputs <= 4)
8134     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
8135
8136   // Check whether an interleaving lowering is likely to be more efficient.
8137   // This isn't perfect but it is a strong heuristic that tends to work well on
8138   // the kinds of shuffles that show up in practice.
8139   //
8140   // FIXME: Handle 1x, 2x, and 4x interleaving.
8141   if (shouldLowerAsInterleaving(Mask)) {
8142     // FIXME: Figure out whether we should pack these into the low or high
8143     // halves.
8144
8145     int EMask[8], OMask[8];
8146     for (int i = 0; i < 4; ++i) {
8147       EMask[i] = Mask[2*i];
8148       OMask[i] = Mask[2*i + 1];
8149       EMask[i + 4] = -1;
8150       OMask[i + 4] = -1;
8151     }
8152
8153     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8154     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8155
8156     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8157   }
8158
8159   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8160   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8161
8162   for (int i = 0; i < 4; ++i) {
8163     LoBlendMask[i] = Mask[i];
8164     HiBlendMask[i] = Mask[i + 4];
8165   }
8166
8167   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8168   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8169   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8170   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8171
8172   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8173                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8174 }
8175
8176 /// \brief Check whether a compaction lowering can be done by dropping even
8177 /// elements and compute how many times even elements must be dropped.
8178 ///
8179 /// This handles shuffles which take every Nth element where N is a power of
8180 /// two. Example shuffle masks:
8181 ///
8182 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8183 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8184 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8185 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8186 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8187 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8188 ///
8189 /// Any of these lanes can of course be undef.
8190 ///
8191 /// This routine only supports N <= 3.
8192 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8193 /// for larger N.
8194 ///
8195 /// \returns N above, or the number of times even elements must be dropped if
8196 /// there is such a number. Otherwise returns zero.
8197 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8198   // Figure out whether we're looping over two inputs or just one.
8199   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8200
8201   // The modulus for the shuffle vector entries is based on whether this is
8202   // a single input or not.
8203   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8204   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8205          "We should only be called with masks with a power-of-2 size!");
8206
8207   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8208
8209   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8210   // and 2^3 simultaneously. This is because we may have ambiguity with
8211   // partially undef inputs.
8212   bool ViableForN[3] = {true, true, true};
8213
8214   for (int i = 0, e = Mask.size(); i < e; ++i) {
8215     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8216     // want.
8217     if (Mask[i] == -1)
8218       continue;
8219
8220     bool IsAnyViable = false;
8221     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8222       if (ViableForN[j]) {
8223         uint64_t N = j + 1;
8224
8225         // The shuffle mask must be equal to (i * 2^N) % M.
8226         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8227           IsAnyViable = true;
8228         else
8229           ViableForN[j] = false;
8230       }
8231     // Early exit if we exhaust the possible powers of two.
8232     if (!IsAnyViable)
8233       break;
8234   }
8235
8236   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8237     if (ViableForN[j])
8238       return j + 1;
8239
8240   // Return 0 as there is no viable power of two.
8241   return 0;
8242 }
8243
8244 /// \brief Generic lowering of v16i8 shuffles.
8245 ///
8246 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8247 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8248 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8249 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8250 /// back together.
8251 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8252                                        const X86Subtarget *Subtarget,
8253                                        SelectionDAG &DAG) {
8254   SDLoc DL(Op);
8255   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8256   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8257   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8258   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8259   ArrayRef<int> OrigMask = SVOp->getMask();
8260   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8261   int MaskStorage[16] = {
8262       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
8263       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
8264       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
8265       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8266   MutableArrayRef<int> Mask(MaskStorage);
8267   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8268   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8269
8270   // For single-input shuffles, there are some nicer lowering tricks we can use.
8271   if (isSingleInputShuffleMask(Mask)) {
8272     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8273     // Notably, this handles splat and partial-splat shuffles more efficiently.
8274     // However, it only makes sense if the pre-duplication shuffle simplifies
8275     // things significantly. Currently, this means we need to be able to
8276     // express the pre-duplication shuffle as an i16 shuffle.
8277     //
8278     // FIXME: We should check for other patterns which can be widened into an
8279     // i16 shuffle as well.
8280     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8281       for (int i = 0; i < 16; i += 2) {
8282         if (Mask[i] != Mask[i + 1])
8283           return false;
8284       }
8285       return true;
8286     };
8287     auto tryToWidenViaDuplication = [&]() -> SDValue {
8288       if (!canWidenViaDuplication(Mask))
8289         return SDValue();
8290       SmallVector<int, 4> LoInputs;
8291       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8292                    [](int M) { return M >= 0 && M < 8; });
8293       std::sort(LoInputs.begin(), LoInputs.end());
8294       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8295                      LoInputs.end());
8296       SmallVector<int, 4> HiInputs;
8297       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8298                    [](int M) { return M >= 8; });
8299       std::sort(HiInputs.begin(), HiInputs.end());
8300       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8301                      HiInputs.end());
8302
8303       bool TargetLo = LoInputs.size() >= HiInputs.size();
8304       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8305       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8306
8307       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8308       SmallDenseMap<int, int, 8> LaneMap;
8309       for (int I : InPlaceInputs) {
8310         PreDupI16Shuffle[I/2] = I/2;
8311         LaneMap[I] = I;
8312       }
8313       int j = TargetLo ? 0 : 4, je = j + 4;
8314       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8315         // Check if j is already a shuffle of this input. This happens when
8316         // there are two adjacent bytes after we move the low one.
8317         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8318           // If we haven't yet mapped the input, search for a slot into which
8319           // we can map it.
8320           while (j < je && PreDupI16Shuffle[j] != -1)
8321             ++j;
8322
8323           if (j == je)
8324             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8325             return SDValue();
8326
8327           // Map this input with the i16 shuffle.
8328           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8329         }
8330
8331         // Update the lane map based on the mapping we ended up with.
8332         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8333       }
8334       V1 = DAG.getNode(
8335           ISD::BITCAST, DL, MVT::v16i8,
8336           DAG.getVectorShuffle(MVT::v8i16, DL,
8337                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8338                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8339
8340       // Unpack the bytes to form the i16s that will be shuffled into place.
8341       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8342                        MVT::v16i8, V1, V1);
8343
8344       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8345       for (int i = 0; i < 16; i += 2) {
8346         if (Mask[i] != -1)
8347           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8348         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8349       }
8350       return DAG.getNode(
8351           ISD::BITCAST, DL, MVT::v16i8,
8352           DAG.getVectorShuffle(MVT::v8i16, DL,
8353                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8354                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8355     };
8356     if (SDValue V = tryToWidenViaDuplication())
8357       return V;
8358   }
8359
8360   // Check whether an interleaving lowering is likely to be more efficient.
8361   // This isn't perfect but it is a strong heuristic that tends to work well on
8362   // the kinds of shuffles that show up in practice.
8363   //
8364   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8365   if (shouldLowerAsInterleaving(Mask)) {
8366     // FIXME: Figure out whether we should pack these into the low or high
8367     // halves.
8368
8369     int EMask[16], OMask[16];
8370     for (int i = 0; i < 8; ++i) {
8371       EMask[i] = Mask[2*i];
8372       OMask[i] = Mask[2*i + 1];
8373       EMask[i + 8] = -1;
8374       OMask[i + 8] = -1;
8375     }
8376
8377     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8378     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8379
8380     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8381   }
8382
8383   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8384   // with PSHUFB. It is important to do this before we attempt to generate any
8385   // blends but after all of the single-input lowerings. If the single input
8386   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8387   // want to preserve that and we can DAG combine any longer sequences into
8388   // a PSHUFB in the end. But once we start blending from multiple inputs,
8389   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8390   // and there are *very* few patterns that would actually be faster than the
8391   // PSHUFB approach because of its ability to zero lanes.
8392   //
8393   // FIXME: The only exceptions to the above are blends which are exact
8394   // interleavings with direct instructions supporting them. We currently don't
8395   // handle those well here.
8396   if (Subtarget->hasSSSE3()) {
8397     SDValue V1Mask[16];
8398     SDValue V2Mask[16];
8399     for (int i = 0; i < 16; ++i)
8400       if (Mask[i] == -1) {
8401         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8402       } else {
8403         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8404         V2Mask[i] =
8405             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8406       }
8407     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8408                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8409     if (isSingleInputShuffleMask(Mask))
8410       return V1; // Single inputs are easy.
8411
8412     // Otherwise, blend the two.
8413     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8414                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8415     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8416   }
8417
8418   // Check whether a compaction lowering can be done. This handles shuffles
8419   // which take every Nth element for some even N. See the helper function for
8420   // details.
8421   //
8422   // We special case these as they can be particularly efficiently handled with
8423   // the PACKUSB instruction on x86 and they show up in common patterns of
8424   // rearranging bytes to truncate wide elements.
8425   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8426     // NumEvenDrops is the power of two stride of the elements. Another way of
8427     // thinking about it is that we need to drop the even elements this many
8428     // times to get the original input.
8429     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8430
8431     // First we need to zero all the dropped bytes.
8432     assert(NumEvenDrops <= 3 &&
8433            "No support for dropping even elements more than 3 times.");
8434     // We use the mask type to pick which bytes are preserved based on how many
8435     // elements are dropped.
8436     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8437     SDValue ByteClearMask =
8438         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8439                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8440     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8441     if (!IsSingleInput)
8442       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8443
8444     // Now pack things back together.
8445     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8446     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8447     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8448     for (int i = 1; i < NumEvenDrops; ++i) {
8449       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8450       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8451     }
8452
8453     return Result;
8454   }
8455
8456   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8457   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8458   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8459   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8460
8461   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8462                             MutableArrayRef<int> V1HalfBlendMask,
8463                             MutableArrayRef<int> V2HalfBlendMask) {
8464     for (int i = 0; i < 8; ++i)
8465       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8466         V1HalfBlendMask[i] = HalfMask[i];
8467         HalfMask[i] = i;
8468       } else if (HalfMask[i] >= 16) {
8469         V2HalfBlendMask[i] = HalfMask[i] - 16;
8470         HalfMask[i] = i + 8;
8471       }
8472   };
8473   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8474   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8475
8476   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8477
8478   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8479                              MutableArrayRef<int> HiBlendMask) {
8480     SDValue V1, V2;
8481     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8482     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8483     // i16s.
8484     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8485                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8486         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8487                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8488       // Use a mask to drop the high bytes.
8489       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8490       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8491                        DAG.getConstant(0x00FF, MVT::v8i16));
8492
8493       // This will be a single vector shuffle instead of a blend so nuke V2.
8494       V2 = DAG.getUNDEF(MVT::v8i16);
8495
8496       // Squash the masks to point directly into V1.
8497       for (int &M : LoBlendMask)
8498         if (M >= 0)
8499           M /= 2;
8500       for (int &M : HiBlendMask)
8501         if (M >= 0)
8502           M /= 2;
8503     } else {
8504       // Otherwise just unpack the low half of V into V1 and the high half into
8505       // V2 so that we can blend them as i16s.
8506       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8507                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8508       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8509                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8510     }
8511
8512     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8513     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8514     return std::make_pair(BlendedLo, BlendedHi);
8515   };
8516   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8517   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8518   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8519
8520   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8521   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8522
8523   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8524 }
8525
8526 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8527 ///
8528 /// This routine breaks down the specific type of 128-bit shuffle and
8529 /// dispatches to the lowering routines accordingly.
8530 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8531                                         MVT VT, const X86Subtarget *Subtarget,
8532                                         SelectionDAG &DAG) {
8533   switch (VT.SimpleTy) {
8534   case MVT::v2i64:
8535     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8536   case MVT::v2f64:
8537     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8538   case MVT::v4i32:
8539     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8540   case MVT::v4f32:
8541     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8542   case MVT::v8i16:
8543     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8544   case MVT::v16i8:
8545     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8546
8547   default:
8548     llvm_unreachable("Unimplemented!");
8549   }
8550 }
8551
8552 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8553   int Size = Mask.size();
8554   for (int M : Mask.slice(0, Size / 2))
8555     if (M >= 0 && (M % Size) >= Size / 2)
8556       return true;
8557   for (int M : Mask.slice(Size / 2, Size / 2))
8558     if (M >= 0 && (M % Size) < Size / 2)
8559       return true;
8560   return false;
8561 }
8562
8563 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8564 /// shuffles.
8565 ///
8566 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8567 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8568 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8569 /// we encode the logic here for specific shuffle lowering routines to bail to
8570 /// when they exhaust the features avaible to more directly handle the shuffle.
8571 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8572                                                 SDValue V2,
8573                                                 const X86Subtarget *Subtarget,
8574                                                 SelectionDAG &DAG) {
8575   SDLoc DL(Op);
8576   MVT VT = Op.getSimpleValueType();
8577   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8578   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8579   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8580   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8581   ArrayRef<int> Mask = SVOp->getMask();
8582
8583   ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8584   ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8585
8586   int NumElements = VT.getVectorNumElements();
8587   int SplitNumElements = NumElements / 2;
8588   MVT ScalarVT = VT.getScalarType();
8589   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8590
8591   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8592                              DAG.getIntPtrConstant(0));
8593   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8594                              DAG.getIntPtrConstant(SplitNumElements));
8595   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8596                              DAG.getIntPtrConstant(0));
8597   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8598                              DAG.getIntPtrConstant(SplitNumElements));
8599
8600   // Now create two 4-way blends of these half-width vectors.
8601   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8602     SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8603     for (int i = 0; i < SplitNumElements; ++i) {
8604       int M = HalfMask[i];
8605       if (M >= NumElements) {
8606         V2BlendMask.push_back(M - NumElements);
8607         V1BlendMask.push_back(-1);
8608         BlendMask.push_back(SplitNumElements + i);
8609       } else if (M >= 0) {
8610         V2BlendMask.push_back(-1);
8611         V1BlendMask.push_back(M);
8612         BlendMask.push_back(i);
8613       } else {
8614         V2BlendMask.push_back(-1);
8615         V1BlendMask.push_back(-1);
8616         BlendMask.push_back(-1);
8617       }
8618     }
8619     SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8620     SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8621     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8622   };
8623   SDValue Lo = HalfBlend(LoMask);
8624   SDValue Hi = HalfBlend(HiMask);
8625   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8626 }
8627
8628 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8629 ///
8630 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8631 /// isn't available.
8632 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8633                                        const X86Subtarget *Subtarget,
8634                                        SelectionDAG &DAG) {
8635   SDLoc DL(Op);
8636   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8637   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8638   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8639   ArrayRef<int> Mask = SVOp->getMask();
8640   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8641
8642   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8643   // shuffles aren't a problem and FP and int have the same patterns.
8644
8645   // FIXME: We can handle these more cleverly than splitting for v4f64.
8646   if (isHalfCrossingShuffleMask(Mask))
8647     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8648
8649   if (isSingleInputShuffleMask(Mask)) {
8650     // Non-half-crossing single input shuffles can be lowerid with an
8651     // interleaved permutation.
8652     unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8653                             ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8654     return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8655                        DAG.getConstant(VPERMILPMask, MVT::i8));
8656   }
8657
8658   // X86 has dedicated unpack instructions that can handle specific blend
8659   // operations: UNPCKH and UNPCKL.
8660   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8661     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8662   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8663     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8664   // FIXME: It would be nice to find a way to get canonicalization to commute
8665   // these patterns.
8666   if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8667     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8668   if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8669     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8670
8671   // Check if the blend happens to exactly fit that of SHUFPD.
8672   if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8673       Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8674     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8675                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8676     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8677                        DAG.getConstant(SHUFPDMask, MVT::i8));
8678   }
8679   if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8680       (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8681     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8682                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8683     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8684                        DAG.getConstant(SHUFPDMask, MVT::i8));
8685   }
8686
8687   // Shuffle the input elements into the desired positions in V1 and V2 and
8688   // blend them together.
8689   int V1Mask[] = {-1, -1, -1, -1};
8690   int V2Mask[] = {-1, -1, -1, -1};
8691   for (int i = 0; i < 4; ++i)
8692     if (Mask[i] >= 0 && Mask[i] < 4)
8693       V1Mask[i] = Mask[i];
8694     else if (Mask[i] >= 4)
8695       V2Mask[i] = Mask[i] - 4;
8696
8697   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8698   V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8699
8700   unsigned BlendMask = 0;
8701   for (int i = 0; i < 4; ++i)
8702     if (Mask[i] >= 4)
8703       BlendMask |= 1 << i;
8704
8705   return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8706                      DAG.getConstant(BlendMask, MVT::i8));
8707 }
8708
8709 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8710 ///
8711 /// Largely delegates to common code when we have AVX2 and to the floating-point
8712 /// code when we only have AVX.
8713 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8714                                        const X86Subtarget *Subtarget,
8715                                        SelectionDAG &DAG) {
8716   SDLoc DL(Op);
8717   assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8718   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8719   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8720   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8721   ArrayRef<int> Mask = SVOp->getMask();
8722   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8723
8724   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8725   // shuffles aren't a problem and FP and int have the same patterns.
8726
8727   if (isHalfCrossingShuffleMask(Mask))
8728     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8729
8730   // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8731   // delegate to floating point code.
8732   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8733   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8734   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8735                      lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8736 }
8737
8738 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8739 ///
8740 /// This routine either breaks down the specific type of a 256-bit x86 vector
8741 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8742 /// together based on the available instructions.
8743 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8744                                         MVT VT, const X86Subtarget *Subtarget,
8745                                         SelectionDAG &DAG) {
8746   switch (VT.SimpleTy) {
8747   case MVT::v4f64:
8748     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8749   case MVT::v4i64:
8750     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8751   case MVT::v8i32:
8752   case MVT::v8f32:
8753   case MVT::v16i16:
8754   case MVT::v32i8:
8755     // Fall back to the basic pattern of extracting the high half and forming
8756     // a 4-way blend.
8757     // FIXME: Add targeted lowering for each type that can document rationale
8758     // for delegating to this when necessary.
8759     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8760
8761   default:
8762     llvm_unreachable("Not a valid 256-bit x86 vector type!");
8763   }
8764 }
8765
8766 /// \brief Tiny helper function to test whether a shuffle mask could be
8767 /// simplified by widening the elements being shuffled.
8768 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8769   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8770     if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8771       return false;
8772
8773   return true;
8774 }
8775
8776 /// \brief Top-level lowering for x86 vector shuffles.
8777 ///
8778 /// This handles decomposition, canonicalization, and lowering of all x86
8779 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8780 /// above in helper routines. The canonicalization attempts to widen shuffles
8781 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8782 /// s.t. only one of the two inputs needs to be tested, etc.
8783 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8784                                   SelectionDAG &DAG) {
8785   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8786   ArrayRef<int> Mask = SVOp->getMask();
8787   SDValue V1 = Op.getOperand(0);
8788   SDValue V2 = Op.getOperand(1);
8789   MVT VT = Op.getSimpleValueType();
8790   int NumElements = VT.getVectorNumElements();
8791   SDLoc dl(Op);
8792
8793   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8794
8795   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8796   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8797   if (V1IsUndef && V2IsUndef)
8798     return DAG.getUNDEF(VT);
8799
8800   // When we create a shuffle node we put the UNDEF node to second operand,
8801   // but in some cases the first operand may be transformed to UNDEF.
8802   // In this case we should just commute the node.
8803   if (V1IsUndef)
8804     return DAG.getCommutedVectorShuffle(*SVOp);
8805
8806   // Check for non-undef masks pointing at an undef vector and make the masks
8807   // undef as well. This makes it easier to match the shuffle based solely on
8808   // the mask.
8809   if (V2IsUndef)
8810     for (int M : Mask)
8811       if (M >= NumElements) {
8812         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8813         for (int &M : NewMask)
8814           if (M >= NumElements)
8815             M = -1;
8816         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8817       }
8818
8819   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8820   // lanes but wider integers. We cap this to not form integers larger than i64
8821   // but it might be interesting to form i128 integers to handle flipping the
8822   // low and high halves of AVX 256-bit vectors.
8823   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8824       canWidenShuffleElements(Mask)) {
8825     SmallVector<int, 8> NewMask;
8826     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8827       NewMask.push_back(Mask[i] / 2);
8828     MVT NewVT =
8829         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8830                          VT.getVectorNumElements() / 2);
8831     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8832     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8833     return DAG.getNode(ISD::BITCAST, dl, VT,
8834                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8835   }
8836
8837   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8838   for (int M : SVOp->getMask())
8839     if (M < 0)
8840       ++NumUndefElements;
8841     else if (M < NumElements)
8842       ++NumV1Elements;
8843     else
8844       ++NumV2Elements;
8845
8846   // Commute the shuffle as needed such that more elements come from V1 than
8847   // V2. This allows us to match the shuffle pattern strictly on how many
8848   // elements come from V1 without handling the symmetric cases.
8849   if (NumV2Elements > NumV1Elements)
8850     return DAG.getCommutedVectorShuffle(*SVOp);
8851
8852   // When the number of V1 and V2 elements are the same, try to minimize the
8853   // number of uses of V2 in the low half of the vector.
8854   if (NumV1Elements == NumV2Elements) {
8855     int LowV1Elements = 0, LowV2Elements = 0;
8856     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8857       if (M >= NumElements)
8858         ++LowV2Elements;
8859       else if (M >= 0)
8860         ++LowV1Elements;
8861     if (LowV2Elements > LowV1Elements)
8862       return DAG.getCommutedVectorShuffle(*SVOp);
8863   }
8864
8865   // For each vector width, delegate to a specialized lowering routine.
8866   if (VT.getSizeInBits() == 128)
8867     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8868
8869   if (VT.getSizeInBits() == 256)
8870     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8871
8872   llvm_unreachable("Unimplemented!");
8873 }
8874
8875
8876 //===----------------------------------------------------------------------===//
8877 // Legacy vector shuffle lowering
8878 //
8879 // This code is the legacy code handling vector shuffles until the above
8880 // replaces its functionality and performance.
8881 //===----------------------------------------------------------------------===//
8882
8883 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8884                         bool hasInt256, unsigned *MaskOut = nullptr) {
8885   MVT EltVT = VT.getVectorElementType();
8886
8887   // There is no blend with immediate in AVX-512.
8888   if (VT.is512BitVector())
8889     return false;
8890
8891   if (!hasSSE41 || EltVT == MVT::i8)
8892     return false;
8893   if (!hasInt256 && VT == MVT::v16i16)
8894     return false;
8895
8896   unsigned MaskValue = 0;
8897   unsigned NumElems = VT.getVectorNumElements();
8898   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8899   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8900   unsigned NumElemsInLane = NumElems / NumLanes;
8901
8902   // Blend for v16i16 should be symetric for the both lanes.
8903   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8904
8905     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8906     int EltIdx = MaskVals[i];
8907
8908     if ((EltIdx < 0 || EltIdx == (int)i) &&
8909         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8910       continue;
8911
8912     if (((unsigned)EltIdx == (i + NumElems)) &&
8913         (SndLaneEltIdx < 0 ||
8914          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8915       MaskValue |= (1 << i);
8916     else
8917       return false;
8918   }
8919
8920   if (MaskOut)
8921     *MaskOut = MaskValue;
8922   return true;
8923 }
8924
8925 // Try to lower a shuffle node into a simple blend instruction.
8926 // This function assumes isBlendMask returns true for this
8927 // SuffleVectorSDNode
8928 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8929                                           unsigned MaskValue,
8930                                           const X86Subtarget *Subtarget,
8931                                           SelectionDAG &DAG) {
8932   MVT VT = SVOp->getSimpleValueType(0);
8933   MVT EltVT = VT.getVectorElementType();
8934   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8935                      Subtarget->hasInt256() && "Trying to lower a "
8936                                                "VECTOR_SHUFFLE to a Blend but "
8937                                                "with the wrong mask"));
8938   SDValue V1 = SVOp->getOperand(0);
8939   SDValue V2 = SVOp->getOperand(1);
8940   SDLoc dl(SVOp);
8941   unsigned NumElems = VT.getVectorNumElements();
8942
8943   // Convert i32 vectors to floating point if it is not AVX2.
8944   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8945   MVT BlendVT = VT;
8946   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8947     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8948                                NumElems);
8949     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8950     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8951   }
8952
8953   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8954                             DAG.getConstant(MaskValue, MVT::i32));
8955   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8956 }
8957
8958 /// In vector type \p VT, return true if the element at index \p InputIdx
8959 /// falls on a different 128-bit lane than \p OutputIdx.
8960 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8961                                      unsigned OutputIdx) {
8962   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8963   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8964 }
8965
8966 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8967 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8968 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8969 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8970 /// zero.
8971 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8972                          SelectionDAG &DAG) {
8973   MVT VT = V1.getSimpleValueType();
8974   assert(VT.is128BitVector() || VT.is256BitVector());
8975
8976   MVT EltVT = VT.getVectorElementType();
8977   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8978   unsigned NumElts = VT.getVectorNumElements();
8979
8980   SmallVector<SDValue, 32> PshufbMask;
8981   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8982     int InputIdx = MaskVals[OutputIdx];
8983     unsigned InputByteIdx;
8984
8985     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8986       InputByteIdx = 0x80;
8987     else {
8988       // Cross lane is not allowed.
8989       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8990         return SDValue();
8991       InputByteIdx = InputIdx * EltSizeInBytes;
8992       // Index is an byte offset within the 128-bit lane.
8993       InputByteIdx &= 0xf;
8994     }
8995
8996     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8997       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8998       if (InputByteIdx != 0x80)
8999         ++InputByteIdx;
9000     }
9001   }
9002
9003   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
9004   if (ShufVT != VT)
9005     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
9006   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
9007                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
9008 }
9009
9010 // v8i16 shuffles - Prefer shuffles in the following order:
9011 // 1. [all]   pshuflw, pshufhw, optional move
9012 // 2. [ssse3] 1 x pshufb
9013 // 3. [ssse3] 2 x pshufb + 1 x por
9014 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
9015 static SDValue
9016 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
9017                          SelectionDAG &DAG) {
9018   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9019   SDValue V1 = SVOp->getOperand(0);
9020   SDValue V2 = SVOp->getOperand(1);
9021   SDLoc dl(SVOp);
9022   SmallVector<int, 8> MaskVals;
9023
9024   // Determine if more than 1 of the words in each of the low and high quadwords
9025   // of the result come from the same quadword of one of the two inputs.  Undef
9026   // mask values count as coming from any quadword, for better codegen.
9027   //
9028   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
9029   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
9030   unsigned LoQuad[] = { 0, 0, 0, 0 };
9031   unsigned HiQuad[] = { 0, 0, 0, 0 };
9032   // Indices of quads used.
9033   std::bitset<4> InputQuads;
9034   for (unsigned i = 0; i < 8; ++i) {
9035     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
9036     int EltIdx = SVOp->getMaskElt(i);
9037     MaskVals.push_back(EltIdx);
9038     if (EltIdx < 0) {
9039       ++Quad[0];
9040       ++Quad[1];
9041       ++Quad[2];
9042       ++Quad[3];
9043       continue;
9044     }
9045     ++Quad[EltIdx / 4];
9046     InputQuads.set(EltIdx / 4);
9047   }
9048
9049   int BestLoQuad = -1;
9050   unsigned MaxQuad = 1;
9051   for (unsigned i = 0; i < 4; ++i) {
9052     if (LoQuad[i] > MaxQuad) {
9053       BestLoQuad = i;
9054       MaxQuad = LoQuad[i];
9055     }
9056   }
9057
9058   int BestHiQuad = -1;
9059   MaxQuad = 1;
9060   for (unsigned i = 0; i < 4; ++i) {
9061     if (HiQuad[i] > MaxQuad) {
9062       BestHiQuad = i;
9063       MaxQuad = HiQuad[i];
9064     }
9065   }
9066
9067   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
9068   // of the two input vectors, shuffle them into one input vector so only a
9069   // single pshufb instruction is necessary. If there are more than 2 input
9070   // quads, disable the next transformation since it does not help SSSE3.
9071   bool V1Used = InputQuads[0] || InputQuads[1];
9072   bool V2Used = InputQuads[2] || InputQuads[3];
9073   if (Subtarget->hasSSSE3()) {
9074     if (InputQuads.count() == 2 && V1Used && V2Used) {
9075       BestLoQuad = InputQuads[0] ? 0 : 1;
9076       BestHiQuad = InputQuads[2] ? 2 : 3;
9077     }
9078     if (InputQuads.count() > 2) {
9079       BestLoQuad = -1;
9080       BestHiQuad = -1;
9081     }
9082   }
9083
9084   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
9085   // the shuffle mask.  If a quad is scored as -1, that means that it contains
9086   // words from all 4 input quadwords.
9087   SDValue NewV;
9088   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
9089     int MaskV[] = {
9090       BestLoQuad < 0 ? 0 : BestLoQuad,
9091       BestHiQuad < 0 ? 1 : BestHiQuad
9092     };
9093     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
9094                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
9095                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
9096     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
9097
9098     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
9099     // source words for the shuffle, to aid later transformations.
9100     bool AllWordsInNewV = true;
9101     bool InOrder[2] = { true, true };
9102     for (unsigned i = 0; i != 8; ++i) {
9103       int idx = MaskVals[i];
9104       if (idx != (int)i)
9105         InOrder[i/4] = false;
9106       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
9107         continue;
9108       AllWordsInNewV = false;
9109       break;
9110     }
9111
9112     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
9113     if (AllWordsInNewV) {
9114       for (int i = 0; i != 8; ++i) {
9115         int idx = MaskVals[i];
9116         if (idx < 0)
9117           continue;
9118         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
9119         if ((idx != i) && idx < 4)
9120           pshufhw = false;
9121         if ((idx != i) && idx > 3)
9122           pshuflw = false;
9123       }
9124       V1 = NewV;
9125       V2Used = false;
9126       BestLoQuad = 0;
9127       BestHiQuad = 1;
9128     }
9129
9130     // If we've eliminated the use of V2, and the new mask is a pshuflw or
9131     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
9132     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
9133       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
9134       unsigned TargetMask = 0;
9135       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
9136                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
9137       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9138       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
9139                              getShufflePSHUFLWImmediate(SVOp);
9140       V1 = NewV.getOperand(0);
9141       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
9142     }
9143   }
9144
9145   // Promote splats to a larger type which usually leads to more efficient code.
9146   // FIXME: Is this true if pshufb is available?
9147   if (SVOp->isSplat())
9148     return PromoteSplat(SVOp, DAG);
9149
9150   // If we have SSSE3, and all words of the result are from 1 input vector,
9151   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
9152   // is present, fall back to case 4.
9153   if (Subtarget->hasSSSE3()) {
9154     SmallVector<SDValue,16> pshufbMask;
9155
9156     // If we have elements from both input vectors, set the high bit of the
9157     // shuffle mask element to zero out elements that come from V2 in the V1
9158     // mask, and elements that come from V1 in the V2 mask, so that the two
9159     // results can be OR'd together.
9160     bool TwoInputs = V1Used && V2Used;
9161     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9162     if (!TwoInputs)
9163       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9164
9165     // Calculate the shuffle mask for the second input, shuffle it, and
9166     // OR it with the first shuffled input.
9167     CommuteVectorShuffleMask(MaskVals, 8);
9168     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9169     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9170     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9171   }
9172
9173   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9174   // and update MaskVals with new element order.
9175   std::bitset<8> InOrder;
9176   if (BestLoQuad >= 0) {
9177     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9178     for (int i = 0; i != 4; ++i) {
9179       int idx = MaskVals[i];
9180       if (idx < 0) {
9181         InOrder.set(i);
9182       } else if ((idx / 4) == BestLoQuad) {
9183         MaskV[i] = idx & 3;
9184         InOrder.set(i);
9185       }
9186     }
9187     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9188                                 &MaskV[0]);
9189
9190     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9191       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9192       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9193                                   NewV.getOperand(0),
9194                                   getShufflePSHUFLWImmediate(SVOp), DAG);
9195     }
9196   }
9197
9198   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9199   // and update MaskVals with the new element order.
9200   if (BestHiQuad >= 0) {
9201     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9202     for (unsigned i = 4; i != 8; ++i) {
9203       int idx = MaskVals[i];
9204       if (idx < 0) {
9205         InOrder.set(i);
9206       } else if ((idx / 4) == BestHiQuad) {
9207         MaskV[i] = (idx & 3) + 4;
9208         InOrder.set(i);
9209       }
9210     }
9211     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9212                                 &MaskV[0]);
9213
9214     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9215       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9216       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9217                                   NewV.getOperand(0),
9218                                   getShufflePSHUFHWImmediate(SVOp), DAG);
9219     }
9220   }
9221
9222   // In case BestHi & BestLo were both -1, which means each quadword has a word
9223   // from each of the four input quadwords, calculate the InOrder bitvector now
9224   // before falling through to the insert/extract cleanup.
9225   if (BestLoQuad == -1 && BestHiQuad == -1) {
9226     NewV = V1;
9227     for (int i = 0; i != 8; ++i)
9228       if (MaskVals[i] < 0 || MaskVals[i] == i)
9229         InOrder.set(i);
9230   }
9231
9232   // The other elements are put in the right place using pextrw and pinsrw.
9233   for (unsigned i = 0; i != 8; ++i) {
9234     if (InOrder[i])
9235       continue;
9236     int EltIdx = MaskVals[i];
9237     if (EltIdx < 0)
9238       continue;
9239     SDValue ExtOp = (EltIdx < 8) ?
9240       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9241                   DAG.getIntPtrConstant(EltIdx)) :
9242       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9243                   DAG.getIntPtrConstant(EltIdx - 8));
9244     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9245                        DAG.getIntPtrConstant(i));
9246   }
9247   return NewV;
9248 }
9249
9250 /// \brief v16i16 shuffles
9251 ///
9252 /// FIXME: We only support generation of a single pshufb currently.  We can
9253 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9254 /// well (e.g 2 x pshufb + 1 x por).
9255 static SDValue
9256 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9257   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9258   SDValue V1 = SVOp->getOperand(0);
9259   SDValue V2 = SVOp->getOperand(1);
9260   SDLoc dl(SVOp);
9261
9262   if (V2.getOpcode() != ISD::UNDEF)
9263     return SDValue();
9264
9265   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9266   return getPSHUFB(MaskVals, V1, dl, DAG);
9267 }
9268
9269 // v16i8 shuffles - Prefer shuffles in the following order:
9270 // 1. [ssse3] 1 x pshufb
9271 // 2. [ssse3] 2 x pshufb + 1 x por
9272 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
9273 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9274                                         const X86Subtarget* Subtarget,
9275                                         SelectionDAG &DAG) {
9276   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9277   SDValue V1 = SVOp->getOperand(0);
9278   SDValue V2 = SVOp->getOperand(1);
9279   SDLoc dl(SVOp);
9280   ArrayRef<int> MaskVals = SVOp->getMask();
9281
9282   // Promote splats to a larger type which usually leads to more efficient code.
9283   // FIXME: Is this true if pshufb is available?
9284   if (SVOp->isSplat())
9285     return PromoteSplat(SVOp, DAG);
9286
9287   // If we have SSSE3, case 1 is generated when all result bytes come from
9288   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
9289   // present, fall back to case 3.
9290
9291   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9292   if (Subtarget->hasSSSE3()) {
9293     SmallVector<SDValue,16> pshufbMask;
9294
9295     // If all result elements are from one input vector, then only translate
9296     // undef mask values to 0x80 (zero out result) in the pshufb mask.
9297     //
9298     // Otherwise, we have elements from both input vectors, and must zero out
9299     // elements that come from V2 in the first mask, and V1 in the second mask
9300     // so that we can OR them together.
9301     for (unsigned i = 0; i != 16; ++i) {
9302       int EltIdx = MaskVals[i];
9303       if (EltIdx < 0 || EltIdx >= 16)
9304         EltIdx = 0x80;
9305       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9306     }
9307     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9308                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9309                                  MVT::v16i8, pshufbMask));
9310
9311     // As PSHUFB will zero elements with negative indices, it's safe to ignore
9312     // the 2nd operand if it's undefined or zero.
9313     if (V2.getOpcode() == ISD::UNDEF ||
9314         ISD::isBuildVectorAllZeros(V2.getNode()))
9315       return V1;
9316
9317     // Calculate the shuffle mask for the second input, shuffle it, and
9318     // OR it with the first shuffled input.
9319     pshufbMask.clear();
9320     for (unsigned i = 0; i != 16; ++i) {
9321       int EltIdx = MaskVals[i];
9322       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9323       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9324     }
9325     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9326                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9327                                  MVT::v16i8, pshufbMask));
9328     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9329   }
9330
9331   // No SSSE3 - Calculate in place words and then fix all out of place words
9332   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
9333   // the 16 different words that comprise the two doublequadword input vectors.
9334   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9335   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9336   SDValue NewV = V1;
9337   for (int i = 0; i != 8; ++i) {
9338     int Elt0 = MaskVals[i*2];
9339     int Elt1 = MaskVals[i*2+1];
9340
9341     // This word of the result is all undef, skip it.
9342     if (Elt0 < 0 && Elt1 < 0)
9343       continue;
9344
9345     // This word of the result is already in the correct place, skip it.
9346     if ((Elt0 == i*2) && (Elt1 == i*2+1))
9347       continue;
9348
9349     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9350     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9351     SDValue InsElt;
9352
9353     // If Elt0 and Elt1 are defined, are consecutive, and can be load
9354     // using a single extract together, load it and store it.
9355     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9356       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9357                            DAG.getIntPtrConstant(Elt1 / 2));
9358       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9359                         DAG.getIntPtrConstant(i));
9360       continue;
9361     }
9362
9363     // If Elt1 is defined, extract it from the appropriate source.  If the
9364     // source byte is not also odd, shift the extracted word left 8 bits
9365     // otherwise clear the bottom 8 bits if we need to do an or.
9366     if (Elt1 >= 0) {
9367       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9368                            DAG.getIntPtrConstant(Elt1 / 2));
9369       if ((Elt1 & 1) == 0)
9370         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9371                              DAG.getConstant(8,
9372                                   TLI.getShiftAmountTy(InsElt.getValueType())));
9373       else if (Elt0 >= 0)
9374         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9375                              DAG.getConstant(0xFF00, MVT::i16));
9376     }
9377     // If Elt0 is defined, extract it from the appropriate source.  If the
9378     // source byte is not also even, shift the extracted word right 8 bits. If
9379     // Elt1 was also defined, OR the extracted values together before
9380     // inserting them in the result.
9381     if (Elt0 >= 0) {
9382       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9383                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9384       if ((Elt0 & 1) != 0)
9385         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9386                               DAG.getConstant(8,
9387                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
9388       else if (Elt1 >= 0)
9389         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9390                              DAG.getConstant(0x00FF, MVT::i16));
9391       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9392                          : InsElt0;
9393     }
9394     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9395                        DAG.getIntPtrConstant(i));
9396   }
9397   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9398 }
9399
9400 // v32i8 shuffles - Translate to VPSHUFB if possible.
9401 static
9402 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9403                                  const X86Subtarget *Subtarget,
9404                                  SelectionDAG &DAG) {
9405   MVT VT = SVOp->getSimpleValueType(0);
9406   SDValue V1 = SVOp->getOperand(0);
9407   SDValue V2 = SVOp->getOperand(1);
9408   SDLoc dl(SVOp);
9409   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9410
9411   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9412   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9413   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9414
9415   // VPSHUFB may be generated if
9416   // (1) one of input vector is undefined or zeroinitializer.
9417   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9418   // And (2) the mask indexes don't cross the 128-bit lane.
9419   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9420       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9421     return SDValue();
9422
9423   if (V1IsAllZero && !V2IsAllZero) {
9424     CommuteVectorShuffleMask(MaskVals, 32);
9425     V1 = V2;
9426   }
9427   return getPSHUFB(MaskVals, V1, dl, DAG);
9428 }
9429
9430 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9431 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9432 /// done when every pair / quad of shuffle mask elements point to elements in
9433 /// the right sequence. e.g.
9434 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9435 static
9436 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9437                                  SelectionDAG &DAG) {
9438   MVT VT = SVOp->getSimpleValueType(0);
9439   SDLoc dl(SVOp);
9440   unsigned NumElems = VT.getVectorNumElements();
9441   MVT NewVT;
9442   unsigned Scale;
9443   switch (VT.SimpleTy) {
9444   default: llvm_unreachable("Unexpected!");
9445   case MVT::v2i64:
9446   case MVT::v2f64:
9447            return SDValue(SVOp, 0);
9448   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
9449   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
9450   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
9451   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
9452   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9453   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
9454   }
9455
9456   SmallVector<int, 8> MaskVec;
9457   for (unsigned i = 0; i != NumElems; i += Scale) {
9458     int StartIdx = -1;
9459     for (unsigned j = 0; j != Scale; ++j) {
9460       int EltIdx = SVOp->getMaskElt(i+j);
9461       if (EltIdx < 0)
9462         continue;
9463       if (StartIdx < 0)
9464         StartIdx = (EltIdx / Scale);
9465       if (EltIdx != (int)(StartIdx*Scale + j))
9466         return SDValue();
9467     }
9468     MaskVec.push_back(StartIdx);
9469   }
9470
9471   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9472   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9473   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9474 }
9475
9476 /// getVZextMovL - Return a zero-extending vector move low node.
9477 ///
9478 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9479                             SDValue SrcOp, SelectionDAG &DAG,
9480                             const X86Subtarget *Subtarget, SDLoc dl) {
9481   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9482     LoadSDNode *LD = nullptr;
9483     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9484       LD = dyn_cast<LoadSDNode>(SrcOp);
9485     if (!LD) {
9486       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9487       // instead.
9488       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9489       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9490           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9491           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9492           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9493         // PR2108
9494         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9495         return DAG.getNode(ISD::BITCAST, dl, VT,
9496                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9497                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9498                                                    OpVT,
9499                                                    SrcOp.getOperand(0)
9500                                                           .getOperand(0))));
9501       }
9502     }
9503   }
9504
9505   return DAG.getNode(ISD::BITCAST, dl, VT,
9506                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9507                                  DAG.getNode(ISD::BITCAST, dl,
9508                                              OpVT, SrcOp)));
9509 }
9510
9511 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9512 /// which could not be matched by any known target speficic shuffle
9513 static SDValue
9514 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9515
9516   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9517   if (NewOp.getNode())
9518     return NewOp;
9519
9520   MVT VT = SVOp->getSimpleValueType(0);
9521
9522   unsigned NumElems = VT.getVectorNumElements();
9523   unsigned NumLaneElems = NumElems / 2;
9524
9525   SDLoc dl(SVOp);
9526   MVT EltVT = VT.getVectorElementType();
9527   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9528   SDValue Output[2];
9529
9530   SmallVector<int, 16> Mask;
9531   for (unsigned l = 0; l < 2; ++l) {
9532     // Build a shuffle mask for the output, discovering on the fly which
9533     // input vectors to use as shuffle operands (recorded in InputUsed).
9534     // If building a suitable shuffle vector proves too hard, then bail
9535     // out with UseBuildVector set.
9536     bool UseBuildVector = false;
9537     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9538     unsigned LaneStart = l * NumLaneElems;
9539     for (unsigned i = 0; i != NumLaneElems; ++i) {
9540       // The mask element.  This indexes into the input.
9541       int Idx = SVOp->getMaskElt(i+LaneStart);
9542       if (Idx < 0) {
9543         // the mask element does not index into any input vector.
9544         Mask.push_back(-1);
9545         continue;
9546       }
9547
9548       // The input vector this mask element indexes into.
9549       int Input = Idx / NumLaneElems;
9550
9551       // Turn the index into an offset from the start of the input vector.
9552       Idx -= Input * NumLaneElems;
9553
9554       // Find or create a shuffle vector operand to hold this input.
9555       unsigned OpNo;
9556       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9557         if (InputUsed[OpNo] == Input)
9558           // This input vector is already an operand.
9559           break;
9560         if (InputUsed[OpNo] < 0) {
9561           // Create a new operand for this input vector.
9562           InputUsed[OpNo] = Input;
9563           break;
9564         }
9565       }
9566
9567       if (OpNo >= array_lengthof(InputUsed)) {
9568         // More than two input vectors used!  Give up on trying to create a
9569         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9570         UseBuildVector = true;
9571         break;
9572       }
9573
9574       // Add the mask index for the new shuffle vector.
9575       Mask.push_back(Idx + OpNo * NumLaneElems);
9576     }
9577
9578     if (UseBuildVector) {
9579       SmallVector<SDValue, 16> SVOps;
9580       for (unsigned i = 0; i != NumLaneElems; ++i) {
9581         // The mask element.  This indexes into the input.
9582         int Idx = SVOp->getMaskElt(i+LaneStart);
9583         if (Idx < 0) {
9584           SVOps.push_back(DAG.getUNDEF(EltVT));
9585           continue;
9586         }
9587
9588         // The input vector this mask element indexes into.
9589         int Input = Idx / NumElems;
9590
9591         // Turn the index into an offset from the start of the input vector.
9592         Idx -= Input * NumElems;
9593
9594         // Extract the vector element by hand.
9595         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9596                                     SVOp->getOperand(Input),
9597                                     DAG.getIntPtrConstant(Idx)));
9598       }
9599
9600       // Construct the output using a BUILD_VECTOR.
9601       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9602     } else if (InputUsed[0] < 0) {
9603       // No input vectors were used! The result is undefined.
9604       Output[l] = DAG.getUNDEF(NVT);
9605     } else {
9606       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9607                                         (InputUsed[0] % 2) * NumLaneElems,
9608                                         DAG, dl);
9609       // If only one input was used, use an undefined vector for the other.
9610       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9611         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9612                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9613       // At least one input vector was used. Create a new shuffle vector.
9614       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9615     }
9616
9617     Mask.clear();
9618   }
9619
9620   // Concatenate the result back
9621   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9622 }
9623
9624 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9625 /// 4 elements, and match them with several different shuffle types.
9626 static SDValue
9627 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9628   SDValue V1 = SVOp->getOperand(0);
9629   SDValue V2 = SVOp->getOperand(1);
9630   SDLoc dl(SVOp);
9631   MVT VT = SVOp->getSimpleValueType(0);
9632
9633   assert(VT.is128BitVector() && "Unsupported vector size");
9634
9635   std::pair<int, int> Locs[4];
9636   int Mask1[] = { -1, -1, -1, -1 };
9637   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9638
9639   unsigned NumHi = 0;
9640   unsigned NumLo = 0;
9641   for (unsigned i = 0; i != 4; ++i) {
9642     int Idx = PermMask[i];
9643     if (Idx < 0) {
9644       Locs[i] = std::make_pair(-1, -1);
9645     } else {
9646       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9647       if (Idx < 4) {
9648         Locs[i] = std::make_pair(0, NumLo);
9649         Mask1[NumLo] = Idx;
9650         NumLo++;
9651       } else {
9652         Locs[i] = std::make_pair(1, NumHi);
9653         if (2+NumHi < 4)
9654           Mask1[2+NumHi] = Idx;
9655         NumHi++;
9656       }
9657     }
9658   }
9659
9660   if (NumLo <= 2 && NumHi <= 2) {
9661     // If no more than two elements come from either vector. This can be
9662     // implemented with two shuffles. First shuffle gather the elements.
9663     // The second shuffle, which takes the first shuffle as both of its
9664     // vector operands, put the elements into the right order.
9665     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9666
9667     int Mask2[] = { -1, -1, -1, -1 };
9668
9669     for (unsigned i = 0; i != 4; ++i)
9670       if (Locs[i].first != -1) {
9671         unsigned Idx = (i < 2) ? 0 : 4;
9672         Idx += Locs[i].first * 2 + Locs[i].second;
9673         Mask2[i] = Idx;
9674       }
9675
9676     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9677   }
9678
9679   if (NumLo == 3 || NumHi == 3) {
9680     // Otherwise, we must have three elements from one vector, call it X, and
9681     // one element from the other, call it Y.  First, use a shufps to build an
9682     // intermediate vector with the one element from Y and the element from X
9683     // that will be in the same half in the final destination (the indexes don't
9684     // matter). Then, use a shufps to build the final vector, taking the half
9685     // containing the element from Y from the intermediate, and the other half
9686     // from X.
9687     if (NumHi == 3) {
9688       // Normalize it so the 3 elements come from V1.
9689       CommuteVectorShuffleMask(PermMask, 4);
9690       std::swap(V1, V2);
9691     }
9692
9693     // Find the element from V2.
9694     unsigned HiIndex;
9695     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9696       int Val = PermMask[HiIndex];
9697       if (Val < 0)
9698         continue;
9699       if (Val >= 4)
9700         break;
9701     }
9702
9703     Mask1[0] = PermMask[HiIndex];
9704     Mask1[1] = -1;
9705     Mask1[2] = PermMask[HiIndex^1];
9706     Mask1[3] = -1;
9707     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9708
9709     if (HiIndex >= 2) {
9710       Mask1[0] = PermMask[0];
9711       Mask1[1] = PermMask[1];
9712       Mask1[2] = HiIndex & 1 ? 6 : 4;
9713       Mask1[3] = HiIndex & 1 ? 4 : 6;
9714       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9715     }
9716
9717     Mask1[0] = HiIndex & 1 ? 2 : 0;
9718     Mask1[1] = HiIndex & 1 ? 0 : 2;
9719     Mask1[2] = PermMask[2];
9720     Mask1[3] = PermMask[3];
9721     if (Mask1[2] >= 0)
9722       Mask1[2] += 4;
9723     if (Mask1[3] >= 0)
9724       Mask1[3] += 4;
9725     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9726   }
9727
9728   // Break it into (shuffle shuffle_hi, shuffle_lo).
9729   int LoMask[] = { -1, -1, -1, -1 };
9730   int HiMask[] = { -1, -1, -1, -1 };
9731
9732   int *MaskPtr = LoMask;
9733   unsigned MaskIdx = 0;
9734   unsigned LoIdx = 0;
9735   unsigned HiIdx = 2;
9736   for (unsigned i = 0; i != 4; ++i) {
9737     if (i == 2) {
9738       MaskPtr = HiMask;
9739       MaskIdx = 1;
9740       LoIdx = 0;
9741       HiIdx = 2;
9742     }
9743     int Idx = PermMask[i];
9744     if (Idx < 0) {
9745       Locs[i] = std::make_pair(-1, -1);
9746     } else if (Idx < 4) {
9747       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9748       MaskPtr[LoIdx] = Idx;
9749       LoIdx++;
9750     } else {
9751       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9752       MaskPtr[HiIdx] = Idx;
9753       HiIdx++;
9754     }
9755   }
9756
9757   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9758   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9759   int MaskOps[] = { -1, -1, -1, -1 };
9760   for (unsigned i = 0; i != 4; ++i)
9761     if (Locs[i].first != -1)
9762       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9763   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9764 }
9765
9766 static bool MayFoldVectorLoad(SDValue V) {
9767   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9768     V = V.getOperand(0);
9769
9770   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9771     V = V.getOperand(0);
9772   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9773       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9774     // BUILD_VECTOR (load), undef
9775     V = V.getOperand(0);
9776
9777   return MayFoldLoad(V);
9778 }
9779
9780 static
9781 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9782   MVT VT = Op.getSimpleValueType();
9783
9784   // Canonizalize to v2f64.
9785   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9786   return DAG.getNode(ISD::BITCAST, dl, VT,
9787                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9788                                           V1, DAG));
9789 }
9790
9791 static
9792 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9793                         bool HasSSE2) {
9794   SDValue V1 = Op.getOperand(0);
9795   SDValue V2 = Op.getOperand(1);
9796   MVT VT = Op.getSimpleValueType();
9797
9798   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9799
9800   if (HasSSE2 && VT == MVT::v2f64)
9801     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9802
9803   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9804   return DAG.getNode(ISD::BITCAST, dl, VT,
9805                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9806                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9807                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9808 }
9809
9810 static
9811 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9812   SDValue V1 = Op.getOperand(0);
9813   SDValue V2 = Op.getOperand(1);
9814   MVT VT = Op.getSimpleValueType();
9815
9816   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9817          "unsupported shuffle type");
9818
9819   if (V2.getOpcode() == ISD::UNDEF)
9820     V2 = V1;
9821
9822   // v4i32 or v4f32
9823   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9824 }
9825
9826 static
9827 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9828   SDValue V1 = Op.getOperand(0);
9829   SDValue V2 = Op.getOperand(1);
9830   MVT VT = Op.getSimpleValueType();
9831   unsigned NumElems = VT.getVectorNumElements();
9832
9833   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9834   // operand of these instructions is only memory, so check if there's a
9835   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9836   // same masks.
9837   bool CanFoldLoad = false;
9838
9839   // Trivial case, when V2 comes from a load.
9840   if (MayFoldVectorLoad(V2))
9841     CanFoldLoad = true;
9842
9843   // When V1 is a load, it can be folded later into a store in isel, example:
9844   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9845   //    turns into:
9846   //  (MOVLPSmr addr:$src1, VR128:$src2)
9847   // So, recognize this potential and also use MOVLPS or MOVLPD
9848   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9849     CanFoldLoad = true;
9850
9851   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9852   if (CanFoldLoad) {
9853     if (HasSSE2 && NumElems == 2)
9854       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9855
9856     if (NumElems == 4)
9857       // If we don't care about the second element, proceed to use movss.
9858       if (SVOp->getMaskElt(1) != -1)
9859         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9860   }
9861
9862   // movl and movlp will both match v2i64, but v2i64 is never matched by
9863   // movl earlier because we make it strict to avoid messing with the movlp load
9864   // folding logic (see the code above getMOVLP call). Match it here then,
9865   // this is horrible, but will stay like this until we move all shuffle
9866   // matching to x86 specific nodes. Note that for the 1st condition all
9867   // types are matched with movsd.
9868   if (HasSSE2) {
9869     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9870     // as to remove this logic from here, as much as possible
9871     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9872       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9873     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9874   }
9875
9876   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9877
9878   // Invert the operand order and use SHUFPS to match it.
9879   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9880                               getShuffleSHUFImmediate(SVOp), DAG);
9881 }
9882
9883 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9884                                          SelectionDAG &DAG) {
9885   SDLoc dl(Load);
9886   MVT VT = Load->getSimpleValueType(0);
9887   MVT EVT = VT.getVectorElementType();
9888   SDValue Addr = Load->getOperand(1);
9889   SDValue NewAddr = DAG.getNode(
9890       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9891       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9892
9893   SDValue NewLoad =
9894       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9895                   DAG.getMachineFunction().getMachineMemOperand(
9896                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9897   return NewLoad;
9898 }
9899
9900 // It is only safe to call this function if isINSERTPSMask is true for
9901 // this shufflevector mask.
9902 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9903                            SelectionDAG &DAG) {
9904   // Generate an insertps instruction when inserting an f32 from memory onto a
9905   // v4f32 or when copying a member from one v4f32 to another.
9906   // We also use it for transferring i32 from one register to another,
9907   // since it simply copies the same bits.
9908   // If we're transferring an i32 from memory to a specific element in a
9909   // register, we output a generic DAG that will match the PINSRD
9910   // instruction.
9911   MVT VT = SVOp->getSimpleValueType(0);
9912   MVT EVT = VT.getVectorElementType();
9913   SDValue V1 = SVOp->getOperand(0);
9914   SDValue V2 = SVOp->getOperand(1);
9915   auto Mask = SVOp->getMask();
9916   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9917          "unsupported vector type for insertps/pinsrd");
9918
9919   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9920   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9921   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9922
9923   SDValue From;
9924   SDValue To;
9925   unsigned DestIndex;
9926   if (FromV1 == 1) {
9927     From = V1;
9928     To = V2;
9929     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9930                 Mask.begin();
9931
9932     // If we have 1 element from each vector, we have to check if we're
9933     // changing V1's element's place. If so, we're done. Otherwise, we
9934     // should assume we're changing V2's element's place and behave
9935     // accordingly.
9936     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9937     assert(DestIndex <= INT32_MAX && "truncated destination index");
9938     if (FromV1 == FromV2 &&
9939         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9940       From = V2;
9941       To = V1;
9942       DestIndex =
9943           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9944     }
9945   } else {
9946     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9947            "More than one element from V1 and from V2, or no elements from one "
9948            "of the vectors. This case should not have returned true from "
9949            "isINSERTPSMask");
9950     From = V2;
9951     To = V1;
9952     DestIndex =
9953         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9954   }
9955
9956   // Get an index into the source vector in the range [0,4) (the mask is
9957   // in the range [0,8) because it can address V1 and V2)
9958   unsigned SrcIndex = Mask[DestIndex] % 4;
9959   if (MayFoldLoad(From)) {
9960     // Trivial case, when From comes from a load and is only used by the
9961     // shuffle. Make it use insertps from the vector that we need from that
9962     // load.
9963     SDValue NewLoad =
9964         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9965     if (!NewLoad.getNode())
9966       return SDValue();
9967
9968     if (EVT == MVT::f32) {
9969       // Create this as a scalar to vector to match the instruction pattern.
9970       SDValue LoadScalarToVector =
9971           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9972       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9973       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9974                          InsertpsMask);
9975     } else { // EVT == MVT::i32
9976       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9977       // instruction, to match the PINSRD instruction, which loads an i32 to a
9978       // certain vector element.
9979       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9980                          DAG.getConstant(DestIndex, MVT::i32));
9981     }
9982   }
9983
9984   // Vector-element-to-vector
9985   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9986   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9987 }
9988
9989 // Reduce a vector shuffle to zext.
9990 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9991                                     SelectionDAG &DAG) {
9992   // PMOVZX is only available from SSE41.
9993   if (!Subtarget->hasSSE41())
9994     return SDValue();
9995
9996   MVT VT = Op.getSimpleValueType();
9997
9998   // Only AVX2 support 256-bit vector integer extending.
9999   if (!Subtarget->hasInt256() && VT.is256BitVector())
10000     return SDValue();
10001
10002   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10003   SDLoc DL(Op);
10004   SDValue V1 = Op.getOperand(0);
10005   SDValue V2 = Op.getOperand(1);
10006   unsigned NumElems = VT.getVectorNumElements();
10007
10008   // Extending is an unary operation and the element type of the source vector
10009   // won't be equal to or larger than i64.
10010   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
10011       VT.getVectorElementType() == MVT::i64)
10012     return SDValue();
10013
10014   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
10015   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
10016   while ((1U << Shift) < NumElems) {
10017     if (SVOp->getMaskElt(1U << Shift) == 1)
10018       break;
10019     Shift += 1;
10020     // The maximal ratio is 8, i.e. from i8 to i64.
10021     if (Shift > 3)
10022       return SDValue();
10023   }
10024
10025   // Check the shuffle mask.
10026   unsigned Mask = (1U << Shift) - 1;
10027   for (unsigned i = 0; i != NumElems; ++i) {
10028     int EltIdx = SVOp->getMaskElt(i);
10029     if ((i & Mask) != 0 && EltIdx != -1)
10030       return SDValue();
10031     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
10032       return SDValue();
10033   }
10034
10035   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
10036   MVT NeVT = MVT::getIntegerVT(NBits);
10037   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
10038
10039   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
10040     return SDValue();
10041
10042   // Simplify the operand as it's prepared to be fed into shuffle.
10043   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
10044   if (V1.getOpcode() == ISD::BITCAST &&
10045       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
10046       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
10047       V1.getOperand(0).getOperand(0)
10048         .getSimpleValueType().getSizeInBits() == SignificantBits) {
10049     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
10050     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
10051     ConstantSDNode *CIdx =
10052       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
10053     // If it's foldable, i.e. normal load with single use, we will let code
10054     // selection to fold it. Otherwise, we will short the conversion sequence.
10055     if (CIdx && CIdx->getZExtValue() == 0 &&
10056         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
10057       MVT FullVT = V.getSimpleValueType();
10058       MVT V1VT = V1.getSimpleValueType();
10059       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
10060         // The "ext_vec_elt" node is wider than the result node.
10061         // In this case we should extract subvector from V.
10062         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
10063         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
10064         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
10065                                         FullVT.getVectorNumElements()/Ratio);
10066         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
10067                         DAG.getIntPtrConstant(0));
10068       }
10069       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
10070     }
10071   }
10072
10073   return DAG.getNode(ISD::BITCAST, DL, VT,
10074                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
10075 }
10076
10077 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10078                                       SelectionDAG &DAG) {
10079   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10080   MVT VT = Op.getSimpleValueType();
10081   SDLoc dl(Op);
10082   SDValue V1 = Op.getOperand(0);
10083   SDValue V2 = Op.getOperand(1);
10084
10085   if (isZeroShuffle(SVOp))
10086     return getZeroVector(VT, Subtarget, DAG, dl);
10087
10088   // Handle splat operations
10089   if (SVOp->isSplat()) {
10090     // Use vbroadcast whenever the splat comes from a foldable load
10091     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
10092     if (Broadcast.getNode())
10093       return Broadcast;
10094   }
10095
10096   // Check integer expanding shuffles.
10097   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
10098   if (NewOp.getNode())
10099     return NewOp;
10100
10101   // If the shuffle can be profitably rewritten as a narrower shuffle, then
10102   // do it!
10103   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
10104       VT == MVT::v32i8) {
10105     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10106     if (NewOp.getNode())
10107       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
10108   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
10109     // FIXME: Figure out a cleaner way to do this.
10110     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
10111       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10112       if (NewOp.getNode()) {
10113         MVT NewVT = NewOp.getSimpleValueType();
10114         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
10115                                NewVT, true, false))
10116           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
10117                               dl);
10118       }
10119     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
10120       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10121       if (NewOp.getNode()) {
10122         MVT NewVT = NewOp.getSimpleValueType();
10123         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
10124           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
10125                               dl);
10126       }
10127     }
10128   }
10129   return SDValue();
10130 }
10131
10132 SDValue
10133 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
10134   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10135   SDValue V1 = Op.getOperand(0);
10136   SDValue V2 = Op.getOperand(1);
10137   MVT VT = Op.getSimpleValueType();
10138   SDLoc dl(Op);
10139   unsigned NumElems = VT.getVectorNumElements();
10140   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10141   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10142   bool V1IsSplat = false;
10143   bool V2IsSplat = false;
10144   bool HasSSE2 = Subtarget->hasSSE2();
10145   bool HasFp256    = Subtarget->hasFp256();
10146   bool HasInt256   = Subtarget->hasInt256();
10147   MachineFunction &MF = DAG.getMachineFunction();
10148   bool OptForSize = MF.getFunction()->getAttributes().
10149     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
10150
10151   // Check if we should use the experimental vector shuffle lowering. If so,
10152   // delegate completely to that code path.
10153   if (ExperimentalVectorShuffleLowering)
10154     return lowerVectorShuffle(Op, Subtarget, DAG);
10155
10156   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10157
10158   if (V1IsUndef && V2IsUndef)
10159     return DAG.getUNDEF(VT);
10160
10161   // When we create a shuffle node we put the UNDEF node to second operand,
10162   // but in some cases the first operand may be transformed to UNDEF.
10163   // In this case we should just commute the node.
10164   if (V1IsUndef)
10165     return DAG.getCommutedVectorShuffle(*SVOp);
10166
10167   // Vector shuffle lowering takes 3 steps:
10168   //
10169   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10170   //    narrowing and commutation of operands should be handled.
10171   // 2) Matching of shuffles with known shuffle masks to x86 target specific
10172   //    shuffle nodes.
10173   // 3) Rewriting of unmatched masks into new generic shuffle operations,
10174   //    so the shuffle can be broken into other shuffles and the legalizer can
10175   //    try the lowering again.
10176   //
10177   // The general idea is that no vector_shuffle operation should be left to
10178   // be matched during isel, all of them must be converted to a target specific
10179   // node here.
10180
10181   // Normalize the input vectors. Here splats, zeroed vectors, profitable
10182   // narrowing and commutation of operands should be handled. The actual code
10183   // doesn't include all of those, work in progress...
10184   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10185   if (NewOp.getNode())
10186     return NewOp;
10187
10188   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10189
10190   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10191   // unpckh_undef). Only use pshufd if speed is more important than size.
10192   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10193     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10194   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10195     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10196
10197   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10198       V2IsUndef && MayFoldVectorLoad(V1))
10199     return getMOVDDup(Op, dl, V1, DAG);
10200
10201   if (isMOVHLPS_v_undef_Mask(M, VT))
10202     return getMOVHighToLow(Op, dl, DAG);
10203
10204   // Use to match splats
10205   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10206       (VT == MVT::v2f64 || VT == MVT::v2i64))
10207     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10208
10209   if (isPSHUFDMask(M, VT)) {
10210     // The actual implementation will match the mask in the if above and then
10211     // during isel it can match several different instructions, not only pshufd
10212     // as its name says, sad but true, emulate the behavior for now...
10213     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10214       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10215
10216     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10217
10218     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10219       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10220
10221     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10222       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10223                                   DAG);
10224
10225     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10226                                 TargetMask, DAG);
10227   }
10228
10229   if (isPALIGNRMask(M, VT, Subtarget))
10230     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10231                                 getShufflePALIGNRImmediate(SVOp),
10232                                 DAG);
10233
10234   if (isVALIGNMask(M, VT, Subtarget))
10235     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10236                                 getShuffleVALIGNImmediate(SVOp),
10237                                 DAG);
10238
10239   // Check if this can be converted into a logical shift.
10240   bool isLeft = false;
10241   unsigned ShAmt = 0;
10242   SDValue ShVal;
10243   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10244   if (isShift && ShVal.hasOneUse()) {
10245     // If the shifted value has multiple uses, it may be cheaper to use
10246     // v_set0 + movlhps or movhlps, etc.
10247     MVT EltVT = VT.getVectorElementType();
10248     ShAmt *= EltVT.getSizeInBits();
10249     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10250   }
10251
10252   if (isMOVLMask(M, VT)) {
10253     if (ISD::isBuildVectorAllZeros(V1.getNode()))
10254       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10255     if (!isMOVLPMask(M, VT)) {
10256       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10257         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10258
10259       if (VT == MVT::v4i32 || VT == MVT::v4f32)
10260         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10261     }
10262   }
10263
10264   // FIXME: fold these into legal mask.
10265   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10266     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10267
10268   if (isMOVHLPSMask(M, VT))
10269     return getMOVHighToLow(Op, dl, DAG);
10270
10271   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10272     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10273
10274   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10275     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10276
10277   if (isMOVLPMask(M, VT))
10278     return getMOVLP(Op, dl, DAG, HasSSE2);
10279
10280   if (ShouldXformToMOVHLPS(M, VT) ||
10281       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10282     return DAG.getCommutedVectorShuffle(*SVOp);
10283
10284   if (isShift) {
10285     // No better options. Use a vshldq / vsrldq.
10286     MVT EltVT = VT.getVectorElementType();
10287     ShAmt *= EltVT.getSizeInBits();
10288     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10289   }
10290
10291   bool Commuted = false;
10292   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
10293   // 1,1,1,1 -> v8i16 though.
10294   BitVector UndefElements;
10295   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10296     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10297       V1IsSplat = true;
10298   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10299     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10300       V2IsSplat = true;
10301
10302   // Canonicalize the splat or undef, if present, to be on the RHS.
10303   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10304     CommuteVectorShuffleMask(M, NumElems);
10305     std::swap(V1, V2);
10306     std::swap(V1IsSplat, V2IsSplat);
10307     Commuted = true;
10308   }
10309
10310   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10311     // Shuffling low element of v1 into undef, just return v1.
10312     if (V2IsUndef)
10313       return V1;
10314     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10315     // the instruction selector will not match, so get a canonical MOVL with
10316     // swapped operands to undo the commute.
10317     return getMOVL(DAG, dl, VT, V2, V1);
10318   }
10319
10320   if (isUNPCKLMask(M, VT, HasInt256))
10321     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10322
10323   if (isUNPCKHMask(M, VT, HasInt256))
10324     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10325
10326   if (V2IsSplat) {
10327     // Normalize mask so all entries that point to V2 points to its first
10328     // element then try to match unpck{h|l} again. If match, return a
10329     // new vector_shuffle with the corrected mask.p
10330     SmallVector<int, 8> NewMask(M.begin(), M.end());
10331     NormalizeMask(NewMask, NumElems);
10332     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10333       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10334     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10335       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10336   }
10337
10338   if (Commuted) {
10339     // Commute is back and try unpck* again.
10340     // FIXME: this seems wrong.
10341     CommuteVectorShuffleMask(M, NumElems);
10342     std::swap(V1, V2);
10343     std::swap(V1IsSplat, V2IsSplat);
10344
10345     if (isUNPCKLMask(M, VT, HasInt256))
10346       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10347
10348     if (isUNPCKHMask(M, VT, HasInt256))
10349       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10350   }
10351
10352   // Normalize the node to match x86 shuffle ops if needed
10353   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10354     return DAG.getCommutedVectorShuffle(*SVOp);
10355
10356   // The checks below are all present in isShuffleMaskLegal, but they are
10357   // inlined here right now to enable us to directly emit target specific
10358   // nodes, and remove one by one until they don't return Op anymore.
10359
10360   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10361       SVOp->getSplatIndex() == 0 && V2IsUndef) {
10362     if (VT == MVT::v2f64 || VT == MVT::v2i64)
10363       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10364   }
10365
10366   if (isPSHUFHWMask(M, VT, HasInt256))
10367     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10368                                 getShufflePSHUFHWImmediate(SVOp),
10369                                 DAG);
10370
10371   if (isPSHUFLWMask(M, VT, HasInt256))
10372     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10373                                 getShufflePSHUFLWImmediate(SVOp),
10374                                 DAG);
10375
10376   unsigned MaskValue;
10377   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10378                   &MaskValue))
10379     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10380
10381   if (isSHUFPMask(M, VT))
10382     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10383                                 getShuffleSHUFImmediate(SVOp), DAG);
10384
10385   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10386     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10387   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10388     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10389
10390   //===--------------------------------------------------------------------===//
10391   // Generate target specific nodes for 128 or 256-bit shuffles only
10392   // supported in the AVX instruction set.
10393   //
10394
10395   // Handle VMOVDDUPY permutations
10396   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10397     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10398
10399   // Handle VPERMILPS/D* permutations
10400   if (isVPERMILPMask(M, VT)) {
10401     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10402       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10403                                   getShuffleSHUFImmediate(SVOp), DAG);
10404     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10405                                 getShuffleSHUFImmediate(SVOp), DAG);
10406   }
10407
10408   unsigned Idx;
10409   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10410     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10411                               Idx*(NumElems/2), DAG, dl);
10412
10413   // Handle VPERM2F128/VPERM2I128 permutations
10414   if (isVPERM2X128Mask(M, VT, HasFp256))
10415     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10416                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10417
10418   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10419     return getINSERTPS(SVOp, dl, DAG);
10420
10421   unsigned Imm8;
10422   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10423     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10424
10425   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10426       VT.is512BitVector()) {
10427     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10428     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10429     SmallVector<SDValue, 16> permclMask;
10430     for (unsigned i = 0; i != NumElems; ++i) {
10431       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10432     }
10433
10434     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10435     if (V2IsUndef)
10436       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10437       return DAG.getNode(X86ISD::VPERMV, dl, VT,
10438                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10439     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10440                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10441   }
10442
10443   //===--------------------------------------------------------------------===//
10444   // Since no target specific shuffle was selected for this generic one,
10445   // lower it into other known shuffles. FIXME: this isn't true yet, but
10446   // this is the plan.
10447   //
10448
10449   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10450   if (VT == MVT::v8i16) {
10451     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10452     if (NewOp.getNode())
10453       return NewOp;
10454   }
10455
10456   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10457     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10458     if (NewOp.getNode())
10459       return NewOp;
10460   }
10461
10462   if (VT == MVT::v16i8) {
10463     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10464     if (NewOp.getNode())
10465       return NewOp;
10466   }
10467
10468   if (VT == MVT::v32i8) {
10469     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10470     if (NewOp.getNode())
10471       return NewOp;
10472   }
10473
10474   // Handle all 128-bit wide vectors with 4 elements, and match them with
10475   // several different shuffle types.
10476   if (NumElems == 4 && VT.is128BitVector())
10477     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10478
10479   // Handle general 256-bit shuffles
10480   if (VT.is256BitVector())
10481     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10482
10483   return SDValue();
10484 }
10485
10486 // This function assumes its argument is a BUILD_VECTOR of constants or
10487 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10488 // true.
10489 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10490                                     unsigned &MaskValue) {
10491   MaskValue = 0;
10492   unsigned NumElems = BuildVector->getNumOperands();
10493   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10494   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10495   unsigned NumElemsInLane = NumElems / NumLanes;
10496
10497   // Blend for v16i16 should be symetric for the both lanes.
10498   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10499     SDValue EltCond = BuildVector->getOperand(i);
10500     SDValue SndLaneEltCond =
10501         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10502
10503     int Lane1Cond = -1, Lane2Cond = -1;
10504     if (isa<ConstantSDNode>(EltCond))
10505       Lane1Cond = !isZero(EltCond);
10506     if (isa<ConstantSDNode>(SndLaneEltCond))
10507       Lane2Cond = !isZero(SndLaneEltCond);
10508
10509     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10510       // Lane1Cond != 0, means we want the first argument.
10511       // Lane1Cond == 0, means we want the second argument.
10512       // The encoding of this argument is 0 for the first argument, 1
10513       // for the second. Therefore, invert the condition.
10514       MaskValue |= !Lane1Cond << i;
10515     else if (Lane1Cond < 0)
10516       MaskValue |= !Lane2Cond << i;
10517     else
10518       return false;
10519   }
10520   return true;
10521 }
10522
10523 // Try to lower a vselect node into a simple blend instruction.
10524 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10525                                    SelectionDAG &DAG) {
10526   SDValue Cond = Op.getOperand(0);
10527   SDValue LHS = Op.getOperand(1);
10528   SDValue RHS = Op.getOperand(2);
10529   SDLoc dl(Op);
10530   MVT VT = Op.getSimpleValueType();
10531   MVT EltVT = VT.getVectorElementType();
10532   unsigned NumElems = VT.getVectorNumElements();
10533
10534   // There is no blend with immediate in AVX-512.
10535   if (VT.is512BitVector())
10536     return SDValue();
10537
10538   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10539     return SDValue();
10540   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10541     return SDValue();
10542
10543   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10544     return SDValue();
10545
10546   // Check the mask for BLEND and build the value.
10547   unsigned MaskValue = 0;
10548   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10549     return SDValue();
10550
10551   // Convert i32 vectors to floating point if it is not AVX2.
10552   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10553   MVT BlendVT = VT;
10554   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10555     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10556                                NumElems);
10557     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10558     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10559   }
10560
10561   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10562                             DAG.getConstant(MaskValue, MVT::i32));
10563   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10564 }
10565
10566 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10567   // A vselect where all conditions and data are constants can be optimized into
10568   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10569   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10570       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10571       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10572     return SDValue();
10573   
10574   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10575   if (BlendOp.getNode())
10576     return BlendOp;
10577
10578   // Some types for vselect were previously set to Expand, not Legal or
10579   // Custom. Return an empty SDValue so we fall-through to Expand, after
10580   // the Custom lowering phase.
10581   MVT VT = Op.getSimpleValueType();
10582   switch (VT.SimpleTy) {
10583   default:
10584     break;
10585   case MVT::v8i16:
10586   case MVT::v16i16:
10587     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10588       break;
10589     return SDValue();
10590   }
10591
10592   // We couldn't create a "Blend with immediate" node.
10593   // This node should still be legal, but we'll have to emit a blendv*
10594   // instruction.
10595   return Op;
10596 }
10597
10598 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10599   MVT VT = Op.getSimpleValueType();
10600   SDLoc dl(Op);
10601
10602   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10603     return SDValue();
10604
10605   if (VT.getSizeInBits() == 8) {
10606     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10607                                   Op.getOperand(0), Op.getOperand(1));
10608     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10609                                   DAG.getValueType(VT));
10610     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10611   }
10612
10613   if (VT.getSizeInBits() == 16) {
10614     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10615     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10616     if (Idx == 0)
10617       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10618                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10619                                      DAG.getNode(ISD::BITCAST, dl,
10620                                                  MVT::v4i32,
10621                                                  Op.getOperand(0)),
10622                                      Op.getOperand(1)));
10623     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10624                                   Op.getOperand(0), Op.getOperand(1));
10625     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10626                                   DAG.getValueType(VT));
10627     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10628   }
10629
10630   if (VT == MVT::f32) {
10631     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10632     // the result back to FR32 register. It's only worth matching if the
10633     // result has a single use which is a store or a bitcast to i32.  And in
10634     // the case of a store, it's not worth it if the index is a constant 0,
10635     // because a MOVSSmr can be used instead, which is smaller and faster.
10636     if (!Op.hasOneUse())
10637       return SDValue();
10638     SDNode *User = *Op.getNode()->use_begin();
10639     if ((User->getOpcode() != ISD::STORE ||
10640          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10641           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10642         (User->getOpcode() != ISD::BITCAST ||
10643          User->getValueType(0) != MVT::i32))
10644       return SDValue();
10645     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10646                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10647                                               Op.getOperand(0)),
10648                                               Op.getOperand(1));
10649     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10650   }
10651
10652   if (VT == MVT::i32 || VT == MVT::i64) {
10653     // ExtractPS/pextrq works with constant index.
10654     if (isa<ConstantSDNode>(Op.getOperand(1)))
10655       return Op;
10656   }
10657   return SDValue();
10658 }
10659
10660 /// Extract one bit from mask vector, like v16i1 or v8i1.
10661 /// AVX-512 feature.
10662 SDValue
10663 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10664   SDValue Vec = Op.getOperand(0);
10665   SDLoc dl(Vec);
10666   MVT VecVT = Vec.getSimpleValueType();
10667   SDValue Idx = Op.getOperand(1);
10668   MVT EltVT = Op.getSimpleValueType();
10669
10670   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10671
10672   // variable index can't be handled in mask registers,
10673   // extend vector to VR512
10674   if (!isa<ConstantSDNode>(Idx)) {
10675     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10676     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10677     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10678                               ExtVT.getVectorElementType(), Ext, Idx);
10679     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10680   }
10681
10682   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10683   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10684   unsigned MaxSift = rc->getSize()*8 - 1;
10685   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10686                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10687   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10688                     DAG.getConstant(MaxSift, MVT::i8));
10689   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10690                        DAG.getIntPtrConstant(0));
10691 }
10692
10693 SDValue
10694 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10695                                            SelectionDAG &DAG) const {
10696   SDLoc dl(Op);
10697   SDValue Vec = Op.getOperand(0);
10698   MVT VecVT = Vec.getSimpleValueType();
10699   SDValue Idx = Op.getOperand(1);
10700
10701   if (Op.getSimpleValueType() == MVT::i1)
10702     return ExtractBitFromMaskVector(Op, DAG);
10703
10704   if (!isa<ConstantSDNode>(Idx)) {
10705     if (VecVT.is512BitVector() ||
10706         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10707          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10708
10709       MVT MaskEltVT =
10710         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10711       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10712                                     MaskEltVT.getSizeInBits());
10713
10714       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10715       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10716                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10717                                 Idx, DAG.getConstant(0, getPointerTy()));
10718       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10719       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10720                         Perm, DAG.getConstant(0, getPointerTy()));
10721     }
10722     return SDValue();
10723   }
10724
10725   // If this is a 256-bit vector result, first extract the 128-bit vector and
10726   // then extract the element from the 128-bit vector.
10727   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10728
10729     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10730     // Get the 128-bit vector.
10731     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10732     MVT EltVT = VecVT.getVectorElementType();
10733
10734     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10735
10736     //if (IdxVal >= NumElems/2)
10737     //  IdxVal -= NumElems/2;
10738     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10739     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10740                        DAG.getConstant(IdxVal, MVT::i32));
10741   }
10742
10743   assert(VecVT.is128BitVector() && "Unexpected vector length");
10744
10745   if (Subtarget->hasSSE41()) {
10746     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10747     if (Res.getNode())
10748       return Res;
10749   }
10750
10751   MVT VT = Op.getSimpleValueType();
10752   // TODO: handle v16i8.
10753   if (VT.getSizeInBits() == 16) {
10754     SDValue Vec = Op.getOperand(0);
10755     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10756     if (Idx == 0)
10757       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10758                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10759                                      DAG.getNode(ISD::BITCAST, dl,
10760                                                  MVT::v4i32, Vec),
10761                                      Op.getOperand(1)));
10762     // Transform it so it match pextrw which produces a 32-bit result.
10763     MVT EltVT = MVT::i32;
10764     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10765                                   Op.getOperand(0), Op.getOperand(1));
10766     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10767                                   DAG.getValueType(VT));
10768     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10769   }
10770
10771   if (VT.getSizeInBits() == 32) {
10772     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10773     if (Idx == 0)
10774       return Op;
10775
10776     // SHUFPS the element to the lowest double word, then movss.
10777     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10778     MVT VVT = Op.getOperand(0).getSimpleValueType();
10779     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10780                                        DAG.getUNDEF(VVT), Mask);
10781     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10782                        DAG.getIntPtrConstant(0));
10783   }
10784
10785   if (VT.getSizeInBits() == 64) {
10786     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10787     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10788     //        to match extract_elt for f64.
10789     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10790     if (Idx == 0)
10791       return Op;
10792
10793     // UNPCKHPD the element to the lowest double word, then movsd.
10794     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10795     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10796     int Mask[2] = { 1, -1 };
10797     MVT VVT = Op.getOperand(0).getSimpleValueType();
10798     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10799                                        DAG.getUNDEF(VVT), Mask);
10800     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10801                        DAG.getIntPtrConstant(0));
10802   }
10803
10804   return SDValue();
10805 }
10806
10807 /// Insert one bit to mask vector, like v16i1 or v8i1.
10808 /// AVX-512 feature.
10809 SDValue 
10810 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10811   SDLoc dl(Op);
10812   SDValue Vec = Op.getOperand(0);
10813   SDValue Elt = Op.getOperand(1);
10814   SDValue Idx = Op.getOperand(2);
10815   MVT VecVT = Vec.getSimpleValueType();
10816
10817   if (!isa<ConstantSDNode>(Idx)) {
10818     // Non constant index. Extend source and destination,
10819     // insert element and then truncate the result.
10820     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10821     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10822     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10823       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10824       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10825     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10826   }
10827
10828   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10829   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10830   if (Vec.getOpcode() == ISD::UNDEF)
10831     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10832                        DAG.getConstant(IdxVal, MVT::i8));
10833   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10834   unsigned MaxSift = rc->getSize()*8 - 1;
10835   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10836                     DAG.getConstant(MaxSift, MVT::i8));
10837   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10838                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10839   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10840 }
10841
10842 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10843                                                   SelectionDAG &DAG) const {
10844   MVT VT = Op.getSimpleValueType();
10845   MVT EltVT = VT.getVectorElementType();
10846
10847   if (EltVT == MVT::i1)
10848     return InsertBitToMaskVector(Op, DAG);
10849
10850   SDLoc dl(Op);
10851   SDValue N0 = Op.getOperand(0);
10852   SDValue N1 = Op.getOperand(1);
10853   SDValue N2 = Op.getOperand(2);
10854   if (!isa<ConstantSDNode>(N2))
10855     return SDValue();
10856   auto *N2C = cast<ConstantSDNode>(N2);
10857   unsigned IdxVal = N2C->getZExtValue();
10858
10859   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10860   // into that, and then insert the subvector back into the result.
10861   if (VT.is256BitVector() || VT.is512BitVector()) {
10862     // Get the desired 128-bit vector half.
10863     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10864
10865     // Insert the element into the desired half.
10866     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10867     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10868
10869     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10870                     DAG.getConstant(IdxIn128, MVT::i32));
10871
10872     // Insert the changed part back to the 256-bit vector
10873     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10874   }
10875   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10876
10877   if (Subtarget->hasSSE41()) {
10878     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10879       unsigned Opc;
10880       if (VT == MVT::v8i16) {
10881         Opc = X86ISD::PINSRW;
10882       } else {
10883         assert(VT == MVT::v16i8);
10884         Opc = X86ISD::PINSRB;
10885       }
10886
10887       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10888       // argument.
10889       if (N1.getValueType() != MVT::i32)
10890         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10891       if (N2.getValueType() != MVT::i32)
10892         N2 = DAG.getIntPtrConstant(IdxVal);
10893       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10894     }
10895
10896     if (EltVT == MVT::f32) {
10897       // Bits [7:6] of the constant are the source select.  This will always be
10898       //  zero here.  The DAG Combiner may combine an extract_elt index into
10899       //  these
10900       //  bits.  For example (insert (extract, 3), 2) could be matched by
10901       //  putting
10902       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10903       // Bits [5:4] of the constant are the destination select.  This is the
10904       //  value of the incoming immediate.
10905       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10906       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10907       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10908       // Create this as a scalar to vector..
10909       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10910       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10911     }
10912
10913     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10914       // PINSR* works with constant index.
10915       return Op;
10916     }
10917   }
10918
10919   if (EltVT == MVT::i8)
10920     return SDValue();
10921
10922   if (EltVT.getSizeInBits() == 16) {
10923     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10924     // as its second argument.
10925     if (N1.getValueType() != MVT::i32)
10926       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10927     if (N2.getValueType() != MVT::i32)
10928       N2 = DAG.getIntPtrConstant(IdxVal);
10929     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10930   }
10931   return SDValue();
10932 }
10933
10934 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10935   SDLoc dl(Op);
10936   MVT OpVT = Op.getSimpleValueType();
10937
10938   // If this is a 256-bit vector result, first insert into a 128-bit
10939   // vector and then insert into the 256-bit vector.
10940   if (!OpVT.is128BitVector()) {
10941     // Insert into a 128-bit vector.
10942     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10943     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10944                                  OpVT.getVectorNumElements() / SizeFactor);
10945
10946     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10947
10948     // Insert the 128-bit vector.
10949     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10950   }
10951
10952   if (OpVT == MVT::v1i64 &&
10953       Op.getOperand(0).getValueType() == MVT::i64)
10954     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10955
10956   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10957   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10958   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10959                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10960 }
10961
10962 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10963 // a simple subregister reference or explicit instructions to grab
10964 // upper bits of a vector.
10965 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10966                                       SelectionDAG &DAG) {
10967   SDLoc dl(Op);
10968   SDValue In =  Op.getOperand(0);
10969   SDValue Idx = Op.getOperand(1);
10970   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10971   MVT ResVT   = Op.getSimpleValueType();
10972   MVT InVT    = In.getSimpleValueType();
10973
10974   if (Subtarget->hasFp256()) {
10975     if (ResVT.is128BitVector() &&
10976         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10977         isa<ConstantSDNode>(Idx)) {
10978       return Extract128BitVector(In, IdxVal, DAG, dl);
10979     }
10980     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10981         isa<ConstantSDNode>(Idx)) {
10982       return Extract256BitVector(In, IdxVal, DAG, dl);
10983     }
10984   }
10985   return SDValue();
10986 }
10987
10988 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10989 // simple superregister reference or explicit instructions to insert
10990 // the upper bits of a vector.
10991 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10992                                      SelectionDAG &DAG) {
10993   if (Subtarget->hasFp256()) {
10994     SDLoc dl(Op.getNode());
10995     SDValue Vec = Op.getNode()->getOperand(0);
10996     SDValue SubVec = Op.getNode()->getOperand(1);
10997     SDValue Idx = Op.getNode()->getOperand(2);
10998
10999     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
11000          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
11001         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
11002         isa<ConstantSDNode>(Idx)) {
11003       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11004       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11005     }
11006
11007     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
11008         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
11009         isa<ConstantSDNode>(Idx)) {
11010       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11011       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11012     }
11013   }
11014   return SDValue();
11015 }
11016
11017 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11018 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11019 // one of the above mentioned nodes. It has to be wrapped because otherwise
11020 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11021 // be used to form addressing mode. These wrapped nodes will be selected
11022 // into MOV32ri.
11023 SDValue
11024 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11025   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11026
11027   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11028   // global base reg.
11029   unsigned char OpFlag = 0;
11030   unsigned WrapperKind = X86ISD::Wrapper;
11031   CodeModel::Model M = DAG.getTarget().getCodeModel();
11032
11033   if (Subtarget->isPICStyleRIPRel() &&
11034       (M == CodeModel::Small || M == CodeModel::Kernel))
11035     WrapperKind = X86ISD::WrapperRIP;
11036   else if (Subtarget->isPICStyleGOT())
11037     OpFlag = X86II::MO_GOTOFF;
11038   else if (Subtarget->isPICStyleStubPIC())
11039     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11040
11041   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11042                                              CP->getAlignment(),
11043                                              CP->getOffset(), OpFlag);
11044   SDLoc DL(CP);
11045   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11046   // With PIC, the address is actually $g + Offset.
11047   if (OpFlag) {
11048     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11049                          DAG.getNode(X86ISD::GlobalBaseReg,
11050                                      SDLoc(), getPointerTy()),
11051                          Result);
11052   }
11053
11054   return Result;
11055 }
11056
11057 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11058   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11059
11060   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11061   // global base reg.
11062   unsigned char OpFlag = 0;
11063   unsigned WrapperKind = X86ISD::Wrapper;
11064   CodeModel::Model M = DAG.getTarget().getCodeModel();
11065
11066   if (Subtarget->isPICStyleRIPRel() &&
11067       (M == CodeModel::Small || M == CodeModel::Kernel))
11068     WrapperKind = X86ISD::WrapperRIP;
11069   else if (Subtarget->isPICStyleGOT())
11070     OpFlag = X86II::MO_GOTOFF;
11071   else if (Subtarget->isPICStyleStubPIC())
11072     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11073
11074   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11075                                           OpFlag);
11076   SDLoc DL(JT);
11077   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11078
11079   // With PIC, the address is actually $g + Offset.
11080   if (OpFlag)
11081     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11082                          DAG.getNode(X86ISD::GlobalBaseReg,
11083                                      SDLoc(), getPointerTy()),
11084                          Result);
11085
11086   return Result;
11087 }
11088
11089 SDValue
11090 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11091   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11092
11093   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11094   // global base reg.
11095   unsigned char OpFlag = 0;
11096   unsigned WrapperKind = X86ISD::Wrapper;
11097   CodeModel::Model M = DAG.getTarget().getCodeModel();
11098
11099   if (Subtarget->isPICStyleRIPRel() &&
11100       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11101     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11102       OpFlag = X86II::MO_GOTPCREL;
11103     WrapperKind = X86ISD::WrapperRIP;
11104   } else if (Subtarget->isPICStyleGOT()) {
11105     OpFlag = X86II::MO_GOT;
11106   } else if (Subtarget->isPICStyleStubPIC()) {
11107     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11108   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11109     OpFlag = X86II::MO_DARWIN_NONLAZY;
11110   }
11111
11112   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11113
11114   SDLoc DL(Op);
11115   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11116
11117   // With PIC, the address is actually $g + Offset.
11118   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11119       !Subtarget->is64Bit()) {
11120     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11121                          DAG.getNode(X86ISD::GlobalBaseReg,
11122                                      SDLoc(), getPointerTy()),
11123                          Result);
11124   }
11125
11126   // For symbols that require a load from a stub to get the address, emit the
11127   // load.
11128   if (isGlobalStubReference(OpFlag))
11129     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11130                          MachinePointerInfo::getGOT(), false, false, false, 0);
11131
11132   return Result;
11133 }
11134
11135 SDValue
11136 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11137   // Create the TargetBlockAddressAddress node.
11138   unsigned char OpFlags =
11139     Subtarget->ClassifyBlockAddressReference();
11140   CodeModel::Model M = DAG.getTarget().getCodeModel();
11141   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11142   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11143   SDLoc dl(Op);
11144   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11145                                              OpFlags);
11146
11147   if (Subtarget->isPICStyleRIPRel() &&
11148       (M == CodeModel::Small || M == CodeModel::Kernel))
11149     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11150   else
11151     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11152
11153   // With PIC, the address is actually $g + Offset.
11154   if (isGlobalRelativeToPICBase(OpFlags)) {
11155     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11156                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11157                          Result);
11158   }
11159
11160   return Result;
11161 }
11162
11163 SDValue
11164 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11165                                       int64_t Offset, SelectionDAG &DAG) const {
11166   // Create the TargetGlobalAddress node, folding in the constant
11167   // offset if it is legal.
11168   unsigned char OpFlags =
11169       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11170   CodeModel::Model M = DAG.getTarget().getCodeModel();
11171   SDValue Result;
11172   if (OpFlags == X86II::MO_NO_FLAG &&
11173       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11174     // A direct static reference to a global.
11175     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11176     Offset = 0;
11177   } else {
11178     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11179   }
11180
11181   if (Subtarget->isPICStyleRIPRel() &&
11182       (M == CodeModel::Small || M == CodeModel::Kernel))
11183     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11184   else
11185     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11186
11187   // With PIC, the address is actually $g + Offset.
11188   if (isGlobalRelativeToPICBase(OpFlags)) {
11189     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11190                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11191                          Result);
11192   }
11193
11194   // For globals that require a load from a stub to get the address, emit the
11195   // load.
11196   if (isGlobalStubReference(OpFlags))
11197     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11198                          MachinePointerInfo::getGOT(), false, false, false, 0);
11199
11200   // If there was a non-zero offset that we didn't fold, create an explicit
11201   // addition for it.
11202   if (Offset != 0)
11203     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11204                          DAG.getConstant(Offset, getPointerTy()));
11205
11206   return Result;
11207 }
11208
11209 SDValue
11210 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11211   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11212   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11213   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11214 }
11215
11216 static SDValue
11217 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11218            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11219            unsigned char OperandFlags, bool LocalDynamic = false) {
11220   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11221   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11222   SDLoc dl(GA);
11223   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11224                                            GA->getValueType(0),
11225                                            GA->getOffset(),
11226                                            OperandFlags);
11227
11228   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11229                                            : X86ISD::TLSADDR;
11230
11231   if (InFlag) {
11232     SDValue Ops[] = { Chain,  TGA, *InFlag };
11233     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11234   } else {
11235     SDValue Ops[]  = { Chain, TGA };
11236     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11237   }
11238
11239   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11240   MFI->setAdjustsStack(true);
11241
11242   SDValue Flag = Chain.getValue(1);
11243   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11244 }
11245
11246 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11247 static SDValue
11248 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11249                                 const EVT PtrVT) {
11250   SDValue InFlag;
11251   SDLoc dl(GA);  // ? function entry point might be better
11252   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11253                                    DAG.getNode(X86ISD::GlobalBaseReg,
11254                                                SDLoc(), PtrVT), InFlag);
11255   InFlag = Chain.getValue(1);
11256
11257   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11258 }
11259
11260 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11261 static SDValue
11262 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11263                                 const EVT PtrVT) {
11264   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11265                     X86::RAX, X86II::MO_TLSGD);
11266 }
11267
11268 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11269                                            SelectionDAG &DAG,
11270                                            const EVT PtrVT,
11271                                            bool is64Bit) {
11272   SDLoc dl(GA);
11273
11274   // Get the start address of the TLS block for this module.
11275   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11276       .getInfo<X86MachineFunctionInfo>();
11277   MFI->incNumLocalDynamicTLSAccesses();
11278
11279   SDValue Base;
11280   if (is64Bit) {
11281     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11282                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11283   } else {
11284     SDValue InFlag;
11285     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11286         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11287     InFlag = Chain.getValue(1);
11288     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11289                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11290   }
11291
11292   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11293   // of Base.
11294
11295   // Build x@dtpoff.
11296   unsigned char OperandFlags = X86II::MO_DTPOFF;
11297   unsigned WrapperKind = X86ISD::Wrapper;
11298   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11299                                            GA->getValueType(0),
11300                                            GA->getOffset(), OperandFlags);
11301   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11302
11303   // Add x@dtpoff with the base.
11304   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11305 }
11306
11307 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11308 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11309                                    const EVT PtrVT, TLSModel::Model model,
11310                                    bool is64Bit, bool isPIC) {
11311   SDLoc dl(GA);
11312
11313   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11314   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11315                                                          is64Bit ? 257 : 256));
11316
11317   SDValue ThreadPointer =
11318       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11319                   MachinePointerInfo(Ptr), false, false, false, 0);
11320
11321   unsigned char OperandFlags = 0;
11322   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11323   // initialexec.
11324   unsigned WrapperKind = X86ISD::Wrapper;
11325   if (model == TLSModel::LocalExec) {
11326     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11327   } else if (model == TLSModel::InitialExec) {
11328     if (is64Bit) {
11329       OperandFlags = X86II::MO_GOTTPOFF;
11330       WrapperKind = X86ISD::WrapperRIP;
11331     } else {
11332       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11333     }
11334   } else {
11335     llvm_unreachable("Unexpected model");
11336   }
11337
11338   // emit "addl x@ntpoff,%eax" (local exec)
11339   // or "addl x@indntpoff,%eax" (initial exec)
11340   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11341   SDValue TGA =
11342       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11343                                  GA->getOffset(), OperandFlags);
11344   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11345
11346   if (model == TLSModel::InitialExec) {
11347     if (isPIC && !is64Bit) {
11348       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11349                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11350                            Offset);
11351     }
11352
11353     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11354                          MachinePointerInfo::getGOT(), false, false, false, 0);
11355   }
11356
11357   // The address of the thread local variable is the add of the thread
11358   // pointer with the offset of the variable.
11359   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11360 }
11361
11362 SDValue
11363 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11364
11365   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11366   const GlobalValue *GV = GA->getGlobal();
11367
11368   if (Subtarget->isTargetELF()) {
11369     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11370
11371     switch (model) {
11372       case TLSModel::GeneralDynamic:
11373         if (Subtarget->is64Bit())
11374           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11375         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11376       case TLSModel::LocalDynamic:
11377         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11378                                            Subtarget->is64Bit());
11379       case TLSModel::InitialExec:
11380       case TLSModel::LocalExec:
11381         return LowerToTLSExecModel(
11382             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11383             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11384     }
11385     llvm_unreachable("Unknown TLS model.");
11386   }
11387
11388   if (Subtarget->isTargetDarwin()) {
11389     // Darwin only has one model of TLS.  Lower to that.
11390     unsigned char OpFlag = 0;
11391     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11392                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11393
11394     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11395     // global base reg.
11396     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11397                  !Subtarget->is64Bit();
11398     if (PIC32)
11399       OpFlag = X86II::MO_TLVP_PIC_BASE;
11400     else
11401       OpFlag = X86II::MO_TLVP;
11402     SDLoc DL(Op);
11403     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11404                                                 GA->getValueType(0),
11405                                                 GA->getOffset(), OpFlag);
11406     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11407
11408     // With PIC32, the address is actually $g + Offset.
11409     if (PIC32)
11410       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11411                            DAG.getNode(X86ISD::GlobalBaseReg,
11412                                        SDLoc(), getPointerTy()),
11413                            Offset);
11414
11415     // Lowering the machine isd will make sure everything is in the right
11416     // location.
11417     SDValue Chain = DAG.getEntryNode();
11418     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11419     SDValue Args[] = { Chain, Offset };
11420     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11421
11422     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11423     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11424     MFI->setAdjustsStack(true);
11425
11426     // And our return value (tls address) is in the standard call return value
11427     // location.
11428     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11429     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11430                               Chain.getValue(1));
11431   }
11432
11433   if (Subtarget->isTargetKnownWindowsMSVC() ||
11434       Subtarget->isTargetWindowsGNU()) {
11435     // Just use the implicit TLS architecture
11436     // Need to generate someting similar to:
11437     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11438     //                                  ; from TEB
11439     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11440     //   mov     rcx, qword [rdx+rcx*8]
11441     //   mov     eax, .tls$:tlsvar
11442     //   [rax+rcx] contains the address
11443     // Windows 64bit: gs:0x58
11444     // Windows 32bit: fs:__tls_array
11445
11446     SDLoc dl(GA);
11447     SDValue Chain = DAG.getEntryNode();
11448
11449     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11450     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11451     // use its literal value of 0x2C.
11452     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11453                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11454                                                              256)
11455                                         : Type::getInt32PtrTy(*DAG.getContext(),
11456                                                               257));
11457
11458     SDValue TlsArray =
11459         Subtarget->is64Bit()
11460             ? DAG.getIntPtrConstant(0x58)
11461             : (Subtarget->isTargetWindowsGNU()
11462                    ? DAG.getIntPtrConstant(0x2C)
11463                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11464
11465     SDValue ThreadPointer =
11466         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11467                     MachinePointerInfo(Ptr), false, false, false, 0);
11468
11469     // Load the _tls_index variable
11470     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11471     if (Subtarget->is64Bit())
11472       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11473                            IDX, MachinePointerInfo(), MVT::i32,
11474                            false, false, false, 0);
11475     else
11476       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11477                         false, false, false, 0);
11478
11479     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11480                                     getPointerTy());
11481     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11482
11483     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11484     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11485                       false, false, false, 0);
11486
11487     // Get the offset of start of .tls section
11488     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11489                                              GA->getValueType(0),
11490                                              GA->getOffset(), X86II::MO_SECREL);
11491     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11492
11493     // The address of the thread local variable is the add of the thread
11494     // pointer with the offset of the variable.
11495     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11496   }
11497
11498   llvm_unreachable("TLS not implemented for this target.");
11499 }
11500
11501 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11502 /// and take a 2 x i32 value to shift plus a shift amount.
11503 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11504   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11505   MVT VT = Op.getSimpleValueType();
11506   unsigned VTBits = VT.getSizeInBits();
11507   SDLoc dl(Op);
11508   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11509   SDValue ShOpLo = Op.getOperand(0);
11510   SDValue ShOpHi = Op.getOperand(1);
11511   SDValue ShAmt  = Op.getOperand(2);
11512   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11513   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11514   // during isel.
11515   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11516                                   DAG.getConstant(VTBits - 1, MVT::i8));
11517   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11518                                      DAG.getConstant(VTBits - 1, MVT::i8))
11519                        : DAG.getConstant(0, VT);
11520
11521   SDValue Tmp2, Tmp3;
11522   if (Op.getOpcode() == ISD::SHL_PARTS) {
11523     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11524     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11525   } else {
11526     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11527     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11528   }
11529
11530   // If the shift amount is larger or equal than the width of a part we can't
11531   // rely on the results of shld/shrd. Insert a test and select the appropriate
11532   // values for large shift amounts.
11533   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11534                                 DAG.getConstant(VTBits, MVT::i8));
11535   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11536                              AndNode, DAG.getConstant(0, MVT::i8));
11537
11538   SDValue Hi, Lo;
11539   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11540   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11541   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11542
11543   if (Op.getOpcode() == ISD::SHL_PARTS) {
11544     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11545     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11546   } else {
11547     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11548     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11549   }
11550
11551   SDValue Ops[2] = { Lo, Hi };
11552   return DAG.getMergeValues(Ops, dl);
11553 }
11554
11555 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11556                                            SelectionDAG &DAG) const {
11557   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11558
11559   if (SrcVT.isVector())
11560     return SDValue();
11561
11562   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11563          "Unknown SINT_TO_FP to lower!");
11564
11565   // These are really Legal; return the operand so the caller accepts it as
11566   // Legal.
11567   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11568     return Op;
11569   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11570       Subtarget->is64Bit()) {
11571     return Op;
11572   }
11573
11574   SDLoc dl(Op);
11575   unsigned Size = SrcVT.getSizeInBits()/8;
11576   MachineFunction &MF = DAG.getMachineFunction();
11577   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11578   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11579   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11580                                StackSlot,
11581                                MachinePointerInfo::getFixedStack(SSFI),
11582                                false, false, 0);
11583   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11584 }
11585
11586 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11587                                      SDValue StackSlot,
11588                                      SelectionDAG &DAG) const {
11589   // Build the FILD
11590   SDLoc DL(Op);
11591   SDVTList Tys;
11592   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11593   if (useSSE)
11594     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11595   else
11596     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11597
11598   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11599
11600   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11601   MachineMemOperand *MMO;
11602   if (FI) {
11603     int SSFI = FI->getIndex();
11604     MMO =
11605       DAG.getMachineFunction()
11606       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11607                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11608   } else {
11609     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11610     StackSlot = StackSlot.getOperand(1);
11611   }
11612   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11613   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11614                                            X86ISD::FILD, DL,
11615                                            Tys, Ops, SrcVT, MMO);
11616
11617   if (useSSE) {
11618     Chain = Result.getValue(1);
11619     SDValue InFlag = Result.getValue(2);
11620
11621     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11622     // shouldn't be necessary except that RFP cannot be live across
11623     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11624     MachineFunction &MF = DAG.getMachineFunction();
11625     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11626     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11627     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11628     Tys = DAG.getVTList(MVT::Other);
11629     SDValue Ops[] = {
11630       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11631     };
11632     MachineMemOperand *MMO =
11633       DAG.getMachineFunction()
11634       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11635                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11636
11637     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11638                                     Ops, Op.getValueType(), MMO);
11639     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11640                          MachinePointerInfo::getFixedStack(SSFI),
11641                          false, false, false, 0);
11642   }
11643
11644   return Result;
11645 }
11646
11647 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11648 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11649                                                SelectionDAG &DAG) const {
11650   // This algorithm is not obvious. Here it is what we're trying to output:
11651   /*
11652      movq       %rax,  %xmm0
11653      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11654      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11655      #ifdef __SSE3__
11656        haddpd   %xmm0, %xmm0
11657      #else
11658        pshufd   $0x4e, %xmm0, %xmm1
11659        addpd    %xmm1, %xmm0
11660      #endif
11661   */
11662
11663   SDLoc dl(Op);
11664   LLVMContext *Context = DAG.getContext();
11665
11666   // Build some magic constants.
11667   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11668   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11669   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11670
11671   SmallVector<Constant*,2> CV1;
11672   CV1.push_back(
11673     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11674                                       APInt(64, 0x4330000000000000ULL))));
11675   CV1.push_back(
11676     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11677                                       APInt(64, 0x4530000000000000ULL))));
11678   Constant *C1 = ConstantVector::get(CV1);
11679   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11680
11681   // Load the 64-bit value into an XMM register.
11682   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11683                             Op.getOperand(0));
11684   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11685                               MachinePointerInfo::getConstantPool(),
11686                               false, false, false, 16);
11687   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11688                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11689                               CLod0);
11690
11691   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11692                               MachinePointerInfo::getConstantPool(),
11693                               false, false, false, 16);
11694   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11695   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11696   SDValue Result;
11697
11698   if (Subtarget->hasSSE3()) {
11699     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11700     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11701   } else {
11702     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11703     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11704                                            S2F, 0x4E, DAG);
11705     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11706                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11707                          Sub);
11708   }
11709
11710   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11711                      DAG.getIntPtrConstant(0));
11712 }
11713
11714 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11715 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11716                                                SelectionDAG &DAG) const {
11717   SDLoc dl(Op);
11718   // FP constant to bias correct the final result.
11719   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11720                                    MVT::f64);
11721
11722   // Load the 32-bit value into an XMM register.
11723   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11724                              Op.getOperand(0));
11725
11726   // Zero out the upper parts of the register.
11727   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11728
11729   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11730                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11731                      DAG.getIntPtrConstant(0));
11732
11733   // Or the load with the bias.
11734   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11735                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11736                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11737                                                    MVT::v2f64, Load)),
11738                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11739                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11740                                                    MVT::v2f64, Bias)));
11741   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11742                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11743                    DAG.getIntPtrConstant(0));
11744
11745   // Subtract the bias.
11746   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11747
11748   // Handle final rounding.
11749   EVT DestVT = Op.getValueType();
11750
11751   if (DestVT.bitsLT(MVT::f64))
11752     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11753                        DAG.getIntPtrConstant(0));
11754   if (DestVT.bitsGT(MVT::f64))
11755     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11756
11757   // Handle final rounding.
11758   return Sub;
11759 }
11760
11761 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11762                                                SelectionDAG &DAG) const {
11763   SDValue N0 = Op.getOperand(0);
11764   MVT SVT = N0.getSimpleValueType();
11765   SDLoc dl(Op);
11766
11767   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11768           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11769          "Custom UINT_TO_FP is not supported!");
11770
11771   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11772   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11773                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11774 }
11775
11776 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11777                                            SelectionDAG &DAG) const {
11778   SDValue N0 = Op.getOperand(0);
11779   SDLoc dl(Op);
11780
11781   if (Op.getValueType().isVector())
11782     return lowerUINT_TO_FP_vec(Op, DAG);
11783
11784   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11785   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11786   // the optimization here.
11787   if (DAG.SignBitIsZero(N0))
11788     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11789
11790   MVT SrcVT = N0.getSimpleValueType();
11791   MVT DstVT = Op.getSimpleValueType();
11792   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11793     return LowerUINT_TO_FP_i64(Op, DAG);
11794   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11795     return LowerUINT_TO_FP_i32(Op, DAG);
11796   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11797     return SDValue();
11798
11799   // Make a 64-bit buffer, and use it to build an FILD.
11800   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11801   if (SrcVT == MVT::i32) {
11802     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11803     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11804                                      getPointerTy(), StackSlot, WordOff);
11805     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11806                                   StackSlot, MachinePointerInfo(),
11807                                   false, false, 0);
11808     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11809                                   OffsetSlot, MachinePointerInfo(),
11810                                   false, false, 0);
11811     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11812     return Fild;
11813   }
11814
11815   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11816   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11817                                StackSlot, MachinePointerInfo(),
11818                                false, false, 0);
11819   // For i64 source, we need to add the appropriate power of 2 if the input
11820   // was negative.  This is the same as the optimization in
11821   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11822   // we must be careful to do the computation in x87 extended precision, not
11823   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11824   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11825   MachineMemOperand *MMO =
11826     DAG.getMachineFunction()
11827     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11828                           MachineMemOperand::MOLoad, 8, 8);
11829
11830   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11831   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11832   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11833                                          MVT::i64, MMO);
11834
11835   APInt FF(32, 0x5F800000ULL);
11836
11837   // Check whether the sign bit is set.
11838   SDValue SignSet = DAG.getSetCC(dl,
11839                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11840                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11841                                  ISD::SETLT);
11842
11843   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11844   SDValue FudgePtr = DAG.getConstantPool(
11845                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11846                                          getPointerTy());
11847
11848   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11849   SDValue Zero = DAG.getIntPtrConstant(0);
11850   SDValue Four = DAG.getIntPtrConstant(4);
11851   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11852                                Zero, Four);
11853   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11854
11855   // Load the value out, extending it from f32 to f80.
11856   // FIXME: Avoid the extend by constructing the right constant pool?
11857   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11858                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11859                                  MVT::f32, false, false, false, 4);
11860   // Extend everything to 80 bits to force it to be done on x87.
11861   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11862   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11863 }
11864
11865 std::pair<SDValue,SDValue>
11866 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11867                                     bool IsSigned, bool IsReplace) const {
11868   SDLoc DL(Op);
11869
11870   EVT DstTy = Op.getValueType();
11871
11872   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11873     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11874     DstTy = MVT::i64;
11875   }
11876
11877   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11878          DstTy.getSimpleVT() >= MVT::i16 &&
11879          "Unknown FP_TO_INT to lower!");
11880
11881   // These are really Legal.
11882   if (DstTy == MVT::i32 &&
11883       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11884     return std::make_pair(SDValue(), SDValue());
11885   if (Subtarget->is64Bit() &&
11886       DstTy == MVT::i64 &&
11887       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11888     return std::make_pair(SDValue(), SDValue());
11889
11890   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11891   // stack slot, or into the FTOL runtime function.
11892   MachineFunction &MF = DAG.getMachineFunction();
11893   unsigned MemSize = DstTy.getSizeInBits()/8;
11894   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11895   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11896
11897   unsigned Opc;
11898   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11899     Opc = X86ISD::WIN_FTOL;
11900   else
11901     switch (DstTy.getSimpleVT().SimpleTy) {
11902     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11903     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11904     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11905     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11906     }
11907
11908   SDValue Chain = DAG.getEntryNode();
11909   SDValue Value = Op.getOperand(0);
11910   EVT TheVT = Op.getOperand(0).getValueType();
11911   // FIXME This causes a redundant load/store if the SSE-class value is already
11912   // in memory, such as if it is on the callstack.
11913   if (isScalarFPTypeInSSEReg(TheVT)) {
11914     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11915     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11916                          MachinePointerInfo::getFixedStack(SSFI),
11917                          false, false, 0);
11918     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11919     SDValue Ops[] = {
11920       Chain, StackSlot, DAG.getValueType(TheVT)
11921     };
11922
11923     MachineMemOperand *MMO =
11924       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11925                               MachineMemOperand::MOLoad, MemSize, MemSize);
11926     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11927     Chain = Value.getValue(1);
11928     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11929     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11930   }
11931
11932   MachineMemOperand *MMO =
11933     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11934                             MachineMemOperand::MOStore, MemSize, MemSize);
11935
11936   if (Opc != X86ISD::WIN_FTOL) {
11937     // Build the FP_TO_INT*_IN_MEM
11938     SDValue Ops[] = { Chain, Value, StackSlot };
11939     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11940                                            Ops, DstTy, MMO);
11941     return std::make_pair(FIST, StackSlot);
11942   } else {
11943     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11944       DAG.getVTList(MVT::Other, MVT::Glue),
11945       Chain, Value);
11946     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11947       MVT::i32, ftol.getValue(1));
11948     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11949       MVT::i32, eax.getValue(2));
11950     SDValue Ops[] = { eax, edx };
11951     SDValue pair = IsReplace
11952       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11953       : DAG.getMergeValues(Ops, DL);
11954     return std::make_pair(pair, SDValue());
11955   }
11956 }
11957
11958 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11959                               const X86Subtarget *Subtarget) {
11960   MVT VT = Op->getSimpleValueType(0);
11961   SDValue In = Op->getOperand(0);
11962   MVT InVT = In.getSimpleValueType();
11963   SDLoc dl(Op);
11964
11965   // Optimize vectors in AVX mode:
11966   //
11967   //   v8i16 -> v8i32
11968   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11969   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11970   //   Concat upper and lower parts.
11971   //
11972   //   v4i32 -> v4i64
11973   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11974   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11975   //   Concat upper and lower parts.
11976   //
11977
11978   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11979       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11980       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11981     return SDValue();
11982
11983   if (Subtarget->hasInt256())
11984     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11985
11986   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11987   SDValue Undef = DAG.getUNDEF(InVT);
11988   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11989   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11990   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11991
11992   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11993                              VT.getVectorNumElements()/2);
11994
11995   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11996   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11997
11998   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11999 }
12000
12001 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12002                                         SelectionDAG &DAG) {
12003   MVT VT = Op->getSimpleValueType(0);
12004   SDValue In = Op->getOperand(0);
12005   MVT InVT = In.getSimpleValueType();
12006   SDLoc DL(Op);
12007   unsigned int NumElts = VT.getVectorNumElements();
12008   if (NumElts != 8 && NumElts != 16)
12009     return SDValue();
12010
12011   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12012     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12013
12014   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
12015   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12016   // Now we have only mask extension
12017   assert(InVT.getVectorElementType() == MVT::i1);
12018   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
12019   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12020   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12021   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12022   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12023                            MachinePointerInfo::getConstantPool(),
12024                            false, false, false, Alignment);
12025
12026   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
12027   if (VT.is512BitVector())
12028     return Brcst;
12029   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
12030 }
12031
12032 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12033                                SelectionDAG &DAG) {
12034   if (Subtarget->hasFp256()) {
12035     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12036     if (Res.getNode())
12037       return Res;
12038   }
12039
12040   return SDValue();
12041 }
12042
12043 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12044                                 SelectionDAG &DAG) {
12045   SDLoc DL(Op);
12046   MVT VT = Op.getSimpleValueType();
12047   SDValue In = Op.getOperand(0);
12048   MVT SVT = In.getSimpleValueType();
12049
12050   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12051     return LowerZERO_EXTEND_AVX512(Op, DAG);
12052
12053   if (Subtarget->hasFp256()) {
12054     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12055     if (Res.getNode())
12056       return Res;
12057   }
12058
12059   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12060          VT.getVectorNumElements() != SVT.getVectorNumElements());
12061   return SDValue();
12062 }
12063
12064 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12065   SDLoc DL(Op);
12066   MVT VT = Op.getSimpleValueType();
12067   SDValue In = Op.getOperand(0);
12068   MVT InVT = In.getSimpleValueType();
12069
12070   if (VT == MVT::i1) {
12071     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12072            "Invalid scalar TRUNCATE operation");
12073     if (InVT.getSizeInBits() >= 32)
12074       return SDValue();
12075     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12076     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12077   }
12078   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12079          "Invalid TRUNCATE operation");
12080
12081   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12082     if (VT.getVectorElementType().getSizeInBits() >=8)
12083       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12084
12085     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12086     unsigned NumElts = InVT.getVectorNumElements();
12087     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12088     if (InVT.getSizeInBits() < 512) {
12089       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12090       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12091       InVT = ExtVT;
12092     }
12093     
12094     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12095     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12096     SDValue CP = DAG.getConstantPool(C, getPointerTy());
12097     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12098     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12099                            MachinePointerInfo::getConstantPool(),
12100                            false, false, false, Alignment);
12101     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12102     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12103     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12104   }
12105
12106   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12107     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12108     if (Subtarget->hasInt256()) {
12109       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12110       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12111       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12112                                 ShufMask);
12113       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12114                          DAG.getIntPtrConstant(0));
12115     }
12116
12117     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12118                                DAG.getIntPtrConstant(0));
12119     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12120                                DAG.getIntPtrConstant(2));
12121     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12122     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12123     static const int ShufMask[] = {0, 2, 4, 6};
12124     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12125   }
12126
12127   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12128     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12129     if (Subtarget->hasInt256()) {
12130       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12131
12132       SmallVector<SDValue,32> pshufbMask;
12133       for (unsigned i = 0; i < 2; ++i) {
12134         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12135         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12136         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12137         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12138         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12139         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12140         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12141         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12142         for (unsigned j = 0; j < 8; ++j)
12143           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12144       }
12145       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12146       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12147       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12148
12149       static const int ShufMask[] = {0,  2,  -1,  -1};
12150       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12151                                 &ShufMask[0]);
12152       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12153                        DAG.getIntPtrConstant(0));
12154       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12155     }
12156
12157     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12158                                DAG.getIntPtrConstant(0));
12159
12160     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12161                                DAG.getIntPtrConstant(4));
12162
12163     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12164     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12165
12166     // The PSHUFB mask:
12167     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12168                                    -1, -1, -1, -1, -1, -1, -1, -1};
12169
12170     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12171     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12172     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12173
12174     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12175     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12176
12177     // The MOVLHPS Mask:
12178     static const int ShufMask2[] = {0, 1, 4, 5};
12179     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12180     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12181   }
12182
12183   // Handle truncation of V256 to V128 using shuffles.
12184   if (!VT.is128BitVector() || !InVT.is256BitVector())
12185     return SDValue();
12186
12187   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12188
12189   unsigned NumElems = VT.getVectorNumElements();
12190   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12191
12192   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12193   // Prepare truncation shuffle mask
12194   for (unsigned i = 0; i != NumElems; ++i)
12195     MaskVec[i] = i * 2;
12196   SDValue V = DAG.getVectorShuffle(NVT, DL,
12197                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12198                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12199   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12200                      DAG.getIntPtrConstant(0));
12201 }
12202
12203 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12204                                            SelectionDAG &DAG) const {
12205   assert(!Op.getSimpleValueType().isVector());
12206
12207   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12208     /*IsSigned=*/ true, /*IsReplace=*/ false);
12209   SDValue FIST = Vals.first, StackSlot = Vals.second;
12210   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12211   if (!FIST.getNode()) return Op;
12212
12213   if (StackSlot.getNode())
12214     // Load the result.
12215     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12216                        FIST, StackSlot, MachinePointerInfo(),
12217                        false, false, false, 0);
12218
12219   // The node is the result.
12220   return FIST;
12221 }
12222
12223 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12224                                            SelectionDAG &DAG) const {
12225   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12226     /*IsSigned=*/ false, /*IsReplace=*/ false);
12227   SDValue FIST = Vals.first, StackSlot = Vals.second;
12228   assert(FIST.getNode() && "Unexpected failure");
12229
12230   if (StackSlot.getNode())
12231     // Load the result.
12232     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12233                        FIST, StackSlot, MachinePointerInfo(),
12234                        false, false, false, 0);
12235
12236   // The node is the result.
12237   return FIST;
12238 }
12239
12240 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12241   SDLoc DL(Op);
12242   MVT VT = Op.getSimpleValueType();
12243   SDValue In = Op.getOperand(0);
12244   MVT SVT = In.getSimpleValueType();
12245
12246   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12247
12248   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12249                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12250                                  In, DAG.getUNDEF(SVT)));
12251 }
12252
12253 // The only differences between FABS and FNEG are the mask and the logic op.
12254 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12255   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12256          "Wrong opcode for lowering FABS or FNEG.");
12257
12258   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12259   SDLoc dl(Op);
12260   MVT VT = Op.getSimpleValueType();
12261   // Assume scalar op for initialization; update for vector if needed.
12262   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12263   // generate a 16-byte vector constant and logic op even for the scalar case.
12264   // Using a 16-byte mask allows folding the load of the mask with
12265   // the logic op, so it can save (~4 bytes) on code size.
12266   MVT EltVT = VT;
12267   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12268   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12269   // decide if we should generate a 16-byte constant mask when we only need 4 or
12270   // 8 bytes for the scalar case.
12271   if (VT.isVector()) {
12272     EltVT = VT.getVectorElementType();
12273     NumElts = VT.getVectorNumElements();
12274   }
12275   
12276   unsigned EltBits = EltVT.getSizeInBits();
12277   LLVMContext *Context = DAG.getContext();
12278   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12279   APInt MaskElt =
12280     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12281   Constant *C = ConstantInt::get(*Context, MaskElt);
12282   C = ConstantVector::getSplat(NumElts, C);
12283   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12284   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12285   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12286   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12287                              MachinePointerInfo::getConstantPool(),
12288                              false, false, false, Alignment);
12289
12290   if (VT.isVector()) {
12291     // For a vector, cast operands to a vector type, perform the logic op,
12292     // and cast the result back to the original value type.
12293     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12294     SDValue Op0Casted = DAG.getNode(ISD::BITCAST, dl, VecVT, Op.getOperand(0));
12295     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12296     unsigned LogicOp = IsFABS ? ISD::AND : ISD::XOR;
12297     return DAG.getNode(ISD::BITCAST, dl, VT,
12298                        DAG.getNode(LogicOp, dl, VecVT, Op0Casted, MaskCasted));
12299   }
12300   // If not vector, then scalar.
12301   unsigned LogicOp = IsFABS ? X86ISD::FAND : X86ISD::FXOR;
12302   return DAG.getNode(LogicOp, dl, VT, Op.getOperand(0), Mask);
12303 }
12304
12305 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12307   LLVMContext *Context = DAG.getContext();
12308   SDValue Op0 = Op.getOperand(0);
12309   SDValue Op1 = Op.getOperand(1);
12310   SDLoc dl(Op);
12311   MVT VT = Op.getSimpleValueType();
12312   MVT SrcVT = Op1.getSimpleValueType();
12313
12314   // If second operand is smaller, extend it first.
12315   if (SrcVT.bitsLT(VT)) {
12316     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12317     SrcVT = VT;
12318   }
12319   // And if it is bigger, shrink it first.
12320   if (SrcVT.bitsGT(VT)) {
12321     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12322     SrcVT = VT;
12323   }
12324
12325   // At this point the operands and the result should have the same
12326   // type, and that won't be f80 since that is not custom lowered.
12327
12328   // First get the sign bit of second operand.
12329   SmallVector<Constant*,4> CV;
12330   if (SrcVT == MVT::f64) {
12331     const fltSemantics &Sem = APFloat::IEEEdouble;
12332     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12333     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12334   } else {
12335     const fltSemantics &Sem = APFloat::IEEEsingle;
12336     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12337     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12338     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12339     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12340   }
12341   Constant *C = ConstantVector::get(CV);
12342   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12343   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12344                               MachinePointerInfo::getConstantPool(),
12345                               false, false, false, 16);
12346   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12347
12348   // Shift sign bit right or left if the two operands have different types.
12349   if (SrcVT.bitsGT(VT)) {
12350     // Op0 is MVT::f32, Op1 is MVT::f64.
12351     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12352     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12353                           DAG.getConstant(32, MVT::i32));
12354     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12355     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12356                           DAG.getIntPtrConstant(0));
12357   }
12358
12359   // Clear first operand sign bit.
12360   CV.clear();
12361   if (VT == MVT::f64) {
12362     const fltSemantics &Sem = APFloat::IEEEdouble;
12363     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12364                                                    APInt(64, ~(1ULL << 63)))));
12365     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12366   } else {
12367     const fltSemantics &Sem = APFloat::IEEEsingle;
12368     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12369                                                    APInt(32, ~(1U << 31)))));
12370     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12371     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12372     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12373   }
12374   C = ConstantVector::get(CV);
12375   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12376   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12377                               MachinePointerInfo::getConstantPool(),
12378                               false, false, false, 16);
12379   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12380
12381   // Or the value with the sign bit.
12382   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12383 }
12384
12385 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12386   SDValue N0 = Op.getOperand(0);
12387   SDLoc dl(Op);
12388   MVT VT = Op.getSimpleValueType();
12389
12390   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12391   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12392                                   DAG.getConstant(1, VT));
12393   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12394 }
12395
12396 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12397 //
12398 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12399                                       SelectionDAG &DAG) {
12400   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12401
12402   if (!Subtarget->hasSSE41())
12403     return SDValue();
12404
12405   if (!Op->hasOneUse())
12406     return SDValue();
12407
12408   SDNode *N = Op.getNode();
12409   SDLoc DL(N);
12410
12411   SmallVector<SDValue, 8> Opnds;
12412   DenseMap<SDValue, unsigned> VecInMap;
12413   SmallVector<SDValue, 8> VecIns;
12414   EVT VT = MVT::Other;
12415
12416   // Recognize a special case where a vector is casted into wide integer to
12417   // test all 0s.
12418   Opnds.push_back(N->getOperand(0));
12419   Opnds.push_back(N->getOperand(1));
12420
12421   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12422     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12423     // BFS traverse all OR'd operands.
12424     if (I->getOpcode() == ISD::OR) {
12425       Opnds.push_back(I->getOperand(0));
12426       Opnds.push_back(I->getOperand(1));
12427       // Re-evaluate the number of nodes to be traversed.
12428       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12429       continue;
12430     }
12431
12432     // Quit if a non-EXTRACT_VECTOR_ELT
12433     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12434       return SDValue();
12435
12436     // Quit if without a constant index.
12437     SDValue Idx = I->getOperand(1);
12438     if (!isa<ConstantSDNode>(Idx))
12439       return SDValue();
12440
12441     SDValue ExtractedFromVec = I->getOperand(0);
12442     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12443     if (M == VecInMap.end()) {
12444       VT = ExtractedFromVec.getValueType();
12445       // Quit if not 128/256-bit vector.
12446       if (!VT.is128BitVector() && !VT.is256BitVector())
12447         return SDValue();
12448       // Quit if not the same type.
12449       if (VecInMap.begin() != VecInMap.end() &&
12450           VT != VecInMap.begin()->first.getValueType())
12451         return SDValue();
12452       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12453       VecIns.push_back(ExtractedFromVec);
12454     }
12455     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12456   }
12457
12458   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12459          "Not extracted from 128-/256-bit vector.");
12460
12461   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12462
12463   for (DenseMap<SDValue, unsigned>::const_iterator
12464         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12465     // Quit if not all elements are used.
12466     if (I->second != FullMask)
12467       return SDValue();
12468   }
12469
12470   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12471
12472   // Cast all vectors into TestVT for PTEST.
12473   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12474     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12475
12476   // If more than one full vectors are evaluated, OR them first before PTEST.
12477   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12478     // Each iteration will OR 2 nodes and append the result until there is only
12479     // 1 node left, i.e. the final OR'd value of all vectors.
12480     SDValue LHS = VecIns[Slot];
12481     SDValue RHS = VecIns[Slot + 1];
12482     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12483   }
12484
12485   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12486                      VecIns.back(), VecIns.back());
12487 }
12488
12489 /// \brief return true if \c Op has a use that doesn't just read flags.
12490 static bool hasNonFlagsUse(SDValue Op) {
12491   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12492        ++UI) {
12493     SDNode *User = *UI;
12494     unsigned UOpNo = UI.getOperandNo();
12495     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12496       // Look pass truncate.
12497       UOpNo = User->use_begin().getOperandNo();
12498       User = *User->use_begin();
12499     }
12500
12501     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12502         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12503       return true;
12504   }
12505   return false;
12506 }
12507
12508 /// Emit nodes that will be selected as "test Op0,Op0", or something
12509 /// equivalent.
12510 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12511                                     SelectionDAG &DAG) const {
12512   if (Op.getValueType() == MVT::i1)
12513     // KORTEST instruction should be selected
12514     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12515                        DAG.getConstant(0, Op.getValueType()));
12516
12517   // CF and OF aren't always set the way we want. Determine which
12518   // of these we need.
12519   bool NeedCF = false;
12520   bool NeedOF = false;
12521   switch (X86CC) {
12522   default: break;
12523   case X86::COND_A: case X86::COND_AE:
12524   case X86::COND_B: case X86::COND_BE:
12525     NeedCF = true;
12526     break;
12527   case X86::COND_G: case X86::COND_GE:
12528   case X86::COND_L: case X86::COND_LE:
12529   case X86::COND_O: case X86::COND_NO: {
12530     // Check if we really need to set the
12531     // Overflow flag. If NoSignedWrap is present
12532     // that is not actually needed.
12533     switch (Op->getOpcode()) {
12534     case ISD::ADD:
12535     case ISD::SUB:
12536     case ISD::MUL:
12537     case ISD::SHL: {
12538       const BinaryWithFlagsSDNode *BinNode =
12539           cast<BinaryWithFlagsSDNode>(Op.getNode());
12540       if (BinNode->hasNoSignedWrap())
12541         break;
12542     }
12543     default:
12544       NeedOF = true;
12545       break;
12546     }
12547     break;
12548   }
12549   }
12550   // See if we can use the EFLAGS value from the operand instead of
12551   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12552   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12553   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12554     // Emit a CMP with 0, which is the TEST pattern.
12555     //if (Op.getValueType() == MVT::i1)
12556     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12557     //                     DAG.getConstant(0, MVT::i1));
12558     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12559                        DAG.getConstant(0, Op.getValueType()));
12560   }
12561   unsigned Opcode = 0;
12562   unsigned NumOperands = 0;
12563
12564   // Truncate operations may prevent the merge of the SETCC instruction
12565   // and the arithmetic instruction before it. Attempt to truncate the operands
12566   // of the arithmetic instruction and use a reduced bit-width instruction.
12567   bool NeedTruncation = false;
12568   SDValue ArithOp = Op;
12569   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12570     SDValue Arith = Op->getOperand(0);
12571     // Both the trunc and the arithmetic op need to have one user each.
12572     if (Arith->hasOneUse())
12573       switch (Arith.getOpcode()) {
12574         default: break;
12575         case ISD::ADD:
12576         case ISD::SUB:
12577         case ISD::AND:
12578         case ISD::OR:
12579         case ISD::XOR: {
12580           NeedTruncation = true;
12581           ArithOp = Arith;
12582         }
12583       }
12584   }
12585
12586   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12587   // which may be the result of a CAST.  We use the variable 'Op', which is the
12588   // non-casted variable when we check for possible users.
12589   switch (ArithOp.getOpcode()) {
12590   case ISD::ADD:
12591     // Due to an isel shortcoming, be conservative if this add is likely to be
12592     // selected as part of a load-modify-store instruction. When the root node
12593     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12594     // uses of other nodes in the match, such as the ADD in this case. This
12595     // leads to the ADD being left around and reselected, with the result being
12596     // two adds in the output.  Alas, even if none our users are stores, that
12597     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12598     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12599     // climbing the DAG back to the root, and it doesn't seem to be worth the
12600     // effort.
12601     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12602          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12603       if (UI->getOpcode() != ISD::CopyToReg &&
12604           UI->getOpcode() != ISD::SETCC &&
12605           UI->getOpcode() != ISD::STORE)
12606         goto default_case;
12607
12608     if (ConstantSDNode *C =
12609         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12610       // An add of one will be selected as an INC.
12611       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12612         Opcode = X86ISD::INC;
12613         NumOperands = 1;
12614         break;
12615       }
12616
12617       // An add of negative one (subtract of one) will be selected as a DEC.
12618       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12619         Opcode = X86ISD::DEC;
12620         NumOperands = 1;
12621         break;
12622       }
12623     }
12624
12625     // Otherwise use a regular EFLAGS-setting add.
12626     Opcode = X86ISD::ADD;
12627     NumOperands = 2;
12628     break;
12629   case ISD::SHL:
12630   case ISD::SRL:
12631     // If we have a constant logical shift that's only used in a comparison
12632     // against zero turn it into an equivalent AND. This allows turning it into
12633     // a TEST instruction later.
12634     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12635         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12636       EVT VT = Op.getValueType();
12637       unsigned BitWidth = VT.getSizeInBits();
12638       unsigned ShAmt = Op->getConstantOperandVal(1);
12639       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12640         break;
12641       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12642                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12643                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12644       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12645         break;
12646       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12647                                 DAG.getConstant(Mask, VT));
12648       DAG.ReplaceAllUsesWith(Op, New);
12649       Op = New;
12650     }
12651     break;
12652
12653   case ISD::AND:
12654     // If the primary and result isn't used, don't bother using X86ISD::AND,
12655     // because a TEST instruction will be better.
12656     if (!hasNonFlagsUse(Op))
12657       break;
12658     // FALL THROUGH
12659   case ISD::SUB:
12660   case ISD::OR:
12661   case ISD::XOR:
12662     // Due to the ISEL shortcoming noted above, be conservative if this op is
12663     // likely to be selected as part of a load-modify-store instruction.
12664     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12665            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12666       if (UI->getOpcode() == ISD::STORE)
12667         goto default_case;
12668
12669     // Otherwise use a regular EFLAGS-setting instruction.
12670     switch (ArithOp.getOpcode()) {
12671     default: llvm_unreachable("unexpected operator!");
12672     case ISD::SUB: Opcode = X86ISD::SUB; break;
12673     case ISD::XOR: Opcode = X86ISD::XOR; break;
12674     case ISD::AND: Opcode = X86ISD::AND; break;
12675     case ISD::OR: {
12676       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12677         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12678         if (EFLAGS.getNode())
12679           return EFLAGS;
12680       }
12681       Opcode = X86ISD::OR;
12682       break;
12683     }
12684     }
12685
12686     NumOperands = 2;
12687     break;
12688   case X86ISD::ADD:
12689   case X86ISD::SUB:
12690   case X86ISD::INC:
12691   case X86ISD::DEC:
12692   case X86ISD::OR:
12693   case X86ISD::XOR:
12694   case X86ISD::AND:
12695     return SDValue(Op.getNode(), 1);
12696   default:
12697   default_case:
12698     break;
12699   }
12700
12701   // If we found that truncation is beneficial, perform the truncation and
12702   // update 'Op'.
12703   if (NeedTruncation) {
12704     EVT VT = Op.getValueType();
12705     SDValue WideVal = Op->getOperand(0);
12706     EVT WideVT = WideVal.getValueType();
12707     unsigned ConvertedOp = 0;
12708     // Use a target machine opcode to prevent further DAGCombine
12709     // optimizations that may separate the arithmetic operations
12710     // from the setcc node.
12711     switch (WideVal.getOpcode()) {
12712       default: break;
12713       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12714       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12715       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12716       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12717       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12718     }
12719
12720     if (ConvertedOp) {
12721       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12722       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12723         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12724         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12725         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12726       }
12727     }
12728   }
12729
12730   if (Opcode == 0)
12731     // Emit a CMP with 0, which is the TEST pattern.
12732     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12733                        DAG.getConstant(0, Op.getValueType()));
12734
12735   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12736   SmallVector<SDValue, 4> Ops;
12737   for (unsigned i = 0; i != NumOperands; ++i)
12738     Ops.push_back(Op.getOperand(i));
12739
12740   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12741   DAG.ReplaceAllUsesWith(Op, New);
12742   return SDValue(New.getNode(), 1);
12743 }
12744
12745 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12746 /// equivalent.
12747 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12748                                    SDLoc dl, SelectionDAG &DAG) const {
12749   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12750     if (C->getAPIntValue() == 0)
12751       return EmitTest(Op0, X86CC, dl, DAG);
12752
12753      if (Op0.getValueType() == MVT::i1)
12754        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12755   }
12756  
12757   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12758        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12759     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12760     // This avoids subregister aliasing issues. Keep the smaller reference 
12761     // if we're optimizing for size, however, as that'll allow better folding 
12762     // of memory operations.
12763     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12764         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12765              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12766         !Subtarget->isAtom()) {
12767       unsigned ExtendOp =
12768           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12769       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12770       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12771     }
12772     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12773     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12774     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12775                               Op0, Op1);
12776     return SDValue(Sub.getNode(), 1);
12777   }
12778   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12779 }
12780
12781 /// Convert a comparison if required by the subtarget.
12782 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12783                                                  SelectionDAG &DAG) const {
12784   // If the subtarget does not support the FUCOMI instruction, floating-point
12785   // comparisons have to be converted.
12786   if (Subtarget->hasCMov() ||
12787       Cmp.getOpcode() != X86ISD::CMP ||
12788       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12789       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12790     return Cmp;
12791
12792   // The instruction selector will select an FUCOM instruction instead of
12793   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12794   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12795   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12796   SDLoc dl(Cmp);
12797   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12798   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12799   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12800                             DAG.getConstant(8, MVT::i8));
12801   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12802   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12803 }
12804
12805 static bool isAllOnes(SDValue V) {
12806   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12807   return C && C->isAllOnesValue();
12808 }
12809
12810 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12811 /// if it's possible.
12812 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12813                                      SDLoc dl, SelectionDAG &DAG) const {
12814   SDValue Op0 = And.getOperand(0);
12815   SDValue Op1 = And.getOperand(1);
12816   if (Op0.getOpcode() == ISD::TRUNCATE)
12817     Op0 = Op0.getOperand(0);
12818   if (Op1.getOpcode() == ISD::TRUNCATE)
12819     Op1 = Op1.getOperand(0);
12820
12821   SDValue LHS, RHS;
12822   if (Op1.getOpcode() == ISD::SHL)
12823     std::swap(Op0, Op1);
12824   if (Op0.getOpcode() == ISD::SHL) {
12825     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12826       if (And00C->getZExtValue() == 1) {
12827         // If we looked past a truncate, check that it's only truncating away
12828         // known zeros.
12829         unsigned BitWidth = Op0.getValueSizeInBits();
12830         unsigned AndBitWidth = And.getValueSizeInBits();
12831         if (BitWidth > AndBitWidth) {
12832           APInt Zeros, Ones;
12833           DAG.computeKnownBits(Op0, Zeros, Ones);
12834           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12835             return SDValue();
12836         }
12837         LHS = Op1;
12838         RHS = Op0.getOperand(1);
12839       }
12840   } else if (Op1.getOpcode() == ISD::Constant) {
12841     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12842     uint64_t AndRHSVal = AndRHS->getZExtValue();
12843     SDValue AndLHS = Op0;
12844
12845     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12846       LHS = AndLHS.getOperand(0);
12847       RHS = AndLHS.getOperand(1);
12848     }
12849
12850     // Use BT if the immediate can't be encoded in a TEST instruction.
12851     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12852       LHS = AndLHS;
12853       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12854     }
12855   }
12856
12857   if (LHS.getNode()) {
12858     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12859     // instruction.  Since the shift amount is in-range-or-undefined, we know
12860     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12861     // the encoding for the i16 version is larger than the i32 version.
12862     // Also promote i16 to i32 for performance / code size reason.
12863     if (LHS.getValueType() == MVT::i8 ||
12864         LHS.getValueType() == MVT::i16)
12865       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12866
12867     // If the operand types disagree, extend the shift amount to match.  Since
12868     // BT ignores high bits (like shifts) we can use anyextend.
12869     if (LHS.getValueType() != RHS.getValueType())
12870       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12871
12872     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12873     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12874     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12875                        DAG.getConstant(Cond, MVT::i8), BT);
12876   }
12877
12878   return SDValue();
12879 }
12880
12881 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12882 /// mask CMPs.
12883 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12884                               SDValue &Op1) {
12885   unsigned SSECC;
12886   bool Swap = false;
12887
12888   // SSE Condition code mapping:
12889   //  0 - EQ
12890   //  1 - LT
12891   //  2 - LE
12892   //  3 - UNORD
12893   //  4 - NEQ
12894   //  5 - NLT
12895   //  6 - NLE
12896   //  7 - ORD
12897   switch (SetCCOpcode) {
12898   default: llvm_unreachable("Unexpected SETCC condition");
12899   case ISD::SETOEQ:
12900   case ISD::SETEQ:  SSECC = 0; break;
12901   case ISD::SETOGT:
12902   case ISD::SETGT:  Swap = true; // Fallthrough
12903   case ISD::SETLT:
12904   case ISD::SETOLT: SSECC = 1; break;
12905   case ISD::SETOGE:
12906   case ISD::SETGE:  Swap = true; // Fallthrough
12907   case ISD::SETLE:
12908   case ISD::SETOLE: SSECC = 2; break;
12909   case ISD::SETUO:  SSECC = 3; break;
12910   case ISD::SETUNE:
12911   case ISD::SETNE:  SSECC = 4; break;
12912   case ISD::SETULE: Swap = true; // Fallthrough
12913   case ISD::SETUGE: SSECC = 5; break;
12914   case ISD::SETULT: Swap = true; // Fallthrough
12915   case ISD::SETUGT: SSECC = 6; break;
12916   case ISD::SETO:   SSECC = 7; break;
12917   case ISD::SETUEQ:
12918   case ISD::SETONE: SSECC = 8; break;
12919   }
12920   if (Swap)
12921     std::swap(Op0, Op1);
12922
12923   return SSECC;
12924 }
12925
12926 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12927 // ones, and then concatenate the result back.
12928 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12929   MVT VT = Op.getSimpleValueType();
12930
12931   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12932          "Unsupported value type for operation");
12933
12934   unsigned NumElems = VT.getVectorNumElements();
12935   SDLoc dl(Op);
12936   SDValue CC = Op.getOperand(2);
12937
12938   // Extract the LHS vectors
12939   SDValue LHS = Op.getOperand(0);
12940   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12941   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12942
12943   // Extract the RHS vectors
12944   SDValue RHS = Op.getOperand(1);
12945   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12946   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12947
12948   // Issue the operation on the smaller types and concatenate the result back
12949   MVT EltVT = VT.getVectorElementType();
12950   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12951   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12952                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12953                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12954 }
12955
12956 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12957                                      const X86Subtarget *Subtarget) {
12958   SDValue Op0 = Op.getOperand(0);
12959   SDValue Op1 = Op.getOperand(1);
12960   SDValue CC = Op.getOperand(2);
12961   MVT VT = Op.getSimpleValueType();
12962   SDLoc dl(Op);
12963
12964   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12965          Op.getValueType().getScalarType() == MVT::i1 &&
12966          "Cannot set masked compare for this operation");
12967
12968   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12969   unsigned  Opc = 0;
12970   bool Unsigned = false;
12971   bool Swap = false;
12972   unsigned SSECC;
12973   switch (SetCCOpcode) {
12974   default: llvm_unreachable("Unexpected SETCC condition");
12975   case ISD::SETNE:  SSECC = 4; break;
12976   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12977   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12978   case ISD::SETLT:  Swap = true; //fall-through
12979   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12980   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12981   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12982   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12983   case ISD::SETULE: Unsigned = true; //fall-through
12984   case ISD::SETLE:  SSECC = 2; break;
12985   }
12986
12987   if (Swap)
12988     std::swap(Op0, Op1);
12989   if (Opc)
12990     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12991   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12992   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12993                      DAG.getConstant(SSECC, MVT::i8));
12994 }
12995
12996 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12997 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12998 /// return an empty value.
12999 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13000 {
13001   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13002   if (!BV)
13003     return SDValue();
13004
13005   MVT VT = Op1.getSimpleValueType();
13006   MVT EVT = VT.getVectorElementType();
13007   unsigned n = VT.getVectorNumElements();
13008   SmallVector<SDValue, 8> ULTOp1;
13009
13010   for (unsigned i = 0; i < n; ++i) {
13011     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13012     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13013       return SDValue();
13014
13015     // Avoid underflow.
13016     APInt Val = Elt->getAPIntValue();
13017     if (Val == 0)
13018       return SDValue();
13019
13020     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
13021   }
13022
13023   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13024 }
13025
13026 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13027                            SelectionDAG &DAG) {
13028   SDValue Op0 = Op.getOperand(0);
13029   SDValue Op1 = Op.getOperand(1);
13030   SDValue CC = Op.getOperand(2);
13031   MVT VT = Op.getSimpleValueType();
13032   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13033   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13034   SDLoc dl(Op);
13035
13036   if (isFP) {
13037 #ifndef NDEBUG
13038     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13039     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13040 #endif
13041
13042     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13043     unsigned Opc = X86ISD::CMPP;
13044     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13045       assert(VT.getVectorNumElements() <= 16);
13046       Opc = X86ISD::CMPM;
13047     }
13048     // In the two special cases we can't handle, emit two comparisons.
13049     if (SSECC == 8) {
13050       unsigned CC0, CC1;
13051       unsigned CombineOpc;
13052       if (SetCCOpcode == ISD::SETUEQ) {
13053         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13054       } else {
13055         assert(SetCCOpcode == ISD::SETONE);
13056         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13057       }
13058
13059       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13060                                  DAG.getConstant(CC0, MVT::i8));
13061       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13062                                  DAG.getConstant(CC1, MVT::i8));
13063       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13064     }
13065     // Handle all other FP comparisons here.
13066     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13067                        DAG.getConstant(SSECC, MVT::i8));
13068   }
13069
13070   // Break 256-bit integer vector compare into smaller ones.
13071   if (VT.is256BitVector() && !Subtarget->hasInt256())
13072     return Lower256IntVSETCC(Op, DAG);
13073
13074   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13075   EVT OpVT = Op1.getValueType();
13076   if (Subtarget->hasAVX512()) {
13077     if (Op1.getValueType().is512BitVector() ||
13078         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13079         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13080       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13081
13082     // In AVX-512 architecture setcc returns mask with i1 elements,
13083     // But there is no compare instruction for i8 and i16 elements in KNL.
13084     // We are not talking about 512-bit operands in this case, these
13085     // types are illegal.
13086     if (MaskResult &&
13087         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13088          OpVT.getVectorElementType().getSizeInBits() >= 8))
13089       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13090                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13091   }
13092
13093   // We are handling one of the integer comparisons here.  Since SSE only has
13094   // GT and EQ comparisons for integer, swapping operands and multiple
13095   // operations may be required for some comparisons.
13096   unsigned Opc;
13097   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13098   bool Subus = false;
13099
13100   switch (SetCCOpcode) {
13101   default: llvm_unreachable("Unexpected SETCC condition");
13102   case ISD::SETNE:  Invert = true;
13103   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13104   case ISD::SETLT:  Swap = true;
13105   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13106   case ISD::SETGE:  Swap = true;
13107   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13108                     Invert = true; break;
13109   case ISD::SETULT: Swap = true;
13110   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13111                     FlipSigns = true; break;
13112   case ISD::SETUGE: Swap = true;
13113   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13114                     FlipSigns = true; Invert = true; break;
13115   }
13116
13117   // Special case: Use min/max operations for SETULE/SETUGE
13118   MVT VET = VT.getVectorElementType();
13119   bool hasMinMax =
13120        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13121     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13122
13123   if (hasMinMax) {
13124     switch (SetCCOpcode) {
13125     default: break;
13126     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13127     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13128     }
13129
13130     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13131   }
13132
13133   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13134   if (!MinMax && hasSubus) {
13135     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13136     // Op0 u<= Op1:
13137     //   t = psubus Op0, Op1
13138     //   pcmpeq t, <0..0>
13139     switch (SetCCOpcode) {
13140     default: break;
13141     case ISD::SETULT: {
13142       // If the comparison is against a constant we can turn this into a
13143       // setule.  With psubus, setule does not require a swap.  This is
13144       // beneficial because the constant in the register is no longer
13145       // destructed as the destination so it can be hoisted out of a loop.
13146       // Only do this pre-AVX since vpcmp* is no longer destructive.
13147       if (Subtarget->hasAVX())
13148         break;
13149       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13150       if (ULEOp1.getNode()) {
13151         Op1 = ULEOp1;
13152         Subus = true; Invert = false; Swap = false;
13153       }
13154       break;
13155     }
13156     // Psubus is better than flip-sign because it requires no inversion.
13157     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13158     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13159     }
13160
13161     if (Subus) {
13162       Opc = X86ISD::SUBUS;
13163       FlipSigns = false;
13164     }
13165   }
13166
13167   if (Swap)
13168     std::swap(Op0, Op1);
13169
13170   // Check that the operation in question is available (most are plain SSE2,
13171   // but PCMPGTQ and PCMPEQQ have different requirements).
13172   if (VT == MVT::v2i64) {
13173     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13174       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13175
13176       // First cast everything to the right type.
13177       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13178       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13179
13180       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13181       // bits of the inputs before performing those operations. The lower
13182       // compare is always unsigned.
13183       SDValue SB;
13184       if (FlipSigns) {
13185         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13186       } else {
13187         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13188         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13189         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13190                          Sign, Zero, Sign, Zero);
13191       }
13192       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13193       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13194
13195       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13196       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13197       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13198
13199       // Create masks for only the low parts/high parts of the 64 bit integers.
13200       static const int MaskHi[] = { 1, 1, 3, 3 };
13201       static const int MaskLo[] = { 0, 0, 2, 2 };
13202       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13203       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13204       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13205
13206       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13207       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13208
13209       if (Invert)
13210         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13211
13212       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13213     }
13214
13215     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13216       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13217       // pcmpeqd + pshufd + pand.
13218       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13219
13220       // First cast everything to the right type.
13221       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13222       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13223
13224       // Do the compare.
13225       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13226
13227       // Make sure the lower and upper halves are both all-ones.
13228       static const int Mask[] = { 1, 0, 3, 2 };
13229       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13230       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13231
13232       if (Invert)
13233         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13234
13235       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13236     }
13237   }
13238
13239   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13240   // bits of the inputs before performing those operations.
13241   if (FlipSigns) {
13242     EVT EltVT = VT.getVectorElementType();
13243     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13244     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13245     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13246   }
13247
13248   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13249
13250   // If the logical-not of the result is required, perform that now.
13251   if (Invert)
13252     Result = DAG.getNOT(dl, Result, VT);
13253
13254   if (MinMax)
13255     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13256
13257   if (Subus)
13258     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13259                          getZeroVector(VT, Subtarget, DAG, dl));
13260
13261   return Result;
13262 }
13263
13264 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13265
13266   MVT VT = Op.getSimpleValueType();
13267
13268   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13269
13270   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13271          && "SetCC type must be 8-bit or 1-bit integer");
13272   SDValue Op0 = Op.getOperand(0);
13273   SDValue Op1 = Op.getOperand(1);
13274   SDLoc dl(Op);
13275   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13276
13277   // Optimize to BT if possible.
13278   // Lower (X & (1 << N)) == 0 to BT(X, N).
13279   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13280   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13281   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13282       Op1.getOpcode() == ISD::Constant &&
13283       cast<ConstantSDNode>(Op1)->isNullValue() &&
13284       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13285     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13286     if (NewSetCC.getNode())
13287       return NewSetCC;
13288   }
13289
13290   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13291   // these.
13292   if (Op1.getOpcode() == ISD::Constant &&
13293       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13294        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13295       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13296
13297     // If the input is a setcc, then reuse the input setcc or use a new one with
13298     // the inverted condition.
13299     if (Op0.getOpcode() == X86ISD::SETCC) {
13300       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13301       bool Invert = (CC == ISD::SETNE) ^
13302         cast<ConstantSDNode>(Op1)->isNullValue();
13303       if (!Invert)
13304         return Op0;
13305
13306       CCode = X86::GetOppositeBranchCondition(CCode);
13307       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13308                                   DAG.getConstant(CCode, MVT::i8),
13309                                   Op0.getOperand(1));
13310       if (VT == MVT::i1)
13311         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13312       return SetCC;
13313     }
13314   }
13315   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13316       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13317       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13318
13319     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13320     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13321   }
13322
13323   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13324   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13325   if (X86CC == X86::COND_INVALID)
13326     return SDValue();
13327
13328   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13329   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13330   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13331                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13332   if (VT == MVT::i1)
13333     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13334   return SetCC;
13335 }
13336
13337 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13338 static bool isX86LogicalCmp(SDValue Op) {
13339   unsigned Opc = Op.getNode()->getOpcode();
13340   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13341       Opc == X86ISD::SAHF)
13342     return true;
13343   if (Op.getResNo() == 1 &&
13344       (Opc == X86ISD::ADD ||
13345        Opc == X86ISD::SUB ||
13346        Opc == X86ISD::ADC ||
13347        Opc == X86ISD::SBB ||
13348        Opc == X86ISD::SMUL ||
13349        Opc == X86ISD::UMUL ||
13350        Opc == X86ISD::INC ||
13351        Opc == X86ISD::DEC ||
13352        Opc == X86ISD::OR ||
13353        Opc == X86ISD::XOR ||
13354        Opc == X86ISD::AND))
13355     return true;
13356
13357   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13358     return true;
13359
13360   return false;
13361 }
13362
13363 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13364   if (V.getOpcode() != ISD::TRUNCATE)
13365     return false;
13366
13367   SDValue VOp0 = V.getOperand(0);
13368   unsigned InBits = VOp0.getValueSizeInBits();
13369   unsigned Bits = V.getValueSizeInBits();
13370   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13371 }
13372
13373 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13374   bool addTest = true;
13375   SDValue Cond  = Op.getOperand(0);
13376   SDValue Op1 = Op.getOperand(1);
13377   SDValue Op2 = Op.getOperand(2);
13378   SDLoc DL(Op);
13379   EVT VT = Op1.getValueType();
13380   SDValue CC;
13381
13382   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13383   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13384   // sequence later on.
13385   if (Cond.getOpcode() == ISD::SETCC &&
13386       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13387        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13388       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13389     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13390     int SSECC = translateX86FSETCC(
13391         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13392
13393     if (SSECC != 8) {
13394       if (Subtarget->hasAVX512()) {
13395         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13396                                   DAG.getConstant(SSECC, MVT::i8));
13397         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13398       }
13399       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13400                                 DAG.getConstant(SSECC, MVT::i8));
13401       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13402       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13403       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13404     }
13405   }
13406
13407   if (Cond.getOpcode() == ISD::SETCC) {
13408     SDValue NewCond = LowerSETCC(Cond, DAG);
13409     if (NewCond.getNode())
13410       Cond = NewCond;
13411   }
13412
13413   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13414   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13415   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13416   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13417   if (Cond.getOpcode() == X86ISD::SETCC &&
13418       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13419       isZero(Cond.getOperand(1).getOperand(1))) {
13420     SDValue Cmp = Cond.getOperand(1);
13421
13422     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13423
13424     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13425         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13426       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13427
13428       SDValue CmpOp0 = Cmp.getOperand(0);
13429       // Apply further optimizations for special cases
13430       // (select (x != 0), -1, 0) -> neg & sbb
13431       // (select (x == 0), 0, -1) -> neg & sbb
13432       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13433         if (YC->isNullValue() &&
13434             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13435           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13436           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13437                                     DAG.getConstant(0, CmpOp0.getValueType()),
13438                                     CmpOp0);
13439           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13440                                     DAG.getConstant(X86::COND_B, MVT::i8),
13441                                     SDValue(Neg.getNode(), 1));
13442           return Res;
13443         }
13444
13445       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13446                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13447       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13448
13449       SDValue Res =   // Res = 0 or -1.
13450         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13451                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13452
13453       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13454         Res = DAG.getNOT(DL, Res, Res.getValueType());
13455
13456       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13457       if (!N2C || !N2C->isNullValue())
13458         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13459       return Res;
13460     }
13461   }
13462
13463   // Look past (and (setcc_carry (cmp ...)), 1).
13464   if (Cond.getOpcode() == ISD::AND &&
13465       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13466     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13467     if (C && C->getAPIntValue() == 1)
13468       Cond = Cond.getOperand(0);
13469   }
13470
13471   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13472   // setting operand in place of the X86ISD::SETCC.
13473   unsigned CondOpcode = Cond.getOpcode();
13474   if (CondOpcode == X86ISD::SETCC ||
13475       CondOpcode == X86ISD::SETCC_CARRY) {
13476     CC = Cond.getOperand(0);
13477
13478     SDValue Cmp = Cond.getOperand(1);
13479     unsigned Opc = Cmp.getOpcode();
13480     MVT VT = Op.getSimpleValueType();
13481
13482     bool IllegalFPCMov = false;
13483     if (VT.isFloatingPoint() && !VT.isVector() &&
13484         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13485       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13486
13487     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13488         Opc == X86ISD::BT) { // FIXME
13489       Cond = Cmp;
13490       addTest = false;
13491     }
13492   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13493              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13494              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13495               Cond.getOperand(0).getValueType() != MVT::i8)) {
13496     SDValue LHS = Cond.getOperand(0);
13497     SDValue RHS = Cond.getOperand(1);
13498     unsigned X86Opcode;
13499     unsigned X86Cond;
13500     SDVTList VTs;
13501     switch (CondOpcode) {
13502     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13503     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13504     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13505     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13506     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13507     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13508     default: llvm_unreachable("unexpected overflowing operator");
13509     }
13510     if (CondOpcode == ISD::UMULO)
13511       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13512                           MVT::i32);
13513     else
13514       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13515
13516     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13517
13518     if (CondOpcode == ISD::UMULO)
13519       Cond = X86Op.getValue(2);
13520     else
13521       Cond = X86Op.getValue(1);
13522
13523     CC = DAG.getConstant(X86Cond, MVT::i8);
13524     addTest = false;
13525   }
13526
13527   if (addTest) {
13528     // Look pass the truncate if the high bits are known zero.
13529     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13530         Cond = Cond.getOperand(0);
13531
13532     // We know the result of AND is compared against zero. Try to match
13533     // it to BT.
13534     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13535       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13536       if (NewSetCC.getNode()) {
13537         CC = NewSetCC.getOperand(0);
13538         Cond = NewSetCC.getOperand(1);
13539         addTest = false;
13540       }
13541     }
13542   }
13543
13544   if (addTest) {
13545     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13546     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13547   }
13548
13549   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13550   // a <  b ?  0 : -1 -> RES = setcc_carry
13551   // a >= b ? -1 :  0 -> RES = setcc_carry
13552   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13553   if (Cond.getOpcode() == X86ISD::SUB) {
13554     Cond = ConvertCmpIfNecessary(Cond, DAG);
13555     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13556
13557     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13558         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13559       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13560                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13561       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13562         return DAG.getNOT(DL, Res, Res.getValueType());
13563       return Res;
13564     }
13565   }
13566
13567   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13568   // widen the cmov and push the truncate through. This avoids introducing a new
13569   // branch during isel and doesn't add any extensions.
13570   if (Op.getValueType() == MVT::i8 &&
13571       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13572     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13573     if (T1.getValueType() == T2.getValueType() &&
13574         // Blacklist CopyFromReg to avoid partial register stalls.
13575         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13576       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13577       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13578       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13579     }
13580   }
13581
13582   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13583   // condition is true.
13584   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13585   SDValue Ops[] = { Op2, Op1, CC, Cond };
13586   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13587 }
13588
13589 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13590   MVT VT = Op->getSimpleValueType(0);
13591   SDValue In = Op->getOperand(0);
13592   MVT InVT = In.getSimpleValueType();
13593   SDLoc dl(Op);
13594
13595   unsigned int NumElts = VT.getVectorNumElements();
13596   if (NumElts != 8 && NumElts != 16)
13597     return SDValue();
13598
13599   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13600     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13601
13602   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13603   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13604
13605   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13606   Constant *C = ConstantInt::get(*DAG.getContext(),
13607     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13608
13609   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13610   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13611   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13612                           MachinePointerInfo::getConstantPool(),
13613                           false, false, false, Alignment);
13614   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13615   if (VT.is512BitVector())
13616     return Brcst;
13617   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13618 }
13619
13620 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13621                                 SelectionDAG &DAG) {
13622   MVT VT = Op->getSimpleValueType(0);
13623   SDValue In = Op->getOperand(0);
13624   MVT InVT = In.getSimpleValueType();
13625   SDLoc dl(Op);
13626
13627   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13628     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13629
13630   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13631       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13632       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13633     return SDValue();
13634
13635   if (Subtarget->hasInt256())
13636     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13637
13638   // Optimize vectors in AVX mode
13639   // Sign extend  v8i16 to v8i32 and
13640   //              v4i32 to v4i64
13641   //
13642   // Divide input vector into two parts
13643   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13644   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13645   // concat the vectors to original VT
13646
13647   unsigned NumElems = InVT.getVectorNumElements();
13648   SDValue Undef = DAG.getUNDEF(InVT);
13649
13650   SmallVector<int,8> ShufMask1(NumElems, -1);
13651   for (unsigned i = 0; i != NumElems/2; ++i)
13652     ShufMask1[i] = i;
13653
13654   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13655
13656   SmallVector<int,8> ShufMask2(NumElems, -1);
13657   for (unsigned i = 0; i != NumElems/2; ++i)
13658     ShufMask2[i] = i + NumElems/2;
13659
13660   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13661
13662   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13663                                 VT.getVectorNumElements()/2);
13664
13665   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13666   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13667
13668   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13669 }
13670
13671 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13672 // may emit an illegal shuffle but the expansion is still better than scalar
13673 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13674 // we'll emit a shuffle and a arithmetic shift.
13675 // TODO: It is possible to support ZExt by zeroing the undef values during
13676 // the shuffle phase or after the shuffle.
13677 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13678                                  SelectionDAG &DAG) {
13679   MVT RegVT = Op.getSimpleValueType();
13680   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13681   assert(RegVT.isInteger() &&
13682          "We only custom lower integer vector sext loads.");
13683
13684   // Nothing useful we can do without SSE2 shuffles.
13685   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13686
13687   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13688   SDLoc dl(Ld);
13689   EVT MemVT = Ld->getMemoryVT();
13690   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13691   unsigned RegSz = RegVT.getSizeInBits();
13692
13693   ISD::LoadExtType Ext = Ld->getExtensionType();
13694
13695   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13696          && "Only anyext and sext are currently implemented.");
13697   assert(MemVT != RegVT && "Cannot extend to the same type");
13698   assert(MemVT.isVector() && "Must load a vector from memory");
13699
13700   unsigned NumElems = RegVT.getVectorNumElements();
13701   unsigned MemSz = MemVT.getSizeInBits();
13702   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13703
13704   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13705     // The only way in which we have a legal 256-bit vector result but not the
13706     // integer 256-bit operations needed to directly lower a sextload is if we
13707     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13708     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13709     // correctly legalized. We do this late to allow the canonical form of
13710     // sextload to persist throughout the rest of the DAG combiner -- it wants
13711     // to fold together any extensions it can, and so will fuse a sign_extend
13712     // of an sextload into a sextload targeting a wider value.
13713     SDValue Load;
13714     if (MemSz == 128) {
13715       // Just switch this to a normal load.
13716       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13717                                        "it must be a legal 128-bit vector "
13718                                        "type!");
13719       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13720                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13721                   Ld->isInvariant(), Ld->getAlignment());
13722     } else {
13723       assert(MemSz < 128 &&
13724              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13725       // Do an sext load to a 128-bit vector type. We want to use the same
13726       // number of elements, but elements half as wide. This will end up being
13727       // recursively lowered by this routine, but will succeed as we definitely
13728       // have all the necessary features if we're using AVX1.
13729       EVT HalfEltVT =
13730           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13731       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13732       Load =
13733           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13734                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13735                          Ld->isNonTemporal(), Ld->isInvariant(),
13736                          Ld->getAlignment());
13737     }
13738
13739     // Replace chain users with the new chain.
13740     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13741     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13742
13743     // Finally, do a normal sign-extend to the desired register.
13744     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13745   }
13746
13747   // All sizes must be a power of two.
13748   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13749          "Non-power-of-two elements are not custom lowered!");
13750
13751   // Attempt to load the original value using scalar loads.
13752   // Find the largest scalar type that divides the total loaded size.
13753   MVT SclrLoadTy = MVT::i8;
13754   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13755        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13756     MVT Tp = (MVT::SimpleValueType)tp;
13757     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13758       SclrLoadTy = Tp;
13759     }
13760   }
13761
13762   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13763   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13764       (64 <= MemSz))
13765     SclrLoadTy = MVT::f64;
13766
13767   // Calculate the number of scalar loads that we need to perform
13768   // in order to load our vector from memory.
13769   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13770
13771   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13772          "Can only lower sext loads with a single scalar load!");
13773
13774   unsigned loadRegZize = RegSz;
13775   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13776     loadRegZize /= 2;
13777
13778   // Represent our vector as a sequence of elements which are the
13779   // largest scalar that we can load.
13780   EVT LoadUnitVecVT = EVT::getVectorVT(
13781       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13782
13783   // Represent the data using the same element type that is stored in
13784   // memory. In practice, we ''widen'' MemVT.
13785   EVT WideVecVT =
13786       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13787                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13788
13789   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13790          "Invalid vector type");
13791
13792   // We can't shuffle using an illegal type.
13793   assert(TLI.isTypeLegal(WideVecVT) &&
13794          "We only lower types that form legal widened vector types");
13795
13796   SmallVector<SDValue, 8> Chains;
13797   SDValue Ptr = Ld->getBasePtr();
13798   SDValue Increment =
13799       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13800   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13801
13802   for (unsigned i = 0; i < NumLoads; ++i) {
13803     // Perform a single load.
13804     SDValue ScalarLoad =
13805         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13806                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13807                     Ld->getAlignment());
13808     Chains.push_back(ScalarLoad.getValue(1));
13809     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13810     // another round of DAGCombining.
13811     if (i == 0)
13812       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13813     else
13814       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13815                         ScalarLoad, DAG.getIntPtrConstant(i));
13816
13817     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13818   }
13819
13820   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13821
13822   // Bitcast the loaded value to a vector of the original element type, in
13823   // the size of the target vector type.
13824   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13825   unsigned SizeRatio = RegSz / MemSz;
13826
13827   if (Ext == ISD::SEXTLOAD) {
13828     // If we have SSE4.1, we can directly emit a VSEXT node.
13829     if (Subtarget->hasSSE41()) {
13830       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13831       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13832       return Sext;
13833     }
13834
13835     // Otherwise we'll shuffle the small elements in the high bits of the
13836     // larger type and perform an arithmetic shift. If the shift is not legal
13837     // it's better to scalarize.
13838     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13839            "We can't implement a sext load without an arithmetic right shift!");
13840
13841     // Redistribute the loaded elements into the different locations.
13842     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13843     for (unsigned i = 0; i != NumElems; ++i)
13844       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13845
13846     SDValue Shuff = DAG.getVectorShuffle(
13847         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13848
13849     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13850
13851     // Build the arithmetic shift.
13852     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13853                    MemVT.getVectorElementType().getSizeInBits();
13854     Shuff =
13855         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13856
13857     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13858     return Shuff;
13859   }
13860
13861   // Redistribute the loaded elements into the different locations.
13862   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13863   for (unsigned i = 0; i != NumElems; ++i)
13864     ShuffleVec[i * SizeRatio] = i;
13865
13866   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13867                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13868
13869   // Bitcast to the requested type.
13870   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13871   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13872   return Shuff;
13873 }
13874
13875 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13876 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13877 // from the AND / OR.
13878 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13879   Opc = Op.getOpcode();
13880   if (Opc != ISD::OR && Opc != ISD::AND)
13881     return false;
13882   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13883           Op.getOperand(0).hasOneUse() &&
13884           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13885           Op.getOperand(1).hasOneUse());
13886 }
13887
13888 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13889 // 1 and that the SETCC node has a single use.
13890 static bool isXor1OfSetCC(SDValue Op) {
13891   if (Op.getOpcode() != ISD::XOR)
13892     return false;
13893   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13894   if (N1C && N1C->getAPIntValue() == 1) {
13895     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13896       Op.getOperand(0).hasOneUse();
13897   }
13898   return false;
13899 }
13900
13901 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13902   bool addTest = true;
13903   SDValue Chain = Op.getOperand(0);
13904   SDValue Cond  = Op.getOperand(1);
13905   SDValue Dest  = Op.getOperand(2);
13906   SDLoc dl(Op);
13907   SDValue CC;
13908   bool Inverted = false;
13909
13910   if (Cond.getOpcode() == ISD::SETCC) {
13911     // Check for setcc([su]{add,sub,mul}o == 0).
13912     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13913         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13914         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13915         Cond.getOperand(0).getResNo() == 1 &&
13916         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13917          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13918          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13919          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13920          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13921          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13922       Inverted = true;
13923       Cond = Cond.getOperand(0);
13924     } else {
13925       SDValue NewCond = LowerSETCC(Cond, DAG);
13926       if (NewCond.getNode())
13927         Cond = NewCond;
13928     }
13929   }
13930 #if 0
13931   // FIXME: LowerXALUO doesn't handle these!!
13932   else if (Cond.getOpcode() == X86ISD::ADD  ||
13933            Cond.getOpcode() == X86ISD::SUB  ||
13934            Cond.getOpcode() == X86ISD::SMUL ||
13935            Cond.getOpcode() == X86ISD::UMUL)
13936     Cond = LowerXALUO(Cond, DAG);
13937 #endif
13938
13939   // Look pass (and (setcc_carry (cmp ...)), 1).
13940   if (Cond.getOpcode() == ISD::AND &&
13941       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13942     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13943     if (C && C->getAPIntValue() == 1)
13944       Cond = Cond.getOperand(0);
13945   }
13946
13947   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13948   // setting operand in place of the X86ISD::SETCC.
13949   unsigned CondOpcode = Cond.getOpcode();
13950   if (CondOpcode == X86ISD::SETCC ||
13951       CondOpcode == X86ISD::SETCC_CARRY) {
13952     CC = Cond.getOperand(0);
13953
13954     SDValue Cmp = Cond.getOperand(1);
13955     unsigned Opc = Cmp.getOpcode();
13956     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13957     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13958       Cond = Cmp;
13959       addTest = false;
13960     } else {
13961       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13962       default: break;
13963       case X86::COND_O:
13964       case X86::COND_B:
13965         // These can only come from an arithmetic instruction with overflow,
13966         // e.g. SADDO, UADDO.
13967         Cond = Cond.getNode()->getOperand(1);
13968         addTest = false;
13969         break;
13970       }
13971     }
13972   }
13973   CondOpcode = Cond.getOpcode();
13974   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13975       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13976       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13977        Cond.getOperand(0).getValueType() != MVT::i8)) {
13978     SDValue LHS = Cond.getOperand(0);
13979     SDValue RHS = Cond.getOperand(1);
13980     unsigned X86Opcode;
13981     unsigned X86Cond;
13982     SDVTList VTs;
13983     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13984     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13985     // X86ISD::INC).
13986     switch (CondOpcode) {
13987     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13988     case ISD::SADDO:
13989       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13990         if (C->isOne()) {
13991           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13992           break;
13993         }
13994       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13995     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13996     case ISD::SSUBO:
13997       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13998         if (C->isOne()) {
13999           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14000           break;
14001         }
14002       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14003     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14004     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14005     default: llvm_unreachable("unexpected overflowing operator");
14006     }
14007     if (Inverted)
14008       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14009     if (CondOpcode == ISD::UMULO)
14010       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14011                           MVT::i32);
14012     else
14013       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14014
14015     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14016
14017     if (CondOpcode == ISD::UMULO)
14018       Cond = X86Op.getValue(2);
14019     else
14020       Cond = X86Op.getValue(1);
14021
14022     CC = DAG.getConstant(X86Cond, MVT::i8);
14023     addTest = false;
14024   } else {
14025     unsigned CondOpc;
14026     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14027       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14028       if (CondOpc == ISD::OR) {
14029         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14030         // two branches instead of an explicit OR instruction with a
14031         // separate test.
14032         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14033             isX86LogicalCmp(Cmp)) {
14034           CC = Cond.getOperand(0).getOperand(0);
14035           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14036                               Chain, Dest, CC, Cmp);
14037           CC = Cond.getOperand(1).getOperand(0);
14038           Cond = Cmp;
14039           addTest = false;
14040         }
14041       } else { // ISD::AND
14042         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14043         // two branches instead of an explicit AND instruction with a
14044         // separate test. However, we only do this if this block doesn't
14045         // have a fall-through edge, because this requires an explicit
14046         // jmp when the condition is false.
14047         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14048             isX86LogicalCmp(Cmp) &&
14049             Op.getNode()->hasOneUse()) {
14050           X86::CondCode CCode =
14051             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14052           CCode = X86::GetOppositeBranchCondition(CCode);
14053           CC = DAG.getConstant(CCode, MVT::i8);
14054           SDNode *User = *Op.getNode()->use_begin();
14055           // Look for an unconditional branch following this conditional branch.
14056           // We need this because we need to reverse the successors in order
14057           // to implement FCMP_OEQ.
14058           if (User->getOpcode() == ISD::BR) {
14059             SDValue FalseBB = User->getOperand(1);
14060             SDNode *NewBR =
14061               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14062             assert(NewBR == User);
14063             (void)NewBR;
14064             Dest = FalseBB;
14065
14066             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14067                                 Chain, Dest, CC, Cmp);
14068             X86::CondCode CCode =
14069               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14070             CCode = X86::GetOppositeBranchCondition(CCode);
14071             CC = DAG.getConstant(CCode, MVT::i8);
14072             Cond = Cmp;
14073             addTest = false;
14074           }
14075         }
14076       }
14077     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14078       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14079       // It should be transformed during dag combiner except when the condition
14080       // is set by a arithmetics with overflow node.
14081       X86::CondCode CCode =
14082         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14083       CCode = X86::GetOppositeBranchCondition(CCode);
14084       CC = DAG.getConstant(CCode, MVT::i8);
14085       Cond = Cond.getOperand(0).getOperand(1);
14086       addTest = false;
14087     } else if (Cond.getOpcode() == ISD::SETCC &&
14088                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14089       // For FCMP_OEQ, we can emit
14090       // two branches instead of an explicit AND instruction with a
14091       // separate test. However, we only do this if this block doesn't
14092       // have a fall-through edge, because this requires an explicit
14093       // jmp when the condition is false.
14094       if (Op.getNode()->hasOneUse()) {
14095         SDNode *User = *Op.getNode()->use_begin();
14096         // Look for an unconditional branch following this conditional branch.
14097         // We need this because we need to reverse the successors in order
14098         // to implement FCMP_OEQ.
14099         if (User->getOpcode() == ISD::BR) {
14100           SDValue FalseBB = User->getOperand(1);
14101           SDNode *NewBR =
14102             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14103           assert(NewBR == User);
14104           (void)NewBR;
14105           Dest = FalseBB;
14106
14107           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14108                                     Cond.getOperand(0), Cond.getOperand(1));
14109           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14110           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14111           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14112                               Chain, Dest, CC, Cmp);
14113           CC = DAG.getConstant(X86::COND_P, MVT::i8);
14114           Cond = Cmp;
14115           addTest = false;
14116         }
14117       }
14118     } else if (Cond.getOpcode() == ISD::SETCC &&
14119                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14120       // For FCMP_UNE, we can emit
14121       // two branches instead of an explicit AND instruction with a
14122       // separate test. However, we only do this if this block doesn't
14123       // have a fall-through edge, because this requires an explicit
14124       // jmp when the condition is false.
14125       if (Op.getNode()->hasOneUse()) {
14126         SDNode *User = *Op.getNode()->use_begin();
14127         // Look for an unconditional branch following this conditional branch.
14128         // We need this because we need to reverse the successors in order
14129         // to implement FCMP_UNE.
14130         if (User->getOpcode() == ISD::BR) {
14131           SDValue FalseBB = User->getOperand(1);
14132           SDNode *NewBR =
14133             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14134           assert(NewBR == User);
14135           (void)NewBR;
14136
14137           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14138                                     Cond.getOperand(0), Cond.getOperand(1));
14139           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14140           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14141           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14142                               Chain, Dest, CC, Cmp);
14143           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14144           Cond = Cmp;
14145           addTest = false;
14146           Dest = FalseBB;
14147         }
14148       }
14149     }
14150   }
14151
14152   if (addTest) {
14153     // Look pass the truncate if the high bits are known zero.
14154     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14155         Cond = Cond.getOperand(0);
14156
14157     // We know the result of AND is compared against zero. Try to match
14158     // it to BT.
14159     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14160       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14161       if (NewSetCC.getNode()) {
14162         CC = NewSetCC.getOperand(0);
14163         Cond = NewSetCC.getOperand(1);
14164         addTest = false;
14165       }
14166     }
14167   }
14168
14169   if (addTest) {
14170     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14171     CC = DAG.getConstant(X86Cond, MVT::i8);
14172     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14173   }
14174   Cond = ConvertCmpIfNecessary(Cond, DAG);
14175   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14176                      Chain, Dest, CC, Cond);
14177 }
14178
14179 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14180 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14181 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14182 // that the guard pages used by the OS virtual memory manager are allocated in
14183 // correct sequence.
14184 SDValue
14185 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14186                                            SelectionDAG &DAG) const {
14187   MachineFunction &MF = DAG.getMachineFunction();
14188   bool SplitStack = MF.shouldSplitStack();
14189   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14190                SplitStack;
14191   SDLoc dl(Op);
14192
14193   if (!Lower) {
14194     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14195     SDNode* Node = Op.getNode();
14196
14197     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14198     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14199         " not tell us which reg is the stack pointer!");
14200     EVT VT = Node->getValueType(0);
14201     SDValue Tmp1 = SDValue(Node, 0);
14202     SDValue Tmp2 = SDValue(Node, 1);
14203     SDValue Tmp3 = Node->getOperand(2);
14204     SDValue Chain = Tmp1.getOperand(0);
14205
14206     // Chain the dynamic stack allocation so that it doesn't modify the stack
14207     // pointer when other instructions are using the stack.
14208     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14209         SDLoc(Node));
14210
14211     SDValue Size = Tmp2.getOperand(1);
14212     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14213     Chain = SP.getValue(1);
14214     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14215     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14216     unsigned StackAlign = TFI.getStackAlignment();
14217     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14218     if (Align > StackAlign)
14219       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14220           DAG.getConstant(-(uint64_t)Align, VT));
14221     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14222
14223     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14224         DAG.getIntPtrConstant(0, true), SDValue(),
14225         SDLoc(Node));
14226
14227     SDValue Ops[2] = { Tmp1, Tmp2 };
14228     return DAG.getMergeValues(Ops, dl);
14229   }
14230
14231   // Get the inputs.
14232   SDValue Chain = Op.getOperand(0);
14233   SDValue Size  = Op.getOperand(1);
14234   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14235   EVT VT = Op.getNode()->getValueType(0);
14236
14237   bool Is64Bit = Subtarget->is64Bit();
14238   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14239
14240   if (SplitStack) {
14241     MachineRegisterInfo &MRI = MF.getRegInfo();
14242
14243     if (Is64Bit) {
14244       // The 64 bit implementation of segmented stacks needs to clobber both r10
14245       // r11. This makes it impossible to use it along with nested parameters.
14246       const Function *F = MF.getFunction();
14247
14248       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14249            I != E; ++I)
14250         if (I->hasNestAttr())
14251           report_fatal_error("Cannot use segmented stacks with functions that "
14252                              "have nested arguments.");
14253     }
14254
14255     const TargetRegisterClass *AddrRegClass =
14256       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14257     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14258     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14259     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14260                                 DAG.getRegister(Vreg, SPTy));
14261     SDValue Ops1[2] = { Value, Chain };
14262     return DAG.getMergeValues(Ops1, dl);
14263   } else {
14264     SDValue Flag;
14265     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14266
14267     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14268     Flag = Chain.getValue(1);
14269     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14270
14271     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14272
14273     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14274         DAG.getSubtarget().getRegisterInfo());
14275     unsigned SPReg = RegInfo->getStackRegister();
14276     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14277     Chain = SP.getValue(1);
14278
14279     if (Align) {
14280       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14281                        DAG.getConstant(-(uint64_t)Align, VT));
14282       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14283     }
14284
14285     SDValue Ops1[2] = { SP, Chain };
14286     return DAG.getMergeValues(Ops1, dl);
14287   }
14288 }
14289
14290 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14291   MachineFunction &MF = DAG.getMachineFunction();
14292   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14293
14294   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14295   SDLoc DL(Op);
14296
14297   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14298     // vastart just stores the address of the VarArgsFrameIndex slot into the
14299     // memory location argument.
14300     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14301                                    getPointerTy());
14302     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14303                         MachinePointerInfo(SV), false, false, 0);
14304   }
14305
14306   // __va_list_tag:
14307   //   gp_offset         (0 - 6 * 8)
14308   //   fp_offset         (48 - 48 + 8 * 16)
14309   //   overflow_arg_area (point to parameters coming in memory).
14310   //   reg_save_area
14311   SmallVector<SDValue, 8> MemOps;
14312   SDValue FIN = Op.getOperand(1);
14313   // Store gp_offset
14314   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14315                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14316                                                MVT::i32),
14317                                FIN, MachinePointerInfo(SV), false, false, 0);
14318   MemOps.push_back(Store);
14319
14320   // Store fp_offset
14321   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14322                     FIN, DAG.getIntPtrConstant(4));
14323   Store = DAG.getStore(Op.getOperand(0), DL,
14324                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14325                                        MVT::i32),
14326                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14327   MemOps.push_back(Store);
14328
14329   // Store ptr to overflow_arg_area
14330   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14331                     FIN, DAG.getIntPtrConstant(4));
14332   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14333                                     getPointerTy());
14334   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14335                        MachinePointerInfo(SV, 8),
14336                        false, false, 0);
14337   MemOps.push_back(Store);
14338
14339   // Store ptr to reg_save_area.
14340   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14341                     FIN, DAG.getIntPtrConstant(8));
14342   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14343                                     getPointerTy());
14344   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14345                        MachinePointerInfo(SV, 16), false, false, 0);
14346   MemOps.push_back(Store);
14347   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14348 }
14349
14350 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14351   assert(Subtarget->is64Bit() &&
14352          "LowerVAARG only handles 64-bit va_arg!");
14353   assert((Subtarget->isTargetLinux() ||
14354           Subtarget->isTargetDarwin()) &&
14355           "Unhandled target in LowerVAARG");
14356   assert(Op.getNode()->getNumOperands() == 4);
14357   SDValue Chain = Op.getOperand(0);
14358   SDValue SrcPtr = Op.getOperand(1);
14359   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14360   unsigned Align = Op.getConstantOperandVal(3);
14361   SDLoc dl(Op);
14362
14363   EVT ArgVT = Op.getNode()->getValueType(0);
14364   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14365   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14366   uint8_t ArgMode;
14367
14368   // Decide which area this value should be read from.
14369   // TODO: Implement the AMD64 ABI in its entirety. This simple
14370   // selection mechanism works only for the basic types.
14371   if (ArgVT == MVT::f80) {
14372     llvm_unreachable("va_arg for f80 not yet implemented");
14373   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14374     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14375   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14376     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14377   } else {
14378     llvm_unreachable("Unhandled argument type in LowerVAARG");
14379   }
14380
14381   if (ArgMode == 2) {
14382     // Sanity Check: Make sure using fp_offset makes sense.
14383     assert(!DAG.getTarget().Options.UseSoftFloat &&
14384            !(DAG.getMachineFunction()
14385                 .getFunction()->getAttributes()
14386                 .hasAttribute(AttributeSet::FunctionIndex,
14387                               Attribute::NoImplicitFloat)) &&
14388            Subtarget->hasSSE1());
14389   }
14390
14391   // Insert VAARG_64 node into the DAG
14392   // VAARG_64 returns two values: Variable Argument Address, Chain
14393   SmallVector<SDValue, 11> InstOps;
14394   InstOps.push_back(Chain);
14395   InstOps.push_back(SrcPtr);
14396   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14397   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14398   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14399   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14400   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14401                                           VTs, InstOps, MVT::i64,
14402                                           MachinePointerInfo(SV),
14403                                           /*Align=*/0,
14404                                           /*Volatile=*/false,
14405                                           /*ReadMem=*/true,
14406                                           /*WriteMem=*/true);
14407   Chain = VAARG.getValue(1);
14408
14409   // Load the next argument and return it
14410   return DAG.getLoad(ArgVT, dl,
14411                      Chain,
14412                      VAARG,
14413                      MachinePointerInfo(),
14414                      false, false, false, 0);
14415 }
14416
14417 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14418                            SelectionDAG &DAG) {
14419   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14420   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14421   SDValue Chain = Op.getOperand(0);
14422   SDValue DstPtr = Op.getOperand(1);
14423   SDValue SrcPtr = Op.getOperand(2);
14424   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14425   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14426   SDLoc DL(Op);
14427
14428   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14429                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14430                        false,
14431                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14432 }
14433
14434 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14435 // amount is a constant. Takes immediate version of shift as input.
14436 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14437                                           SDValue SrcOp, uint64_t ShiftAmt,
14438                                           SelectionDAG &DAG) {
14439   MVT ElementType = VT.getVectorElementType();
14440
14441   // Fold this packed shift into its first operand if ShiftAmt is 0.
14442   if (ShiftAmt == 0)
14443     return SrcOp;
14444
14445   // Check for ShiftAmt >= element width
14446   if (ShiftAmt >= ElementType.getSizeInBits()) {
14447     if (Opc == X86ISD::VSRAI)
14448       ShiftAmt = ElementType.getSizeInBits() - 1;
14449     else
14450       return DAG.getConstant(0, VT);
14451   }
14452
14453   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14454          && "Unknown target vector shift-by-constant node");
14455
14456   // Fold this packed vector shift into a build vector if SrcOp is a
14457   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14458   if (VT == SrcOp.getSimpleValueType() &&
14459       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14460     SmallVector<SDValue, 8> Elts;
14461     unsigned NumElts = SrcOp->getNumOperands();
14462     ConstantSDNode *ND;
14463
14464     switch(Opc) {
14465     default: llvm_unreachable(nullptr);
14466     case X86ISD::VSHLI:
14467       for (unsigned i=0; i!=NumElts; ++i) {
14468         SDValue CurrentOp = SrcOp->getOperand(i);
14469         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14470           Elts.push_back(CurrentOp);
14471           continue;
14472         }
14473         ND = cast<ConstantSDNode>(CurrentOp);
14474         const APInt &C = ND->getAPIntValue();
14475         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14476       }
14477       break;
14478     case X86ISD::VSRLI:
14479       for (unsigned i=0; i!=NumElts; ++i) {
14480         SDValue CurrentOp = SrcOp->getOperand(i);
14481         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14482           Elts.push_back(CurrentOp);
14483           continue;
14484         }
14485         ND = cast<ConstantSDNode>(CurrentOp);
14486         const APInt &C = ND->getAPIntValue();
14487         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14488       }
14489       break;
14490     case X86ISD::VSRAI:
14491       for (unsigned i=0; i!=NumElts; ++i) {
14492         SDValue CurrentOp = SrcOp->getOperand(i);
14493         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14494           Elts.push_back(CurrentOp);
14495           continue;
14496         }
14497         ND = cast<ConstantSDNode>(CurrentOp);
14498         const APInt &C = ND->getAPIntValue();
14499         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14500       }
14501       break;
14502     }
14503
14504     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14505   }
14506
14507   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14508 }
14509
14510 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14511 // may or may not be a constant. Takes immediate version of shift as input.
14512 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14513                                    SDValue SrcOp, SDValue ShAmt,
14514                                    SelectionDAG &DAG) {
14515   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14516
14517   // Catch shift-by-constant.
14518   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14519     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14520                                       CShAmt->getZExtValue(), DAG);
14521
14522   // Change opcode to non-immediate version
14523   switch (Opc) {
14524     default: llvm_unreachable("Unknown target vector shift node");
14525     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14526     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14527     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14528   }
14529
14530   // Need to build a vector containing shift amount
14531   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14532   SDValue ShOps[4];
14533   ShOps[0] = ShAmt;
14534   ShOps[1] = DAG.getConstant(0, MVT::i32);
14535   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14536   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14537
14538   // The return type has to be a 128-bit type with the same element
14539   // type as the input type.
14540   MVT EltVT = VT.getVectorElementType();
14541   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14542
14543   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14544   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14545 }
14546
14547 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14548 /// necessary casting for \p Mask when lowering masking intrinsics.
14549 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14550                                     SDValue PreservedSrc, SelectionDAG &DAG) {
14551     EVT VT = Op.getValueType();
14552     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14553                                   MVT::i1, VT.getVectorNumElements());
14554     SDLoc dl(Op);
14555
14556     assert(MaskVT.isSimple() && "invalid mask type");
14557     return DAG.getNode(ISD::VSELECT, dl, VT,
14558                        DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14559                        Op, PreservedSrc);
14560 }
14561
14562 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14563     switch (IntNo) {
14564     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14565     case Intrinsic::x86_fma_vfmadd_ps:
14566     case Intrinsic::x86_fma_vfmadd_pd:
14567     case Intrinsic::x86_fma_vfmadd_ps_256:
14568     case Intrinsic::x86_fma_vfmadd_pd_256:
14569     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14570     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14571       return X86ISD::FMADD;
14572     case Intrinsic::x86_fma_vfmsub_ps:
14573     case Intrinsic::x86_fma_vfmsub_pd:
14574     case Intrinsic::x86_fma_vfmsub_ps_256:
14575     case Intrinsic::x86_fma_vfmsub_pd_256:
14576     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14577     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14578       return X86ISD::FMSUB;
14579     case Intrinsic::x86_fma_vfnmadd_ps:
14580     case Intrinsic::x86_fma_vfnmadd_pd:
14581     case Intrinsic::x86_fma_vfnmadd_ps_256:
14582     case Intrinsic::x86_fma_vfnmadd_pd_256:
14583     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14584     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14585       return X86ISD::FNMADD;
14586     case Intrinsic::x86_fma_vfnmsub_ps:
14587     case Intrinsic::x86_fma_vfnmsub_pd:
14588     case Intrinsic::x86_fma_vfnmsub_ps_256:
14589     case Intrinsic::x86_fma_vfnmsub_pd_256:
14590     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14591     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14592       return X86ISD::FNMSUB;
14593     case Intrinsic::x86_fma_vfmaddsub_ps:
14594     case Intrinsic::x86_fma_vfmaddsub_pd:
14595     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14596     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14597     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14598     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14599       return X86ISD::FMADDSUB;
14600     case Intrinsic::x86_fma_vfmsubadd_ps:
14601     case Intrinsic::x86_fma_vfmsubadd_pd:
14602     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14603     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14604     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14605     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14606       return X86ISD::FMSUBADD;
14607     }
14608 }
14609
14610 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14611   SDLoc dl(Op);
14612   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14613
14614   const IntrinsicData* IntrData = GetIntrinsicWithoutChain(IntNo);
14615   if (IntrData) {
14616     switch(IntrData->Type) {
14617     case INTR_TYPE_1OP:
14618       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14619     case INTR_TYPE_2OP:
14620       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14621         Op.getOperand(2));
14622     case INTR_TYPE_3OP:
14623       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14624         Op.getOperand(2), Op.getOperand(3));
14625     case COMI: { // Comparison intrinsics
14626       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14627       SDValue LHS = Op.getOperand(1);
14628       SDValue RHS = Op.getOperand(2);
14629       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14630       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14631       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14632       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14633                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14634       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14635     }
14636     case VSHIFT:
14637       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14638                                  Op.getOperand(1), Op.getOperand(2), DAG);
14639     default:
14640       break;
14641     }
14642   }
14643
14644   switch (IntNo) {
14645   default: return SDValue();    // Don't custom lower most intrinsics.
14646
14647   // Arithmetic intrinsics.
14648   case Intrinsic::x86_sse2_pmulu_dq:
14649   case Intrinsic::x86_avx2_pmulu_dq:
14650     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14651                        Op.getOperand(1), Op.getOperand(2));
14652
14653   case Intrinsic::x86_sse41_pmuldq:
14654   case Intrinsic::x86_avx2_pmul_dq:
14655     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14656                        Op.getOperand(1), Op.getOperand(2));
14657
14658   case Intrinsic::x86_sse2_pmulhu_w:
14659   case Intrinsic::x86_avx2_pmulhu_w:
14660     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14661                        Op.getOperand(1), Op.getOperand(2));
14662
14663   case Intrinsic::x86_sse2_pmulh_w:
14664   case Intrinsic::x86_avx2_pmulh_w:
14665     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14666                        Op.getOperand(1), Op.getOperand(2));
14667
14668   // SSE/SSE2/AVX floating point max/min intrinsics.
14669   case Intrinsic::x86_sse_max_ps:
14670   case Intrinsic::x86_sse2_max_pd:
14671   case Intrinsic::x86_avx_max_ps_256:
14672   case Intrinsic::x86_avx_max_pd_256:
14673   case Intrinsic::x86_sse_min_ps:
14674   case Intrinsic::x86_sse2_min_pd:
14675   case Intrinsic::x86_avx_min_ps_256:
14676   case Intrinsic::x86_avx_min_pd_256: {
14677     unsigned Opcode;
14678     switch (IntNo) {
14679     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14680     case Intrinsic::x86_sse_max_ps:
14681     case Intrinsic::x86_sse2_max_pd:
14682     case Intrinsic::x86_avx_max_ps_256:
14683     case Intrinsic::x86_avx_max_pd_256:
14684       Opcode = X86ISD::FMAX;
14685       break;
14686     case Intrinsic::x86_sse_min_ps:
14687     case Intrinsic::x86_sse2_min_pd:
14688     case Intrinsic::x86_avx_min_ps_256:
14689     case Intrinsic::x86_avx_min_pd_256:
14690       Opcode = X86ISD::FMIN;
14691       break;
14692     }
14693     return DAG.getNode(Opcode, dl, Op.getValueType(),
14694                        Op.getOperand(1), Op.getOperand(2));
14695   }
14696
14697   // AVX2 variable shift intrinsics
14698   case Intrinsic::x86_avx2_psllv_d:
14699   case Intrinsic::x86_avx2_psllv_q:
14700   case Intrinsic::x86_avx2_psllv_d_256:
14701   case Intrinsic::x86_avx2_psllv_q_256:
14702   case Intrinsic::x86_avx2_psrlv_d:
14703   case Intrinsic::x86_avx2_psrlv_q:
14704   case Intrinsic::x86_avx2_psrlv_d_256:
14705   case Intrinsic::x86_avx2_psrlv_q_256:
14706   case Intrinsic::x86_avx2_psrav_d:
14707   case Intrinsic::x86_avx2_psrav_d_256: {
14708     unsigned Opcode;
14709     switch (IntNo) {
14710     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14711     case Intrinsic::x86_avx2_psllv_d:
14712     case Intrinsic::x86_avx2_psllv_q:
14713     case Intrinsic::x86_avx2_psllv_d_256:
14714     case Intrinsic::x86_avx2_psllv_q_256:
14715       Opcode = ISD::SHL;
14716       break;
14717     case Intrinsic::x86_avx2_psrlv_d:
14718     case Intrinsic::x86_avx2_psrlv_q:
14719     case Intrinsic::x86_avx2_psrlv_d_256:
14720     case Intrinsic::x86_avx2_psrlv_q_256:
14721       Opcode = ISD::SRL;
14722       break;
14723     case Intrinsic::x86_avx2_psrav_d:
14724     case Intrinsic::x86_avx2_psrav_d_256:
14725       Opcode = ISD::SRA;
14726       break;
14727     }
14728     return DAG.getNode(Opcode, dl, Op.getValueType(),
14729                        Op.getOperand(1), Op.getOperand(2));
14730   }
14731
14732   case Intrinsic::x86_sse2_packssdw_128:
14733   case Intrinsic::x86_sse2_packsswb_128:
14734   case Intrinsic::x86_avx2_packssdw:
14735   case Intrinsic::x86_avx2_packsswb:
14736     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14737                        Op.getOperand(1), Op.getOperand(2));
14738
14739   case Intrinsic::x86_sse2_packuswb_128:
14740   case Intrinsic::x86_sse41_packusdw:
14741   case Intrinsic::x86_avx2_packuswb:
14742   case Intrinsic::x86_avx2_packusdw:
14743     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14744                        Op.getOperand(1), Op.getOperand(2));
14745
14746   case Intrinsic::x86_ssse3_pshuf_b_128:
14747   case Intrinsic::x86_avx2_pshuf_b:
14748     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14749                        Op.getOperand(1), Op.getOperand(2));
14750
14751   case Intrinsic::x86_sse2_pshuf_d:
14752     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14753                        Op.getOperand(1), Op.getOperand(2));
14754
14755   case Intrinsic::x86_sse2_pshufl_w:
14756     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14757                        Op.getOperand(1), Op.getOperand(2));
14758
14759   case Intrinsic::x86_sse2_pshufh_w:
14760     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14761                        Op.getOperand(1), Op.getOperand(2));
14762
14763   case Intrinsic::x86_ssse3_psign_b_128:
14764   case Intrinsic::x86_ssse3_psign_w_128:
14765   case Intrinsic::x86_ssse3_psign_d_128:
14766   case Intrinsic::x86_avx2_psign_b:
14767   case Intrinsic::x86_avx2_psign_w:
14768   case Intrinsic::x86_avx2_psign_d:
14769     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14770                        Op.getOperand(1), Op.getOperand(2));
14771
14772   case Intrinsic::x86_avx2_permd:
14773   case Intrinsic::x86_avx2_permps:
14774     // Operands intentionally swapped. Mask is last operand to intrinsic,
14775     // but second operand for node/instruction.
14776     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14777                        Op.getOperand(2), Op.getOperand(1));
14778
14779   case Intrinsic::x86_avx512_mask_valign_q_512:
14780   case Intrinsic::x86_avx512_mask_valign_d_512:
14781     // Vector source operands are swapped.
14782     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14783                                             Op.getValueType(), Op.getOperand(2),
14784                                             Op.getOperand(1),
14785                                             Op.getOperand(3)),
14786                                 Op.getOperand(5), Op.getOperand(4), DAG);
14787
14788   // ptest and testp intrinsics. The intrinsic these come from are designed to
14789   // return an integer value, not just an instruction so lower it to the ptest
14790   // or testp pattern and a setcc for the result.
14791   case Intrinsic::x86_sse41_ptestz:
14792   case Intrinsic::x86_sse41_ptestc:
14793   case Intrinsic::x86_sse41_ptestnzc:
14794   case Intrinsic::x86_avx_ptestz_256:
14795   case Intrinsic::x86_avx_ptestc_256:
14796   case Intrinsic::x86_avx_ptestnzc_256:
14797   case Intrinsic::x86_avx_vtestz_ps:
14798   case Intrinsic::x86_avx_vtestc_ps:
14799   case Intrinsic::x86_avx_vtestnzc_ps:
14800   case Intrinsic::x86_avx_vtestz_pd:
14801   case Intrinsic::x86_avx_vtestc_pd:
14802   case Intrinsic::x86_avx_vtestnzc_pd:
14803   case Intrinsic::x86_avx_vtestz_ps_256:
14804   case Intrinsic::x86_avx_vtestc_ps_256:
14805   case Intrinsic::x86_avx_vtestnzc_ps_256:
14806   case Intrinsic::x86_avx_vtestz_pd_256:
14807   case Intrinsic::x86_avx_vtestc_pd_256:
14808   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14809     bool IsTestPacked = false;
14810     unsigned X86CC;
14811     switch (IntNo) {
14812     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14813     case Intrinsic::x86_avx_vtestz_ps:
14814     case Intrinsic::x86_avx_vtestz_pd:
14815     case Intrinsic::x86_avx_vtestz_ps_256:
14816     case Intrinsic::x86_avx_vtestz_pd_256:
14817       IsTestPacked = true; // Fallthrough
14818     case Intrinsic::x86_sse41_ptestz:
14819     case Intrinsic::x86_avx_ptestz_256:
14820       // ZF = 1
14821       X86CC = X86::COND_E;
14822       break;
14823     case Intrinsic::x86_avx_vtestc_ps:
14824     case Intrinsic::x86_avx_vtestc_pd:
14825     case Intrinsic::x86_avx_vtestc_ps_256:
14826     case Intrinsic::x86_avx_vtestc_pd_256:
14827       IsTestPacked = true; // Fallthrough
14828     case Intrinsic::x86_sse41_ptestc:
14829     case Intrinsic::x86_avx_ptestc_256:
14830       // CF = 1
14831       X86CC = X86::COND_B;
14832       break;
14833     case Intrinsic::x86_avx_vtestnzc_ps:
14834     case Intrinsic::x86_avx_vtestnzc_pd:
14835     case Intrinsic::x86_avx_vtestnzc_ps_256:
14836     case Intrinsic::x86_avx_vtestnzc_pd_256:
14837       IsTestPacked = true; // Fallthrough
14838     case Intrinsic::x86_sse41_ptestnzc:
14839     case Intrinsic::x86_avx_ptestnzc_256:
14840       // ZF and CF = 0
14841       X86CC = X86::COND_A;
14842       break;
14843     }
14844
14845     SDValue LHS = Op.getOperand(1);
14846     SDValue RHS = Op.getOperand(2);
14847     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14848     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14849     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14850     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14851     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14852   }
14853   case Intrinsic::x86_avx512_kortestz_w:
14854   case Intrinsic::x86_avx512_kortestc_w: {
14855     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14856     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14857     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14858     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14859     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14860     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14861     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14862   }
14863
14864   case Intrinsic::x86_sse42_pcmpistria128:
14865   case Intrinsic::x86_sse42_pcmpestria128:
14866   case Intrinsic::x86_sse42_pcmpistric128:
14867   case Intrinsic::x86_sse42_pcmpestric128:
14868   case Intrinsic::x86_sse42_pcmpistrio128:
14869   case Intrinsic::x86_sse42_pcmpestrio128:
14870   case Intrinsic::x86_sse42_pcmpistris128:
14871   case Intrinsic::x86_sse42_pcmpestris128:
14872   case Intrinsic::x86_sse42_pcmpistriz128:
14873   case Intrinsic::x86_sse42_pcmpestriz128: {
14874     unsigned Opcode;
14875     unsigned X86CC;
14876     switch (IntNo) {
14877     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14878     case Intrinsic::x86_sse42_pcmpistria128:
14879       Opcode = X86ISD::PCMPISTRI;
14880       X86CC = X86::COND_A;
14881       break;
14882     case Intrinsic::x86_sse42_pcmpestria128:
14883       Opcode = X86ISD::PCMPESTRI;
14884       X86CC = X86::COND_A;
14885       break;
14886     case Intrinsic::x86_sse42_pcmpistric128:
14887       Opcode = X86ISD::PCMPISTRI;
14888       X86CC = X86::COND_B;
14889       break;
14890     case Intrinsic::x86_sse42_pcmpestric128:
14891       Opcode = X86ISD::PCMPESTRI;
14892       X86CC = X86::COND_B;
14893       break;
14894     case Intrinsic::x86_sse42_pcmpistrio128:
14895       Opcode = X86ISD::PCMPISTRI;
14896       X86CC = X86::COND_O;
14897       break;
14898     case Intrinsic::x86_sse42_pcmpestrio128:
14899       Opcode = X86ISD::PCMPESTRI;
14900       X86CC = X86::COND_O;
14901       break;
14902     case Intrinsic::x86_sse42_pcmpistris128:
14903       Opcode = X86ISD::PCMPISTRI;
14904       X86CC = X86::COND_S;
14905       break;
14906     case Intrinsic::x86_sse42_pcmpestris128:
14907       Opcode = X86ISD::PCMPESTRI;
14908       X86CC = X86::COND_S;
14909       break;
14910     case Intrinsic::x86_sse42_pcmpistriz128:
14911       Opcode = X86ISD::PCMPISTRI;
14912       X86CC = X86::COND_E;
14913       break;
14914     case Intrinsic::x86_sse42_pcmpestriz128:
14915       Opcode = X86ISD::PCMPESTRI;
14916       X86CC = X86::COND_E;
14917       break;
14918     }
14919     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14920     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14921     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14922     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14923                                 DAG.getConstant(X86CC, MVT::i8),
14924                                 SDValue(PCMP.getNode(), 1));
14925     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14926   }
14927
14928   case Intrinsic::x86_sse42_pcmpistri128:
14929   case Intrinsic::x86_sse42_pcmpestri128: {
14930     unsigned Opcode;
14931     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14932       Opcode = X86ISD::PCMPISTRI;
14933     else
14934       Opcode = X86ISD::PCMPESTRI;
14935
14936     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14937     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14938     return DAG.getNode(Opcode, dl, VTs, NewOps);
14939   }
14940
14941   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14942   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14943   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14944   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14945   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14946   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14947   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14948   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14949   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14950   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14951   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14952   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
14953     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
14954     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
14955       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
14956                                               dl, Op.getValueType(),
14957                                               Op.getOperand(1),
14958                                               Op.getOperand(2),
14959                                               Op.getOperand(3)),
14960                                   Op.getOperand(4), Op.getOperand(1), DAG);
14961     else
14962       return SDValue();
14963   }
14964
14965   case Intrinsic::x86_fma_vfmadd_ps:
14966   case Intrinsic::x86_fma_vfmadd_pd:
14967   case Intrinsic::x86_fma_vfmsub_ps:
14968   case Intrinsic::x86_fma_vfmsub_pd:
14969   case Intrinsic::x86_fma_vfnmadd_ps:
14970   case Intrinsic::x86_fma_vfnmadd_pd:
14971   case Intrinsic::x86_fma_vfnmsub_ps:
14972   case Intrinsic::x86_fma_vfnmsub_pd:
14973   case Intrinsic::x86_fma_vfmaddsub_ps:
14974   case Intrinsic::x86_fma_vfmaddsub_pd:
14975   case Intrinsic::x86_fma_vfmsubadd_ps:
14976   case Intrinsic::x86_fma_vfmsubadd_pd:
14977   case Intrinsic::x86_fma_vfmadd_ps_256:
14978   case Intrinsic::x86_fma_vfmadd_pd_256:
14979   case Intrinsic::x86_fma_vfmsub_ps_256:
14980   case Intrinsic::x86_fma_vfmsub_pd_256:
14981   case Intrinsic::x86_fma_vfnmadd_ps_256:
14982   case Intrinsic::x86_fma_vfnmadd_pd_256:
14983   case Intrinsic::x86_fma_vfnmsub_ps_256:
14984   case Intrinsic::x86_fma_vfnmsub_pd_256:
14985   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14986   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14987   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14988   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14989     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
14990                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14991   }
14992 }
14993
14994 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14995                               SDValue Src, SDValue Mask, SDValue Base,
14996                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14997                               const X86Subtarget * Subtarget) {
14998   SDLoc dl(Op);
14999   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15000   assert(C && "Invalid scale type");
15001   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15002   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15003                              Index.getSimpleValueType().getVectorNumElements());
15004   SDValue MaskInReg;
15005   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15006   if (MaskC)
15007     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15008   else
15009     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15010   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15011   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15012   SDValue Segment = DAG.getRegister(0, MVT::i32);
15013   if (Src.getOpcode() == ISD::UNDEF)
15014     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15015   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15016   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15017   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15018   return DAG.getMergeValues(RetOps, dl);
15019 }
15020
15021 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15022                                SDValue Src, SDValue Mask, SDValue Base,
15023                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15024   SDLoc dl(Op);
15025   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15026   assert(C && "Invalid scale type");
15027   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15028   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15029   SDValue Segment = DAG.getRegister(0, MVT::i32);
15030   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15031                              Index.getSimpleValueType().getVectorNumElements());
15032   SDValue MaskInReg;
15033   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15034   if (MaskC)
15035     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15036   else
15037     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15038   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15039   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15040   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15041   return SDValue(Res, 1);
15042 }
15043
15044 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15045                                SDValue Mask, SDValue Base, SDValue Index,
15046                                SDValue ScaleOp, SDValue Chain) {
15047   SDLoc dl(Op);
15048   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15049   assert(C && "Invalid scale type");
15050   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15051   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15052   SDValue Segment = DAG.getRegister(0, MVT::i32);
15053   EVT MaskVT =
15054     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15055   SDValue MaskInReg;
15056   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15057   if (MaskC)
15058     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15059   else
15060     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15061   //SDVTList VTs = DAG.getVTList(MVT::Other);
15062   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15063   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15064   return SDValue(Res, 0);
15065 }
15066
15067 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15068 // read performance monitor counters (x86_rdpmc).
15069 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15070                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15071                               SmallVectorImpl<SDValue> &Results) {
15072   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15073   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15074   SDValue LO, HI;
15075
15076   // The ECX register is used to select the index of the performance counter
15077   // to read.
15078   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15079                                    N->getOperand(2));
15080   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15081
15082   // Reads the content of a 64-bit performance counter and returns it in the
15083   // registers EDX:EAX.
15084   if (Subtarget->is64Bit()) {
15085     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15086     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15087                             LO.getValue(2));
15088   } else {
15089     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15090     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15091                             LO.getValue(2));
15092   }
15093   Chain = HI.getValue(1);
15094
15095   if (Subtarget->is64Bit()) {
15096     // The EAX register is loaded with the low-order 32 bits. The EDX register
15097     // is loaded with the supported high-order bits of the counter.
15098     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15099                               DAG.getConstant(32, MVT::i8));
15100     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15101     Results.push_back(Chain);
15102     return;
15103   }
15104
15105   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15106   SDValue Ops[] = { LO, HI };
15107   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15108   Results.push_back(Pair);
15109   Results.push_back(Chain);
15110 }
15111
15112 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15113 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15114 // also used to custom lower READCYCLECOUNTER nodes.
15115 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15116                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15117                               SmallVectorImpl<SDValue> &Results) {
15118   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15119   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15120   SDValue LO, HI;
15121
15122   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15123   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15124   // and the EAX register is loaded with the low-order 32 bits.
15125   if (Subtarget->is64Bit()) {
15126     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15127     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15128                             LO.getValue(2));
15129   } else {
15130     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15131     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15132                             LO.getValue(2));
15133   }
15134   SDValue Chain = HI.getValue(1);
15135
15136   if (Opcode == X86ISD::RDTSCP_DAG) {
15137     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15138
15139     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15140     // the ECX register. Add 'ecx' explicitly to the chain.
15141     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15142                                      HI.getValue(2));
15143     // Explicitly store the content of ECX at the location passed in input
15144     // to the 'rdtscp' intrinsic.
15145     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15146                          MachinePointerInfo(), false, false, 0);
15147   }
15148
15149   if (Subtarget->is64Bit()) {
15150     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15151     // the EAX register is loaded with the low-order 32 bits.
15152     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15153                               DAG.getConstant(32, MVT::i8));
15154     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15155     Results.push_back(Chain);
15156     return;
15157   }
15158
15159   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15160   SDValue Ops[] = { LO, HI };
15161   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15162   Results.push_back(Pair);
15163   Results.push_back(Chain);
15164 }
15165
15166 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15167                                      SelectionDAG &DAG) {
15168   SmallVector<SDValue, 2> Results;
15169   SDLoc DL(Op);
15170   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15171                           Results);
15172   return DAG.getMergeValues(Results, DL);
15173 }
15174
15175
15176 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15177                                       SelectionDAG &DAG) {
15178   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15179
15180   const IntrinsicData* IntrData = GetIntrinsicWithChain(IntNo);
15181   if (!IntrData)
15182     return SDValue();
15183
15184   SDLoc dl(Op);
15185   switch(IntrData->Type) {
15186   default:
15187     llvm_unreachable("Unknown Intrinsic Type");
15188     break;    
15189   case RDSEED:
15190   case RDRAND: {
15191     // Emit the node with the right value type.
15192     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15193     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15194
15195     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15196     // Otherwise return the value from Rand, which is always 0, casted to i32.
15197     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15198                       DAG.getConstant(1, Op->getValueType(1)),
15199                       DAG.getConstant(X86::COND_B, MVT::i32),
15200                       SDValue(Result.getNode(), 1) };
15201     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15202                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15203                                   Ops);
15204
15205     // Return { result, isValid, chain }.
15206     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15207                        SDValue(Result.getNode(), 2));
15208   }
15209   case GATHER: {
15210   //gather(v1, mask, index, base, scale);
15211     SDValue Chain = Op.getOperand(0);
15212     SDValue Src   = Op.getOperand(2);
15213     SDValue Base  = Op.getOperand(3);
15214     SDValue Index = Op.getOperand(4);
15215     SDValue Mask  = Op.getOperand(5);
15216     SDValue Scale = Op.getOperand(6);
15217     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15218                           Subtarget);
15219   }
15220   case SCATTER: {
15221   //scatter(base, mask, index, v1, scale);
15222     SDValue Chain = Op.getOperand(0);
15223     SDValue Base  = Op.getOperand(2);
15224     SDValue Mask  = Op.getOperand(3);
15225     SDValue Index = Op.getOperand(4);
15226     SDValue Src   = Op.getOperand(5);
15227     SDValue Scale = Op.getOperand(6);
15228     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15229   }
15230   case PREFETCH: {
15231     SDValue Hint = Op.getOperand(6);
15232     unsigned HintVal;
15233     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15234         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15235       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15236     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15237     SDValue Chain = Op.getOperand(0);
15238     SDValue Mask  = Op.getOperand(2);
15239     SDValue Index = Op.getOperand(3);
15240     SDValue Base  = Op.getOperand(4);
15241     SDValue Scale = Op.getOperand(5);
15242     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15243   }
15244   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15245   case RDTSC: {
15246     SmallVector<SDValue, 2> Results;
15247     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15248     return DAG.getMergeValues(Results, dl);
15249   }
15250   // Read Performance Monitoring Counters.
15251   case RDPMC: {
15252     SmallVector<SDValue, 2> Results;
15253     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15254     return DAG.getMergeValues(Results, dl);
15255   }
15256   // XTEST intrinsics.
15257   case XTEST: {
15258     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15259     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15260     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15261                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15262                                 InTrans);
15263     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15264     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15265                        Ret, SDValue(InTrans.getNode(), 1));
15266   }
15267   // ADC/ADCX/SBB
15268   case ADX: {
15269     SmallVector<SDValue, 2> Results;
15270     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15271     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15272     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15273                                 DAG.getConstant(-1, MVT::i8));
15274     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15275                               Op.getOperand(4), GenCF.getValue(1));
15276     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15277                                  Op.getOperand(5), MachinePointerInfo(),
15278                                  false, false, 0);
15279     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15280                                 DAG.getConstant(X86::COND_B, MVT::i8),
15281                                 Res.getValue(1));
15282     Results.push_back(SetCC);
15283     Results.push_back(Store);
15284     return DAG.getMergeValues(Results, dl);
15285   }
15286   }
15287 }
15288
15289 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15290                                            SelectionDAG &DAG) const {
15291   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15292   MFI->setReturnAddressIsTaken(true);
15293
15294   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15295     return SDValue();
15296
15297   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15298   SDLoc dl(Op);
15299   EVT PtrVT = getPointerTy();
15300
15301   if (Depth > 0) {
15302     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15303     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15304         DAG.getSubtarget().getRegisterInfo());
15305     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15306     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15307                        DAG.getNode(ISD::ADD, dl, PtrVT,
15308                                    FrameAddr, Offset),
15309                        MachinePointerInfo(), false, false, false, 0);
15310   }
15311
15312   // Just load the return address.
15313   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15314   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15315                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15316 }
15317
15318 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15319   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15320   MFI->setFrameAddressIsTaken(true);
15321
15322   EVT VT = Op.getValueType();
15323   SDLoc dl(Op);  // FIXME probably not meaningful
15324   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15325   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15326       DAG.getSubtarget().getRegisterInfo());
15327   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15328   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15329           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15330          "Invalid Frame Register!");
15331   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15332   while (Depth--)
15333     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15334                             MachinePointerInfo(),
15335                             false, false, false, 0);
15336   return FrameAddr;
15337 }
15338
15339 // FIXME? Maybe this could be a TableGen attribute on some registers and
15340 // this table could be generated automatically from RegInfo.
15341 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15342                                               EVT VT) const {
15343   unsigned Reg = StringSwitch<unsigned>(RegName)
15344                        .Case("esp", X86::ESP)
15345                        .Case("rsp", X86::RSP)
15346                        .Default(0);
15347   if (Reg)
15348     return Reg;
15349   report_fatal_error("Invalid register name global variable");
15350 }
15351
15352 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15353                                                      SelectionDAG &DAG) const {
15354   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15355       DAG.getSubtarget().getRegisterInfo());
15356   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15357 }
15358
15359 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15360   SDValue Chain     = Op.getOperand(0);
15361   SDValue Offset    = Op.getOperand(1);
15362   SDValue Handler   = Op.getOperand(2);
15363   SDLoc dl      (Op);
15364
15365   EVT PtrVT = getPointerTy();
15366   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15367       DAG.getSubtarget().getRegisterInfo());
15368   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15369   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15370           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15371          "Invalid Frame Register!");
15372   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15373   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15374
15375   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15376                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15377   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15378   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15379                        false, false, 0);
15380   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15381
15382   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15383                      DAG.getRegister(StoreAddrReg, PtrVT));
15384 }
15385
15386 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15387                                                SelectionDAG &DAG) const {
15388   SDLoc DL(Op);
15389   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15390                      DAG.getVTList(MVT::i32, MVT::Other),
15391                      Op.getOperand(0), Op.getOperand(1));
15392 }
15393
15394 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15395                                                 SelectionDAG &DAG) const {
15396   SDLoc DL(Op);
15397   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15398                      Op.getOperand(0), Op.getOperand(1));
15399 }
15400
15401 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15402   return Op.getOperand(0);
15403 }
15404
15405 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15406                                                 SelectionDAG &DAG) const {
15407   SDValue Root = Op.getOperand(0);
15408   SDValue Trmp = Op.getOperand(1); // trampoline
15409   SDValue FPtr = Op.getOperand(2); // nested function
15410   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15411   SDLoc dl (Op);
15412
15413   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15414   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15415
15416   if (Subtarget->is64Bit()) {
15417     SDValue OutChains[6];
15418
15419     // Large code-model.
15420     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15421     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15422
15423     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15424     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15425
15426     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15427
15428     // Load the pointer to the nested function into R11.
15429     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15430     SDValue Addr = Trmp;
15431     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15432                                 Addr, MachinePointerInfo(TrmpAddr),
15433                                 false, false, 0);
15434
15435     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15436                        DAG.getConstant(2, MVT::i64));
15437     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15438                                 MachinePointerInfo(TrmpAddr, 2),
15439                                 false, false, 2);
15440
15441     // Load the 'nest' parameter value into R10.
15442     // R10 is specified in X86CallingConv.td
15443     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15444     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15445                        DAG.getConstant(10, MVT::i64));
15446     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15447                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15448                                 false, false, 0);
15449
15450     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15451                        DAG.getConstant(12, MVT::i64));
15452     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15453                                 MachinePointerInfo(TrmpAddr, 12),
15454                                 false, false, 2);
15455
15456     // Jump to the nested function.
15457     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15458     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15459                        DAG.getConstant(20, MVT::i64));
15460     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15461                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15462                                 false, false, 0);
15463
15464     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15465     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15466                        DAG.getConstant(22, MVT::i64));
15467     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15468                                 MachinePointerInfo(TrmpAddr, 22),
15469                                 false, false, 0);
15470
15471     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15472   } else {
15473     const Function *Func =
15474       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15475     CallingConv::ID CC = Func->getCallingConv();
15476     unsigned NestReg;
15477
15478     switch (CC) {
15479     default:
15480       llvm_unreachable("Unsupported calling convention");
15481     case CallingConv::C:
15482     case CallingConv::X86_StdCall: {
15483       // Pass 'nest' parameter in ECX.
15484       // Must be kept in sync with X86CallingConv.td
15485       NestReg = X86::ECX;
15486
15487       // Check that ECX wasn't needed by an 'inreg' parameter.
15488       FunctionType *FTy = Func->getFunctionType();
15489       const AttributeSet &Attrs = Func->getAttributes();
15490
15491       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15492         unsigned InRegCount = 0;
15493         unsigned Idx = 1;
15494
15495         for (FunctionType::param_iterator I = FTy->param_begin(),
15496              E = FTy->param_end(); I != E; ++I, ++Idx)
15497           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15498             // FIXME: should only count parameters that are lowered to integers.
15499             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15500
15501         if (InRegCount > 2) {
15502           report_fatal_error("Nest register in use - reduce number of inreg"
15503                              " parameters!");
15504         }
15505       }
15506       break;
15507     }
15508     case CallingConv::X86_FastCall:
15509     case CallingConv::X86_ThisCall:
15510     case CallingConv::Fast:
15511       // Pass 'nest' parameter in EAX.
15512       // Must be kept in sync with X86CallingConv.td
15513       NestReg = X86::EAX;
15514       break;
15515     }
15516
15517     SDValue OutChains[4];
15518     SDValue Addr, Disp;
15519
15520     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15521                        DAG.getConstant(10, MVT::i32));
15522     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15523
15524     // This is storing the opcode for MOV32ri.
15525     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15526     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15527     OutChains[0] = DAG.getStore(Root, dl,
15528                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15529                                 Trmp, MachinePointerInfo(TrmpAddr),
15530                                 false, false, 0);
15531
15532     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15533                        DAG.getConstant(1, MVT::i32));
15534     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15535                                 MachinePointerInfo(TrmpAddr, 1),
15536                                 false, false, 1);
15537
15538     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15539     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15540                        DAG.getConstant(5, MVT::i32));
15541     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15542                                 MachinePointerInfo(TrmpAddr, 5),
15543                                 false, false, 1);
15544
15545     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15546                        DAG.getConstant(6, MVT::i32));
15547     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15548                                 MachinePointerInfo(TrmpAddr, 6),
15549                                 false, false, 1);
15550
15551     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15552   }
15553 }
15554
15555 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15556                                             SelectionDAG &DAG) const {
15557   /*
15558    The rounding mode is in bits 11:10 of FPSR, and has the following
15559    settings:
15560      00 Round to nearest
15561      01 Round to -inf
15562      10 Round to +inf
15563      11 Round to 0
15564
15565   FLT_ROUNDS, on the other hand, expects the following:
15566     -1 Undefined
15567      0 Round to 0
15568      1 Round to nearest
15569      2 Round to +inf
15570      3 Round to -inf
15571
15572   To perform the conversion, we do:
15573     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15574   */
15575
15576   MachineFunction &MF = DAG.getMachineFunction();
15577   const TargetMachine &TM = MF.getTarget();
15578   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15579   unsigned StackAlignment = TFI.getStackAlignment();
15580   MVT VT = Op.getSimpleValueType();
15581   SDLoc DL(Op);
15582
15583   // Save FP Control Word to stack slot
15584   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15585   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15586
15587   MachineMemOperand *MMO =
15588    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15589                            MachineMemOperand::MOStore, 2, 2);
15590
15591   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15592   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15593                                           DAG.getVTList(MVT::Other),
15594                                           Ops, MVT::i16, MMO);
15595
15596   // Load FP Control Word from stack slot
15597   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15598                             MachinePointerInfo(), false, false, false, 0);
15599
15600   // Transform as necessary
15601   SDValue CWD1 =
15602     DAG.getNode(ISD::SRL, DL, MVT::i16,
15603                 DAG.getNode(ISD::AND, DL, MVT::i16,
15604                             CWD, DAG.getConstant(0x800, MVT::i16)),
15605                 DAG.getConstant(11, MVT::i8));
15606   SDValue CWD2 =
15607     DAG.getNode(ISD::SRL, DL, MVT::i16,
15608                 DAG.getNode(ISD::AND, DL, MVT::i16,
15609                             CWD, DAG.getConstant(0x400, MVT::i16)),
15610                 DAG.getConstant(9, MVT::i8));
15611
15612   SDValue RetVal =
15613     DAG.getNode(ISD::AND, DL, MVT::i16,
15614                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15615                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15616                             DAG.getConstant(1, MVT::i16)),
15617                 DAG.getConstant(3, MVT::i16));
15618
15619   return DAG.getNode((VT.getSizeInBits() < 16 ?
15620                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15621 }
15622
15623 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15624   MVT VT = Op.getSimpleValueType();
15625   EVT OpVT = VT;
15626   unsigned NumBits = VT.getSizeInBits();
15627   SDLoc dl(Op);
15628
15629   Op = Op.getOperand(0);
15630   if (VT == MVT::i8) {
15631     // Zero extend to i32 since there is not an i8 bsr.
15632     OpVT = MVT::i32;
15633     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15634   }
15635
15636   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15637   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15638   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15639
15640   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15641   SDValue Ops[] = {
15642     Op,
15643     DAG.getConstant(NumBits+NumBits-1, OpVT),
15644     DAG.getConstant(X86::COND_E, MVT::i8),
15645     Op.getValue(1)
15646   };
15647   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15648
15649   // Finally xor with NumBits-1.
15650   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15651
15652   if (VT == MVT::i8)
15653     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15654   return Op;
15655 }
15656
15657 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15658   MVT VT = Op.getSimpleValueType();
15659   EVT OpVT = VT;
15660   unsigned NumBits = VT.getSizeInBits();
15661   SDLoc dl(Op);
15662
15663   Op = Op.getOperand(0);
15664   if (VT == MVT::i8) {
15665     // Zero extend to i32 since there is not an i8 bsr.
15666     OpVT = MVT::i32;
15667     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15668   }
15669
15670   // Issue a bsr (scan bits in reverse).
15671   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15672   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15673
15674   // And xor with NumBits-1.
15675   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15676
15677   if (VT == MVT::i8)
15678     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15679   return Op;
15680 }
15681
15682 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15683   MVT VT = Op.getSimpleValueType();
15684   unsigned NumBits = VT.getSizeInBits();
15685   SDLoc dl(Op);
15686   Op = Op.getOperand(0);
15687
15688   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15689   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15690   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15691
15692   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15693   SDValue Ops[] = {
15694     Op,
15695     DAG.getConstant(NumBits, VT),
15696     DAG.getConstant(X86::COND_E, MVT::i8),
15697     Op.getValue(1)
15698   };
15699   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15700 }
15701
15702 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15703 // ones, and then concatenate the result back.
15704 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15705   MVT VT = Op.getSimpleValueType();
15706
15707   assert(VT.is256BitVector() && VT.isInteger() &&
15708          "Unsupported value type for operation");
15709
15710   unsigned NumElems = VT.getVectorNumElements();
15711   SDLoc dl(Op);
15712
15713   // Extract the LHS vectors
15714   SDValue LHS = Op.getOperand(0);
15715   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15716   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15717
15718   // Extract the RHS vectors
15719   SDValue RHS = Op.getOperand(1);
15720   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15721   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15722
15723   MVT EltVT = VT.getVectorElementType();
15724   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15725
15726   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15727                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15728                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15729 }
15730
15731 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15732   assert(Op.getSimpleValueType().is256BitVector() &&
15733          Op.getSimpleValueType().isInteger() &&
15734          "Only handle AVX 256-bit vector integer operation");
15735   return Lower256IntArith(Op, DAG);
15736 }
15737
15738 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15739   assert(Op.getSimpleValueType().is256BitVector() &&
15740          Op.getSimpleValueType().isInteger() &&
15741          "Only handle AVX 256-bit vector integer operation");
15742   return Lower256IntArith(Op, DAG);
15743 }
15744
15745 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15746                         SelectionDAG &DAG) {
15747   SDLoc dl(Op);
15748   MVT VT = Op.getSimpleValueType();
15749
15750   // Decompose 256-bit ops into smaller 128-bit ops.
15751   if (VT.is256BitVector() && !Subtarget->hasInt256())
15752     return Lower256IntArith(Op, DAG);
15753
15754   SDValue A = Op.getOperand(0);
15755   SDValue B = Op.getOperand(1);
15756
15757   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15758   if (VT == MVT::v4i32) {
15759     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15760            "Should not custom lower when pmuldq is available!");
15761
15762     // Extract the odd parts.
15763     static const int UnpackMask[] = { 1, -1, 3, -1 };
15764     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15765     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15766
15767     // Multiply the even parts.
15768     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15769     // Now multiply odd parts.
15770     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15771
15772     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15773     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15774
15775     // Merge the two vectors back together with a shuffle. This expands into 2
15776     // shuffles.
15777     static const int ShufMask[] = { 0, 4, 2, 6 };
15778     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15779   }
15780
15781   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15782          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15783
15784   //  Ahi = psrlqi(a, 32);
15785   //  Bhi = psrlqi(b, 32);
15786   //
15787   //  AloBlo = pmuludq(a, b);
15788   //  AloBhi = pmuludq(a, Bhi);
15789   //  AhiBlo = pmuludq(Ahi, b);
15790
15791   //  AloBhi = psllqi(AloBhi, 32);
15792   //  AhiBlo = psllqi(AhiBlo, 32);
15793   //  return AloBlo + AloBhi + AhiBlo;
15794
15795   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15796   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15797
15798   // Bit cast to 32-bit vectors for MULUDQ
15799   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15800                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15801   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15802   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15803   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15804   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15805
15806   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15807   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15808   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15809
15810   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15811   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15812
15813   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15814   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15815 }
15816
15817 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15818   assert(Subtarget->isTargetWin64() && "Unexpected target");
15819   EVT VT = Op.getValueType();
15820   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15821          "Unexpected return type for lowering");
15822
15823   RTLIB::Libcall LC;
15824   bool isSigned;
15825   switch (Op->getOpcode()) {
15826   default: llvm_unreachable("Unexpected request for libcall!");
15827   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15828   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15829   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15830   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15831   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15832   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15833   }
15834
15835   SDLoc dl(Op);
15836   SDValue InChain = DAG.getEntryNode();
15837
15838   TargetLowering::ArgListTy Args;
15839   TargetLowering::ArgListEntry Entry;
15840   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15841     EVT ArgVT = Op->getOperand(i).getValueType();
15842     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15843            "Unexpected argument type for lowering");
15844     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15845     Entry.Node = StackPtr;
15846     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15847                            false, false, 16);
15848     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15849     Entry.Ty = PointerType::get(ArgTy,0);
15850     Entry.isSExt = false;
15851     Entry.isZExt = false;
15852     Args.push_back(Entry);
15853   }
15854
15855   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15856                                          getPointerTy());
15857
15858   TargetLowering::CallLoweringInfo CLI(DAG);
15859   CLI.setDebugLoc(dl).setChain(InChain)
15860     .setCallee(getLibcallCallingConv(LC),
15861                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15862                Callee, std::move(Args), 0)
15863     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15864
15865   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15866   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15867 }
15868
15869 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15870                              SelectionDAG &DAG) {
15871   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15872   EVT VT = Op0.getValueType();
15873   SDLoc dl(Op);
15874
15875   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15876          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15877
15878   // PMULxD operations multiply each even value (starting at 0) of LHS with
15879   // the related value of RHS and produce a widen result.
15880   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15881   // => <2 x i64> <ae|cg>
15882   //
15883   // In other word, to have all the results, we need to perform two PMULxD:
15884   // 1. one with the even values.
15885   // 2. one with the odd values.
15886   // To achieve #2, with need to place the odd values at an even position.
15887   //
15888   // Place the odd value at an even position (basically, shift all values 1
15889   // step to the left):
15890   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15891   // <a|b|c|d> => <b|undef|d|undef>
15892   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15893   // <e|f|g|h> => <f|undef|h|undef>
15894   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15895
15896   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15897   // ints.
15898   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15899   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15900   unsigned Opcode =
15901       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15902   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15903   // => <2 x i64> <ae|cg>
15904   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15905                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15906   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15907   // => <2 x i64> <bf|dh>
15908   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15909                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15910
15911   // Shuffle it back into the right order.
15912   SDValue Highs, Lows;
15913   if (VT == MVT::v8i32) {
15914     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15915     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15916     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15917     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15918   } else {
15919     const int HighMask[] = {1, 5, 3, 7};
15920     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15921     const int LowMask[] = {0, 4, 2, 6};
15922     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15923   }
15924
15925   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15926   // unsigned multiply.
15927   if (IsSigned && !Subtarget->hasSSE41()) {
15928     SDValue ShAmt =
15929         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15930     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15931                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15932     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15933                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15934
15935     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15936     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15937   }
15938
15939   // The first result of MUL_LOHI is actually the low value, followed by the
15940   // high value.
15941   SDValue Ops[] = {Lows, Highs};
15942   return DAG.getMergeValues(Ops, dl);
15943 }
15944
15945 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15946                                          const X86Subtarget *Subtarget) {
15947   MVT VT = Op.getSimpleValueType();
15948   SDLoc dl(Op);
15949   SDValue R = Op.getOperand(0);
15950   SDValue Amt = Op.getOperand(1);
15951
15952   // Optimize shl/srl/sra with constant shift amount.
15953   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15954     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15955       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15956
15957       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15958           (Subtarget->hasInt256() &&
15959            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15960           (Subtarget->hasAVX512() &&
15961            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15962         if (Op.getOpcode() == ISD::SHL)
15963           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15964                                             DAG);
15965         if (Op.getOpcode() == ISD::SRL)
15966           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15967                                             DAG);
15968         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15969           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15970                                             DAG);
15971       }
15972
15973       if (VT == MVT::v16i8) {
15974         if (Op.getOpcode() == ISD::SHL) {
15975           // Make a large shift.
15976           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15977                                                    MVT::v8i16, R, ShiftAmt,
15978                                                    DAG);
15979           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15980           // Zero out the rightmost bits.
15981           SmallVector<SDValue, 16> V(16,
15982                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15983                                                      MVT::i8));
15984           return DAG.getNode(ISD::AND, dl, VT, SHL,
15985                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15986         }
15987         if (Op.getOpcode() == ISD::SRL) {
15988           // Make a large shift.
15989           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15990                                                    MVT::v8i16, R, ShiftAmt,
15991                                                    DAG);
15992           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15993           // Zero out the leftmost bits.
15994           SmallVector<SDValue, 16> V(16,
15995                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15996                                                      MVT::i8));
15997           return DAG.getNode(ISD::AND, dl, VT, SRL,
15998                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15999         }
16000         if (Op.getOpcode() == ISD::SRA) {
16001           if (ShiftAmt == 7) {
16002             // R s>> 7  ===  R s< 0
16003             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16004             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16005           }
16006
16007           // R s>> a === ((R u>> a) ^ m) - m
16008           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16009           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
16010                                                          MVT::i8));
16011           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16012           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16013           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16014           return Res;
16015         }
16016         llvm_unreachable("Unknown shift opcode.");
16017       }
16018
16019       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
16020         if (Op.getOpcode() == ISD::SHL) {
16021           // Make a large shift.
16022           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16023                                                    MVT::v16i16, R, ShiftAmt,
16024                                                    DAG);
16025           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16026           // Zero out the rightmost bits.
16027           SmallVector<SDValue, 32> V(32,
16028                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16029                                                      MVT::i8));
16030           return DAG.getNode(ISD::AND, dl, VT, SHL,
16031                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16032         }
16033         if (Op.getOpcode() == ISD::SRL) {
16034           // Make a large shift.
16035           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16036                                                    MVT::v16i16, R, ShiftAmt,
16037                                                    DAG);
16038           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16039           // Zero out the leftmost bits.
16040           SmallVector<SDValue, 32> V(32,
16041                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16042                                                      MVT::i8));
16043           return DAG.getNode(ISD::AND, dl, VT, SRL,
16044                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16045         }
16046         if (Op.getOpcode() == ISD::SRA) {
16047           if (ShiftAmt == 7) {
16048             // R s>> 7  ===  R s< 0
16049             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16050             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16051           }
16052
16053           // R s>> a === ((R u>> a) ^ m) - m
16054           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16055           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
16056                                                          MVT::i8));
16057           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16058           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16059           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16060           return Res;
16061         }
16062         llvm_unreachable("Unknown shift opcode.");
16063       }
16064     }
16065   }
16066
16067   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16068   if (!Subtarget->is64Bit() &&
16069       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16070       Amt.getOpcode() == ISD::BITCAST &&
16071       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16072     Amt = Amt.getOperand(0);
16073     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16074                      VT.getVectorNumElements();
16075     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16076     uint64_t ShiftAmt = 0;
16077     for (unsigned i = 0; i != Ratio; ++i) {
16078       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16079       if (!C)
16080         return SDValue();
16081       // 6 == Log2(64)
16082       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16083     }
16084     // Check remaining shift amounts.
16085     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16086       uint64_t ShAmt = 0;
16087       for (unsigned j = 0; j != Ratio; ++j) {
16088         ConstantSDNode *C =
16089           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16090         if (!C)
16091           return SDValue();
16092         // 6 == Log2(64)
16093         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16094       }
16095       if (ShAmt != ShiftAmt)
16096         return SDValue();
16097     }
16098     switch (Op.getOpcode()) {
16099     default:
16100       llvm_unreachable("Unknown shift opcode!");
16101     case ISD::SHL:
16102       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16103                                         DAG);
16104     case ISD::SRL:
16105       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16106                                         DAG);
16107     case ISD::SRA:
16108       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16109                                         DAG);
16110     }
16111   }
16112
16113   return SDValue();
16114 }
16115
16116 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16117                                         const X86Subtarget* Subtarget) {
16118   MVT VT = Op.getSimpleValueType();
16119   SDLoc dl(Op);
16120   SDValue R = Op.getOperand(0);
16121   SDValue Amt = Op.getOperand(1);
16122
16123   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16124       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16125       (Subtarget->hasInt256() &&
16126        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16127         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16128        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16129     SDValue BaseShAmt;
16130     EVT EltVT = VT.getVectorElementType();
16131
16132     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16133       unsigned NumElts = VT.getVectorNumElements();
16134       unsigned i, j;
16135       for (i = 0; i != NumElts; ++i) {
16136         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16137           continue;
16138         break;
16139       }
16140       for (j = i; j != NumElts; ++j) {
16141         SDValue Arg = Amt.getOperand(j);
16142         if (Arg.getOpcode() == ISD::UNDEF) continue;
16143         if (Arg != Amt.getOperand(i))
16144           break;
16145       }
16146       if (i != NumElts && j == NumElts)
16147         BaseShAmt = Amt.getOperand(i);
16148     } else {
16149       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16150         Amt = Amt.getOperand(0);
16151       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16152                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16153         SDValue InVec = Amt.getOperand(0);
16154         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16155           unsigned NumElts = InVec.getValueType().getVectorNumElements();
16156           unsigned i = 0;
16157           for (; i != NumElts; ++i) {
16158             SDValue Arg = InVec.getOperand(i);
16159             if (Arg.getOpcode() == ISD::UNDEF) continue;
16160             BaseShAmt = Arg;
16161             break;
16162           }
16163         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16164            if (ConstantSDNode *C =
16165                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16166              unsigned SplatIdx =
16167                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16168              if (C->getZExtValue() == SplatIdx)
16169                BaseShAmt = InVec.getOperand(1);
16170            }
16171         }
16172         if (!BaseShAmt.getNode())
16173           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16174                                   DAG.getIntPtrConstant(0));
16175       }
16176     }
16177
16178     if (BaseShAmt.getNode()) {
16179       if (EltVT.bitsGT(MVT::i32))
16180         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16181       else if (EltVT.bitsLT(MVT::i32))
16182         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16183
16184       switch (Op.getOpcode()) {
16185       default:
16186         llvm_unreachable("Unknown shift opcode!");
16187       case ISD::SHL:
16188         switch (VT.SimpleTy) {
16189         default: return SDValue();
16190         case MVT::v2i64:
16191         case MVT::v4i32:
16192         case MVT::v8i16:
16193         case MVT::v4i64:
16194         case MVT::v8i32:
16195         case MVT::v16i16:
16196         case MVT::v16i32:
16197         case MVT::v8i64:
16198           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16199         }
16200       case ISD::SRA:
16201         switch (VT.SimpleTy) {
16202         default: return SDValue();
16203         case MVT::v4i32:
16204         case MVT::v8i16:
16205         case MVT::v8i32:
16206         case MVT::v16i16:
16207         case MVT::v16i32:
16208         case MVT::v8i64:
16209           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16210         }
16211       case ISD::SRL:
16212         switch (VT.SimpleTy) {
16213         default: return SDValue();
16214         case MVT::v2i64:
16215         case MVT::v4i32:
16216         case MVT::v8i16:
16217         case MVT::v4i64:
16218         case MVT::v8i32:
16219         case MVT::v16i16:
16220         case MVT::v16i32:
16221         case MVT::v8i64:
16222           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16223         }
16224       }
16225     }
16226   }
16227
16228   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16229   if (!Subtarget->is64Bit() &&
16230       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16231       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16232       Amt.getOpcode() == ISD::BITCAST &&
16233       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16234     Amt = Amt.getOperand(0);
16235     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16236                      VT.getVectorNumElements();
16237     std::vector<SDValue> Vals(Ratio);
16238     for (unsigned i = 0; i != Ratio; ++i)
16239       Vals[i] = Amt.getOperand(i);
16240     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16241       for (unsigned j = 0; j != Ratio; ++j)
16242         if (Vals[j] != Amt.getOperand(i + j))
16243           return SDValue();
16244     }
16245     switch (Op.getOpcode()) {
16246     default:
16247       llvm_unreachable("Unknown shift opcode!");
16248     case ISD::SHL:
16249       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16250     case ISD::SRL:
16251       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16252     case ISD::SRA:
16253       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16254     }
16255   }
16256
16257   return SDValue();
16258 }
16259
16260 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16261                           SelectionDAG &DAG) {
16262   MVT VT = Op.getSimpleValueType();
16263   SDLoc dl(Op);
16264   SDValue R = Op.getOperand(0);
16265   SDValue Amt = Op.getOperand(1);
16266   SDValue V;
16267
16268   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16269   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16270
16271   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16272   if (V.getNode())
16273     return V;
16274
16275   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16276   if (V.getNode())
16277       return V;
16278
16279   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16280     return Op;
16281   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16282   if (Subtarget->hasInt256()) {
16283     if (Op.getOpcode() == ISD::SRL &&
16284         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16285          VT == MVT::v4i64 || VT == MVT::v8i32))
16286       return Op;
16287     if (Op.getOpcode() == ISD::SHL &&
16288         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16289          VT == MVT::v4i64 || VT == MVT::v8i32))
16290       return Op;
16291     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16292       return Op;
16293   }
16294
16295   // If possible, lower this packed shift into a vector multiply instead of
16296   // expanding it into a sequence of scalar shifts.
16297   // Do this only if the vector shift count is a constant build_vector.
16298   if (Op.getOpcode() == ISD::SHL && 
16299       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16300        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16301       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16302     SmallVector<SDValue, 8> Elts;
16303     EVT SVT = VT.getScalarType();
16304     unsigned SVTBits = SVT.getSizeInBits();
16305     const APInt &One = APInt(SVTBits, 1);
16306     unsigned NumElems = VT.getVectorNumElements();
16307
16308     for (unsigned i=0; i !=NumElems; ++i) {
16309       SDValue Op = Amt->getOperand(i);
16310       if (Op->getOpcode() == ISD::UNDEF) {
16311         Elts.push_back(Op);
16312         continue;
16313       }
16314
16315       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16316       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16317       uint64_t ShAmt = C.getZExtValue();
16318       if (ShAmt >= SVTBits) {
16319         Elts.push_back(DAG.getUNDEF(SVT));
16320         continue;
16321       }
16322       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16323     }
16324     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16325     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16326   }
16327
16328   // Lower SHL with variable shift amount.
16329   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16330     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16331
16332     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16333     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16334     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16335     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16336   }
16337
16338   // If possible, lower this shift as a sequence of two shifts by
16339   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16340   // Example:
16341   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16342   //
16343   // Could be rewritten as:
16344   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16345   //
16346   // The advantage is that the two shifts from the example would be
16347   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16348   // the vector shift into four scalar shifts plus four pairs of vector
16349   // insert/extract.
16350   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16351       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16352     unsigned TargetOpcode = X86ISD::MOVSS;
16353     bool CanBeSimplified;
16354     // The splat value for the first packed shift (the 'X' from the example).
16355     SDValue Amt1 = Amt->getOperand(0);
16356     // The splat value for the second packed shift (the 'Y' from the example).
16357     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16358                                         Amt->getOperand(2);
16359
16360     // See if it is possible to replace this node with a sequence of
16361     // two shifts followed by a MOVSS/MOVSD
16362     if (VT == MVT::v4i32) {
16363       // Check if it is legal to use a MOVSS.
16364       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16365                         Amt2 == Amt->getOperand(3);
16366       if (!CanBeSimplified) {
16367         // Otherwise, check if we can still simplify this node using a MOVSD.
16368         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16369                           Amt->getOperand(2) == Amt->getOperand(3);
16370         TargetOpcode = X86ISD::MOVSD;
16371         Amt2 = Amt->getOperand(2);
16372       }
16373     } else {
16374       // Do similar checks for the case where the machine value type
16375       // is MVT::v8i16.
16376       CanBeSimplified = Amt1 == Amt->getOperand(1);
16377       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16378         CanBeSimplified = Amt2 == Amt->getOperand(i);
16379
16380       if (!CanBeSimplified) {
16381         TargetOpcode = X86ISD::MOVSD;
16382         CanBeSimplified = true;
16383         Amt2 = Amt->getOperand(4);
16384         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16385           CanBeSimplified = Amt1 == Amt->getOperand(i);
16386         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16387           CanBeSimplified = Amt2 == Amt->getOperand(j);
16388       }
16389     }
16390     
16391     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16392         isa<ConstantSDNode>(Amt2)) {
16393       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16394       EVT CastVT = MVT::v4i32;
16395       SDValue Splat1 = 
16396         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16397       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16398       SDValue Splat2 = 
16399         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16400       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16401       if (TargetOpcode == X86ISD::MOVSD)
16402         CastVT = MVT::v2i64;
16403       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16404       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16405       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16406                                             BitCast1, DAG);
16407       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16408     }
16409   }
16410
16411   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16412     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16413
16414     // a = a << 5;
16415     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16416     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16417
16418     // Turn 'a' into a mask suitable for VSELECT
16419     SDValue VSelM = DAG.getConstant(0x80, VT);
16420     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16421     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16422
16423     SDValue CM1 = DAG.getConstant(0x0f, VT);
16424     SDValue CM2 = DAG.getConstant(0x3f, VT);
16425
16426     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16427     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16428     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16429     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16430     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16431
16432     // a += a
16433     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16434     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16435     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16436
16437     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16438     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16439     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16440     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16441     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16442
16443     // a += a
16444     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16445     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16446     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16447
16448     // return VSELECT(r, r+r, a);
16449     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16450                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16451     return R;
16452   }
16453
16454   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16455   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16456   // solution better.
16457   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16458     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16459     unsigned ExtOpc =
16460         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16461     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16462     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16463     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16464                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16465     }
16466
16467   // Decompose 256-bit shifts into smaller 128-bit shifts.
16468   if (VT.is256BitVector()) {
16469     unsigned NumElems = VT.getVectorNumElements();
16470     MVT EltVT = VT.getVectorElementType();
16471     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16472
16473     // Extract the two vectors
16474     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16475     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16476
16477     // Recreate the shift amount vectors
16478     SDValue Amt1, Amt2;
16479     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16480       // Constant shift amount
16481       SmallVector<SDValue, 4> Amt1Csts;
16482       SmallVector<SDValue, 4> Amt2Csts;
16483       for (unsigned i = 0; i != NumElems/2; ++i)
16484         Amt1Csts.push_back(Amt->getOperand(i));
16485       for (unsigned i = NumElems/2; i != NumElems; ++i)
16486         Amt2Csts.push_back(Amt->getOperand(i));
16487
16488       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16489       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16490     } else {
16491       // Variable shift amount
16492       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16493       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16494     }
16495
16496     // Issue new vector shifts for the smaller types
16497     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16498     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16499
16500     // Concatenate the result back
16501     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16502   }
16503
16504   return SDValue();
16505 }
16506
16507 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16508   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16509   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16510   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16511   // has only one use.
16512   SDNode *N = Op.getNode();
16513   SDValue LHS = N->getOperand(0);
16514   SDValue RHS = N->getOperand(1);
16515   unsigned BaseOp = 0;
16516   unsigned Cond = 0;
16517   SDLoc DL(Op);
16518   switch (Op.getOpcode()) {
16519   default: llvm_unreachable("Unknown ovf instruction!");
16520   case ISD::SADDO:
16521     // A subtract of one will be selected as a INC. Note that INC doesn't
16522     // set CF, so we can't do this for UADDO.
16523     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16524       if (C->isOne()) {
16525         BaseOp = X86ISD::INC;
16526         Cond = X86::COND_O;
16527         break;
16528       }
16529     BaseOp = X86ISD::ADD;
16530     Cond = X86::COND_O;
16531     break;
16532   case ISD::UADDO:
16533     BaseOp = X86ISD::ADD;
16534     Cond = X86::COND_B;
16535     break;
16536   case ISD::SSUBO:
16537     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16538     // set CF, so we can't do this for USUBO.
16539     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16540       if (C->isOne()) {
16541         BaseOp = X86ISD::DEC;
16542         Cond = X86::COND_O;
16543         break;
16544       }
16545     BaseOp = X86ISD::SUB;
16546     Cond = X86::COND_O;
16547     break;
16548   case ISD::USUBO:
16549     BaseOp = X86ISD::SUB;
16550     Cond = X86::COND_B;
16551     break;
16552   case ISD::SMULO:
16553     BaseOp = X86ISD::SMUL;
16554     Cond = X86::COND_O;
16555     break;
16556   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16557     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16558                                  MVT::i32);
16559     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16560
16561     SDValue SetCC =
16562       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16563                   DAG.getConstant(X86::COND_O, MVT::i32),
16564                   SDValue(Sum.getNode(), 2));
16565
16566     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16567   }
16568   }
16569
16570   // Also sets EFLAGS.
16571   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16572   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16573
16574   SDValue SetCC =
16575     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16576                 DAG.getConstant(Cond, MVT::i32),
16577                 SDValue(Sum.getNode(), 1));
16578
16579   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16580 }
16581
16582 // Sign extension of the low part of vector elements. This may be used either
16583 // when sign extend instructions are not available or if the vector element
16584 // sizes already match the sign-extended size. If the vector elements are in
16585 // their pre-extended size and sign extend instructions are available, that will
16586 // be handled by LowerSIGN_EXTEND.
16587 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16588                                                   SelectionDAG &DAG) const {
16589   SDLoc dl(Op);
16590   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16591   MVT VT = Op.getSimpleValueType();
16592
16593   if (!Subtarget->hasSSE2() || !VT.isVector())
16594     return SDValue();
16595
16596   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16597                       ExtraVT.getScalarType().getSizeInBits();
16598
16599   switch (VT.SimpleTy) {
16600     default: return SDValue();
16601     case MVT::v8i32:
16602     case MVT::v16i16:
16603       if (!Subtarget->hasFp256())
16604         return SDValue();
16605       if (!Subtarget->hasInt256()) {
16606         // needs to be split
16607         unsigned NumElems = VT.getVectorNumElements();
16608
16609         // Extract the LHS vectors
16610         SDValue LHS = Op.getOperand(0);
16611         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16612         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16613
16614         MVT EltVT = VT.getVectorElementType();
16615         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16616
16617         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16618         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16619         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16620                                    ExtraNumElems/2);
16621         SDValue Extra = DAG.getValueType(ExtraVT);
16622
16623         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16624         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16625
16626         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16627       }
16628       // fall through
16629     case MVT::v4i32:
16630     case MVT::v8i16: {
16631       SDValue Op0 = Op.getOperand(0);
16632
16633       // This is a sign extension of some low part of vector elements without
16634       // changing the size of the vector elements themselves:
16635       // Shift-Left + Shift-Right-Algebraic.
16636       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
16637                                                BitsDiff, DAG);
16638       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
16639                                         DAG);
16640     }
16641   }
16642 }
16643
16644 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16645                                  SelectionDAG &DAG) {
16646   SDLoc dl(Op);
16647   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16648     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16649   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16650     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16651
16652   // The only fence that needs an instruction is a sequentially-consistent
16653   // cross-thread fence.
16654   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16655     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16656     // no-sse2). There isn't any reason to disable it if the target processor
16657     // supports it.
16658     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16659       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16660
16661     SDValue Chain = Op.getOperand(0);
16662     SDValue Zero = DAG.getConstant(0, MVT::i32);
16663     SDValue Ops[] = {
16664       DAG.getRegister(X86::ESP, MVT::i32), // Base
16665       DAG.getTargetConstant(1, MVT::i8),   // Scale
16666       DAG.getRegister(0, MVT::i32),        // Index
16667       DAG.getTargetConstant(0, MVT::i32),  // Disp
16668       DAG.getRegister(0, MVT::i32),        // Segment.
16669       Zero,
16670       Chain
16671     };
16672     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16673     return SDValue(Res, 0);
16674   }
16675
16676   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16677   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16678 }
16679
16680 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16681                              SelectionDAG &DAG) {
16682   MVT T = Op.getSimpleValueType();
16683   SDLoc DL(Op);
16684   unsigned Reg = 0;
16685   unsigned size = 0;
16686   switch(T.SimpleTy) {
16687   default: llvm_unreachable("Invalid value type!");
16688   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16689   case MVT::i16: Reg = X86::AX;  size = 2; break;
16690   case MVT::i32: Reg = X86::EAX; size = 4; break;
16691   case MVT::i64:
16692     assert(Subtarget->is64Bit() && "Node not type legal!");
16693     Reg = X86::RAX; size = 8;
16694     break;
16695   }
16696   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16697                                   Op.getOperand(2), SDValue());
16698   SDValue Ops[] = { cpIn.getValue(0),
16699                     Op.getOperand(1),
16700                     Op.getOperand(3),
16701                     DAG.getTargetConstant(size, MVT::i8),
16702                     cpIn.getValue(1) };
16703   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16704   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16705   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16706                                            Ops, T, MMO);
16707
16708   SDValue cpOut =
16709     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16710   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16711                                       MVT::i32, cpOut.getValue(2));
16712   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16713                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16714
16715   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16716   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16717   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16718   return SDValue();
16719 }
16720
16721 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16722                             SelectionDAG &DAG) {
16723   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16724   MVT DstVT = Op.getSimpleValueType();
16725
16726   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16727     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16728     if (DstVT != MVT::f64)
16729       // This conversion needs to be expanded.
16730       return SDValue();
16731
16732     SDValue InVec = Op->getOperand(0);
16733     SDLoc dl(Op);
16734     unsigned NumElts = SrcVT.getVectorNumElements();
16735     EVT SVT = SrcVT.getVectorElementType();
16736
16737     // Widen the vector in input in the case of MVT::v2i32.
16738     // Example: from MVT::v2i32 to MVT::v4i32.
16739     SmallVector<SDValue, 16> Elts;
16740     for (unsigned i = 0, e = NumElts; i != e; ++i)
16741       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16742                                  DAG.getIntPtrConstant(i)));
16743
16744     // Explicitly mark the extra elements as Undef.
16745     SDValue Undef = DAG.getUNDEF(SVT);
16746     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16747       Elts.push_back(Undef);
16748
16749     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16750     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16751     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16752     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16753                        DAG.getIntPtrConstant(0));
16754   }
16755
16756   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16757          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16758   assert((DstVT == MVT::i64 ||
16759           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16760          "Unexpected custom BITCAST");
16761   // i64 <=> MMX conversions are Legal.
16762   if (SrcVT==MVT::i64 && DstVT.isVector())
16763     return Op;
16764   if (DstVT==MVT::i64 && SrcVT.isVector())
16765     return Op;
16766   // MMX <=> MMX conversions are Legal.
16767   if (SrcVT.isVector() && DstVT.isVector())
16768     return Op;
16769   // All other conversions need to be expanded.
16770   return SDValue();
16771 }
16772
16773 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16774   SDNode *Node = Op.getNode();
16775   SDLoc dl(Node);
16776   EVT T = Node->getValueType(0);
16777   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16778                               DAG.getConstant(0, T), Node->getOperand(2));
16779   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16780                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16781                        Node->getOperand(0),
16782                        Node->getOperand(1), negOp,
16783                        cast<AtomicSDNode>(Node)->getMemOperand(),
16784                        cast<AtomicSDNode>(Node)->getOrdering(),
16785                        cast<AtomicSDNode>(Node)->getSynchScope());
16786 }
16787
16788 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16789   SDNode *Node = Op.getNode();
16790   SDLoc dl(Node);
16791   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16792
16793   // Convert seq_cst store -> xchg
16794   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16795   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16796   //        (The only way to get a 16-byte store is cmpxchg16b)
16797   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16798   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16799       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16800     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16801                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16802                                  Node->getOperand(0),
16803                                  Node->getOperand(1), Node->getOperand(2),
16804                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16805                                  cast<AtomicSDNode>(Node)->getOrdering(),
16806                                  cast<AtomicSDNode>(Node)->getSynchScope());
16807     return Swap.getValue(1);
16808   }
16809   // Other atomic stores have a simple pattern.
16810   return Op;
16811 }
16812
16813 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16814   EVT VT = Op.getNode()->getSimpleValueType(0);
16815
16816   // Let legalize expand this if it isn't a legal type yet.
16817   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16818     return SDValue();
16819
16820   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16821
16822   unsigned Opc;
16823   bool ExtraOp = false;
16824   switch (Op.getOpcode()) {
16825   default: llvm_unreachable("Invalid code");
16826   case ISD::ADDC: Opc = X86ISD::ADD; break;
16827   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16828   case ISD::SUBC: Opc = X86ISD::SUB; break;
16829   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16830   }
16831
16832   if (!ExtraOp)
16833     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16834                        Op.getOperand(1));
16835   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16836                      Op.getOperand(1), Op.getOperand(2));
16837 }
16838
16839 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16840                             SelectionDAG &DAG) {
16841   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16842
16843   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16844   // which returns the values as { float, float } (in XMM0) or
16845   // { double, double } (which is returned in XMM0, XMM1).
16846   SDLoc dl(Op);
16847   SDValue Arg = Op.getOperand(0);
16848   EVT ArgVT = Arg.getValueType();
16849   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16850
16851   TargetLowering::ArgListTy Args;
16852   TargetLowering::ArgListEntry Entry;
16853
16854   Entry.Node = Arg;
16855   Entry.Ty = ArgTy;
16856   Entry.isSExt = false;
16857   Entry.isZExt = false;
16858   Args.push_back(Entry);
16859
16860   bool isF64 = ArgVT == MVT::f64;
16861   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16862   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16863   // the results are returned via SRet in memory.
16864   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16866   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16867
16868   Type *RetTy = isF64
16869     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16870     : (Type*)VectorType::get(ArgTy, 4);
16871
16872   TargetLowering::CallLoweringInfo CLI(DAG);
16873   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16874     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16875
16876   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16877
16878   if (isF64)
16879     // Returned in xmm0 and xmm1.
16880     return CallResult.first;
16881
16882   // Returned in bits 0:31 and 32:64 xmm0.
16883   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16884                                CallResult.first, DAG.getIntPtrConstant(0));
16885   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16886                                CallResult.first, DAG.getIntPtrConstant(1));
16887   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16888   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16889 }
16890
16891 /// LowerOperation - Provide custom lowering hooks for some operations.
16892 ///
16893 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16894   switch (Op.getOpcode()) {
16895   default: llvm_unreachable("Should not custom lower this!");
16896   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16897   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16898   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16899     return LowerCMP_SWAP(Op, Subtarget, DAG);
16900   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16901   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16902   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16903   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16904   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16905   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16906   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16907   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16908   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16909   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16910   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16911   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16912   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16913   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16914   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16915   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16916   case ISD::SHL_PARTS:
16917   case ISD::SRA_PARTS:
16918   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16919   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16920   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16921   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16922   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16923   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16924   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16925   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16926   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16927   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16928   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16929   case ISD::FABS:
16930   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
16931   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16932   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16933   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16934   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16935   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16936   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16937   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16938   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16939   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16940   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16941   case ISD::INTRINSIC_VOID:
16942   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16943   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16944   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16945   case ISD::FRAME_TO_ARGS_OFFSET:
16946                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16947   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16948   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16949   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16950   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16951   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16952   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16953   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16954   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16955   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16956   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16957   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16958   case ISD::UMUL_LOHI:
16959   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16960   case ISD::SRA:
16961   case ISD::SRL:
16962   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16963   case ISD::SADDO:
16964   case ISD::UADDO:
16965   case ISD::SSUBO:
16966   case ISD::USUBO:
16967   case ISD::SMULO:
16968   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16969   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16970   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16971   case ISD::ADDC:
16972   case ISD::ADDE:
16973   case ISD::SUBC:
16974   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16975   case ISD::ADD:                return LowerADD(Op, DAG);
16976   case ISD::SUB:                return LowerSUB(Op, DAG);
16977   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16978   }
16979 }
16980
16981 static void ReplaceATOMIC_LOAD(SDNode *Node,
16982                                SmallVectorImpl<SDValue> &Results,
16983                                SelectionDAG &DAG) {
16984   SDLoc dl(Node);
16985   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16986
16987   // Convert wide load -> cmpxchg8b/cmpxchg16b
16988   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16989   //        (The only way to get a 16-byte load is cmpxchg16b)
16990   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16991   SDValue Zero = DAG.getConstant(0, VT);
16992   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16993   SDValue Swap =
16994       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16995                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16996                            cast<AtomicSDNode>(Node)->getMemOperand(),
16997                            cast<AtomicSDNode>(Node)->getOrdering(),
16998                            cast<AtomicSDNode>(Node)->getOrdering(),
16999                            cast<AtomicSDNode>(Node)->getSynchScope());
17000   Results.push_back(Swap.getValue(0));
17001   Results.push_back(Swap.getValue(2));
17002 }
17003
17004 /// ReplaceNodeResults - Replace a node with an illegal result type
17005 /// with a new node built out of custom code.
17006 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17007                                            SmallVectorImpl<SDValue>&Results,
17008                                            SelectionDAG &DAG) const {
17009   SDLoc dl(N);
17010   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17011   switch (N->getOpcode()) {
17012   default:
17013     llvm_unreachable("Do not know how to custom type legalize this operation!");
17014   case ISD::SIGN_EXTEND_INREG:
17015   case ISD::ADDC:
17016   case ISD::ADDE:
17017   case ISD::SUBC:
17018   case ISD::SUBE:
17019     // We don't want to expand or promote these.
17020     return;
17021   case ISD::SDIV:
17022   case ISD::UDIV:
17023   case ISD::SREM:
17024   case ISD::UREM:
17025   case ISD::SDIVREM:
17026   case ISD::UDIVREM: {
17027     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17028     Results.push_back(V);
17029     return;
17030   }
17031   case ISD::FP_TO_SINT:
17032   case ISD::FP_TO_UINT: {
17033     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17034
17035     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17036       return;
17037
17038     std::pair<SDValue,SDValue> Vals =
17039         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17040     SDValue FIST = Vals.first, StackSlot = Vals.second;
17041     if (FIST.getNode()) {
17042       EVT VT = N->getValueType(0);
17043       // Return a load from the stack slot.
17044       if (StackSlot.getNode())
17045         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17046                                       MachinePointerInfo(),
17047                                       false, false, false, 0));
17048       else
17049         Results.push_back(FIST);
17050     }
17051     return;
17052   }
17053   case ISD::UINT_TO_FP: {
17054     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17055     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17056         N->getValueType(0) != MVT::v2f32)
17057       return;
17058     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17059                                  N->getOperand(0));
17060     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17061                                      MVT::f64);
17062     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17063     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17064                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17065     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17066     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17067     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17068     return;
17069   }
17070   case ISD::FP_ROUND: {
17071     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17072         return;
17073     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17074     Results.push_back(V);
17075     return;
17076   }
17077   case ISD::INTRINSIC_W_CHAIN: {
17078     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17079     switch (IntNo) {
17080     default : llvm_unreachable("Do not know how to custom type "
17081                                "legalize this intrinsic operation!");
17082     case Intrinsic::x86_rdtsc:
17083       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17084                                      Results);
17085     case Intrinsic::x86_rdtscp:
17086       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17087                                      Results);
17088     case Intrinsic::x86_rdpmc:
17089       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17090     }
17091   }
17092   case ISD::READCYCLECOUNTER: {
17093     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17094                                    Results);
17095   }
17096   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17097     EVT T = N->getValueType(0);
17098     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17099     bool Regs64bit = T == MVT::i128;
17100     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17101     SDValue cpInL, cpInH;
17102     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17103                         DAG.getConstant(0, HalfT));
17104     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17105                         DAG.getConstant(1, HalfT));
17106     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17107                              Regs64bit ? X86::RAX : X86::EAX,
17108                              cpInL, SDValue());
17109     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17110                              Regs64bit ? X86::RDX : X86::EDX,
17111                              cpInH, cpInL.getValue(1));
17112     SDValue swapInL, swapInH;
17113     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17114                           DAG.getConstant(0, HalfT));
17115     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17116                           DAG.getConstant(1, HalfT));
17117     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17118                                Regs64bit ? X86::RBX : X86::EBX,
17119                                swapInL, cpInH.getValue(1));
17120     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17121                                Regs64bit ? X86::RCX : X86::ECX,
17122                                swapInH, swapInL.getValue(1));
17123     SDValue Ops[] = { swapInH.getValue(0),
17124                       N->getOperand(1),
17125                       swapInH.getValue(1) };
17126     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17127     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17128     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17129                                   X86ISD::LCMPXCHG8_DAG;
17130     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17131     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17132                                         Regs64bit ? X86::RAX : X86::EAX,
17133                                         HalfT, Result.getValue(1));
17134     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17135                                         Regs64bit ? X86::RDX : X86::EDX,
17136                                         HalfT, cpOutL.getValue(2));
17137     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17138
17139     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17140                                         MVT::i32, cpOutH.getValue(2));
17141     SDValue Success =
17142         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17143                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17144     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17145
17146     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17147     Results.push_back(Success);
17148     Results.push_back(EFLAGS.getValue(1));
17149     return;
17150   }
17151   case ISD::ATOMIC_SWAP:
17152   case ISD::ATOMIC_LOAD_ADD:
17153   case ISD::ATOMIC_LOAD_SUB:
17154   case ISD::ATOMIC_LOAD_AND:
17155   case ISD::ATOMIC_LOAD_OR:
17156   case ISD::ATOMIC_LOAD_XOR:
17157   case ISD::ATOMIC_LOAD_NAND:
17158   case ISD::ATOMIC_LOAD_MIN:
17159   case ISD::ATOMIC_LOAD_MAX:
17160   case ISD::ATOMIC_LOAD_UMIN:
17161   case ISD::ATOMIC_LOAD_UMAX:
17162     // Delegate to generic TypeLegalization. Situations we can really handle
17163     // should have already been dealt with by X86AtomicExpandPass.cpp.
17164     break;
17165   case ISD::ATOMIC_LOAD: {
17166     ReplaceATOMIC_LOAD(N, Results, DAG);
17167     return;
17168   }
17169   case ISD::BITCAST: {
17170     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17171     EVT DstVT = N->getValueType(0);
17172     EVT SrcVT = N->getOperand(0)->getValueType(0);
17173
17174     if (SrcVT != MVT::f64 ||
17175         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17176       return;
17177
17178     unsigned NumElts = DstVT.getVectorNumElements();
17179     EVT SVT = DstVT.getVectorElementType();
17180     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17181     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17182                                    MVT::v2f64, N->getOperand(0));
17183     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17184
17185     if (ExperimentalVectorWideningLegalization) {
17186       // If we are legalizing vectors by widening, we already have the desired
17187       // legal vector type, just return it.
17188       Results.push_back(ToVecInt);
17189       return;
17190     }
17191
17192     SmallVector<SDValue, 8> Elts;
17193     for (unsigned i = 0, e = NumElts; i != e; ++i)
17194       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17195                                    ToVecInt, DAG.getIntPtrConstant(i)));
17196
17197     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17198   }
17199   }
17200 }
17201
17202 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17203   switch (Opcode) {
17204   default: return nullptr;
17205   case X86ISD::BSF:                return "X86ISD::BSF";
17206   case X86ISD::BSR:                return "X86ISD::BSR";
17207   case X86ISD::SHLD:               return "X86ISD::SHLD";
17208   case X86ISD::SHRD:               return "X86ISD::SHRD";
17209   case X86ISD::FAND:               return "X86ISD::FAND";
17210   case X86ISD::FANDN:              return "X86ISD::FANDN";
17211   case X86ISD::FOR:                return "X86ISD::FOR";
17212   case X86ISD::FXOR:               return "X86ISD::FXOR";
17213   case X86ISD::FSRL:               return "X86ISD::FSRL";
17214   case X86ISD::FILD:               return "X86ISD::FILD";
17215   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17216   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17217   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17218   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17219   case X86ISD::FLD:                return "X86ISD::FLD";
17220   case X86ISD::FST:                return "X86ISD::FST";
17221   case X86ISD::CALL:               return "X86ISD::CALL";
17222   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17223   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17224   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17225   case X86ISD::BT:                 return "X86ISD::BT";
17226   case X86ISD::CMP:                return "X86ISD::CMP";
17227   case X86ISD::COMI:               return "X86ISD::COMI";
17228   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17229   case X86ISD::CMPM:               return "X86ISD::CMPM";
17230   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17231   case X86ISD::SETCC:              return "X86ISD::SETCC";
17232   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17233   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17234   case X86ISD::CMOV:               return "X86ISD::CMOV";
17235   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17236   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17237   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17238   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17239   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17240   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17241   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17242   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17243   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17244   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17245   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17246   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17247   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17248   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17249   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17250   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17251   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17252   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17253   case X86ISD::HADD:               return "X86ISD::HADD";
17254   case X86ISD::HSUB:               return "X86ISD::HSUB";
17255   case X86ISD::FHADD:              return "X86ISD::FHADD";
17256   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17257   case X86ISD::UMAX:               return "X86ISD::UMAX";
17258   case X86ISD::UMIN:               return "X86ISD::UMIN";
17259   case X86ISD::SMAX:               return "X86ISD::SMAX";
17260   case X86ISD::SMIN:               return "X86ISD::SMIN";
17261   case X86ISD::FMAX:               return "X86ISD::FMAX";
17262   case X86ISD::FMIN:               return "X86ISD::FMIN";
17263   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17264   case X86ISD::FMINC:              return "X86ISD::FMINC";
17265   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17266   case X86ISD::FRCP:               return "X86ISD::FRCP";
17267   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17268   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17269   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17270   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17271   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17272   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17273   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17274   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17275   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17276   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17277   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17278   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17279   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17280   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17281   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17282   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17283   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17284   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17285   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17286   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17287   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17288   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17289   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17290   case X86ISD::VSHL:               return "X86ISD::VSHL";
17291   case X86ISD::VSRL:               return "X86ISD::VSRL";
17292   case X86ISD::VSRA:               return "X86ISD::VSRA";
17293   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17294   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17295   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17296   case X86ISD::CMPP:               return "X86ISD::CMPP";
17297   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17298   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17299   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17300   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17301   case X86ISD::ADD:                return "X86ISD::ADD";
17302   case X86ISD::SUB:                return "X86ISD::SUB";
17303   case X86ISD::ADC:                return "X86ISD::ADC";
17304   case X86ISD::SBB:                return "X86ISD::SBB";
17305   case X86ISD::SMUL:               return "X86ISD::SMUL";
17306   case X86ISD::UMUL:               return "X86ISD::UMUL";
17307   case X86ISD::INC:                return "X86ISD::INC";
17308   case X86ISD::DEC:                return "X86ISD::DEC";
17309   case X86ISD::OR:                 return "X86ISD::OR";
17310   case X86ISD::XOR:                return "X86ISD::XOR";
17311   case X86ISD::AND:                return "X86ISD::AND";
17312   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17313   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17314   case X86ISD::PTEST:              return "X86ISD::PTEST";
17315   case X86ISD::TESTP:              return "X86ISD::TESTP";
17316   case X86ISD::TESTM:              return "X86ISD::TESTM";
17317   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17318   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17319   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17320   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17321   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17322   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17323   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17324   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17325   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17326   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17327   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17328   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17329   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17330   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17331   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17332   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17333   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17334   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17335   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17336   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17337   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17338   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17339   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17340   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17341   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17342   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17343   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17344   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17345   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17346   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17347   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17348   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17349   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17350   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17351   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17352   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17353   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17354   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17355   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17356   case X86ISD::SAHF:               return "X86ISD::SAHF";
17357   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17358   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17359   case X86ISD::FMADD:              return "X86ISD::FMADD";
17360   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17361   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17362   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17363   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17364   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17365   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17366   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17367   case X86ISD::XTEST:              return "X86ISD::XTEST";
17368   }
17369 }
17370
17371 // isLegalAddressingMode - Return true if the addressing mode represented
17372 // by AM is legal for this target, for a load/store of the specified type.
17373 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17374                                               Type *Ty) const {
17375   // X86 supports extremely general addressing modes.
17376   CodeModel::Model M = getTargetMachine().getCodeModel();
17377   Reloc::Model R = getTargetMachine().getRelocationModel();
17378
17379   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17380   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17381     return false;
17382
17383   if (AM.BaseGV) {
17384     unsigned GVFlags =
17385       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17386
17387     // If a reference to this global requires an extra load, we can't fold it.
17388     if (isGlobalStubReference(GVFlags))
17389       return false;
17390
17391     // If BaseGV requires a register for the PIC base, we cannot also have a
17392     // BaseReg specified.
17393     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17394       return false;
17395
17396     // If lower 4G is not available, then we must use rip-relative addressing.
17397     if ((M != CodeModel::Small || R != Reloc::Static) &&
17398         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17399       return false;
17400   }
17401
17402   switch (AM.Scale) {
17403   case 0:
17404   case 1:
17405   case 2:
17406   case 4:
17407   case 8:
17408     // These scales always work.
17409     break;
17410   case 3:
17411   case 5:
17412   case 9:
17413     // These scales are formed with basereg+scalereg.  Only accept if there is
17414     // no basereg yet.
17415     if (AM.HasBaseReg)
17416       return false;
17417     break;
17418   default:  // Other stuff never works.
17419     return false;
17420   }
17421
17422   return true;
17423 }
17424
17425 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17426   unsigned Bits = Ty->getScalarSizeInBits();
17427
17428   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17429   // particularly cheaper than those without.
17430   if (Bits == 8)
17431     return false;
17432
17433   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17434   // variable shifts just as cheap as scalar ones.
17435   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17436     return false;
17437
17438   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17439   // fully general vector.
17440   return true;
17441 }
17442
17443 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17444   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17445     return false;
17446   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17447   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17448   return NumBits1 > NumBits2;
17449 }
17450
17451 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17452   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17453     return false;
17454
17455   if (!isTypeLegal(EVT::getEVT(Ty1)))
17456     return false;
17457
17458   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17459
17460   // Assuming the caller doesn't have a zeroext or signext return parameter,
17461   // truncation all the way down to i1 is valid.
17462   return true;
17463 }
17464
17465 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17466   return isInt<32>(Imm);
17467 }
17468
17469 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17470   // Can also use sub to handle negated immediates.
17471   return isInt<32>(Imm);
17472 }
17473
17474 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17475   if (!VT1.isInteger() || !VT2.isInteger())
17476     return false;
17477   unsigned NumBits1 = VT1.getSizeInBits();
17478   unsigned NumBits2 = VT2.getSizeInBits();
17479   return NumBits1 > NumBits2;
17480 }
17481
17482 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17483   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17484   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17485 }
17486
17487 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17488   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17489   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17490 }
17491
17492 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17493   EVT VT1 = Val.getValueType();
17494   if (isZExtFree(VT1, VT2))
17495     return true;
17496
17497   if (Val.getOpcode() != ISD::LOAD)
17498     return false;
17499
17500   if (!VT1.isSimple() || !VT1.isInteger() ||
17501       !VT2.isSimple() || !VT2.isInteger())
17502     return false;
17503
17504   switch (VT1.getSimpleVT().SimpleTy) {
17505   default: break;
17506   case MVT::i8:
17507   case MVT::i16:
17508   case MVT::i32:
17509     // X86 has 8, 16, and 32-bit zero-extending loads.
17510     return true;
17511   }
17512
17513   return false;
17514 }
17515
17516 bool
17517 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17518   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17519     return false;
17520
17521   VT = VT.getScalarType();
17522
17523   if (!VT.isSimple())
17524     return false;
17525
17526   switch (VT.getSimpleVT().SimpleTy) {
17527   case MVT::f32:
17528   case MVT::f64:
17529     return true;
17530   default:
17531     break;
17532   }
17533
17534   return false;
17535 }
17536
17537 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17538   // i16 instructions are longer (0x66 prefix) and potentially slower.
17539   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17540 }
17541
17542 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17543 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17544 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17545 /// are assumed to be legal.
17546 bool
17547 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17548                                       EVT VT) const {
17549   if (!VT.isSimple())
17550     return false;
17551
17552   MVT SVT = VT.getSimpleVT();
17553
17554   // Very little shuffling can be done for 64-bit vectors right now.
17555   if (VT.getSizeInBits() == 64)
17556     return false;
17557
17558   // If this is a single-input shuffle with no 128 bit lane crossings we can
17559   // lower it into pshufb.
17560   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17561       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17562     bool isLegal = true;
17563     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17564       if (M[I] >= (int)SVT.getVectorNumElements() ||
17565           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17566         isLegal = false;
17567         break;
17568       }
17569     }
17570     if (isLegal)
17571       return true;
17572   }
17573
17574   // FIXME: blends, shifts.
17575   return (SVT.getVectorNumElements() == 2 ||
17576           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17577           isMOVLMask(M, SVT) ||
17578           isMOVHLPSMask(M, SVT) ||
17579           isSHUFPMask(M, SVT) ||
17580           isPSHUFDMask(M, SVT) ||
17581           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17582           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17583           isPALIGNRMask(M, SVT, Subtarget) ||
17584           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17585           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17586           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17587           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17588           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17589 }
17590
17591 bool
17592 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17593                                           EVT VT) const {
17594   if (!VT.isSimple())
17595     return false;
17596
17597   MVT SVT = VT.getSimpleVT();
17598   unsigned NumElts = SVT.getVectorNumElements();
17599   // FIXME: This collection of masks seems suspect.
17600   if (NumElts == 2)
17601     return true;
17602   if (NumElts == 4 && SVT.is128BitVector()) {
17603     return (isMOVLMask(Mask, SVT)  ||
17604             isCommutedMOVLMask(Mask, SVT, true) ||
17605             isSHUFPMask(Mask, SVT) ||
17606             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17607   }
17608   return false;
17609 }
17610
17611 //===----------------------------------------------------------------------===//
17612 //                           X86 Scheduler Hooks
17613 //===----------------------------------------------------------------------===//
17614
17615 /// Utility function to emit xbegin specifying the start of an RTM region.
17616 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17617                                      const TargetInstrInfo *TII) {
17618   DebugLoc DL = MI->getDebugLoc();
17619
17620   const BasicBlock *BB = MBB->getBasicBlock();
17621   MachineFunction::iterator I = MBB;
17622   ++I;
17623
17624   // For the v = xbegin(), we generate
17625   //
17626   // thisMBB:
17627   //  xbegin sinkMBB
17628   //
17629   // mainMBB:
17630   //  eax = -1
17631   //
17632   // sinkMBB:
17633   //  v = eax
17634
17635   MachineBasicBlock *thisMBB = MBB;
17636   MachineFunction *MF = MBB->getParent();
17637   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17638   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17639   MF->insert(I, mainMBB);
17640   MF->insert(I, sinkMBB);
17641
17642   // Transfer the remainder of BB and its successor edges to sinkMBB.
17643   sinkMBB->splice(sinkMBB->begin(), MBB,
17644                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17645   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17646
17647   // thisMBB:
17648   //  xbegin sinkMBB
17649   //  # fallthrough to mainMBB
17650   //  # abortion to sinkMBB
17651   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17652   thisMBB->addSuccessor(mainMBB);
17653   thisMBB->addSuccessor(sinkMBB);
17654
17655   // mainMBB:
17656   //  EAX = -1
17657   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17658   mainMBB->addSuccessor(sinkMBB);
17659
17660   // sinkMBB:
17661   // EAX is live into the sinkMBB
17662   sinkMBB->addLiveIn(X86::EAX);
17663   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17664           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17665     .addReg(X86::EAX);
17666
17667   MI->eraseFromParent();
17668   return sinkMBB;
17669 }
17670
17671 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17672 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17673 // in the .td file.
17674 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17675                                        const TargetInstrInfo *TII) {
17676   unsigned Opc;
17677   switch (MI->getOpcode()) {
17678   default: llvm_unreachable("illegal opcode!");
17679   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17680   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17681   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17682   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17683   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17684   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17685   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17686   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17687   }
17688
17689   DebugLoc dl = MI->getDebugLoc();
17690   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17691
17692   unsigned NumArgs = MI->getNumOperands();
17693   for (unsigned i = 1; i < NumArgs; ++i) {
17694     MachineOperand &Op = MI->getOperand(i);
17695     if (!(Op.isReg() && Op.isImplicit()))
17696       MIB.addOperand(Op);
17697   }
17698   if (MI->hasOneMemOperand())
17699     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17700
17701   BuildMI(*BB, MI, dl,
17702     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17703     .addReg(X86::XMM0);
17704
17705   MI->eraseFromParent();
17706   return BB;
17707 }
17708
17709 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17710 // defs in an instruction pattern
17711 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17712                                        const TargetInstrInfo *TII) {
17713   unsigned Opc;
17714   switch (MI->getOpcode()) {
17715   default: llvm_unreachable("illegal opcode!");
17716   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17717   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17718   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17719   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17720   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17721   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17722   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17723   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17724   }
17725
17726   DebugLoc dl = MI->getDebugLoc();
17727   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17728
17729   unsigned NumArgs = MI->getNumOperands(); // remove the results
17730   for (unsigned i = 1; i < NumArgs; ++i) {
17731     MachineOperand &Op = MI->getOperand(i);
17732     if (!(Op.isReg() && Op.isImplicit()))
17733       MIB.addOperand(Op);
17734   }
17735   if (MI->hasOneMemOperand())
17736     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17737
17738   BuildMI(*BB, MI, dl,
17739     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17740     .addReg(X86::ECX);
17741
17742   MI->eraseFromParent();
17743   return BB;
17744 }
17745
17746 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17747                                        const TargetInstrInfo *TII,
17748                                        const X86Subtarget* Subtarget) {
17749   DebugLoc dl = MI->getDebugLoc();
17750
17751   // Address into RAX/EAX, other two args into ECX, EDX.
17752   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17753   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17754   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17755   for (int i = 0; i < X86::AddrNumOperands; ++i)
17756     MIB.addOperand(MI->getOperand(i));
17757
17758   unsigned ValOps = X86::AddrNumOperands;
17759   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17760     .addReg(MI->getOperand(ValOps).getReg());
17761   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17762     .addReg(MI->getOperand(ValOps+1).getReg());
17763
17764   // The instruction doesn't actually take any operands though.
17765   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17766
17767   MI->eraseFromParent(); // The pseudo is gone now.
17768   return BB;
17769 }
17770
17771 MachineBasicBlock *
17772 X86TargetLowering::EmitVAARG64WithCustomInserter(
17773                    MachineInstr *MI,
17774                    MachineBasicBlock *MBB) const {
17775   // Emit va_arg instruction on X86-64.
17776
17777   // Operands to this pseudo-instruction:
17778   // 0  ) Output        : destination address (reg)
17779   // 1-5) Input         : va_list address (addr, i64mem)
17780   // 6  ) ArgSize       : Size (in bytes) of vararg type
17781   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17782   // 8  ) Align         : Alignment of type
17783   // 9  ) EFLAGS (implicit-def)
17784
17785   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17786   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17787
17788   unsigned DestReg = MI->getOperand(0).getReg();
17789   MachineOperand &Base = MI->getOperand(1);
17790   MachineOperand &Scale = MI->getOperand(2);
17791   MachineOperand &Index = MI->getOperand(3);
17792   MachineOperand &Disp = MI->getOperand(4);
17793   MachineOperand &Segment = MI->getOperand(5);
17794   unsigned ArgSize = MI->getOperand(6).getImm();
17795   unsigned ArgMode = MI->getOperand(7).getImm();
17796   unsigned Align = MI->getOperand(8).getImm();
17797
17798   // Memory Reference
17799   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17800   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17801   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17802
17803   // Machine Information
17804   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17805   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17806   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17807   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17808   DebugLoc DL = MI->getDebugLoc();
17809
17810   // struct va_list {
17811   //   i32   gp_offset
17812   //   i32   fp_offset
17813   //   i64   overflow_area (address)
17814   //   i64   reg_save_area (address)
17815   // }
17816   // sizeof(va_list) = 24
17817   // alignment(va_list) = 8
17818
17819   unsigned TotalNumIntRegs = 6;
17820   unsigned TotalNumXMMRegs = 8;
17821   bool UseGPOffset = (ArgMode == 1);
17822   bool UseFPOffset = (ArgMode == 2);
17823   unsigned MaxOffset = TotalNumIntRegs * 8 +
17824                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17825
17826   /* Align ArgSize to a multiple of 8 */
17827   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17828   bool NeedsAlign = (Align > 8);
17829
17830   MachineBasicBlock *thisMBB = MBB;
17831   MachineBasicBlock *overflowMBB;
17832   MachineBasicBlock *offsetMBB;
17833   MachineBasicBlock *endMBB;
17834
17835   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17836   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17837   unsigned OffsetReg = 0;
17838
17839   if (!UseGPOffset && !UseFPOffset) {
17840     // If we only pull from the overflow region, we don't create a branch.
17841     // We don't need to alter control flow.
17842     OffsetDestReg = 0; // unused
17843     OverflowDestReg = DestReg;
17844
17845     offsetMBB = nullptr;
17846     overflowMBB = thisMBB;
17847     endMBB = thisMBB;
17848   } else {
17849     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17850     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17851     // If not, pull from overflow_area. (branch to overflowMBB)
17852     //
17853     //       thisMBB
17854     //         |     .
17855     //         |        .
17856     //     offsetMBB   overflowMBB
17857     //         |        .
17858     //         |     .
17859     //        endMBB
17860
17861     // Registers for the PHI in endMBB
17862     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17863     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17864
17865     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17866     MachineFunction *MF = MBB->getParent();
17867     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17868     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17869     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17870
17871     MachineFunction::iterator MBBIter = MBB;
17872     ++MBBIter;
17873
17874     // Insert the new basic blocks
17875     MF->insert(MBBIter, offsetMBB);
17876     MF->insert(MBBIter, overflowMBB);
17877     MF->insert(MBBIter, endMBB);
17878
17879     // Transfer the remainder of MBB and its successor edges to endMBB.
17880     endMBB->splice(endMBB->begin(), thisMBB,
17881                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17882     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17883
17884     // Make offsetMBB and overflowMBB successors of thisMBB
17885     thisMBB->addSuccessor(offsetMBB);
17886     thisMBB->addSuccessor(overflowMBB);
17887
17888     // endMBB is a successor of both offsetMBB and overflowMBB
17889     offsetMBB->addSuccessor(endMBB);
17890     overflowMBB->addSuccessor(endMBB);
17891
17892     // Load the offset value into a register
17893     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17894     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17895       .addOperand(Base)
17896       .addOperand(Scale)
17897       .addOperand(Index)
17898       .addDisp(Disp, UseFPOffset ? 4 : 0)
17899       .addOperand(Segment)
17900       .setMemRefs(MMOBegin, MMOEnd);
17901
17902     // Check if there is enough room left to pull this argument.
17903     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17904       .addReg(OffsetReg)
17905       .addImm(MaxOffset + 8 - ArgSizeA8);
17906
17907     // Branch to "overflowMBB" if offset >= max
17908     // Fall through to "offsetMBB" otherwise
17909     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17910       .addMBB(overflowMBB);
17911   }
17912
17913   // In offsetMBB, emit code to use the reg_save_area.
17914   if (offsetMBB) {
17915     assert(OffsetReg != 0);
17916
17917     // Read the reg_save_area address.
17918     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17919     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17920       .addOperand(Base)
17921       .addOperand(Scale)
17922       .addOperand(Index)
17923       .addDisp(Disp, 16)
17924       .addOperand(Segment)
17925       .setMemRefs(MMOBegin, MMOEnd);
17926
17927     // Zero-extend the offset
17928     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17929       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17930         .addImm(0)
17931         .addReg(OffsetReg)
17932         .addImm(X86::sub_32bit);
17933
17934     // Add the offset to the reg_save_area to get the final address.
17935     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17936       .addReg(OffsetReg64)
17937       .addReg(RegSaveReg);
17938
17939     // Compute the offset for the next argument
17940     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17941     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17942       .addReg(OffsetReg)
17943       .addImm(UseFPOffset ? 16 : 8);
17944
17945     // Store it back into the va_list.
17946     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17947       .addOperand(Base)
17948       .addOperand(Scale)
17949       .addOperand(Index)
17950       .addDisp(Disp, UseFPOffset ? 4 : 0)
17951       .addOperand(Segment)
17952       .addReg(NextOffsetReg)
17953       .setMemRefs(MMOBegin, MMOEnd);
17954
17955     // Jump to endMBB
17956     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17957       .addMBB(endMBB);
17958   }
17959
17960   //
17961   // Emit code to use overflow area
17962   //
17963
17964   // Load the overflow_area address into a register.
17965   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17966   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17967     .addOperand(Base)
17968     .addOperand(Scale)
17969     .addOperand(Index)
17970     .addDisp(Disp, 8)
17971     .addOperand(Segment)
17972     .setMemRefs(MMOBegin, MMOEnd);
17973
17974   // If we need to align it, do so. Otherwise, just copy the address
17975   // to OverflowDestReg.
17976   if (NeedsAlign) {
17977     // Align the overflow address
17978     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17979     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17980
17981     // aligned_addr = (addr + (align-1)) & ~(align-1)
17982     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17983       .addReg(OverflowAddrReg)
17984       .addImm(Align-1);
17985
17986     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17987       .addReg(TmpReg)
17988       .addImm(~(uint64_t)(Align-1));
17989   } else {
17990     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17991       .addReg(OverflowAddrReg);
17992   }
17993
17994   // Compute the next overflow address after this argument.
17995   // (the overflow address should be kept 8-byte aligned)
17996   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17997   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17998     .addReg(OverflowDestReg)
17999     .addImm(ArgSizeA8);
18000
18001   // Store the new overflow address.
18002   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18003     .addOperand(Base)
18004     .addOperand(Scale)
18005     .addOperand(Index)
18006     .addDisp(Disp, 8)
18007     .addOperand(Segment)
18008     .addReg(NextAddrReg)
18009     .setMemRefs(MMOBegin, MMOEnd);
18010
18011   // If we branched, emit the PHI to the front of endMBB.
18012   if (offsetMBB) {
18013     BuildMI(*endMBB, endMBB->begin(), DL,
18014             TII->get(X86::PHI), DestReg)
18015       .addReg(OffsetDestReg).addMBB(offsetMBB)
18016       .addReg(OverflowDestReg).addMBB(overflowMBB);
18017   }
18018
18019   // Erase the pseudo instruction
18020   MI->eraseFromParent();
18021
18022   return endMBB;
18023 }
18024
18025 MachineBasicBlock *
18026 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18027                                                  MachineInstr *MI,
18028                                                  MachineBasicBlock *MBB) const {
18029   // Emit code to save XMM registers to the stack. The ABI says that the
18030   // number of registers to save is given in %al, so it's theoretically
18031   // possible to do an indirect jump trick to avoid saving all of them,
18032   // however this code takes a simpler approach and just executes all
18033   // of the stores if %al is non-zero. It's less code, and it's probably
18034   // easier on the hardware branch predictor, and stores aren't all that
18035   // expensive anyway.
18036
18037   // Create the new basic blocks. One block contains all the XMM stores,
18038   // and one block is the final destination regardless of whether any
18039   // stores were performed.
18040   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18041   MachineFunction *F = MBB->getParent();
18042   MachineFunction::iterator MBBIter = MBB;
18043   ++MBBIter;
18044   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18045   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18046   F->insert(MBBIter, XMMSaveMBB);
18047   F->insert(MBBIter, EndMBB);
18048
18049   // Transfer the remainder of MBB and its successor edges to EndMBB.
18050   EndMBB->splice(EndMBB->begin(), MBB,
18051                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18052   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18053
18054   // The original block will now fall through to the XMM save block.
18055   MBB->addSuccessor(XMMSaveMBB);
18056   // The XMMSaveMBB will fall through to the end block.
18057   XMMSaveMBB->addSuccessor(EndMBB);
18058
18059   // Now add the instructions.
18060   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18061   DebugLoc DL = MI->getDebugLoc();
18062
18063   unsigned CountReg = MI->getOperand(0).getReg();
18064   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18065   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18066
18067   if (!Subtarget->isTargetWin64()) {
18068     // If %al is 0, branch around the XMM save block.
18069     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18070     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18071     MBB->addSuccessor(EndMBB);
18072   }
18073
18074   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18075   // that was just emitted, but clearly shouldn't be "saved".
18076   assert((MI->getNumOperands() <= 3 ||
18077           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18078           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18079          && "Expected last argument to be EFLAGS");
18080   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18081   // In the XMM save block, save all the XMM argument registers.
18082   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18083     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18084     MachineMemOperand *MMO =
18085       F->getMachineMemOperand(
18086           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18087         MachineMemOperand::MOStore,
18088         /*Size=*/16, /*Align=*/16);
18089     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18090       .addFrameIndex(RegSaveFrameIndex)
18091       .addImm(/*Scale=*/1)
18092       .addReg(/*IndexReg=*/0)
18093       .addImm(/*Disp=*/Offset)
18094       .addReg(/*Segment=*/0)
18095       .addReg(MI->getOperand(i).getReg())
18096       .addMemOperand(MMO);
18097   }
18098
18099   MI->eraseFromParent();   // The pseudo instruction is gone now.
18100
18101   return EndMBB;
18102 }
18103
18104 // The EFLAGS operand of SelectItr might be missing a kill marker
18105 // because there were multiple uses of EFLAGS, and ISel didn't know
18106 // which to mark. Figure out whether SelectItr should have had a
18107 // kill marker, and set it if it should. Returns the correct kill
18108 // marker value.
18109 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18110                                      MachineBasicBlock* BB,
18111                                      const TargetRegisterInfo* TRI) {
18112   // Scan forward through BB for a use/def of EFLAGS.
18113   MachineBasicBlock::iterator miI(std::next(SelectItr));
18114   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18115     const MachineInstr& mi = *miI;
18116     if (mi.readsRegister(X86::EFLAGS))
18117       return false;
18118     if (mi.definesRegister(X86::EFLAGS))
18119       break; // Should have kill-flag - update below.
18120   }
18121
18122   // If we hit the end of the block, check whether EFLAGS is live into a
18123   // successor.
18124   if (miI == BB->end()) {
18125     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18126                                           sEnd = BB->succ_end();
18127          sItr != sEnd; ++sItr) {
18128       MachineBasicBlock* succ = *sItr;
18129       if (succ->isLiveIn(X86::EFLAGS))
18130         return false;
18131     }
18132   }
18133
18134   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18135   // out. SelectMI should have a kill flag on EFLAGS.
18136   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18137   return true;
18138 }
18139
18140 MachineBasicBlock *
18141 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18142                                      MachineBasicBlock *BB) const {
18143   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18144   DebugLoc DL = MI->getDebugLoc();
18145
18146   // To "insert" a SELECT_CC instruction, we actually have to insert the
18147   // diamond control-flow pattern.  The incoming instruction knows the
18148   // destination vreg to set, the condition code register to branch on, the
18149   // true/false values to select between, and a branch opcode to use.
18150   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18151   MachineFunction::iterator It = BB;
18152   ++It;
18153
18154   //  thisMBB:
18155   //  ...
18156   //   TrueVal = ...
18157   //   cmpTY ccX, r1, r2
18158   //   bCC copy1MBB
18159   //   fallthrough --> copy0MBB
18160   MachineBasicBlock *thisMBB = BB;
18161   MachineFunction *F = BB->getParent();
18162   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18163   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18164   F->insert(It, copy0MBB);
18165   F->insert(It, sinkMBB);
18166
18167   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18168   // live into the sink and copy blocks.
18169   const TargetRegisterInfo *TRI =
18170       BB->getParent()->getSubtarget().getRegisterInfo();
18171   if (!MI->killsRegister(X86::EFLAGS) &&
18172       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18173     copy0MBB->addLiveIn(X86::EFLAGS);
18174     sinkMBB->addLiveIn(X86::EFLAGS);
18175   }
18176
18177   // Transfer the remainder of BB and its successor edges to sinkMBB.
18178   sinkMBB->splice(sinkMBB->begin(), BB,
18179                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18180   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18181
18182   // Add the true and fallthrough blocks as its successors.
18183   BB->addSuccessor(copy0MBB);
18184   BB->addSuccessor(sinkMBB);
18185
18186   // Create the conditional branch instruction.
18187   unsigned Opc =
18188     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18189   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18190
18191   //  copy0MBB:
18192   //   %FalseValue = ...
18193   //   # fallthrough to sinkMBB
18194   copy0MBB->addSuccessor(sinkMBB);
18195
18196   //  sinkMBB:
18197   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18198   //  ...
18199   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18200           TII->get(X86::PHI), MI->getOperand(0).getReg())
18201     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18202     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18203
18204   MI->eraseFromParent();   // The pseudo instruction is gone now.
18205   return sinkMBB;
18206 }
18207
18208 MachineBasicBlock *
18209 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18210                                         bool Is64Bit) const {
18211   MachineFunction *MF = BB->getParent();
18212   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18213   DebugLoc DL = MI->getDebugLoc();
18214   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18215
18216   assert(MF->shouldSplitStack());
18217
18218   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18219   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18220
18221   // BB:
18222   //  ... [Till the alloca]
18223   // If stacklet is not large enough, jump to mallocMBB
18224   //
18225   // bumpMBB:
18226   //  Allocate by subtracting from RSP
18227   //  Jump to continueMBB
18228   //
18229   // mallocMBB:
18230   //  Allocate by call to runtime
18231   //
18232   // continueMBB:
18233   //  ...
18234   //  [rest of original BB]
18235   //
18236
18237   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18238   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18239   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18240
18241   MachineRegisterInfo &MRI = MF->getRegInfo();
18242   const TargetRegisterClass *AddrRegClass =
18243     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18244
18245   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18246     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18247     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18248     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18249     sizeVReg = MI->getOperand(1).getReg(),
18250     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18251
18252   MachineFunction::iterator MBBIter = BB;
18253   ++MBBIter;
18254
18255   MF->insert(MBBIter, bumpMBB);
18256   MF->insert(MBBIter, mallocMBB);
18257   MF->insert(MBBIter, continueMBB);
18258
18259   continueMBB->splice(continueMBB->begin(), BB,
18260                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18261   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18262
18263   // Add code to the main basic block to check if the stack limit has been hit,
18264   // and if so, jump to mallocMBB otherwise to bumpMBB.
18265   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18266   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18267     .addReg(tmpSPVReg).addReg(sizeVReg);
18268   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18269     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18270     .addReg(SPLimitVReg);
18271   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18272
18273   // bumpMBB simply decreases the stack pointer, since we know the current
18274   // stacklet has enough space.
18275   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18276     .addReg(SPLimitVReg);
18277   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18278     .addReg(SPLimitVReg);
18279   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18280
18281   // Calls into a routine in libgcc to allocate more space from the heap.
18282   const uint32_t *RegMask = MF->getTarget()
18283                                 .getSubtargetImpl()
18284                                 ->getRegisterInfo()
18285                                 ->getCallPreservedMask(CallingConv::C);
18286   if (Is64Bit) {
18287     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18288       .addReg(sizeVReg);
18289     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18290       .addExternalSymbol("__morestack_allocate_stack_space")
18291       .addRegMask(RegMask)
18292       .addReg(X86::RDI, RegState::Implicit)
18293       .addReg(X86::RAX, RegState::ImplicitDefine);
18294   } else {
18295     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18296       .addImm(12);
18297     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18298     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18299       .addExternalSymbol("__morestack_allocate_stack_space")
18300       .addRegMask(RegMask)
18301       .addReg(X86::EAX, RegState::ImplicitDefine);
18302   }
18303
18304   if (!Is64Bit)
18305     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18306       .addImm(16);
18307
18308   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18309     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18310   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18311
18312   // Set up the CFG correctly.
18313   BB->addSuccessor(bumpMBB);
18314   BB->addSuccessor(mallocMBB);
18315   mallocMBB->addSuccessor(continueMBB);
18316   bumpMBB->addSuccessor(continueMBB);
18317
18318   // Take care of the PHI nodes.
18319   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18320           MI->getOperand(0).getReg())
18321     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18322     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18323
18324   // Delete the original pseudo instruction.
18325   MI->eraseFromParent();
18326
18327   // And we're done.
18328   return continueMBB;
18329 }
18330
18331 MachineBasicBlock *
18332 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18333                                         MachineBasicBlock *BB) const {
18334   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18335   DebugLoc DL = MI->getDebugLoc();
18336
18337   assert(!Subtarget->isTargetMacho());
18338
18339   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18340   // non-trivial part is impdef of ESP.
18341
18342   if (Subtarget->isTargetWin64()) {
18343     if (Subtarget->isTargetCygMing()) {
18344       // ___chkstk(Mingw64):
18345       // Clobbers R10, R11, RAX and EFLAGS.
18346       // Updates RSP.
18347       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18348         .addExternalSymbol("___chkstk")
18349         .addReg(X86::RAX, RegState::Implicit)
18350         .addReg(X86::RSP, RegState::Implicit)
18351         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18352         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18353         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18354     } else {
18355       // __chkstk(MSVCRT): does not update stack pointer.
18356       // Clobbers R10, R11 and EFLAGS.
18357       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18358         .addExternalSymbol("__chkstk")
18359         .addReg(X86::RAX, RegState::Implicit)
18360         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18361       // RAX has the offset to be subtracted from RSP.
18362       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18363         .addReg(X86::RSP)
18364         .addReg(X86::RAX);
18365     }
18366   } else {
18367     const char *StackProbeSymbol =
18368       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18369
18370     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18371       .addExternalSymbol(StackProbeSymbol)
18372       .addReg(X86::EAX, RegState::Implicit)
18373       .addReg(X86::ESP, RegState::Implicit)
18374       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18375       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18376       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18377   }
18378
18379   MI->eraseFromParent();   // The pseudo instruction is gone now.
18380   return BB;
18381 }
18382
18383 MachineBasicBlock *
18384 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18385                                       MachineBasicBlock *BB) const {
18386   // This is pretty easy.  We're taking the value that we received from
18387   // our load from the relocation, sticking it in either RDI (x86-64)
18388   // or EAX and doing an indirect call.  The return value will then
18389   // be in the normal return register.
18390   MachineFunction *F = BB->getParent();
18391   const X86InstrInfo *TII =
18392       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18393   DebugLoc DL = MI->getDebugLoc();
18394
18395   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18396   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18397
18398   // Get a register mask for the lowered call.
18399   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18400   // proper register mask.
18401   const uint32_t *RegMask = F->getTarget()
18402                                 .getSubtargetImpl()
18403                                 ->getRegisterInfo()
18404                                 ->getCallPreservedMask(CallingConv::C);
18405   if (Subtarget->is64Bit()) {
18406     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18407                                       TII->get(X86::MOV64rm), X86::RDI)
18408     .addReg(X86::RIP)
18409     .addImm(0).addReg(0)
18410     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18411                       MI->getOperand(3).getTargetFlags())
18412     .addReg(0);
18413     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18414     addDirectMem(MIB, X86::RDI);
18415     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18416   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18417     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18418                                       TII->get(X86::MOV32rm), X86::EAX)
18419     .addReg(0)
18420     .addImm(0).addReg(0)
18421     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18422                       MI->getOperand(3).getTargetFlags())
18423     .addReg(0);
18424     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18425     addDirectMem(MIB, X86::EAX);
18426     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18427   } else {
18428     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18429                                       TII->get(X86::MOV32rm), X86::EAX)
18430     .addReg(TII->getGlobalBaseReg(F))
18431     .addImm(0).addReg(0)
18432     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18433                       MI->getOperand(3).getTargetFlags())
18434     .addReg(0);
18435     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18436     addDirectMem(MIB, X86::EAX);
18437     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18438   }
18439
18440   MI->eraseFromParent(); // The pseudo instruction is gone now.
18441   return BB;
18442 }
18443
18444 MachineBasicBlock *
18445 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18446                                     MachineBasicBlock *MBB) const {
18447   DebugLoc DL = MI->getDebugLoc();
18448   MachineFunction *MF = MBB->getParent();
18449   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18450   MachineRegisterInfo &MRI = MF->getRegInfo();
18451
18452   const BasicBlock *BB = MBB->getBasicBlock();
18453   MachineFunction::iterator I = MBB;
18454   ++I;
18455
18456   // Memory Reference
18457   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18458   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18459
18460   unsigned DstReg;
18461   unsigned MemOpndSlot = 0;
18462
18463   unsigned CurOp = 0;
18464
18465   DstReg = MI->getOperand(CurOp++).getReg();
18466   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18467   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18468   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18469   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18470
18471   MemOpndSlot = CurOp;
18472
18473   MVT PVT = getPointerTy();
18474   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18475          "Invalid Pointer Size!");
18476
18477   // For v = setjmp(buf), we generate
18478   //
18479   // thisMBB:
18480   //  buf[LabelOffset] = restoreMBB
18481   //  SjLjSetup restoreMBB
18482   //
18483   // mainMBB:
18484   //  v_main = 0
18485   //
18486   // sinkMBB:
18487   //  v = phi(main, restore)
18488   //
18489   // restoreMBB:
18490   //  v_restore = 1
18491
18492   MachineBasicBlock *thisMBB = MBB;
18493   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18494   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18495   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18496   MF->insert(I, mainMBB);
18497   MF->insert(I, sinkMBB);
18498   MF->push_back(restoreMBB);
18499
18500   MachineInstrBuilder MIB;
18501
18502   // Transfer the remainder of BB and its successor edges to sinkMBB.
18503   sinkMBB->splice(sinkMBB->begin(), MBB,
18504                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18505   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18506
18507   // thisMBB:
18508   unsigned PtrStoreOpc = 0;
18509   unsigned LabelReg = 0;
18510   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18511   Reloc::Model RM = MF->getTarget().getRelocationModel();
18512   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18513                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18514
18515   // Prepare IP either in reg or imm.
18516   if (!UseImmLabel) {
18517     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18518     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18519     LabelReg = MRI.createVirtualRegister(PtrRC);
18520     if (Subtarget->is64Bit()) {
18521       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18522               .addReg(X86::RIP)
18523               .addImm(0)
18524               .addReg(0)
18525               .addMBB(restoreMBB)
18526               .addReg(0);
18527     } else {
18528       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18529       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18530               .addReg(XII->getGlobalBaseReg(MF))
18531               .addImm(0)
18532               .addReg(0)
18533               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18534               .addReg(0);
18535     }
18536   } else
18537     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18538   // Store IP
18539   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18540   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18541     if (i == X86::AddrDisp)
18542       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18543     else
18544       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18545   }
18546   if (!UseImmLabel)
18547     MIB.addReg(LabelReg);
18548   else
18549     MIB.addMBB(restoreMBB);
18550   MIB.setMemRefs(MMOBegin, MMOEnd);
18551   // Setup
18552   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18553           .addMBB(restoreMBB);
18554
18555   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18556       MF->getSubtarget().getRegisterInfo());
18557   MIB.addRegMask(RegInfo->getNoPreservedMask());
18558   thisMBB->addSuccessor(mainMBB);
18559   thisMBB->addSuccessor(restoreMBB);
18560
18561   // mainMBB:
18562   //  EAX = 0
18563   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18564   mainMBB->addSuccessor(sinkMBB);
18565
18566   // sinkMBB:
18567   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18568           TII->get(X86::PHI), DstReg)
18569     .addReg(mainDstReg).addMBB(mainMBB)
18570     .addReg(restoreDstReg).addMBB(restoreMBB);
18571
18572   // restoreMBB:
18573   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18574   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18575   restoreMBB->addSuccessor(sinkMBB);
18576
18577   MI->eraseFromParent();
18578   return sinkMBB;
18579 }
18580
18581 MachineBasicBlock *
18582 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18583                                      MachineBasicBlock *MBB) const {
18584   DebugLoc DL = MI->getDebugLoc();
18585   MachineFunction *MF = MBB->getParent();
18586   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18587   MachineRegisterInfo &MRI = MF->getRegInfo();
18588
18589   // Memory Reference
18590   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18591   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18592
18593   MVT PVT = getPointerTy();
18594   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18595          "Invalid Pointer Size!");
18596
18597   const TargetRegisterClass *RC =
18598     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18599   unsigned Tmp = MRI.createVirtualRegister(RC);
18600   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18601   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18602       MF->getSubtarget().getRegisterInfo());
18603   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18604   unsigned SP = RegInfo->getStackRegister();
18605
18606   MachineInstrBuilder MIB;
18607
18608   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18609   const int64_t SPOffset = 2 * PVT.getStoreSize();
18610
18611   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18612   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18613
18614   // Reload FP
18615   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18616   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18617     MIB.addOperand(MI->getOperand(i));
18618   MIB.setMemRefs(MMOBegin, MMOEnd);
18619   // Reload IP
18620   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18621   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18622     if (i == X86::AddrDisp)
18623       MIB.addDisp(MI->getOperand(i), LabelOffset);
18624     else
18625       MIB.addOperand(MI->getOperand(i));
18626   }
18627   MIB.setMemRefs(MMOBegin, MMOEnd);
18628   // Reload SP
18629   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18630   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18631     if (i == X86::AddrDisp)
18632       MIB.addDisp(MI->getOperand(i), SPOffset);
18633     else
18634       MIB.addOperand(MI->getOperand(i));
18635   }
18636   MIB.setMemRefs(MMOBegin, MMOEnd);
18637   // Jump
18638   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18639
18640   MI->eraseFromParent();
18641   return MBB;
18642 }
18643
18644 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18645 // accumulator loops. Writing back to the accumulator allows the coalescer
18646 // to remove extra copies in the loop.   
18647 MachineBasicBlock *
18648 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18649                                  MachineBasicBlock *MBB) const {
18650   MachineOperand &AddendOp = MI->getOperand(3);
18651
18652   // Bail out early if the addend isn't a register - we can't switch these.
18653   if (!AddendOp.isReg())
18654     return MBB;
18655
18656   MachineFunction &MF = *MBB->getParent();
18657   MachineRegisterInfo &MRI = MF.getRegInfo();
18658
18659   // Check whether the addend is defined by a PHI:
18660   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18661   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18662   if (!AddendDef.isPHI())
18663     return MBB;
18664
18665   // Look for the following pattern:
18666   // loop:
18667   //   %addend = phi [%entry, 0], [%loop, %result]
18668   //   ...
18669   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18670
18671   // Replace with:
18672   //   loop:
18673   //   %addend = phi [%entry, 0], [%loop, %result]
18674   //   ...
18675   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18676
18677   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18678     assert(AddendDef.getOperand(i).isReg());
18679     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18680     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18681     if (&PHISrcInst == MI) {
18682       // Found a matching instruction.
18683       unsigned NewFMAOpc = 0;
18684       switch (MI->getOpcode()) {
18685         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18686         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18687         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18688         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18689         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18690         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18691         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18692         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18693         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18694         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18695         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18696         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18697         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18698         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18699         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18700         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18701         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18702         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18703         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18704         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18705         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18706         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18707         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18708         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18709         default: llvm_unreachable("Unrecognized FMA variant.");
18710       }
18711
18712       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18713       MachineInstrBuilder MIB =
18714         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18715         .addOperand(MI->getOperand(0))
18716         .addOperand(MI->getOperand(3))
18717         .addOperand(MI->getOperand(2))
18718         .addOperand(MI->getOperand(1));
18719       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18720       MI->eraseFromParent();
18721     }
18722   }
18723
18724   return MBB;
18725 }
18726
18727 MachineBasicBlock *
18728 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18729                                                MachineBasicBlock *BB) const {
18730   switch (MI->getOpcode()) {
18731   default: llvm_unreachable("Unexpected instr type to insert");
18732   case X86::TAILJMPd64:
18733   case X86::TAILJMPr64:
18734   case X86::TAILJMPm64:
18735     llvm_unreachable("TAILJMP64 would not be touched here.");
18736   case X86::TCRETURNdi64:
18737   case X86::TCRETURNri64:
18738   case X86::TCRETURNmi64:
18739     return BB;
18740   case X86::WIN_ALLOCA:
18741     return EmitLoweredWinAlloca(MI, BB);
18742   case X86::SEG_ALLOCA_32:
18743     return EmitLoweredSegAlloca(MI, BB, false);
18744   case X86::SEG_ALLOCA_64:
18745     return EmitLoweredSegAlloca(MI, BB, true);
18746   case X86::TLSCall_32:
18747   case X86::TLSCall_64:
18748     return EmitLoweredTLSCall(MI, BB);
18749   case X86::CMOV_GR8:
18750   case X86::CMOV_FR32:
18751   case X86::CMOV_FR64:
18752   case X86::CMOV_V4F32:
18753   case X86::CMOV_V2F64:
18754   case X86::CMOV_V2I64:
18755   case X86::CMOV_V8F32:
18756   case X86::CMOV_V4F64:
18757   case X86::CMOV_V4I64:
18758   case X86::CMOV_V16F32:
18759   case X86::CMOV_V8F64:
18760   case X86::CMOV_V8I64:
18761   case X86::CMOV_GR16:
18762   case X86::CMOV_GR32:
18763   case X86::CMOV_RFP32:
18764   case X86::CMOV_RFP64:
18765   case X86::CMOV_RFP80:
18766     return EmitLoweredSelect(MI, BB);
18767
18768   case X86::FP32_TO_INT16_IN_MEM:
18769   case X86::FP32_TO_INT32_IN_MEM:
18770   case X86::FP32_TO_INT64_IN_MEM:
18771   case X86::FP64_TO_INT16_IN_MEM:
18772   case X86::FP64_TO_INT32_IN_MEM:
18773   case X86::FP64_TO_INT64_IN_MEM:
18774   case X86::FP80_TO_INT16_IN_MEM:
18775   case X86::FP80_TO_INT32_IN_MEM:
18776   case X86::FP80_TO_INT64_IN_MEM: {
18777     MachineFunction *F = BB->getParent();
18778     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18779     DebugLoc DL = MI->getDebugLoc();
18780
18781     // Change the floating point control register to use "round towards zero"
18782     // mode when truncating to an integer value.
18783     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18784     addFrameReference(BuildMI(*BB, MI, DL,
18785                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18786
18787     // Load the old value of the high byte of the control word...
18788     unsigned OldCW =
18789       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18790     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18791                       CWFrameIdx);
18792
18793     // Set the high part to be round to zero...
18794     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18795       .addImm(0xC7F);
18796
18797     // Reload the modified control word now...
18798     addFrameReference(BuildMI(*BB, MI, DL,
18799                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18800
18801     // Restore the memory image of control word to original value
18802     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18803       .addReg(OldCW);
18804
18805     // Get the X86 opcode to use.
18806     unsigned Opc;
18807     switch (MI->getOpcode()) {
18808     default: llvm_unreachable("illegal opcode!");
18809     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18810     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18811     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18812     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18813     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18814     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18815     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18816     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18817     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18818     }
18819
18820     X86AddressMode AM;
18821     MachineOperand &Op = MI->getOperand(0);
18822     if (Op.isReg()) {
18823       AM.BaseType = X86AddressMode::RegBase;
18824       AM.Base.Reg = Op.getReg();
18825     } else {
18826       AM.BaseType = X86AddressMode::FrameIndexBase;
18827       AM.Base.FrameIndex = Op.getIndex();
18828     }
18829     Op = MI->getOperand(1);
18830     if (Op.isImm())
18831       AM.Scale = Op.getImm();
18832     Op = MI->getOperand(2);
18833     if (Op.isImm())
18834       AM.IndexReg = Op.getImm();
18835     Op = MI->getOperand(3);
18836     if (Op.isGlobal()) {
18837       AM.GV = Op.getGlobal();
18838     } else {
18839       AM.Disp = Op.getImm();
18840     }
18841     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18842                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18843
18844     // Reload the original control word now.
18845     addFrameReference(BuildMI(*BB, MI, DL,
18846                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18847
18848     MI->eraseFromParent();   // The pseudo instruction is gone now.
18849     return BB;
18850   }
18851     // String/text processing lowering.
18852   case X86::PCMPISTRM128REG:
18853   case X86::VPCMPISTRM128REG:
18854   case X86::PCMPISTRM128MEM:
18855   case X86::VPCMPISTRM128MEM:
18856   case X86::PCMPESTRM128REG:
18857   case X86::VPCMPESTRM128REG:
18858   case X86::PCMPESTRM128MEM:
18859   case X86::VPCMPESTRM128MEM:
18860     assert(Subtarget->hasSSE42() &&
18861            "Target must have SSE4.2 or AVX features enabled");
18862     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18863
18864   // String/text processing lowering.
18865   case X86::PCMPISTRIREG:
18866   case X86::VPCMPISTRIREG:
18867   case X86::PCMPISTRIMEM:
18868   case X86::VPCMPISTRIMEM:
18869   case X86::PCMPESTRIREG:
18870   case X86::VPCMPESTRIREG:
18871   case X86::PCMPESTRIMEM:
18872   case X86::VPCMPESTRIMEM:
18873     assert(Subtarget->hasSSE42() &&
18874            "Target must have SSE4.2 or AVX features enabled");
18875     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18876
18877   // Thread synchronization.
18878   case X86::MONITOR:
18879     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18880                        Subtarget);
18881
18882   // xbegin
18883   case X86::XBEGIN:
18884     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18885
18886   case X86::VASTART_SAVE_XMM_REGS:
18887     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18888
18889   case X86::VAARG_64:
18890     return EmitVAARG64WithCustomInserter(MI, BB);
18891
18892   case X86::EH_SjLj_SetJmp32:
18893   case X86::EH_SjLj_SetJmp64:
18894     return emitEHSjLjSetJmp(MI, BB);
18895
18896   case X86::EH_SjLj_LongJmp32:
18897   case X86::EH_SjLj_LongJmp64:
18898     return emitEHSjLjLongJmp(MI, BB);
18899
18900   case TargetOpcode::STACKMAP:
18901   case TargetOpcode::PATCHPOINT:
18902     return emitPatchPoint(MI, BB);
18903
18904   case X86::VFMADDPDr213r:
18905   case X86::VFMADDPSr213r:
18906   case X86::VFMADDSDr213r:
18907   case X86::VFMADDSSr213r:
18908   case X86::VFMSUBPDr213r:
18909   case X86::VFMSUBPSr213r:
18910   case X86::VFMSUBSDr213r:
18911   case X86::VFMSUBSSr213r:
18912   case X86::VFNMADDPDr213r:
18913   case X86::VFNMADDPSr213r:
18914   case X86::VFNMADDSDr213r:
18915   case X86::VFNMADDSSr213r:
18916   case X86::VFNMSUBPDr213r:
18917   case X86::VFNMSUBPSr213r:
18918   case X86::VFNMSUBSDr213r:
18919   case X86::VFNMSUBSSr213r:
18920   case X86::VFMADDPDr213rY:
18921   case X86::VFMADDPSr213rY:
18922   case X86::VFMSUBPDr213rY:
18923   case X86::VFMSUBPSr213rY:
18924   case X86::VFNMADDPDr213rY:
18925   case X86::VFNMADDPSr213rY:
18926   case X86::VFNMSUBPDr213rY:
18927   case X86::VFNMSUBPSr213rY:
18928     return emitFMA3Instr(MI, BB);
18929   }
18930 }
18931
18932 //===----------------------------------------------------------------------===//
18933 //                           X86 Optimization Hooks
18934 //===----------------------------------------------------------------------===//
18935
18936 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18937                                                       APInt &KnownZero,
18938                                                       APInt &KnownOne,
18939                                                       const SelectionDAG &DAG,
18940                                                       unsigned Depth) const {
18941   unsigned BitWidth = KnownZero.getBitWidth();
18942   unsigned Opc = Op.getOpcode();
18943   assert((Opc >= ISD::BUILTIN_OP_END ||
18944           Opc == ISD::INTRINSIC_WO_CHAIN ||
18945           Opc == ISD::INTRINSIC_W_CHAIN ||
18946           Opc == ISD::INTRINSIC_VOID) &&
18947          "Should use MaskedValueIsZero if you don't know whether Op"
18948          " is a target node!");
18949
18950   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18951   switch (Opc) {
18952   default: break;
18953   case X86ISD::ADD:
18954   case X86ISD::SUB:
18955   case X86ISD::ADC:
18956   case X86ISD::SBB:
18957   case X86ISD::SMUL:
18958   case X86ISD::UMUL:
18959   case X86ISD::INC:
18960   case X86ISD::DEC:
18961   case X86ISD::OR:
18962   case X86ISD::XOR:
18963   case X86ISD::AND:
18964     // These nodes' second result is a boolean.
18965     if (Op.getResNo() == 0)
18966       break;
18967     // Fallthrough
18968   case X86ISD::SETCC:
18969     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18970     break;
18971   case ISD::INTRINSIC_WO_CHAIN: {
18972     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18973     unsigned NumLoBits = 0;
18974     switch (IntId) {
18975     default: break;
18976     case Intrinsic::x86_sse_movmsk_ps:
18977     case Intrinsic::x86_avx_movmsk_ps_256:
18978     case Intrinsic::x86_sse2_movmsk_pd:
18979     case Intrinsic::x86_avx_movmsk_pd_256:
18980     case Intrinsic::x86_mmx_pmovmskb:
18981     case Intrinsic::x86_sse2_pmovmskb_128:
18982     case Intrinsic::x86_avx2_pmovmskb: {
18983       // High bits of movmskp{s|d}, pmovmskb are known zero.
18984       switch (IntId) {
18985         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18986         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18987         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18988         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18989         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18990         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18991         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18992         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18993       }
18994       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18995       break;
18996     }
18997     }
18998     break;
18999   }
19000   }
19001 }
19002
19003 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19004   SDValue Op,
19005   const SelectionDAG &,
19006   unsigned Depth) const {
19007   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19008   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19009     return Op.getValueType().getScalarType().getSizeInBits();
19010
19011   // Fallback case.
19012   return 1;
19013 }
19014
19015 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19016 /// node is a GlobalAddress + offset.
19017 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19018                                        const GlobalValue* &GA,
19019                                        int64_t &Offset) const {
19020   if (N->getOpcode() == X86ISD::Wrapper) {
19021     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19022       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19023       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19024       return true;
19025     }
19026   }
19027   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19028 }
19029
19030 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19031 /// same as extracting the high 128-bit part of 256-bit vector and then
19032 /// inserting the result into the low part of a new 256-bit vector
19033 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19034   EVT VT = SVOp->getValueType(0);
19035   unsigned NumElems = VT.getVectorNumElements();
19036
19037   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19038   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19039     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19040         SVOp->getMaskElt(j) >= 0)
19041       return false;
19042
19043   return true;
19044 }
19045
19046 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19047 /// same as extracting the low 128-bit part of 256-bit vector and then
19048 /// inserting the result into the high part of a new 256-bit vector
19049 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19050   EVT VT = SVOp->getValueType(0);
19051   unsigned NumElems = VT.getVectorNumElements();
19052
19053   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19054   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19055     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19056         SVOp->getMaskElt(j) >= 0)
19057       return false;
19058
19059   return true;
19060 }
19061
19062 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19063 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19064                                         TargetLowering::DAGCombinerInfo &DCI,
19065                                         const X86Subtarget* Subtarget) {
19066   SDLoc dl(N);
19067   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19068   SDValue V1 = SVOp->getOperand(0);
19069   SDValue V2 = SVOp->getOperand(1);
19070   EVT VT = SVOp->getValueType(0);
19071   unsigned NumElems = VT.getVectorNumElements();
19072
19073   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19074       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19075     //
19076     //                   0,0,0,...
19077     //                      |
19078     //    V      UNDEF    BUILD_VECTOR    UNDEF
19079     //     \      /           \           /
19080     //  CONCAT_VECTOR         CONCAT_VECTOR
19081     //         \                  /
19082     //          \                /
19083     //          RESULT: V + zero extended
19084     //
19085     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19086         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19087         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19088       return SDValue();
19089
19090     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19091       return SDValue();
19092
19093     // To match the shuffle mask, the first half of the mask should
19094     // be exactly the first vector, and all the rest a splat with the
19095     // first element of the second one.
19096     for (unsigned i = 0; i != NumElems/2; ++i)
19097       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19098           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19099         return SDValue();
19100
19101     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19102     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19103       if (Ld->hasNUsesOfValue(1, 0)) {
19104         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19105         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19106         SDValue ResNode =
19107           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19108                                   Ld->getMemoryVT(),
19109                                   Ld->getPointerInfo(),
19110                                   Ld->getAlignment(),
19111                                   false/*isVolatile*/, true/*ReadMem*/,
19112                                   false/*WriteMem*/);
19113
19114         // Make sure the newly-created LOAD is in the same position as Ld in
19115         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19116         // and update uses of Ld's output chain to use the TokenFactor.
19117         if (Ld->hasAnyUseOfValue(1)) {
19118           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19119                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19120           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19121           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19122                                  SDValue(ResNode.getNode(), 1));
19123         }
19124
19125         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19126       }
19127     }
19128
19129     // Emit a zeroed vector and insert the desired subvector on its
19130     // first half.
19131     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19132     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19133     return DCI.CombineTo(N, InsV);
19134   }
19135
19136   //===--------------------------------------------------------------------===//
19137   // Combine some shuffles into subvector extracts and inserts:
19138   //
19139
19140   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19141   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19142     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19143     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19144     return DCI.CombineTo(N, InsV);
19145   }
19146
19147   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19148   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19149     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19150     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19151     return DCI.CombineTo(N, InsV);
19152   }
19153
19154   return SDValue();
19155 }
19156
19157 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19158 /// possible.
19159 ///
19160 /// This is the leaf of the recursive combinine below. When we have found some
19161 /// chain of single-use x86 shuffle instructions and accumulated the combined
19162 /// shuffle mask represented by them, this will try to pattern match that mask
19163 /// into either a single instruction if there is a special purpose instruction
19164 /// for this operation, or into a PSHUFB instruction which is a fully general
19165 /// instruction but should only be used to replace chains over a certain depth.
19166 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19167                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19168                                    TargetLowering::DAGCombinerInfo &DCI,
19169                                    const X86Subtarget *Subtarget) {
19170   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19171
19172   // Find the operand that enters the chain. Note that multiple uses are OK
19173   // here, we're not going to remove the operand we find.
19174   SDValue Input = Op.getOperand(0);
19175   while (Input.getOpcode() == ISD::BITCAST)
19176     Input = Input.getOperand(0);
19177
19178   MVT VT = Input.getSimpleValueType();
19179   MVT RootVT = Root.getSimpleValueType();
19180   SDLoc DL(Root);
19181
19182   // Just remove no-op shuffle masks.
19183   if (Mask.size() == 1) {
19184     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19185                   /*AddTo*/ true);
19186     return true;
19187   }
19188
19189   // Use the float domain if the operand type is a floating point type.
19190   bool FloatDomain = VT.isFloatingPoint();
19191
19192   // If we don't have access to VEX encodings, the generic PSHUF instructions
19193   // are preferable to some of the specialized forms despite requiring one more
19194   // byte to encode because they can implicitly copy.
19195   //
19196   // IF we *do* have VEX encodings, than we can use shorter, more specific
19197   // shuffle instructions freely as they can copy due to the extra register
19198   // operand.
19199   if (Subtarget->hasAVX()) {
19200     // We have both floating point and integer variants of shuffles that dup
19201     // either the low or high half of the vector.
19202     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19203       bool Lo = Mask.equals(0, 0);
19204       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19205                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19206       if (Depth == 1 && Root->getOpcode() == Shuffle)
19207         return false; // Nothing to do!
19208       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19209       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19210       DCI.AddToWorklist(Op.getNode());
19211       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19212       DCI.AddToWorklist(Op.getNode());
19213       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19214                     /*AddTo*/ true);
19215       return true;
19216     }
19217
19218     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19219
19220     // For the integer domain we have specialized instructions for duplicating
19221     // any element size from the low or high half.
19222     if (!FloatDomain &&
19223         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19224          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19225          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19226          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19227          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19228                      15))) {
19229       bool Lo = Mask[0] == 0;
19230       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19231       if (Depth == 1 && Root->getOpcode() == Shuffle)
19232         return false; // Nothing to do!
19233       MVT ShuffleVT;
19234       switch (Mask.size()) {
19235       case 4: ShuffleVT = MVT::v4i32; break;
19236       case 8: ShuffleVT = MVT::v8i16; break;
19237       case 16: ShuffleVT = MVT::v16i8; break;
19238       };
19239       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19240       DCI.AddToWorklist(Op.getNode());
19241       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19242       DCI.AddToWorklist(Op.getNode());
19243       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19244                     /*AddTo*/ true);
19245       return true;
19246     }
19247   }
19248
19249   // Don't try to re-form single instruction chains under any circumstances now
19250   // that we've done encoding canonicalization for them.
19251   if (Depth < 2)
19252     return false;
19253
19254   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19255   // can replace them with a single PSHUFB instruction profitably. Intel's
19256   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19257   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19258   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19259     SmallVector<SDValue, 16> PSHUFBMask;
19260     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19261     int Ratio = 16 / Mask.size();
19262     for (unsigned i = 0; i < 16; ++i) {
19263       int M = Mask[i / Ratio] != SM_SentinelZero
19264                   ? Ratio * Mask[i / Ratio] + i % Ratio
19265                   : 255;
19266       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19267     }
19268     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19269     DCI.AddToWorklist(Op.getNode());
19270     SDValue PSHUFBMaskOp =
19271         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19272     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19273     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19274     DCI.AddToWorklist(Op.getNode());
19275     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19276                   /*AddTo*/ true);
19277     return true;
19278   }
19279
19280   // Failed to find any combines.
19281   return false;
19282 }
19283
19284 /// \brief Fully generic combining of x86 shuffle instructions.
19285 ///
19286 /// This should be the last combine run over the x86 shuffle instructions. Once
19287 /// they have been fully optimized, this will recursively consider all chains
19288 /// of single-use shuffle instructions, build a generic model of the cumulative
19289 /// shuffle operation, and check for simpler instructions which implement this
19290 /// operation. We use this primarily for two purposes:
19291 ///
19292 /// 1) Collapse generic shuffles to specialized single instructions when
19293 ///    equivalent. In most cases, this is just an encoding size win, but
19294 ///    sometimes we will collapse multiple generic shuffles into a single
19295 ///    special-purpose shuffle.
19296 /// 2) Look for sequences of shuffle instructions with 3 or more total
19297 ///    instructions, and replace them with the slightly more expensive SSSE3
19298 ///    PSHUFB instruction if available. We do this as the last combining step
19299 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19300 ///    a suitable short sequence of other instructions. The PHUFB will either
19301 ///    use a register or have to read from memory and so is slightly (but only
19302 ///    slightly) more expensive than the other shuffle instructions.
19303 ///
19304 /// Because this is inherently a quadratic operation (for each shuffle in
19305 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19306 /// This should never be an issue in practice as the shuffle lowering doesn't
19307 /// produce sequences of more than 8 instructions.
19308 ///
19309 /// FIXME: We will currently miss some cases where the redundant shuffling
19310 /// would simplify under the threshold for PSHUFB formation because of
19311 /// combine-ordering. To fix this, we should do the redundant instruction
19312 /// combining in this recursive walk.
19313 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19314                                           ArrayRef<int> RootMask,
19315                                           int Depth, bool HasPSHUFB,
19316                                           SelectionDAG &DAG,
19317                                           TargetLowering::DAGCombinerInfo &DCI,
19318                                           const X86Subtarget *Subtarget) {
19319   // Bound the depth of our recursive combine because this is ultimately
19320   // quadratic in nature.
19321   if (Depth > 8)
19322     return false;
19323
19324   // Directly rip through bitcasts to find the underlying operand.
19325   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19326     Op = Op.getOperand(0);
19327
19328   MVT VT = Op.getSimpleValueType();
19329   if (!VT.isVector())
19330     return false; // Bail if we hit a non-vector.
19331   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19332   // version should be added.
19333   if (VT.getSizeInBits() != 128)
19334     return false;
19335
19336   assert(Root.getSimpleValueType().isVector() &&
19337          "Shuffles operate on vector types!");
19338   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19339          "Can only combine shuffles of the same vector register size.");
19340
19341   if (!isTargetShuffle(Op.getOpcode()))
19342     return false;
19343   SmallVector<int, 16> OpMask;
19344   bool IsUnary;
19345   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19346   // We only can combine unary shuffles which we can decode the mask for.
19347   if (!HaveMask || !IsUnary)
19348     return false;
19349
19350   assert(VT.getVectorNumElements() == OpMask.size() &&
19351          "Different mask size from vector size!");
19352   assert(((RootMask.size() > OpMask.size() &&
19353            RootMask.size() % OpMask.size() == 0) ||
19354           (OpMask.size() > RootMask.size() &&
19355            OpMask.size() % RootMask.size() == 0) ||
19356           OpMask.size() == RootMask.size()) &&
19357          "The smaller number of elements must divide the larger.");
19358   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19359   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19360   assert(((RootRatio == 1 && OpRatio == 1) ||
19361           (RootRatio == 1) != (OpRatio == 1)) &&
19362          "Must not have a ratio for both incoming and op masks!");
19363
19364   SmallVector<int, 16> Mask;
19365   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19366
19367   // Merge this shuffle operation's mask into our accumulated mask. Note that
19368   // this shuffle's mask will be the first applied to the input, followed by the
19369   // root mask to get us all the way to the root value arrangement. The reason
19370   // for this order is that we are recursing up the operation chain.
19371   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19372     int RootIdx = i / RootRatio;
19373     if (RootMask[RootIdx] == SM_SentinelZero) {
19374       // This is a zero-ed lane, we're done.
19375       Mask.push_back(SM_SentinelZero);
19376       continue;
19377     }
19378
19379     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19380     int OpIdx = RootMaskedIdx / OpRatio;
19381     if (OpMask[OpIdx] == SM_SentinelZero) {
19382       // The incoming lanes are zero, it doesn't matter which ones we are using.
19383       Mask.push_back(SM_SentinelZero);
19384       continue;
19385     }
19386
19387     // Ok, we have non-zero lanes, map them through.
19388     Mask.push_back(OpMask[OpIdx] * OpRatio +
19389                    RootMaskedIdx % OpRatio);
19390   }
19391
19392   // See if we can recurse into the operand to combine more things.
19393   switch (Op.getOpcode()) {
19394     case X86ISD::PSHUFB:
19395       HasPSHUFB = true;
19396     case X86ISD::PSHUFD:
19397     case X86ISD::PSHUFHW:
19398     case X86ISD::PSHUFLW:
19399       if (Op.getOperand(0).hasOneUse() &&
19400           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19401                                         HasPSHUFB, DAG, DCI, Subtarget))
19402         return true;
19403       break;
19404
19405     case X86ISD::UNPCKL:
19406     case X86ISD::UNPCKH:
19407       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19408       // We can't check for single use, we have to check that this shuffle is the only user.
19409       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19410           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19411                                         HasPSHUFB, DAG, DCI, Subtarget))
19412           return true;
19413       break;
19414   }
19415
19416   // Minor canonicalization of the accumulated shuffle mask to make it easier
19417   // to match below. All this does is detect masks with squential pairs of
19418   // elements, and shrink them to the half-width mask. It does this in a loop
19419   // so it will reduce the size of the mask to the minimal width mask which
19420   // performs an equivalent shuffle.
19421   while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19422     for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19423       Mask[i] = Mask[2 * i] / 2;
19424     Mask.resize(Mask.size() / 2);
19425   }
19426
19427   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19428                                 Subtarget);
19429 }
19430
19431 /// \brief Get the PSHUF-style mask from PSHUF node.
19432 ///
19433 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19434 /// PSHUF-style masks that can be reused with such instructions.
19435 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19436   SmallVector<int, 4> Mask;
19437   bool IsUnary;
19438   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19439   (void)HaveMask;
19440   assert(HaveMask);
19441
19442   switch (N.getOpcode()) {
19443   case X86ISD::PSHUFD:
19444     return Mask;
19445   case X86ISD::PSHUFLW:
19446     Mask.resize(4);
19447     return Mask;
19448   case X86ISD::PSHUFHW:
19449     Mask.erase(Mask.begin(), Mask.begin() + 4);
19450     for (int &M : Mask)
19451       M -= 4;
19452     return Mask;
19453   default:
19454     llvm_unreachable("No valid shuffle instruction found!");
19455   }
19456 }
19457
19458 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19459 ///
19460 /// We walk up the chain and look for a combinable shuffle, skipping over
19461 /// shuffles that we could hoist this shuffle's transformation past without
19462 /// altering anything.
19463 static SDValue
19464 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19465                              SelectionDAG &DAG,
19466                              TargetLowering::DAGCombinerInfo &DCI) {
19467   assert(N.getOpcode() == X86ISD::PSHUFD &&
19468          "Called with something other than an x86 128-bit half shuffle!");
19469   SDLoc DL(N);
19470
19471   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19472   // of the shuffles in the chain so that we can form a fresh chain to replace
19473   // this one.
19474   SmallVector<SDValue, 8> Chain;
19475   SDValue V = N.getOperand(0);
19476   for (; V.hasOneUse(); V = V.getOperand(0)) {
19477     switch (V.getOpcode()) {
19478     default:
19479       return SDValue(); // Nothing combined!
19480
19481     case ISD::BITCAST:
19482       // Skip bitcasts as we always know the type for the target specific
19483       // instructions.
19484       continue;
19485
19486     case X86ISD::PSHUFD:
19487       // Found another dword shuffle.
19488       break;
19489
19490     case X86ISD::PSHUFLW:
19491       // Check that the low words (being shuffled) are the identity in the
19492       // dword shuffle, and the high words are self-contained.
19493       if (Mask[0] != 0 || Mask[1] != 1 ||
19494           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19495         return SDValue();
19496
19497       Chain.push_back(V);
19498       continue;
19499
19500     case X86ISD::PSHUFHW:
19501       // Check that the high words (being shuffled) are the identity in the
19502       // dword shuffle, and the low words are self-contained.
19503       if (Mask[2] != 2 || Mask[3] != 3 ||
19504           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19505         return SDValue();
19506
19507       Chain.push_back(V);
19508       continue;
19509
19510     case X86ISD::UNPCKL:
19511     case X86ISD::UNPCKH:
19512       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19513       // shuffle into a preceding word shuffle.
19514       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19515         return SDValue();
19516
19517       // Search for a half-shuffle which we can combine with.
19518       unsigned CombineOp =
19519           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19520       if (V.getOperand(0) != V.getOperand(1) ||
19521           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19522         return SDValue();
19523       Chain.push_back(V);
19524       V = V.getOperand(0);
19525       do {
19526         switch (V.getOpcode()) {
19527         default:
19528           return SDValue(); // Nothing to combine.
19529
19530         case X86ISD::PSHUFLW:
19531         case X86ISD::PSHUFHW:
19532           if (V.getOpcode() == CombineOp)
19533             break;
19534
19535           Chain.push_back(V);
19536
19537           // Fallthrough!
19538         case ISD::BITCAST:
19539           V = V.getOperand(0);
19540           continue;
19541         }
19542         break;
19543       } while (V.hasOneUse());
19544       break;
19545     }
19546     // Break out of the loop if we break out of the switch.
19547     break;
19548   }
19549
19550   if (!V.hasOneUse())
19551     // We fell out of the loop without finding a viable combining instruction.
19552     return SDValue();
19553
19554   // Merge this node's mask and our incoming mask.
19555   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19556   for (int &M : Mask)
19557     M = VMask[M];
19558   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19559                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19560
19561   // Rebuild the chain around this new shuffle.
19562   while (!Chain.empty()) {
19563     SDValue W = Chain.pop_back_val();
19564
19565     if (V.getValueType() != W.getOperand(0).getValueType())
19566       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19567
19568     switch (W.getOpcode()) {
19569     default:
19570       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19571
19572     case X86ISD::UNPCKL:
19573     case X86ISD::UNPCKH:
19574       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19575       break;
19576
19577     case X86ISD::PSHUFD:
19578     case X86ISD::PSHUFLW:
19579     case X86ISD::PSHUFHW:
19580       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19581       break;
19582     }
19583   }
19584   if (V.getValueType() != N.getValueType())
19585     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19586
19587   // Return the new chain to replace N.
19588   return V;
19589 }
19590
19591 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19592 ///
19593 /// We walk up the chain, skipping shuffles of the other half and looking
19594 /// through shuffles which switch halves trying to find a shuffle of the same
19595 /// pair of dwords.
19596 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19597                                         SelectionDAG &DAG,
19598                                         TargetLowering::DAGCombinerInfo &DCI) {
19599   assert(
19600       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19601       "Called with something other than an x86 128-bit half shuffle!");
19602   SDLoc DL(N);
19603   unsigned CombineOpcode = N.getOpcode();
19604
19605   // Walk up a single-use chain looking for a combinable shuffle.
19606   SDValue V = N.getOperand(0);
19607   for (; V.hasOneUse(); V = V.getOperand(0)) {
19608     switch (V.getOpcode()) {
19609     default:
19610       return false; // Nothing combined!
19611
19612     case ISD::BITCAST:
19613       // Skip bitcasts as we always know the type for the target specific
19614       // instructions.
19615       continue;
19616
19617     case X86ISD::PSHUFLW:
19618     case X86ISD::PSHUFHW:
19619       if (V.getOpcode() == CombineOpcode)
19620         break;
19621
19622       // Other-half shuffles are no-ops.
19623       continue;
19624     }
19625     // Break out of the loop if we break out of the switch.
19626     break;
19627   }
19628
19629   if (!V.hasOneUse())
19630     // We fell out of the loop without finding a viable combining instruction.
19631     return false;
19632
19633   // Combine away the bottom node as its shuffle will be accumulated into
19634   // a preceding shuffle.
19635   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19636
19637   // Record the old value.
19638   SDValue Old = V;
19639
19640   // Merge this node's mask and our incoming mask (adjusted to account for all
19641   // the pshufd instructions encountered).
19642   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19643   for (int &M : Mask)
19644     M = VMask[M];
19645   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19646                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19647
19648   // Check that the shuffles didn't cancel each other out. If not, we need to
19649   // combine to the new one.
19650   if (Old != V)
19651     // Replace the combinable shuffle with the combined one, updating all users
19652     // so that we re-evaluate the chain here.
19653     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19654
19655   return true;
19656 }
19657
19658 /// \brief Try to combine x86 target specific shuffles.
19659 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19660                                            TargetLowering::DAGCombinerInfo &DCI,
19661                                            const X86Subtarget *Subtarget) {
19662   SDLoc DL(N);
19663   MVT VT = N.getSimpleValueType();
19664   SmallVector<int, 4> Mask;
19665
19666   switch (N.getOpcode()) {
19667   case X86ISD::PSHUFD:
19668   case X86ISD::PSHUFLW:
19669   case X86ISD::PSHUFHW:
19670     Mask = getPSHUFShuffleMask(N);
19671     assert(Mask.size() == 4);
19672     break;
19673   default:
19674     return SDValue();
19675   }
19676
19677   // Nuke no-op shuffles that show up after combining.
19678   if (isNoopShuffleMask(Mask))
19679     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19680
19681   // Look for simplifications involving one or two shuffle instructions.
19682   SDValue V = N.getOperand(0);
19683   switch (N.getOpcode()) {
19684   default:
19685     break;
19686   case X86ISD::PSHUFLW:
19687   case X86ISD::PSHUFHW:
19688     assert(VT == MVT::v8i16);
19689     (void)VT;
19690
19691     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19692       return SDValue(); // We combined away this shuffle, so we're done.
19693
19694     // See if this reduces to a PSHUFD which is no more expensive and can
19695     // combine with more operations.
19696     if (canWidenShuffleElements(Mask)) {
19697       int DMask[] = {-1, -1, -1, -1};
19698       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19699       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19700       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19701       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19702       DCI.AddToWorklist(V.getNode());
19703       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19704                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19705       DCI.AddToWorklist(V.getNode());
19706       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19707     }
19708
19709     // Look for shuffle patterns which can be implemented as a single unpack.
19710     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19711     // only works when we have a PSHUFD followed by two half-shuffles.
19712     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19713         (V.getOpcode() == X86ISD::PSHUFLW ||
19714          V.getOpcode() == X86ISD::PSHUFHW) &&
19715         V.getOpcode() != N.getOpcode() &&
19716         V.hasOneUse()) {
19717       SDValue D = V.getOperand(0);
19718       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19719         D = D.getOperand(0);
19720       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19721         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19722         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19723         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19724         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19725         int WordMask[8];
19726         for (int i = 0; i < 4; ++i) {
19727           WordMask[i + NOffset] = Mask[i] + NOffset;
19728           WordMask[i + VOffset] = VMask[i] + VOffset;
19729         }
19730         // Map the word mask through the DWord mask.
19731         int MappedMask[8];
19732         for (int i = 0; i < 8; ++i)
19733           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19734         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19735         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19736         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19737                        std::begin(UnpackLoMask)) ||
19738             std::equal(std::begin(MappedMask), std::end(MappedMask),
19739                        std::begin(UnpackHiMask))) {
19740           // We can replace all three shuffles with an unpack.
19741           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19742           DCI.AddToWorklist(V.getNode());
19743           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19744                                                 : X86ISD::UNPCKH,
19745                              DL, MVT::v8i16, V, V);
19746         }
19747       }
19748     }
19749
19750     break;
19751
19752   case X86ISD::PSHUFD:
19753     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19754       return NewN;
19755
19756     break;
19757   }
19758
19759   return SDValue();
19760 }
19761
19762 /// PerformShuffleCombine - Performs several different shuffle combines.
19763 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19764                                      TargetLowering::DAGCombinerInfo &DCI,
19765                                      const X86Subtarget *Subtarget) {
19766   SDLoc dl(N);
19767   SDValue N0 = N->getOperand(0);
19768   SDValue N1 = N->getOperand(1);
19769   EVT VT = N->getValueType(0);
19770
19771   // Don't create instructions with illegal types after legalize types has run.
19772   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19773   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19774     return SDValue();
19775
19776   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19777   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19778       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19779     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19780
19781   // During Type Legalization, when promoting illegal vector types,
19782   // the backend might introduce new shuffle dag nodes and bitcasts.
19783   //
19784   // This code performs the following transformation:
19785   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19786   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19787   //
19788   // We do this only if both the bitcast and the BINOP dag nodes have
19789   // one use. Also, perform this transformation only if the new binary
19790   // operation is legal. This is to avoid introducing dag nodes that
19791   // potentially need to be further expanded (or custom lowered) into a
19792   // less optimal sequence of dag nodes.
19793   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19794       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19795       N0.getOpcode() == ISD::BITCAST) {
19796     SDValue BC0 = N0.getOperand(0);
19797     EVT SVT = BC0.getValueType();
19798     unsigned Opcode = BC0.getOpcode();
19799     unsigned NumElts = VT.getVectorNumElements();
19800     
19801     if (BC0.hasOneUse() && SVT.isVector() &&
19802         SVT.getVectorNumElements() * 2 == NumElts &&
19803         TLI.isOperationLegal(Opcode, VT)) {
19804       bool CanFold = false;
19805       switch (Opcode) {
19806       default : break;
19807       case ISD::ADD :
19808       case ISD::FADD :
19809       case ISD::SUB :
19810       case ISD::FSUB :
19811       case ISD::MUL :
19812       case ISD::FMUL :
19813         CanFold = true;
19814       }
19815
19816       unsigned SVTNumElts = SVT.getVectorNumElements();
19817       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19818       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19819         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19820       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19821         CanFold = SVOp->getMaskElt(i) < 0;
19822
19823       if (CanFold) {
19824         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19825         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19826         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19827         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19828       }
19829     }
19830   }
19831
19832   // Only handle 128 wide vector from here on.
19833   if (!VT.is128BitVector())
19834     return SDValue();
19835
19836   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19837   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19838   // consecutive, non-overlapping, and in the right order.
19839   SmallVector<SDValue, 16> Elts;
19840   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19841     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19842
19843   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19844   if (LD.getNode())
19845     return LD;
19846
19847   if (isTargetShuffle(N->getOpcode())) {
19848     SDValue Shuffle =
19849         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19850     if (Shuffle.getNode())
19851       return Shuffle;
19852
19853     // Try recursively combining arbitrary sequences of x86 shuffle
19854     // instructions into higher-order shuffles. We do this after combining
19855     // specific PSHUF instruction sequences into their minimal form so that we
19856     // can evaluate how many specialized shuffle instructions are involved in
19857     // a particular chain.
19858     SmallVector<int, 1> NonceMask; // Just a placeholder.
19859     NonceMask.push_back(0);
19860     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19861                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19862                                       DCI, Subtarget))
19863       return SDValue(); // This routine will use CombineTo to replace N.
19864   }
19865
19866   return SDValue();
19867 }
19868
19869 /// PerformTruncateCombine - Converts truncate operation to
19870 /// a sequence of vector shuffle operations.
19871 /// It is possible when we truncate 256-bit vector to 128-bit vector
19872 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19873                                       TargetLowering::DAGCombinerInfo &DCI,
19874                                       const X86Subtarget *Subtarget)  {
19875   return SDValue();
19876 }
19877
19878 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19879 /// specific shuffle of a load can be folded into a single element load.
19880 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19881 /// shuffles have been customed lowered so we need to handle those here.
19882 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19883                                          TargetLowering::DAGCombinerInfo &DCI) {
19884   if (DCI.isBeforeLegalizeOps())
19885     return SDValue();
19886
19887   SDValue InVec = N->getOperand(0);
19888   SDValue EltNo = N->getOperand(1);
19889
19890   if (!isa<ConstantSDNode>(EltNo))
19891     return SDValue();
19892
19893   EVT VT = InVec.getValueType();
19894
19895   if (InVec.getOpcode() == ISD::BITCAST) {
19896     // Don't duplicate a load with other uses.
19897     if (!InVec.hasOneUse())
19898       return SDValue();
19899     EVT BCVT = InVec.getOperand(0).getValueType();
19900     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19901       return SDValue();
19902     InVec = InVec.getOperand(0);
19903   }
19904
19905   if (!isTargetShuffle(InVec.getOpcode()))
19906     return SDValue();
19907
19908   // Don't duplicate a load with other uses.
19909   if (!InVec.hasOneUse())
19910     return SDValue();
19911
19912   SmallVector<int, 16> ShuffleMask;
19913   bool UnaryShuffle;
19914   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19915                             UnaryShuffle))
19916     return SDValue();
19917
19918   // Select the input vector, guarding against out of range extract vector.
19919   unsigned NumElems = VT.getVectorNumElements();
19920   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19921   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19922   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19923                                          : InVec.getOperand(1);
19924
19925   // If inputs to shuffle are the same for both ops, then allow 2 uses
19926   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19927
19928   if (LdNode.getOpcode() == ISD::BITCAST) {
19929     // Don't duplicate a load with other uses.
19930     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19931       return SDValue();
19932
19933     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19934     LdNode = LdNode.getOperand(0);
19935   }
19936
19937   if (!ISD::isNormalLoad(LdNode.getNode()))
19938     return SDValue();
19939
19940   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19941
19942   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19943     return SDValue();
19944
19945   EVT EltVT = N->getValueType(0);
19946   // If there's a bitcast before the shuffle, check if the load type and
19947   // alignment is valid.
19948   unsigned Align = LN0->getAlignment();
19949   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19950   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
19951       EltVT.getTypeForEVT(*DAG.getContext()));
19952
19953   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
19954     return SDValue();
19955
19956   // All checks match so transform back to vector_shuffle so that DAG combiner
19957   // can finish the job
19958   SDLoc dl(N);
19959
19960   // Create shuffle node taking into account the case that its a unary shuffle
19961   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19962   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19963                                  InVec.getOperand(0), Shuffle,
19964                                  &ShuffleMask[0]);
19965   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19966   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19967                      EltNo);
19968 }
19969
19970 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19971 /// generation and convert it from being a bunch of shuffles and extracts
19972 /// to a simple store and scalar loads to extract the elements.
19973 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19974                                          TargetLowering::DAGCombinerInfo &DCI) {
19975   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19976   if (NewOp.getNode())
19977     return NewOp;
19978
19979   SDValue InputVector = N->getOperand(0);
19980
19981   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19982   // from mmx to v2i32 has a single usage.
19983   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19984       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19985       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19986     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19987                        N->getValueType(0),
19988                        InputVector.getNode()->getOperand(0));
19989
19990   // Only operate on vectors of 4 elements, where the alternative shuffling
19991   // gets to be more expensive.
19992   if (InputVector.getValueType() != MVT::v4i32)
19993     return SDValue();
19994
19995   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19996   // single use which is a sign-extend or zero-extend, and all elements are
19997   // used.
19998   SmallVector<SDNode *, 4> Uses;
19999   unsigned ExtractedElements = 0;
20000   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20001        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20002     if (UI.getUse().getResNo() != InputVector.getResNo())
20003       return SDValue();
20004
20005     SDNode *Extract = *UI;
20006     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20007       return SDValue();
20008
20009     if (Extract->getValueType(0) != MVT::i32)
20010       return SDValue();
20011     if (!Extract->hasOneUse())
20012       return SDValue();
20013     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20014         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20015       return SDValue();
20016     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20017       return SDValue();
20018
20019     // Record which element was extracted.
20020     ExtractedElements |=
20021       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20022
20023     Uses.push_back(Extract);
20024   }
20025
20026   // If not all the elements were used, this may not be worthwhile.
20027   if (ExtractedElements != 15)
20028     return SDValue();
20029
20030   // Ok, we've now decided to do the transformation.
20031   SDLoc dl(InputVector);
20032
20033   // Store the value to a temporary stack slot.
20034   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20035   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20036                             MachinePointerInfo(), false, false, 0);
20037
20038   // Replace each use (extract) with a load of the appropriate element.
20039   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20040        UE = Uses.end(); UI != UE; ++UI) {
20041     SDNode *Extract = *UI;
20042
20043     // cOMpute the element's address.
20044     SDValue Idx = Extract->getOperand(1);
20045     unsigned EltSize =
20046         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
20047     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
20048     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20049     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20050
20051     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20052                                      StackPtr, OffsetVal);
20053
20054     // Load the scalar.
20055     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
20056                                      ScalarAddr, MachinePointerInfo(),
20057                                      false, false, false, 0);
20058
20059     // Replace the exact with the load.
20060     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
20061   }
20062
20063   // The replacement was made in place; don't return anything.
20064   return SDValue();
20065 }
20066
20067 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20068 static std::pair<unsigned, bool>
20069 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20070                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20071   if (!VT.isVector())
20072     return std::make_pair(0, false);
20073
20074   bool NeedSplit = false;
20075   switch (VT.getSimpleVT().SimpleTy) {
20076   default: return std::make_pair(0, false);
20077   case MVT::v32i8:
20078   case MVT::v16i16:
20079   case MVT::v8i32:
20080     if (!Subtarget->hasAVX2())
20081       NeedSplit = true;
20082     if (!Subtarget->hasAVX())
20083       return std::make_pair(0, false);
20084     break;
20085   case MVT::v16i8:
20086   case MVT::v8i16:
20087   case MVT::v4i32:
20088     if (!Subtarget->hasSSE2())
20089       return std::make_pair(0, false);
20090   }
20091
20092   // SSE2 has only a small subset of the operations.
20093   bool hasUnsigned = Subtarget->hasSSE41() ||
20094                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20095   bool hasSigned = Subtarget->hasSSE41() ||
20096                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20097
20098   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20099
20100   unsigned Opc = 0;
20101   // Check for x CC y ? x : y.
20102   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20103       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20104     switch (CC) {
20105     default: break;
20106     case ISD::SETULT:
20107     case ISD::SETULE:
20108       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20109     case ISD::SETUGT:
20110     case ISD::SETUGE:
20111       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20112     case ISD::SETLT:
20113     case ISD::SETLE:
20114       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20115     case ISD::SETGT:
20116     case ISD::SETGE:
20117       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20118     }
20119   // Check for x CC y ? y : x -- a min/max with reversed arms.
20120   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20121              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20122     switch (CC) {
20123     default: break;
20124     case ISD::SETULT:
20125     case ISD::SETULE:
20126       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20127     case ISD::SETUGT:
20128     case ISD::SETUGE:
20129       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20130     case ISD::SETLT:
20131     case ISD::SETLE:
20132       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20133     case ISD::SETGT:
20134     case ISD::SETGE:
20135       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20136     }
20137   }
20138
20139   return std::make_pair(Opc, NeedSplit);
20140 }
20141
20142 static SDValue
20143 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20144                                       const X86Subtarget *Subtarget) {
20145   SDLoc dl(N);
20146   SDValue Cond = N->getOperand(0);
20147   SDValue LHS = N->getOperand(1);
20148   SDValue RHS = N->getOperand(2);
20149
20150   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20151     SDValue CondSrc = Cond->getOperand(0);
20152     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20153       Cond = CondSrc->getOperand(0);
20154   }
20155
20156   MVT VT = N->getSimpleValueType(0);
20157   MVT EltVT = VT.getVectorElementType();
20158   unsigned NumElems = VT.getVectorNumElements();
20159   // There is no blend with immediate in AVX-512.
20160   if (VT.is512BitVector())
20161     return SDValue();
20162
20163   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20164     return SDValue();
20165   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20166     return SDValue();
20167
20168   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20169     return SDValue();
20170
20171   // A vselect where all conditions and data are constants can be optimized into
20172   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20173   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20174       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20175     return SDValue();
20176
20177   unsigned MaskValue = 0;
20178   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20179     return SDValue();
20180
20181   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20182   for (unsigned i = 0; i < NumElems; ++i) {
20183     // Be sure we emit undef where we can.
20184     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20185       ShuffleMask[i] = -1;
20186     else
20187       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20188   }
20189
20190   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20191 }
20192
20193 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20194 /// nodes.
20195 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20196                                     TargetLowering::DAGCombinerInfo &DCI,
20197                                     const X86Subtarget *Subtarget) {
20198   SDLoc DL(N);
20199   SDValue Cond = N->getOperand(0);
20200   // Get the LHS/RHS of the select.
20201   SDValue LHS = N->getOperand(1);
20202   SDValue RHS = N->getOperand(2);
20203   EVT VT = LHS.getValueType();
20204   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20205
20206   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20207   // instructions match the semantics of the common C idiom x<y?x:y but not
20208   // x<=y?x:y, because of how they handle negative zero (which can be
20209   // ignored in unsafe-math mode).
20210   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20211       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20212       (Subtarget->hasSSE2() ||
20213        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20214     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20215
20216     unsigned Opcode = 0;
20217     // Check for x CC y ? x : y.
20218     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20219         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20220       switch (CC) {
20221       default: break;
20222       case ISD::SETULT:
20223         // Converting this to a min would handle NaNs incorrectly, and swapping
20224         // the operands would cause it to handle comparisons between positive
20225         // and negative zero incorrectly.
20226         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20227           if (!DAG.getTarget().Options.UnsafeFPMath &&
20228               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20229             break;
20230           std::swap(LHS, RHS);
20231         }
20232         Opcode = X86ISD::FMIN;
20233         break;
20234       case ISD::SETOLE:
20235         // Converting this to a min would handle comparisons between positive
20236         // and negative zero incorrectly.
20237         if (!DAG.getTarget().Options.UnsafeFPMath &&
20238             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20239           break;
20240         Opcode = X86ISD::FMIN;
20241         break;
20242       case ISD::SETULE:
20243         // Converting this to a min would handle both negative zeros and NaNs
20244         // incorrectly, but we can swap the operands to fix both.
20245         std::swap(LHS, RHS);
20246       case ISD::SETOLT:
20247       case ISD::SETLT:
20248       case ISD::SETLE:
20249         Opcode = X86ISD::FMIN;
20250         break;
20251
20252       case ISD::SETOGE:
20253         // Converting this to a max would handle comparisons between positive
20254         // and negative zero incorrectly.
20255         if (!DAG.getTarget().Options.UnsafeFPMath &&
20256             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20257           break;
20258         Opcode = X86ISD::FMAX;
20259         break;
20260       case ISD::SETUGT:
20261         // Converting this to a max would handle NaNs incorrectly, and swapping
20262         // the operands would cause it to handle comparisons between positive
20263         // and negative zero incorrectly.
20264         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20265           if (!DAG.getTarget().Options.UnsafeFPMath &&
20266               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20267             break;
20268           std::swap(LHS, RHS);
20269         }
20270         Opcode = X86ISD::FMAX;
20271         break;
20272       case ISD::SETUGE:
20273         // Converting this to a max would handle both negative zeros and NaNs
20274         // incorrectly, but we can swap the operands to fix both.
20275         std::swap(LHS, RHS);
20276       case ISD::SETOGT:
20277       case ISD::SETGT:
20278       case ISD::SETGE:
20279         Opcode = X86ISD::FMAX;
20280         break;
20281       }
20282     // Check for x CC y ? y : x -- a min/max with reversed arms.
20283     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20284                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20285       switch (CC) {
20286       default: break;
20287       case ISD::SETOGE:
20288         // Converting this to a min would handle comparisons between positive
20289         // and negative zero incorrectly, and swapping the operands would
20290         // cause it to handle NaNs incorrectly.
20291         if (!DAG.getTarget().Options.UnsafeFPMath &&
20292             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20293           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20294             break;
20295           std::swap(LHS, RHS);
20296         }
20297         Opcode = X86ISD::FMIN;
20298         break;
20299       case ISD::SETUGT:
20300         // Converting this to a min would handle NaNs incorrectly.
20301         if (!DAG.getTarget().Options.UnsafeFPMath &&
20302             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20303           break;
20304         Opcode = X86ISD::FMIN;
20305         break;
20306       case ISD::SETUGE:
20307         // Converting this to a min would handle both negative zeros and NaNs
20308         // incorrectly, but we can swap the operands to fix both.
20309         std::swap(LHS, RHS);
20310       case ISD::SETOGT:
20311       case ISD::SETGT:
20312       case ISD::SETGE:
20313         Opcode = X86ISD::FMIN;
20314         break;
20315
20316       case ISD::SETULT:
20317         // Converting this to a max would handle NaNs incorrectly.
20318         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20319           break;
20320         Opcode = X86ISD::FMAX;
20321         break;
20322       case ISD::SETOLE:
20323         // Converting this to a max would handle comparisons between positive
20324         // and negative zero incorrectly, and swapping the operands would
20325         // cause it to handle NaNs incorrectly.
20326         if (!DAG.getTarget().Options.UnsafeFPMath &&
20327             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20328           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20329             break;
20330           std::swap(LHS, RHS);
20331         }
20332         Opcode = X86ISD::FMAX;
20333         break;
20334       case ISD::SETULE:
20335         // Converting this to a max would handle both negative zeros and NaNs
20336         // incorrectly, but we can swap the operands to fix both.
20337         std::swap(LHS, RHS);
20338       case ISD::SETOLT:
20339       case ISD::SETLT:
20340       case ISD::SETLE:
20341         Opcode = X86ISD::FMAX;
20342         break;
20343       }
20344     }
20345
20346     if (Opcode)
20347       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20348   }
20349
20350   EVT CondVT = Cond.getValueType();
20351   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20352       CondVT.getVectorElementType() == MVT::i1) {
20353     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20354     // lowering on KNL. In this case we convert it to
20355     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20356     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20357     // Since SKX these selects have a proper lowering.
20358     EVT OpVT = LHS.getValueType();
20359     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20360         (OpVT.getVectorElementType() == MVT::i8 ||
20361          OpVT.getVectorElementType() == MVT::i16) &&
20362         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20363       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20364       DCI.AddToWorklist(Cond.getNode());
20365       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20366     }
20367   }
20368   // If this is a select between two integer constants, try to do some
20369   // optimizations.
20370   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20371     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20372       // Don't do this for crazy integer types.
20373       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20374         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20375         // so that TrueC (the true value) is larger than FalseC.
20376         bool NeedsCondInvert = false;
20377
20378         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20379             // Efficiently invertible.
20380             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20381              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20382               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20383           NeedsCondInvert = true;
20384           std::swap(TrueC, FalseC);
20385         }
20386
20387         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20388         if (FalseC->getAPIntValue() == 0 &&
20389             TrueC->getAPIntValue().isPowerOf2()) {
20390           if (NeedsCondInvert) // Invert the condition if needed.
20391             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20392                                DAG.getConstant(1, Cond.getValueType()));
20393
20394           // Zero extend the condition if needed.
20395           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20396
20397           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20398           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20399                              DAG.getConstant(ShAmt, MVT::i8));
20400         }
20401
20402         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20403         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20404           if (NeedsCondInvert) // Invert the condition if needed.
20405             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20406                                DAG.getConstant(1, Cond.getValueType()));
20407
20408           // Zero extend the condition if needed.
20409           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20410                              FalseC->getValueType(0), Cond);
20411           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20412                              SDValue(FalseC, 0));
20413         }
20414
20415         // Optimize cases that will turn into an LEA instruction.  This requires
20416         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20417         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20418           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20419           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20420
20421           bool isFastMultiplier = false;
20422           if (Diff < 10) {
20423             switch ((unsigned char)Diff) {
20424               default: break;
20425               case 1:  // result = add base, cond
20426               case 2:  // result = lea base(    , cond*2)
20427               case 3:  // result = lea base(cond, cond*2)
20428               case 4:  // result = lea base(    , cond*4)
20429               case 5:  // result = lea base(cond, cond*4)
20430               case 8:  // result = lea base(    , cond*8)
20431               case 9:  // result = lea base(cond, cond*8)
20432                 isFastMultiplier = true;
20433                 break;
20434             }
20435           }
20436
20437           if (isFastMultiplier) {
20438             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20439             if (NeedsCondInvert) // Invert the condition if needed.
20440               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20441                                  DAG.getConstant(1, Cond.getValueType()));
20442
20443             // Zero extend the condition if needed.
20444             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20445                                Cond);
20446             // Scale the condition by the difference.
20447             if (Diff != 1)
20448               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20449                                  DAG.getConstant(Diff, Cond.getValueType()));
20450
20451             // Add the base if non-zero.
20452             if (FalseC->getAPIntValue() != 0)
20453               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20454                                  SDValue(FalseC, 0));
20455             return Cond;
20456           }
20457         }
20458       }
20459   }
20460
20461   // Canonicalize max and min:
20462   // (x > y) ? x : y -> (x >= y) ? x : y
20463   // (x < y) ? x : y -> (x <= y) ? x : y
20464   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20465   // the need for an extra compare
20466   // against zero. e.g.
20467   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20468   // subl   %esi, %edi
20469   // testl  %edi, %edi
20470   // movl   $0, %eax
20471   // cmovgl %edi, %eax
20472   // =>
20473   // xorl   %eax, %eax
20474   // subl   %esi, $edi
20475   // cmovsl %eax, %edi
20476   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20477       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20478       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20479     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20480     switch (CC) {
20481     default: break;
20482     case ISD::SETLT:
20483     case ISD::SETGT: {
20484       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20485       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20486                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20487       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20488     }
20489     }
20490   }
20491
20492   // Early exit check
20493   if (!TLI.isTypeLegal(VT))
20494     return SDValue();
20495
20496   // Match VSELECTs into subs with unsigned saturation.
20497   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20498       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20499       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20500        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20501     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20502
20503     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20504     // left side invert the predicate to simplify logic below.
20505     SDValue Other;
20506     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20507       Other = RHS;
20508       CC = ISD::getSetCCInverse(CC, true);
20509     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20510       Other = LHS;
20511     }
20512
20513     if (Other.getNode() && Other->getNumOperands() == 2 &&
20514         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20515       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20516       SDValue CondRHS = Cond->getOperand(1);
20517
20518       // Look for a general sub with unsigned saturation first.
20519       // x >= y ? x-y : 0 --> subus x, y
20520       // x >  y ? x-y : 0 --> subus x, y
20521       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20522           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20523         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20524
20525       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20526         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20527           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20528             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20529               // If the RHS is a constant we have to reverse the const
20530               // canonicalization.
20531               // x > C-1 ? x+-C : 0 --> subus x, C
20532               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20533                   CondRHSConst->getAPIntValue() ==
20534                       (-OpRHSConst->getAPIntValue() - 1))
20535                 return DAG.getNode(
20536                     X86ISD::SUBUS, DL, VT, OpLHS,
20537                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20538
20539           // Another special case: If C was a sign bit, the sub has been
20540           // canonicalized into a xor.
20541           // FIXME: Would it be better to use computeKnownBits to determine
20542           //        whether it's safe to decanonicalize the xor?
20543           // x s< 0 ? x^C : 0 --> subus x, C
20544           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20545               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20546               OpRHSConst->getAPIntValue().isSignBit())
20547             // Note that we have to rebuild the RHS constant here to ensure we
20548             // don't rely on particular values of undef lanes.
20549             return DAG.getNode(
20550                 X86ISD::SUBUS, DL, VT, OpLHS,
20551                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20552         }
20553     }
20554   }
20555
20556   // Try to match a min/max vector operation.
20557   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20558     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20559     unsigned Opc = ret.first;
20560     bool NeedSplit = ret.second;
20561
20562     if (Opc && NeedSplit) {
20563       unsigned NumElems = VT.getVectorNumElements();
20564       // Extract the LHS vectors
20565       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20566       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20567
20568       // Extract the RHS vectors
20569       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20570       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20571
20572       // Create min/max for each subvector
20573       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20574       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20575
20576       // Merge the result
20577       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20578     } else if (Opc)
20579       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20580   }
20581
20582   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20583   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20584       // Check if SETCC has already been promoted
20585       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20586       // Check that condition value type matches vselect operand type
20587       CondVT == VT) { 
20588
20589     assert(Cond.getValueType().isVector() &&
20590            "vector select expects a vector selector!");
20591
20592     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20593     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20594
20595     if (!TValIsAllOnes && !FValIsAllZeros) {
20596       // Try invert the condition if true value is not all 1s and false value
20597       // is not all 0s.
20598       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20599       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20600
20601       if (TValIsAllZeros || FValIsAllOnes) {
20602         SDValue CC = Cond.getOperand(2);
20603         ISD::CondCode NewCC =
20604           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20605                                Cond.getOperand(0).getValueType().isInteger());
20606         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20607         std::swap(LHS, RHS);
20608         TValIsAllOnes = FValIsAllOnes;
20609         FValIsAllZeros = TValIsAllZeros;
20610       }
20611     }
20612
20613     if (TValIsAllOnes || FValIsAllZeros) {
20614       SDValue Ret;
20615
20616       if (TValIsAllOnes && FValIsAllZeros)
20617         Ret = Cond;
20618       else if (TValIsAllOnes)
20619         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20620                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20621       else if (FValIsAllZeros)
20622         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20623                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20624
20625       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20626     }
20627   }
20628
20629   // Try to fold this VSELECT into a MOVSS/MOVSD
20630   if (N->getOpcode() == ISD::VSELECT &&
20631       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20632     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20633         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20634       bool CanFold = false;
20635       unsigned NumElems = Cond.getNumOperands();
20636       SDValue A = LHS;
20637       SDValue B = RHS;
20638       
20639       if (isZero(Cond.getOperand(0))) {
20640         CanFold = true;
20641
20642         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20643         // fold (vselect <0,-1> -> (movsd A, B)
20644         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20645           CanFold = isAllOnes(Cond.getOperand(i));
20646       } else if (isAllOnes(Cond.getOperand(0))) {
20647         CanFold = true;
20648         std::swap(A, B);
20649
20650         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20651         // fold (vselect <-1,0> -> (movsd B, A)
20652         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20653           CanFold = isZero(Cond.getOperand(i));
20654       }
20655
20656       if (CanFold) {
20657         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20658           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20659         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20660       }
20661
20662       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20663         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20664         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20665         //                             (v2i64 (bitcast B)))))
20666         //
20667         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20668         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20669         //                             (v2f64 (bitcast B)))))
20670         //
20671         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20672         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20673         //                             (v2i64 (bitcast A)))))
20674         //
20675         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20676         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20677         //                             (v2f64 (bitcast A)))))
20678
20679         CanFold = (isZero(Cond.getOperand(0)) &&
20680                    isZero(Cond.getOperand(1)) &&
20681                    isAllOnes(Cond.getOperand(2)) &&
20682                    isAllOnes(Cond.getOperand(3)));
20683
20684         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20685             isAllOnes(Cond.getOperand(1)) &&
20686             isZero(Cond.getOperand(2)) &&
20687             isZero(Cond.getOperand(3))) {
20688           CanFold = true;
20689           std::swap(LHS, RHS);
20690         }
20691
20692         if (CanFold) {
20693           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20694           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20695           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20696           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20697                                                 NewB, DAG);
20698           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20699         }
20700       }
20701     }
20702   }
20703
20704   // If we know that this node is legal then we know that it is going to be
20705   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20706   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20707   // to simplify previous instructions.
20708   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20709       !DCI.isBeforeLegalize() &&
20710       // We explicitly check against v8i16 and v16i16 because, although
20711       // they're marked as Custom, they might only be legal when Cond is a
20712       // build_vector of constants. This will be taken care in a later
20713       // condition.
20714       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20715        VT != MVT::v8i16)) {
20716     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20717
20718     // Don't optimize vector selects that map to mask-registers.
20719     if (BitWidth == 1)
20720       return SDValue();
20721
20722     // Check all uses of that condition operand to check whether it will be
20723     // consumed by non-BLEND instructions, which may depend on all bits are set
20724     // properly.
20725     for (SDNode::use_iterator I = Cond->use_begin(),
20726                               E = Cond->use_end(); I != E; ++I)
20727       if (I->getOpcode() != ISD::VSELECT)
20728         // TODO: Add other opcodes eventually lowered into BLEND.
20729         return SDValue();
20730
20731     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20732     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20733
20734     APInt KnownZero, KnownOne;
20735     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20736                                           DCI.isBeforeLegalizeOps());
20737     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20738         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20739       DCI.CommitTargetLoweringOpt(TLO);
20740   }
20741
20742   // We should generate an X86ISD::BLENDI from a vselect if its argument
20743   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20744   // constants. This specific pattern gets generated when we split a
20745   // selector for a 512 bit vector in a machine without AVX512 (but with
20746   // 256-bit vectors), during legalization:
20747   //
20748   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20749   //
20750   // Iff we find this pattern and the build_vectors are built from
20751   // constants, we translate the vselect into a shuffle_vector that we
20752   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20753   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20754     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20755     if (Shuffle.getNode())
20756       return Shuffle;
20757   }
20758
20759   return SDValue();
20760 }
20761
20762 // Check whether a boolean test is testing a boolean value generated by
20763 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20764 // code.
20765 //
20766 // Simplify the following patterns:
20767 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20768 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20769 // to (Op EFLAGS Cond)
20770 //
20771 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20772 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20773 // to (Op EFLAGS !Cond)
20774 //
20775 // where Op could be BRCOND or CMOV.
20776 //
20777 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20778   // Quit if not CMP and SUB with its value result used.
20779   if (Cmp.getOpcode() != X86ISD::CMP &&
20780       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20781       return SDValue();
20782
20783   // Quit if not used as a boolean value.
20784   if (CC != X86::COND_E && CC != X86::COND_NE)
20785     return SDValue();
20786
20787   // Check CMP operands. One of them should be 0 or 1 and the other should be
20788   // an SetCC or extended from it.
20789   SDValue Op1 = Cmp.getOperand(0);
20790   SDValue Op2 = Cmp.getOperand(1);
20791
20792   SDValue SetCC;
20793   const ConstantSDNode* C = nullptr;
20794   bool needOppositeCond = (CC == X86::COND_E);
20795   bool checkAgainstTrue = false; // Is it a comparison against 1?
20796
20797   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20798     SetCC = Op2;
20799   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20800     SetCC = Op1;
20801   else // Quit if all operands are not constants.
20802     return SDValue();
20803
20804   if (C->getZExtValue() == 1) {
20805     needOppositeCond = !needOppositeCond;
20806     checkAgainstTrue = true;
20807   } else if (C->getZExtValue() != 0)
20808     // Quit if the constant is neither 0 or 1.
20809     return SDValue();
20810
20811   bool truncatedToBoolWithAnd = false;
20812   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20813   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20814          SetCC.getOpcode() == ISD::TRUNCATE ||
20815          SetCC.getOpcode() == ISD::AND) {
20816     if (SetCC.getOpcode() == ISD::AND) {
20817       int OpIdx = -1;
20818       ConstantSDNode *CS;
20819       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20820           CS->getZExtValue() == 1)
20821         OpIdx = 1;
20822       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20823           CS->getZExtValue() == 1)
20824         OpIdx = 0;
20825       if (OpIdx == -1)
20826         break;
20827       SetCC = SetCC.getOperand(OpIdx);
20828       truncatedToBoolWithAnd = true;
20829     } else
20830       SetCC = SetCC.getOperand(0);
20831   }
20832
20833   switch (SetCC.getOpcode()) {
20834   case X86ISD::SETCC_CARRY:
20835     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20836     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20837     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20838     // truncated to i1 using 'and'.
20839     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20840       break;
20841     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20842            "Invalid use of SETCC_CARRY!");
20843     // FALL THROUGH
20844   case X86ISD::SETCC:
20845     // Set the condition code or opposite one if necessary.
20846     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20847     if (needOppositeCond)
20848       CC = X86::GetOppositeBranchCondition(CC);
20849     return SetCC.getOperand(1);
20850   case X86ISD::CMOV: {
20851     // Check whether false/true value has canonical one, i.e. 0 or 1.
20852     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20853     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20854     // Quit if true value is not a constant.
20855     if (!TVal)
20856       return SDValue();
20857     // Quit if false value is not a constant.
20858     if (!FVal) {
20859       SDValue Op = SetCC.getOperand(0);
20860       // Skip 'zext' or 'trunc' node.
20861       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20862           Op.getOpcode() == ISD::TRUNCATE)
20863         Op = Op.getOperand(0);
20864       // A special case for rdrand/rdseed, where 0 is set if false cond is
20865       // found.
20866       if ((Op.getOpcode() != X86ISD::RDRAND &&
20867            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20868         return SDValue();
20869     }
20870     // Quit if false value is not the constant 0 or 1.
20871     bool FValIsFalse = true;
20872     if (FVal && FVal->getZExtValue() != 0) {
20873       if (FVal->getZExtValue() != 1)
20874         return SDValue();
20875       // If FVal is 1, opposite cond is needed.
20876       needOppositeCond = !needOppositeCond;
20877       FValIsFalse = false;
20878     }
20879     // Quit if TVal is not the constant opposite of FVal.
20880     if (FValIsFalse && TVal->getZExtValue() != 1)
20881       return SDValue();
20882     if (!FValIsFalse && TVal->getZExtValue() != 0)
20883       return SDValue();
20884     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20885     if (needOppositeCond)
20886       CC = X86::GetOppositeBranchCondition(CC);
20887     return SetCC.getOperand(3);
20888   }
20889   }
20890
20891   return SDValue();
20892 }
20893
20894 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20895 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20896                                   TargetLowering::DAGCombinerInfo &DCI,
20897                                   const X86Subtarget *Subtarget) {
20898   SDLoc DL(N);
20899
20900   // If the flag operand isn't dead, don't touch this CMOV.
20901   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20902     return SDValue();
20903
20904   SDValue FalseOp = N->getOperand(0);
20905   SDValue TrueOp = N->getOperand(1);
20906   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20907   SDValue Cond = N->getOperand(3);
20908
20909   if (CC == X86::COND_E || CC == X86::COND_NE) {
20910     switch (Cond.getOpcode()) {
20911     default: break;
20912     case X86ISD::BSR:
20913     case X86ISD::BSF:
20914       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20915       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20916         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20917     }
20918   }
20919
20920   SDValue Flags;
20921
20922   Flags = checkBoolTestSetCCCombine(Cond, CC);
20923   if (Flags.getNode() &&
20924       // Extra check as FCMOV only supports a subset of X86 cond.
20925       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20926     SDValue Ops[] = { FalseOp, TrueOp,
20927                       DAG.getConstant(CC, MVT::i8), Flags };
20928     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20929   }
20930
20931   // If this is a select between two integer constants, try to do some
20932   // optimizations.  Note that the operands are ordered the opposite of SELECT
20933   // operands.
20934   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20935     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20936       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20937       // larger than FalseC (the false value).
20938       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20939         CC = X86::GetOppositeBranchCondition(CC);
20940         std::swap(TrueC, FalseC);
20941         std::swap(TrueOp, FalseOp);
20942       }
20943
20944       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20945       // This is efficient for any integer data type (including i8/i16) and
20946       // shift amount.
20947       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20948         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20949                            DAG.getConstant(CC, MVT::i8), Cond);
20950
20951         // Zero extend the condition if needed.
20952         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20953
20954         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20955         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20956                            DAG.getConstant(ShAmt, MVT::i8));
20957         if (N->getNumValues() == 2)  // Dead flag value?
20958           return DCI.CombineTo(N, Cond, SDValue());
20959         return Cond;
20960       }
20961
20962       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20963       // for any integer data type, including i8/i16.
20964       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20965         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20966                            DAG.getConstant(CC, MVT::i8), Cond);
20967
20968         // Zero extend the condition if needed.
20969         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20970                            FalseC->getValueType(0), Cond);
20971         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20972                            SDValue(FalseC, 0));
20973
20974         if (N->getNumValues() == 2)  // Dead flag value?
20975           return DCI.CombineTo(N, Cond, SDValue());
20976         return Cond;
20977       }
20978
20979       // Optimize cases that will turn into an LEA instruction.  This requires
20980       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20981       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20982         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20983         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20984
20985         bool isFastMultiplier = false;
20986         if (Diff < 10) {
20987           switch ((unsigned char)Diff) {
20988           default: break;
20989           case 1:  // result = add base, cond
20990           case 2:  // result = lea base(    , cond*2)
20991           case 3:  // result = lea base(cond, cond*2)
20992           case 4:  // result = lea base(    , cond*4)
20993           case 5:  // result = lea base(cond, cond*4)
20994           case 8:  // result = lea base(    , cond*8)
20995           case 9:  // result = lea base(cond, cond*8)
20996             isFastMultiplier = true;
20997             break;
20998           }
20999         }
21000
21001         if (isFastMultiplier) {
21002           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21003           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21004                              DAG.getConstant(CC, MVT::i8), Cond);
21005           // Zero extend the condition if needed.
21006           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21007                              Cond);
21008           // Scale the condition by the difference.
21009           if (Diff != 1)
21010             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21011                                DAG.getConstant(Diff, Cond.getValueType()));
21012
21013           // Add the base if non-zero.
21014           if (FalseC->getAPIntValue() != 0)
21015             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21016                                SDValue(FalseC, 0));
21017           if (N->getNumValues() == 2)  // Dead flag value?
21018             return DCI.CombineTo(N, Cond, SDValue());
21019           return Cond;
21020         }
21021       }
21022     }
21023   }
21024
21025   // Handle these cases:
21026   //   (select (x != c), e, c) -> select (x != c), e, x),
21027   //   (select (x == c), c, e) -> select (x == c), x, e)
21028   // where the c is an integer constant, and the "select" is the combination
21029   // of CMOV and CMP.
21030   //
21031   // The rationale for this change is that the conditional-move from a constant
21032   // needs two instructions, however, conditional-move from a register needs
21033   // only one instruction.
21034   //
21035   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21036   //  some instruction-combining opportunities. This opt needs to be
21037   //  postponed as late as possible.
21038   //
21039   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21040     // the DCI.xxxx conditions are provided to postpone the optimization as
21041     // late as possible.
21042
21043     ConstantSDNode *CmpAgainst = nullptr;
21044     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21045         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21046         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21047
21048       if (CC == X86::COND_NE &&
21049           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21050         CC = X86::GetOppositeBranchCondition(CC);
21051         std::swap(TrueOp, FalseOp);
21052       }
21053
21054       if (CC == X86::COND_E &&
21055           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21056         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21057                           DAG.getConstant(CC, MVT::i8), Cond };
21058         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21059       }
21060     }
21061   }
21062
21063   return SDValue();
21064 }
21065
21066 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21067                                                 const X86Subtarget *Subtarget) {
21068   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21069   switch (IntNo) {
21070   default: return SDValue();
21071   // SSE/AVX/AVX2 blend intrinsics.
21072   case Intrinsic::x86_avx2_pblendvb:
21073   case Intrinsic::x86_avx2_pblendw:
21074   case Intrinsic::x86_avx2_pblendd_128:
21075   case Intrinsic::x86_avx2_pblendd_256:
21076     // Don't try to simplify this intrinsic if we don't have AVX2.
21077     if (!Subtarget->hasAVX2())
21078       return SDValue();
21079     // FALL-THROUGH
21080   case Intrinsic::x86_avx_blend_pd_256:
21081   case Intrinsic::x86_avx_blend_ps_256:
21082   case Intrinsic::x86_avx_blendv_pd_256:
21083   case Intrinsic::x86_avx_blendv_ps_256:
21084     // Don't try to simplify this intrinsic if we don't have AVX.
21085     if (!Subtarget->hasAVX())
21086       return SDValue();
21087     // FALL-THROUGH
21088   case Intrinsic::x86_sse41_pblendw:
21089   case Intrinsic::x86_sse41_blendpd:
21090   case Intrinsic::x86_sse41_blendps:
21091   case Intrinsic::x86_sse41_blendvps:
21092   case Intrinsic::x86_sse41_blendvpd:
21093   case Intrinsic::x86_sse41_pblendvb: {
21094     SDValue Op0 = N->getOperand(1);
21095     SDValue Op1 = N->getOperand(2);
21096     SDValue Mask = N->getOperand(3);
21097
21098     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21099     if (!Subtarget->hasSSE41())
21100       return SDValue();
21101
21102     // fold (blend A, A, Mask) -> A
21103     if (Op0 == Op1)
21104       return Op0;
21105     // fold (blend A, B, allZeros) -> A
21106     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21107       return Op0;
21108     // fold (blend A, B, allOnes) -> B
21109     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21110       return Op1;
21111     
21112     // Simplify the case where the mask is a constant i32 value.
21113     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21114       if (C->isNullValue())
21115         return Op0;
21116       if (C->isAllOnesValue())
21117         return Op1;
21118     }
21119
21120     return SDValue();
21121   }
21122
21123   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21124   case Intrinsic::x86_sse2_psrai_w:
21125   case Intrinsic::x86_sse2_psrai_d:
21126   case Intrinsic::x86_avx2_psrai_w:
21127   case Intrinsic::x86_avx2_psrai_d:
21128   case Intrinsic::x86_sse2_psra_w:
21129   case Intrinsic::x86_sse2_psra_d:
21130   case Intrinsic::x86_avx2_psra_w:
21131   case Intrinsic::x86_avx2_psra_d: {
21132     SDValue Op0 = N->getOperand(1);
21133     SDValue Op1 = N->getOperand(2);
21134     EVT VT = Op0.getValueType();
21135     assert(VT.isVector() && "Expected a vector type!");
21136
21137     if (isa<BuildVectorSDNode>(Op1))
21138       Op1 = Op1.getOperand(0);
21139
21140     if (!isa<ConstantSDNode>(Op1))
21141       return SDValue();
21142
21143     EVT SVT = VT.getVectorElementType();
21144     unsigned SVTBits = SVT.getSizeInBits();
21145
21146     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21147     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21148     uint64_t ShAmt = C.getZExtValue();
21149
21150     // Don't try to convert this shift into a ISD::SRA if the shift
21151     // count is bigger than or equal to the element size.
21152     if (ShAmt >= SVTBits)
21153       return SDValue();
21154
21155     // Trivial case: if the shift count is zero, then fold this
21156     // into the first operand.
21157     if (ShAmt == 0)
21158       return Op0;
21159
21160     // Replace this packed shift intrinsic with a target independent
21161     // shift dag node.
21162     SDValue Splat = DAG.getConstant(C, VT);
21163     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21164   }
21165   }
21166 }
21167
21168 /// PerformMulCombine - Optimize a single multiply with constant into two
21169 /// in order to implement it with two cheaper instructions, e.g.
21170 /// LEA + SHL, LEA + LEA.
21171 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21172                                  TargetLowering::DAGCombinerInfo &DCI) {
21173   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21174     return SDValue();
21175
21176   EVT VT = N->getValueType(0);
21177   if (VT != MVT::i64)
21178     return SDValue();
21179
21180   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21181   if (!C)
21182     return SDValue();
21183   uint64_t MulAmt = C->getZExtValue();
21184   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21185     return SDValue();
21186
21187   uint64_t MulAmt1 = 0;
21188   uint64_t MulAmt2 = 0;
21189   if ((MulAmt % 9) == 0) {
21190     MulAmt1 = 9;
21191     MulAmt2 = MulAmt / 9;
21192   } else if ((MulAmt % 5) == 0) {
21193     MulAmt1 = 5;
21194     MulAmt2 = MulAmt / 5;
21195   } else if ((MulAmt % 3) == 0) {
21196     MulAmt1 = 3;
21197     MulAmt2 = MulAmt / 3;
21198   }
21199   if (MulAmt2 &&
21200       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21201     SDLoc DL(N);
21202
21203     if (isPowerOf2_64(MulAmt2) &&
21204         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21205       // If second multiplifer is pow2, issue it first. We want the multiply by
21206       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21207       // is an add.
21208       std::swap(MulAmt1, MulAmt2);
21209
21210     SDValue NewMul;
21211     if (isPowerOf2_64(MulAmt1))
21212       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21213                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21214     else
21215       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21216                            DAG.getConstant(MulAmt1, VT));
21217
21218     if (isPowerOf2_64(MulAmt2))
21219       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21220                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21221     else
21222       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21223                            DAG.getConstant(MulAmt2, VT));
21224
21225     // Do not add new nodes to DAG combiner worklist.
21226     DCI.CombineTo(N, NewMul, false);
21227   }
21228   return SDValue();
21229 }
21230
21231 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21232   SDValue N0 = N->getOperand(0);
21233   SDValue N1 = N->getOperand(1);
21234   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21235   EVT VT = N0.getValueType();
21236
21237   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21238   // since the result of setcc_c is all zero's or all ones.
21239   if (VT.isInteger() && !VT.isVector() &&
21240       N1C && N0.getOpcode() == ISD::AND &&
21241       N0.getOperand(1).getOpcode() == ISD::Constant) {
21242     SDValue N00 = N0.getOperand(0);
21243     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21244         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21245           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21246          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21247       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21248       APInt ShAmt = N1C->getAPIntValue();
21249       Mask = Mask.shl(ShAmt);
21250       if (Mask != 0)
21251         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21252                            N00, DAG.getConstant(Mask, VT));
21253     }
21254   }
21255
21256   // Hardware support for vector shifts is sparse which makes us scalarize the
21257   // vector operations in many cases. Also, on sandybridge ADD is faster than
21258   // shl.
21259   // (shl V, 1) -> add V,V
21260   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21261     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21262       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21263       // We shift all of the values by one. In many cases we do not have
21264       // hardware support for this operation. This is better expressed as an ADD
21265       // of two values.
21266       if (N1SplatC->getZExtValue() == 1)
21267         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21268     }
21269
21270   return SDValue();
21271 }
21272
21273 /// \brief Returns a vector of 0s if the node in input is a vector logical
21274 /// shift by a constant amount which is known to be bigger than or equal
21275 /// to the vector element size in bits.
21276 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21277                                       const X86Subtarget *Subtarget) {
21278   EVT VT = N->getValueType(0);
21279
21280   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21281       (!Subtarget->hasInt256() ||
21282        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21283     return SDValue();
21284
21285   SDValue Amt = N->getOperand(1);
21286   SDLoc DL(N);
21287   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21288     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21289       APInt ShiftAmt = AmtSplat->getAPIntValue();
21290       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21291
21292       // SSE2/AVX2 logical shifts always return a vector of 0s
21293       // if the shift amount is bigger than or equal to
21294       // the element size. The constant shift amount will be
21295       // encoded as a 8-bit immediate.
21296       if (ShiftAmt.trunc(8).uge(MaxAmount))
21297         return getZeroVector(VT, Subtarget, DAG, DL);
21298     }
21299
21300   return SDValue();
21301 }
21302
21303 /// PerformShiftCombine - Combine shifts.
21304 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21305                                    TargetLowering::DAGCombinerInfo &DCI,
21306                                    const X86Subtarget *Subtarget) {
21307   if (N->getOpcode() == ISD::SHL) {
21308     SDValue V = PerformSHLCombine(N, DAG);
21309     if (V.getNode()) return V;
21310   }
21311
21312   if (N->getOpcode() != ISD::SRA) {
21313     // Try to fold this logical shift into a zero vector.
21314     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21315     if (V.getNode()) return V;
21316   }
21317
21318   return SDValue();
21319 }
21320
21321 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21322 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21323 // and friends.  Likewise for OR -> CMPNEQSS.
21324 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21325                             TargetLowering::DAGCombinerInfo &DCI,
21326                             const X86Subtarget *Subtarget) {
21327   unsigned opcode;
21328
21329   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21330   // we're requiring SSE2 for both.
21331   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21332     SDValue N0 = N->getOperand(0);
21333     SDValue N1 = N->getOperand(1);
21334     SDValue CMP0 = N0->getOperand(1);
21335     SDValue CMP1 = N1->getOperand(1);
21336     SDLoc DL(N);
21337
21338     // The SETCCs should both refer to the same CMP.
21339     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21340       return SDValue();
21341
21342     SDValue CMP00 = CMP0->getOperand(0);
21343     SDValue CMP01 = CMP0->getOperand(1);
21344     EVT     VT    = CMP00.getValueType();
21345
21346     if (VT == MVT::f32 || VT == MVT::f64) {
21347       bool ExpectingFlags = false;
21348       // Check for any users that want flags:
21349       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21350            !ExpectingFlags && UI != UE; ++UI)
21351         switch (UI->getOpcode()) {
21352         default:
21353         case ISD::BR_CC:
21354         case ISD::BRCOND:
21355         case ISD::SELECT:
21356           ExpectingFlags = true;
21357           break;
21358         case ISD::CopyToReg:
21359         case ISD::SIGN_EXTEND:
21360         case ISD::ZERO_EXTEND:
21361         case ISD::ANY_EXTEND:
21362           break;
21363         }
21364
21365       if (!ExpectingFlags) {
21366         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21367         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21368
21369         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21370           X86::CondCode tmp = cc0;
21371           cc0 = cc1;
21372           cc1 = tmp;
21373         }
21374
21375         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21376             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21377           // FIXME: need symbolic constants for these magic numbers.
21378           // See X86ATTInstPrinter.cpp:printSSECC().
21379           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21380           if (Subtarget->hasAVX512()) {
21381             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21382                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21383             if (N->getValueType(0) != MVT::i1)
21384               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21385                                  FSetCC);
21386             return FSetCC;
21387           }
21388           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21389                                               CMP00.getValueType(), CMP00, CMP01,
21390                                               DAG.getConstant(x86cc, MVT::i8));
21391
21392           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21393           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21394
21395           if (is64BitFP && !Subtarget->is64Bit()) {
21396             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21397             // 64-bit integer, since that's not a legal type. Since
21398             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21399             // bits, but can do this little dance to extract the lowest 32 bits
21400             // and work with those going forward.
21401             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21402                                            OnesOrZeroesF);
21403             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21404                                            Vector64);
21405             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21406                                         Vector32, DAG.getIntPtrConstant(0));
21407             IntVT = MVT::i32;
21408           }
21409
21410           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21411           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21412                                       DAG.getConstant(1, IntVT));
21413           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21414           return OneBitOfTruth;
21415         }
21416       }
21417     }
21418   }
21419   return SDValue();
21420 }
21421
21422 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21423 /// so it can be folded inside ANDNP.
21424 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21425   EVT VT = N->getValueType(0);
21426
21427   // Match direct AllOnes for 128 and 256-bit vectors
21428   if (ISD::isBuildVectorAllOnes(N))
21429     return true;
21430
21431   // Look through a bit convert.
21432   if (N->getOpcode() == ISD::BITCAST)
21433     N = N->getOperand(0).getNode();
21434
21435   // Sometimes the operand may come from a insert_subvector building a 256-bit
21436   // allones vector
21437   if (VT.is256BitVector() &&
21438       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21439     SDValue V1 = N->getOperand(0);
21440     SDValue V2 = N->getOperand(1);
21441
21442     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21443         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21444         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21445         ISD::isBuildVectorAllOnes(V2.getNode()))
21446       return true;
21447   }
21448
21449   return false;
21450 }
21451
21452 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21453 // register. In most cases we actually compare or select YMM-sized registers
21454 // and mixing the two types creates horrible code. This method optimizes
21455 // some of the transition sequences.
21456 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21457                                  TargetLowering::DAGCombinerInfo &DCI,
21458                                  const X86Subtarget *Subtarget) {
21459   EVT VT = N->getValueType(0);
21460   if (!VT.is256BitVector())
21461     return SDValue();
21462
21463   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21464           N->getOpcode() == ISD::ZERO_EXTEND ||
21465           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21466
21467   SDValue Narrow = N->getOperand(0);
21468   EVT NarrowVT = Narrow->getValueType(0);
21469   if (!NarrowVT.is128BitVector())
21470     return SDValue();
21471
21472   if (Narrow->getOpcode() != ISD::XOR &&
21473       Narrow->getOpcode() != ISD::AND &&
21474       Narrow->getOpcode() != ISD::OR)
21475     return SDValue();
21476
21477   SDValue N0  = Narrow->getOperand(0);
21478   SDValue N1  = Narrow->getOperand(1);
21479   SDLoc DL(Narrow);
21480
21481   // The Left side has to be a trunc.
21482   if (N0.getOpcode() != ISD::TRUNCATE)
21483     return SDValue();
21484
21485   // The type of the truncated inputs.
21486   EVT WideVT = N0->getOperand(0)->getValueType(0);
21487   if (WideVT != VT)
21488     return SDValue();
21489
21490   // The right side has to be a 'trunc' or a constant vector.
21491   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21492   ConstantSDNode *RHSConstSplat = nullptr;
21493   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21494     RHSConstSplat = RHSBV->getConstantSplatNode();
21495   if (!RHSTrunc && !RHSConstSplat)
21496     return SDValue();
21497
21498   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21499
21500   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21501     return SDValue();
21502
21503   // Set N0 and N1 to hold the inputs to the new wide operation.
21504   N0 = N0->getOperand(0);
21505   if (RHSConstSplat) {
21506     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21507                      SDValue(RHSConstSplat, 0));
21508     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21509     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21510   } else if (RHSTrunc) {
21511     N1 = N1->getOperand(0);
21512   }
21513
21514   // Generate the wide operation.
21515   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21516   unsigned Opcode = N->getOpcode();
21517   switch (Opcode) {
21518   case ISD::ANY_EXTEND:
21519     return Op;
21520   case ISD::ZERO_EXTEND: {
21521     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21522     APInt Mask = APInt::getAllOnesValue(InBits);
21523     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21524     return DAG.getNode(ISD::AND, DL, VT,
21525                        Op, DAG.getConstant(Mask, VT));
21526   }
21527   case ISD::SIGN_EXTEND:
21528     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21529                        Op, DAG.getValueType(NarrowVT));
21530   default:
21531     llvm_unreachable("Unexpected opcode");
21532   }
21533 }
21534
21535 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21536                                  TargetLowering::DAGCombinerInfo &DCI,
21537                                  const X86Subtarget *Subtarget) {
21538   EVT VT = N->getValueType(0);
21539   if (DCI.isBeforeLegalizeOps())
21540     return SDValue();
21541
21542   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21543   if (R.getNode())
21544     return R;
21545
21546   // Create BEXTR instructions
21547   // BEXTR is ((X >> imm) & (2**size-1))
21548   if (VT == MVT::i32 || VT == MVT::i64) {
21549     SDValue N0 = N->getOperand(0);
21550     SDValue N1 = N->getOperand(1);
21551     SDLoc DL(N);
21552
21553     // Check for BEXTR.
21554     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21555         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21556       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21557       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21558       if (MaskNode && ShiftNode) {
21559         uint64_t Mask = MaskNode->getZExtValue();
21560         uint64_t Shift = ShiftNode->getZExtValue();
21561         if (isMask_64(Mask)) {
21562           uint64_t MaskSize = CountPopulation_64(Mask);
21563           if (Shift + MaskSize <= VT.getSizeInBits())
21564             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21565                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21566         }
21567       }
21568     } // BEXTR
21569
21570     return SDValue();
21571   }
21572
21573   // Want to form ANDNP nodes:
21574   // 1) In the hopes of then easily combining them with OR and AND nodes
21575   //    to form PBLEND/PSIGN.
21576   // 2) To match ANDN packed intrinsics
21577   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21578     return SDValue();
21579
21580   SDValue N0 = N->getOperand(0);
21581   SDValue N1 = N->getOperand(1);
21582   SDLoc DL(N);
21583
21584   // Check LHS for vnot
21585   if (N0.getOpcode() == ISD::XOR &&
21586       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21587       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21588     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21589
21590   // Check RHS for vnot
21591   if (N1.getOpcode() == ISD::XOR &&
21592       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21593       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21594     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21595
21596   return SDValue();
21597 }
21598
21599 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21600                                 TargetLowering::DAGCombinerInfo &DCI,
21601                                 const X86Subtarget *Subtarget) {
21602   if (DCI.isBeforeLegalizeOps())
21603     return SDValue();
21604
21605   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21606   if (R.getNode())
21607     return R;
21608
21609   SDValue N0 = N->getOperand(0);
21610   SDValue N1 = N->getOperand(1);
21611   EVT VT = N->getValueType(0);
21612
21613   // look for psign/blend
21614   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21615     if (!Subtarget->hasSSSE3() ||
21616         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21617       return SDValue();
21618
21619     // Canonicalize pandn to RHS
21620     if (N0.getOpcode() == X86ISD::ANDNP)
21621       std::swap(N0, N1);
21622     // or (and (m, y), (pandn m, x))
21623     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21624       SDValue Mask = N1.getOperand(0);
21625       SDValue X    = N1.getOperand(1);
21626       SDValue Y;
21627       if (N0.getOperand(0) == Mask)
21628         Y = N0.getOperand(1);
21629       if (N0.getOperand(1) == Mask)
21630         Y = N0.getOperand(0);
21631
21632       // Check to see if the mask appeared in both the AND and ANDNP and
21633       if (!Y.getNode())
21634         return SDValue();
21635
21636       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21637       // Look through mask bitcast.
21638       if (Mask.getOpcode() == ISD::BITCAST)
21639         Mask = Mask.getOperand(0);
21640       if (X.getOpcode() == ISD::BITCAST)
21641         X = X.getOperand(0);
21642       if (Y.getOpcode() == ISD::BITCAST)
21643         Y = Y.getOperand(0);
21644
21645       EVT MaskVT = Mask.getValueType();
21646
21647       // Validate that the Mask operand is a vector sra node.
21648       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21649       // there is no psrai.b
21650       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21651       unsigned SraAmt = ~0;
21652       if (Mask.getOpcode() == ISD::SRA) {
21653         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21654           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21655             SraAmt = AmtConst->getZExtValue();
21656       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21657         SDValue SraC = Mask.getOperand(1);
21658         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21659       }
21660       if ((SraAmt + 1) != EltBits)
21661         return SDValue();
21662
21663       SDLoc DL(N);
21664
21665       // Now we know we at least have a plendvb with the mask val.  See if
21666       // we can form a psignb/w/d.
21667       // psign = x.type == y.type == mask.type && y = sub(0, x);
21668       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21669           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21670           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21671         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21672                "Unsupported VT for PSIGN");
21673         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21674         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21675       }
21676       // PBLENDVB only available on SSE 4.1
21677       if (!Subtarget->hasSSE41())
21678         return SDValue();
21679
21680       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21681
21682       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21683       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21684       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21685       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21686       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21687     }
21688   }
21689
21690   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21691     return SDValue();
21692
21693   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21694   MachineFunction &MF = DAG.getMachineFunction();
21695   bool OptForSize = MF.getFunction()->getAttributes().
21696     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21697
21698   // SHLD/SHRD instructions have lower register pressure, but on some
21699   // platforms they have higher latency than the equivalent
21700   // series of shifts/or that would otherwise be generated.
21701   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21702   // have higher latencies and we are not optimizing for size.
21703   if (!OptForSize && Subtarget->isSHLDSlow())
21704     return SDValue();
21705
21706   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21707     std::swap(N0, N1);
21708   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21709     return SDValue();
21710   if (!N0.hasOneUse() || !N1.hasOneUse())
21711     return SDValue();
21712
21713   SDValue ShAmt0 = N0.getOperand(1);
21714   if (ShAmt0.getValueType() != MVT::i8)
21715     return SDValue();
21716   SDValue ShAmt1 = N1.getOperand(1);
21717   if (ShAmt1.getValueType() != MVT::i8)
21718     return SDValue();
21719   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21720     ShAmt0 = ShAmt0.getOperand(0);
21721   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21722     ShAmt1 = ShAmt1.getOperand(0);
21723
21724   SDLoc DL(N);
21725   unsigned Opc = X86ISD::SHLD;
21726   SDValue Op0 = N0.getOperand(0);
21727   SDValue Op1 = N1.getOperand(0);
21728   if (ShAmt0.getOpcode() == ISD::SUB) {
21729     Opc = X86ISD::SHRD;
21730     std::swap(Op0, Op1);
21731     std::swap(ShAmt0, ShAmt1);
21732   }
21733
21734   unsigned Bits = VT.getSizeInBits();
21735   if (ShAmt1.getOpcode() == ISD::SUB) {
21736     SDValue Sum = ShAmt1.getOperand(0);
21737     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21738       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21739       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21740         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21741       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21742         return DAG.getNode(Opc, DL, VT,
21743                            Op0, Op1,
21744                            DAG.getNode(ISD::TRUNCATE, DL,
21745                                        MVT::i8, ShAmt0));
21746     }
21747   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21748     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21749     if (ShAmt0C &&
21750         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21751       return DAG.getNode(Opc, DL, VT,
21752                          N0.getOperand(0), N1.getOperand(0),
21753                          DAG.getNode(ISD::TRUNCATE, DL,
21754                                        MVT::i8, ShAmt0));
21755   }
21756
21757   return SDValue();
21758 }
21759
21760 // Generate NEG and CMOV for integer abs.
21761 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21762   EVT VT = N->getValueType(0);
21763
21764   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21765   // 8-bit integer abs to NEG and CMOV.
21766   if (VT.isInteger() && VT.getSizeInBits() == 8)
21767     return SDValue();
21768
21769   SDValue N0 = N->getOperand(0);
21770   SDValue N1 = N->getOperand(1);
21771   SDLoc DL(N);
21772
21773   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21774   // and change it to SUB and CMOV.
21775   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21776       N0.getOpcode() == ISD::ADD &&
21777       N0.getOperand(1) == N1 &&
21778       N1.getOpcode() == ISD::SRA &&
21779       N1.getOperand(0) == N0.getOperand(0))
21780     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21781       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21782         // Generate SUB & CMOV.
21783         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21784                                   DAG.getConstant(0, VT), N0.getOperand(0));
21785
21786         SDValue Ops[] = { N0.getOperand(0), Neg,
21787                           DAG.getConstant(X86::COND_GE, MVT::i8),
21788                           SDValue(Neg.getNode(), 1) };
21789         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21790       }
21791   return SDValue();
21792 }
21793
21794 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21795 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21796                                  TargetLowering::DAGCombinerInfo &DCI,
21797                                  const X86Subtarget *Subtarget) {
21798   if (DCI.isBeforeLegalizeOps())
21799     return SDValue();
21800
21801   if (Subtarget->hasCMov()) {
21802     SDValue RV = performIntegerAbsCombine(N, DAG);
21803     if (RV.getNode())
21804       return RV;
21805   }
21806
21807   return SDValue();
21808 }
21809
21810 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21811 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21812                                   TargetLowering::DAGCombinerInfo &DCI,
21813                                   const X86Subtarget *Subtarget) {
21814   LoadSDNode *Ld = cast<LoadSDNode>(N);
21815   EVT RegVT = Ld->getValueType(0);
21816   EVT MemVT = Ld->getMemoryVT();
21817   SDLoc dl(Ld);
21818   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21819
21820   // On Sandybridge unaligned 256bit loads are inefficient.
21821   ISD::LoadExtType Ext = Ld->getExtensionType();
21822   unsigned Alignment = Ld->getAlignment();
21823   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21824   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21825       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21826     unsigned NumElems = RegVT.getVectorNumElements();
21827     if (NumElems < 2)
21828       return SDValue();
21829
21830     SDValue Ptr = Ld->getBasePtr();
21831     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21832
21833     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21834                                   NumElems/2);
21835     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21836                                 Ld->getPointerInfo(), Ld->isVolatile(),
21837                                 Ld->isNonTemporal(), Ld->isInvariant(),
21838                                 Alignment);
21839     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21840     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21841                                 Ld->getPointerInfo(), Ld->isVolatile(),
21842                                 Ld->isNonTemporal(), Ld->isInvariant(),
21843                                 std::min(16U, Alignment));
21844     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21845                              Load1.getValue(1),
21846                              Load2.getValue(1));
21847
21848     SDValue NewVec = DAG.getUNDEF(RegVT);
21849     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21850     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21851     return DCI.CombineTo(N, NewVec, TF, true);
21852   }
21853
21854   return SDValue();
21855 }
21856
21857 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21858 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21859                                    const X86Subtarget *Subtarget) {
21860   StoreSDNode *St = cast<StoreSDNode>(N);
21861   EVT VT = St->getValue().getValueType();
21862   EVT StVT = St->getMemoryVT();
21863   SDLoc dl(St);
21864   SDValue StoredVal = St->getOperand(1);
21865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21866
21867   // If we are saving a concatenation of two XMM registers, perform two stores.
21868   // On Sandy Bridge, 256-bit memory operations are executed by two
21869   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21870   // memory  operation.
21871   unsigned Alignment = St->getAlignment();
21872   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21873   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21874       StVT == VT && !IsAligned) {
21875     unsigned NumElems = VT.getVectorNumElements();
21876     if (NumElems < 2)
21877       return SDValue();
21878
21879     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21880     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21881
21882     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21883     SDValue Ptr0 = St->getBasePtr();
21884     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21885
21886     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21887                                 St->getPointerInfo(), St->isVolatile(),
21888                                 St->isNonTemporal(), Alignment);
21889     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21890                                 St->getPointerInfo(), St->isVolatile(),
21891                                 St->isNonTemporal(),
21892                                 std::min(16U, Alignment));
21893     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21894   }
21895
21896   // Optimize trunc store (of multiple scalars) to shuffle and store.
21897   // First, pack all of the elements in one place. Next, store to memory
21898   // in fewer chunks.
21899   if (St->isTruncatingStore() && VT.isVector()) {
21900     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21901     unsigned NumElems = VT.getVectorNumElements();
21902     assert(StVT != VT && "Cannot truncate to the same type");
21903     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21904     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21905
21906     // From, To sizes and ElemCount must be pow of two
21907     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21908     // We are going to use the original vector elt for storing.
21909     // Accumulated smaller vector elements must be a multiple of the store size.
21910     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21911
21912     unsigned SizeRatio  = FromSz / ToSz;
21913
21914     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21915
21916     // Create a type on which we perform the shuffle
21917     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21918             StVT.getScalarType(), NumElems*SizeRatio);
21919
21920     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21921
21922     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21923     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21924     for (unsigned i = 0; i != NumElems; ++i)
21925       ShuffleVec[i] = i * SizeRatio;
21926
21927     // Can't shuffle using an illegal type.
21928     if (!TLI.isTypeLegal(WideVecVT))
21929       return SDValue();
21930
21931     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21932                                          DAG.getUNDEF(WideVecVT),
21933                                          &ShuffleVec[0]);
21934     // At this point all of the data is stored at the bottom of the
21935     // register. We now need to save it to mem.
21936
21937     // Find the largest store unit
21938     MVT StoreType = MVT::i8;
21939     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21940          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21941       MVT Tp = (MVT::SimpleValueType)tp;
21942       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21943         StoreType = Tp;
21944     }
21945
21946     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21947     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21948         (64 <= NumElems * ToSz))
21949       StoreType = MVT::f64;
21950
21951     // Bitcast the original vector into a vector of store-size units
21952     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21953             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21954     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21955     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21956     SmallVector<SDValue, 8> Chains;
21957     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21958                                         TLI.getPointerTy());
21959     SDValue Ptr = St->getBasePtr();
21960
21961     // Perform one or more big stores into memory.
21962     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21963       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21964                                    StoreType, ShuffWide,
21965                                    DAG.getIntPtrConstant(i));
21966       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21967                                 St->getPointerInfo(), St->isVolatile(),
21968                                 St->isNonTemporal(), St->getAlignment());
21969       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21970       Chains.push_back(Ch);
21971     }
21972
21973     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21974   }
21975
21976   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21977   // the FP state in cases where an emms may be missing.
21978   // A preferable solution to the general problem is to figure out the right
21979   // places to insert EMMS.  This qualifies as a quick hack.
21980
21981   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21982   if (VT.getSizeInBits() != 64)
21983     return SDValue();
21984
21985   const Function *F = DAG.getMachineFunction().getFunction();
21986   bool NoImplicitFloatOps = F->getAttributes().
21987     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21988   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21989                      && Subtarget->hasSSE2();
21990   if ((VT.isVector() ||
21991        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21992       isa<LoadSDNode>(St->getValue()) &&
21993       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21994       St->getChain().hasOneUse() && !St->isVolatile()) {
21995     SDNode* LdVal = St->getValue().getNode();
21996     LoadSDNode *Ld = nullptr;
21997     int TokenFactorIndex = -1;
21998     SmallVector<SDValue, 8> Ops;
21999     SDNode* ChainVal = St->getChain().getNode();
22000     // Must be a store of a load.  We currently handle two cases:  the load
22001     // is a direct child, and it's under an intervening TokenFactor.  It is
22002     // possible to dig deeper under nested TokenFactors.
22003     if (ChainVal == LdVal)
22004       Ld = cast<LoadSDNode>(St->getChain());
22005     else if (St->getValue().hasOneUse() &&
22006              ChainVal->getOpcode() == ISD::TokenFactor) {
22007       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22008         if (ChainVal->getOperand(i).getNode() == LdVal) {
22009           TokenFactorIndex = i;
22010           Ld = cast<LoadSDNode>(St->getValue());
22011         } else
22012           Ops.push_back(ChainVal->getOperand(i));
22013       }
22014     }
22015
22016     if (!Ld || !ISD::isNormalLoad(Ld))
22017       return SDValue();
22018
22019     // If this is not the MMX case, i.e. we are just turning i64 load/store
22020     // into f64 load/store, avoid the transformation if there are multiple
22021     // uses of the loaded value.
22022     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22023       return SDValue();
22024
22025     SDLoc LdDL(Ld);
22026     SDLoc StDL(N);
22027     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22028     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22029     // pair instead.
22030     if (Subtarget->is64Bit() || F64IsLegal) {
22031       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22032       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22033                                   Ld->getPointerInfo(), Ld->isVolatile(),
22034                                   Ld->isNonTemporal(), Ld->isInvariant(),
22035                                   Ld->getAlignment());
22036       SDValue NewChain = NewLd.getValue(1);
22037       if (TokenFactorIndex != -1) {
22038         Ops.push_back(NewChain);
22039         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22040       }
22041       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22042                           St->getPointerInfo(),
22043                           St->isVolatile(), St->isNonTemporal(),
22044                           St->getAlignment());
22045     }
22046
22047     // Otherwise, lower to two pairs of 32-bit loads / stores.
22048     SDValue LoAddr = Ld->getBasePtr();
22049     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22050                                  DAG.getConstant(4, MVT::i32));
22051
22052     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22053                                Ld->getPointerInfo(),
22054                                Ld->isVolatile(), Ld->isNonTemporal(),
22055                                Ld->isInvariant(), Ld->getAlignment());
22056     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22057                                Ld->getPointerInfo().getWithOffset(4),
22058                                Ld->isVolatile(), Ld->isNonTemporal(),
22059                                Ld->isInvariant(),
22060                                MinAlign(Ld->getAlignment(), 4));
22061
22062     SDValue NewChain = LoLd.getValue(1);
22063     if (TokenFactorIndex != -1) {
22064       Ops.push_back(LoLd);
22065       Ops.push_back(HiLd);
22066       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22067     }
22068
22069     LoAddr = St->getBasePtr();
22070     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22071                          DAG.getConstant(4, MVT::i32));
22072
22073     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22074                                 St->getPointerInfo(),
22075                                 St->isVolatile(), St->isNonTemporal(),
22076                                 St->getAlignment());
22077     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22078                                 St->getPointerInfo().getWithOffset(4),
22079                                 St->isVolatile(),
22080                                 St->isNonTemporal(),
22081                                 MinAlign(St->getAlignment(), 4));
22082     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22083   }
22084   return SDValue();
22085 }
22086
22087 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22088 /// and return the operands for the horizontal operation in LHS and RHS.  A
22089 /// horizontal operation performs the binary operation on successive elements
22090 /// of its first operand, then on successive elements of its second operand,
22091 /// returning the resulting values in a vector.  For example, if
22092 ///   A = < float a0, float a1, float a2, float a3 >
22093 /// and
22094 ///   B = < float b0, float b1, float b2, float b3 >
22095 /// then the result of doing a horizontal operation on A and B is
22096 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22097 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22098 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22099 /// set to A, RHS to B, and the routine returns 'true'.
22100 /// Note that the binary operation should have the property that if one of the
22101 /// operands is UNDEF then the result is UNDEF.
22102 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22103   // Look for the following pattern: if
22104   //   A = < float a0, float a1, float a2, float a3 >
22105   //   B = < float b0, float b1, float b2, float b3 >
22106   // and
22107   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22108   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22109   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22110   // which is A horizontal-op B.
22111
22112   // At least one of the operands should be a vector shuffle.
22113   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22114       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22115     return false;
22116
22117   MVT VT = LHS.getSimpleValueType();
22118
22119   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22120          "Unsupported vector type for horizontal add/sub");
22121
22122   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22123   // operate independently on 128-bit lanes.
22124   unsigned NumElts = VT.getVectorNumElements();
22125   unsigned NumLanes = VT.getSizeInBits()/128;
22126   unsigned NumLaneElts = NumElts / NumLanes;
22127   assert((NumLaneElts % 2 == 0) &&
22128          "Vector type should have an even number of elements in each lane");
22129   unsigned HalfLaneElts = NumLaneElts/2;
22130
22131   // View LHS in the form
22132   //   LHS = VECTOR_SHUFFLE A, B, LMask
22133   // If LHS is not a shuffle then pretend it is the shuffle
22134   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22135   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22136   // type VT.
22137   SDValue A, B;
22138   SmallVector<int, 16> LMask(NumElts);
22139   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22140     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22141       A = LHS.getOperand(0);
22142     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22143       B = LHS.getOperand(1);
22144     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22145     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22146   } else {
22147     if (LHS.getOpcode() != ISD::UNDEF)
22148       A = LHS;
22149     for (unsigned i = 0; i != NumElts; ++i)
22150       LMask[i] = i;
22151   }
22152
22153   // Likewise, view RHS in the form
22154   //   RHS = VECTOR_SHUFFLE C, D, RMask
22155   SDValue C, D;
22156   SmallVector<int, 16> RMask(NumElts);
22157   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22158     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22159       C = RHS.getOperand(0);
22160     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22161       D = RHS.getOperand(1);
22162     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22163     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22164   } else {
22165     if (RHS.getOpcode() != ISD::UNDEF)
22166       C = RHS;
22167     for (unsigned i = 0; i != NumElts; ++i)
22168       RMask[i] = i;
22169   }
22170
22171   // Check that the shuffles are both shuffling the same vectors.
22172   if (!(A == C && B == D) && !(A == D && B == C))
22173     return false;
22174
22175   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22176   if (!A.getNode() && !B.getNode())
22177     return false;
22178
22179   // If A and B occur in reverse order in RHS, then "swap" them (which means
22180   // rewriting the mask).
22181   if (A != C)
22182     CommuteVectorShuffleMask(RMask, NumElts);
22183
22184   // At this point LHS and RHS are equivalent to
22185   //   LHS = VECTOR_SHUFFLE A, B, LMask
22186   //   RHS = VECTOR_SHUFFLE A, B, RMask
22187   // Check that the masks correspond to performing a horizontal operation.
22188   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22189     for (unsigned i = 0; i != NumLaneElts; ++i) {
22190       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22191
22192       // Ignore any UNDEF components.
22193       if (LIdx < 0 || RIdx < 0 ||
22194           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22195           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22196         continue;
22197
22198       // Check that successive elements are being operated on.  If not, this is
22199       // not a horizontal operation.
22200       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22201       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22202       if (!(LIdx == Index && RIdx == Index + 1) &&
22203           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22204         return false;
22205     }
22206   }
22207
22208   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22209   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22210   return true;
22211 }
22212
22213 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22214 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22215                                   const X86Subtarget *Subtarget) {
22216   EVT VT = N->getValueType(0);
22217   SDValue LHS = N->getOperand(0);
22218   SDValue RHS = N->getOperand(1);
22219
22220   // Try to synthesize horizontal adds from adds of shuffles.
22221   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22222        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22223       isHorizontalBinOp(LHS, RHS, true))
22224     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22225   return SDValue();
22226 }
22227
22228 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22229 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22230                                   const X86Subtarget *Subtarget) {
22231   EVT VT = N->getValueType(0);
22232   SDValue LHS = N->getOperand(0);
22233   SDValue RHS = N->getOperand(1);
22234
22235   // Try to synthesize horizontal subs from subs of shuffles.
22236   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22237        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22238       isHorizontalBinOp(LHS, RHS, false))
22239     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22240   return SDValue();
22241 }
22242
22243 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22244 /// X86ISD::FXOR nodes.
22245 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22246   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22247   // F[X]OR(0.0, x) -> x
22248   // F[X]OR(x, 0.0) -> x
22249   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22250     if (C->getValueAPF().isPosZero())
22251       return N->getOperand(1);
22252   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22253     if (C->getValueAPF().isPosZero())
22254       return N->getOperand(0);
22255   return SDValue();
22256 }
22257
22258 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22259 /// X86ISD::FMAX nodes.
22260 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22261   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22262
22263   // Only perform optimizations if UnsafeMath is used.
22264   if (!DAG.getTarget().Options.UnsafeFPMath)
22265     return SDValue();
22266
22267   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22268   // into FMINC and FMAXC, which are Commutative operations.
22269   unsigned NewOp = 0;
22270   switch (N->getOpcode()) {
22271     default: llvm_unreachable("unknown opcode");
22272     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22273     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22274   }
22275
22276   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22277                      N->getOperand(0), N->getOperand(1));
22278 }
22279
22280 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22281 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22282   // FAND(0.0, x) -> 0.0
22283   // FAND(x, 0.0) -> 0.0
22284   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22285     if (C->getValueAPF().isPosZero())
22286       return N->getOperand(0);
22287   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22288     if (C->getValueAPF().isPosZero())
22289       return N->getOperand(1);
22290   return SDValue();
22291 }
22292
22293 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22294 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22295   // FANDN(x, 0.0) -> 0.0
22296   // FANDN(0.0, x) -> x
22297   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22298     if (C->getValueAPF().isPosZero())
22299       return N->getOperand(1);
22300   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22301     if (C->getValueAPF().isPosZero())
22302       return N->getOperand(1);
22303   return SDValue();
22304 }
22305
22306 static SDValue PerformBTCombine(SDNode *N,
22307                                 SelectionDAG &DAG,
22308                                 TargetLowering::DAGCombinerInfo &DCI) {
22309   // BT ignores high bits in the bit index operand.
22310   SDValue Op1 = N->getOperand(1);
22311   if (Op1.hasOneUse()) {
22312     unsigned BitWidth = Op1.getValueSizeInBits();
22313     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22314     APInt KnownZero, KnownOne;
22315     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22316                                           !DCI.isBeforeLegalizeOps());
22317     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22318     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22319         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22320       DCI.CommitTargetLoweringOpt(TLO);
22321   }
22322   return SDValue();
22323 }
22324
22325 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22326   SDValue Op = N->getOperand(0);
22327   if (Op.getOpcode() == ISD::BITCAST)
22328     Op = Op.getOperand(0);
22329   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22330   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22331       VT.getVectorElementType().getSizeInBits() ==
22332       OpVT.getVectorElementType().getSizeInBits()) {
22333     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22334   }
22335   return SDValue();
22336 }
22337
22338 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22339                                                const X86Subtarget *Subtarget) {
22340   EVT VT = N->getValueType(0);
22341   if (!VT.isVector())
22342     return SDValue();
22343
22344   SDValue N0 = N->getOperand(0);
22345   SDValue N1 = N->getOperand(1);
22346   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22347   SDLoc dl(N);
22348
22349   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22350   // both SSE and AVX2 since there is no sign-extended shift right
22351   // operation on a vector with 64-bit elements.
22352   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22353   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22354   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22355       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22356     SDValue N00 = N0.getOperand(0);
22357
22358     // EXTLOAD has a better solution on AVX2,
22359     // it may be replaced with X86ISD::VSEXT node.
22360     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22361       if (!ISD::isNormalLoad(N00.getNode()))
22362         return SDValue();
22363
22364     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22365         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22366                                   N00, N1);
22367       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22368     }
22369   }
22370   return SDValue();
22371 }
22372
22373 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22374                                   TargetLowering::DAGCombinerInfo &DCI,
22375                                   const X86Subtarget *Subtarget) {
22376   if (!DCI.isBeforeLegalizeOps())
22377     return SDValue();
22378
22379   if (!Subtarget->hasFp256())
22380     return SDValue();
22381
22382   EVT VT = N->getValueType(0);
22383   if (VT.isVector() && VT.getSizeInBits() == 256) {
22384     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22385     if (R.getNode())
22386       return R;
22387   }
22388
22389   return SDValue();
22390 }
22391
22392 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22393                                  const X86Subtarget* Subtarget) {
22394   SDLoc dl(N);
22395   EVT VT = N->getValueType(0);
22396
22397   // Let legalize expand this if it isn't a legal type yet.
22398   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22399     return SDValue();
22400
22401   EVT ScalarVT = VT.getScalarType();
22402   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22403       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22404     return SDValue();
22405
22406   SDValue A = N->getOperand(0);
22407   SDValue B = N->getOperand(1);
22408   SDValue C = N->getOperand(2);
22409
22410   bool NegA = (A.getOpcode() == ISD::FNEG);
22411   bool NegB = (B.getOpcode() == ISD::FNEG);
22412   bool NegC = (C.getOpcode() == ISD::FNEG);
22413
22414   // Negative multiplication when NegA xor NegB
22415   bool NegMul = (NegA != NegB);
22416   if (NegA)
22417     A = A.getOperand(0);
22418   if (NegB)
22419     B = B.getOperand(0);
22420   if (NegC)
22421     C = C.getOperand(0);
22422
22423   unsigned Opcode;
22424   if (!NegMul)
22425     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22426   else
22427     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22428
22429   return DAG.getNode(Opcode, dl, VT, A, B, C);
22430 }
22431
22432 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22433                                   TargetLowering::DAGCombinerInfo &DCI,
22434                                   const X86Subtarget *Subtarget) {
22435   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22436   //           (and (i32 x86isd::setcc_carry), 1)
22437   // This eliminates the zext. This transformation is necessary because
22438   // ISD::SETCC is always legalized to i8.
22439   SDLoc dl(N);
22440   SDValue N0 = N->getOperand(0);
22441   EVT VT = N->getValueType(0);
22442
22443   if (N0.getOpcode() == ISD::AND &&
22444       N0.hasOneUse() &&
22445       N0.getOperand(0).hasOneUse()) {
22446     SDValue N00 = N0.getOperand(0);
22447     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22448       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22449       if (!C || C->getZExtValue() != 1)
22450         return SDValue();
22451       return DAG.getNode(ISD::AND, dl, VT,
22452                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22453                                      N00.getOperand(0), N00.getOperand(1)),
22454                          DAG.getConstant(1, VT));
22455     }
22456   }
22457
22458   if (N0.getOpcode() == ISD::TRUNCATE &&
22459       N0.hasOneUse() &&
22460       N0.getOperand(0).hasOneUse()) {
22461     SDValue N00 = N0.getOperand(0);
22462     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22463       return DAG.getNode(ISD::AND, dl, VT,
22464                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22465                                      N00.getOperand(0), N00.getOperand(1)),
22466                          DAG.getConstant(1, VT));
22467     }
22468   }
22469   if (VT.is256BitVector()) {
22470     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22471     if (R.getNode())
22472       return R;
22473   }
22474
22475   return SDValue();
22476 }
22477
22478 // Optimize x == -y --> x+y == 0
22479 //          x != -y --> x+y != 0
22480 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22481                                       const X86Subtarget* Subtarget) {
22482   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22483   SDValue LHS = N->getOperand(0);
22484   SDValue RHS = N->getOperand(1);
22485   EVT VT = N->getValueType(0);
22486   SDLoc DL(N);
22487
22488   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22489     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22490       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22491         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22492                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22493         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22494                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22495       }
22496   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22497     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22498       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22499         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22500                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22501         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22502                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22503       }
22504
22505   if (VT.getScalarType() == MVT::i1) {
22506     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22507       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22508     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22509     if (!IsSEXT0 && !IsVZero0)
22510       return SDValue();
22511     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22512       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22513     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22514
22515     if (!IsSEXT1 && !IsVZero1)
22516       return SDValue();
22517
22518     if (IsSEXT0 && IsVZero1) {
22519       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22520       if (CC == ISD::SETEQ)
22521         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22522       return LHS.getOperand(0);
22523     }
22524     if (IsSEXT1 && IsVZero0) {
22525       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22526       if (CC == ISD::SETEQ)
22527         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22528       return RHS.getOperand(0);
22529     }
22530   }
22531
22532   return SDValue();
22533 }
22534
22535 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22536                                       const X86Subtarget *Subtarget) {
22537   SDLoc dl(N);
22538   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22539   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22540          "X86insertps is only defined for v4x32");
22541
22542   SDValue Ld = N->getOperand(1);
22543   if (MayFoldLoad(Ld)) {
22544     // Extract the countS bits from the immediate so we can get the proper
22545     // address when narrowing the vector load to a specific element.
22546     // When the second source op is a memory address, interps doesn't use
22547     // countS and just gets an f32 from that address.
22548     unsigned DestIndex =
22549         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22550     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22551   } else
22552     return SDValue();
22553
22554   // Create this as a scalar to vector to match the instruction pattern.
22555   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22556   // countS bits are ignored when loading from memory on insertps, which
22557   // means we don't need to explicitly set them to 0.
22558   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22559                      LoadScalarToVector, N->getOperand(2));
22560 }
22561
22562 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22563 // as "sbb reg,reg", since it can be extended without zext and produces
22564 // an all-ones bit which is more useful than 0/1 in some cases.
22565 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22566                                MVT VT) {
22567   if (VT == MVT::i8)
22568     return DAG.getNode(ISD::AND, DL, VT,
22569                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22570                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22571                        DAG.getConstant(1, VT));
22572   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22573   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22574                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22575                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22576 }
22577
22578 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22579 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22580                                    TargetLowering::DAGCombinerInfo &DCI,
22581                                    const X86Subtarget *Subtarget) {
22582   SDLoc DL(N);
22583   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22584   SDValue EFLAGS = N->getOperand(1);
22585
22586   if (CC == X86::COND_A) {
22587     // Try to convert COND_A into COND_B in an attempt to facilitate
22588     // materializing "setb reg".
22589     //
22590     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22591     // cannot take an immediate as its first operand.
22592     //
22593     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22594         EFLAGS.getValueType().isInteger() &&
22595         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22596       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22597                                    EFLAGS.getNode()->getVTList(),
22598                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22599       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22600       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22601     }
22602   }
22603
22604   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22605   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22606   // cases.
22607   if (CC == X86::COND_B)
22608     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22609
22610   SDValue Flags;
22611
22612   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22613   if (Flags.getNode()) {
22614     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22615     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22616   }
22617
22618   return SDValue();
22619 }
22620
22621 // Optimize branch condition evaluation.
22622 //
22623 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22624                                     TargetLowering::DAGCombinerInfo &DCI,
22625                                     const X86Subtarget *Subtarget) {
22626   SDLoc DL(N);
22627   SDValue Chain = N->getOperand(0);
22628   SDValue Dest = N->getOperand(1);
22629   SDValue EFLAGS = N->getOperand(3);
22630   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22631
22632   SDValue Flags;
22633
22634   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22635   if (Flags.getNode()) {
22636     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22637     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22638                        Flags);
22639   }
22640
22641   return SDValue();
22642 }
22643
22644 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22645                                                          SelectionDAG &DAG) {
22646   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22647   // optimize away operation when it's from a constant.
22648   //
22649   // The general transformation is:
22650   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22651   //       AND(VECTOR_CMP(x,y), constant2)
22652   //    constant2 = UNARYOP(constant)
22653
22654   // Early exit if this isn't a vector operation, the operand of the
22655   // unary operation isn't a bitwise AND, or if the sizes of the operations
22656   // aren't the same.
22657   EVT VT = N->getValueType(0);
22658   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22659       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22660       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22661     return SDValue();
22662
22663   // Now check that the other operand of the AND is a constant. We could
22664   // make the transformation for non-constant splats as well, but it's unclear
22665   // that would be a benefit as it would not eliminate any operations, just
22666   // perform one more step in scalar code before moving to the vector unit.
22667   if (BuildVectorSDNode *BV =
22668           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22669     // Bail out if the vector isn't a constant.
22670     if (!BV->isConstant())
22671       return SDValue();
22672
22673     // Everything checks out. Build up the new and improved node.
22674     SDLoc DL(N);
22675     EVT IntVT = BV->getValueType(0);
22676     // Create a new constant of the appropriate type for the transformed
22677     // DAG.
22678     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22679     // The AND node needs bitcasts to/from an integer vector type around it.
22680     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22681     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22682                                  N->getOperand(0)->getOperand(0), MaskConst);
22683     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22684     return Res;
22685   }
22686
22687   return SDValue();
22688 }
22689
22690 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22691                                         const X86TargetLowering *XTLI) {
22692   // First try to optimize away the conversion entirely when it's
22693   // conditionally from a constant. Vectors only.
22694   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22695   if (Res != SDValue())
22696     return Res;
22697
22698   // Now move on to more general possibilities.
22699   SDValue Op0 = N->getOperand(0);
22700   EVT InVT = Op0->getValueType(0);
22701
22702   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22703   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22704     SDLoc dl(N);
22705     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22706     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22707     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22708   }
22709
22710   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22711   // a 32-bit target where SSE doesn't support i64->FP operations.
22712   if (Op0.getOpcode() == ISD::LOAD) {
22713     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22714     EVT VT = Ld->getValueType(0);
22715     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22716         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22717         !XTLI->getSubtarget()->is64Bit() &&
22718         VT == MVT::i64) {
22719       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22720                                           Ld->getChain(), Op0, DAG);
22721       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22722       return FILDChain;
22723     }
22724   }
22725   return SDValue();
22726 }
22727
22728 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22729 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22730                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22731   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22732   // the result is either zero or one (depending on the input carry bit).
22733   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22734   if (X86::isZeroNode(N->getOperand(0)) &&
22735       X86::isZeroNode(N->getOperand(1)) &&
22736       // We don't have a good way to replace an EFLAGS use, so only do this when
22737       // dead right now.
22738       SDValue(N, 1).use_empty()) {
22739     SDLoc DL(N);
22740     EVT VT = N->getValueType(0);
22741     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22742     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22743                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22744                                            DAG.getConstant(X86::COND_B,MVT::i8),
22745                                            N->getOperand(2)),
22746                                DAG.getConstant(1, VT));
22747     return DCI.CombineTo(N, Res1, CarryOut);
22748   }
22749
22750   return SDValue();
22751 }
22752
22753 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22754 //      (add Y, (setne X, 0)) -> sbb -1, Y
22755 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22756 //      (sub (setne X, 0), Y) -> adc -1, Y
22757 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22758   SDLoc DL(N);
22759
22760   // Look through ZExts.
22761   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22762   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22763     return SDValue();
22764
22765   SDValue SetCC = Ext.getOperand(0);
22766   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22767     return SDValue();
22768
22769   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22770   if (CC != X86::COND_E && CC != X86::COND_NE)
22771     return SDValue();
22772
22773   SDValue Cmp = SetCC.getOperand(1);
22774   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22775       !X86::isZeroNode(Cmp.getOperand(1)) ||
22776       !Cmp.getOperand(0).getValueType().isInteger())
22777     return SDValue();
22778
22779   SDValue CmpOp0 = Cmp.getOperand(0);
22780   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22781                                DAG.getConstant(1, CmpOp0.getValueType()));
22782
22783   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22784   if (CC == X86::COND_NE)
22785     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22786                        DL, OtherVal.getValueType(), OtherVal,
22787                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22788   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22789                      DL, OtherVal.getValueType(), OtherVal,
22790                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22791 }
22792
22793 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22794 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22795                                  const X86Subtarget *Subtarget) {
22796   EVT VT = N->getValueType(0);
22797   SDValue Op0 = N->getOperand(0);
22798   SDValue Op1 = N->getOperand(1);
22799
22800   // Try to synthesize horizontal adds from adds of shuffles.
22801   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22802        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22803       isHorizontalBinOp(Op0, Op1, true))
22804     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22805
22806   return OptimizeConditionalInDecrement(N, DAG);
22807 }
22808
22809 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22810                                  const X86Subtarget *Subtarget) {
22811   SDValue Op0 = N->getOperand(0);
22812   SDValue Op1 = N->getOperand(1);
22813
22814   // X86 can't encode an immediate LHS of a sub. See if we can push the
22815   // negation into a preceding instruction.
22816   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22817     // If the RHS of the sub is a XOR with one use and a constant, invert the
22818     // immediate. Then add one to the LHS of the sub so we can turn
22819     // X-Y -> X+~Y+1, saving one register.
22820     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22821         isa<ConstantSDNode>(Op1.getOperand(1))) {
22822       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22823       EVT VT = Op0.getValueType();
22824       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22825                                    Op1.getOperand(0),
22826                                    DAG.getConstant(~XorC, VT));
22827       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22828                          DAG.getConstant(C->getAPIntValue()+1, VT));
22829     }
22830   }
22831
22832   // Try to synthesize horizontal adds from adds of shuffles.
22833   EVT VT = N->getValueType(0);
22834   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22835        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22836       isHorizontalBinOp(Op0, Op1, true))
22837     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22838
22839   return OptimizeConditionalInDecrement(N, DAG);
22840 }
22841
22842 /// performVZEXTCombine - Performs build vector combines
22843 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22844                                         TargetLowering::DAGCombinerInfo &DCI,
22845                                         const X86Subtarget *Subtarget) {
22846   // (vzext (bitcast (vzext (x)) -> (vzext x)
22847   SDValue In = N->getOperand(0);
22848   while (In.getOpcode() == ISD::BITCAST)
22849     In = In.getOperand(0);
22850
22851   if (In.getOpcode() != X86ISD::VZEXT)
22852     return SDValue();
22853
22854   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22855                      In.getOperand(0));
22856 }
22857
22858 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22859                                              DAGCombinerInfo &DCI) const {
22860   SelectionDAG &DAG = DCI.DAG;
22861   switch (N->getOpcode()) {
22862   default: break;
22863   case ISD::EXTRACT_VECTOR_ELT:
22864     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22865   case ISD::VSELECT:
22866   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22867   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22868   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22869   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22870   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22871   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22872   case ISD::SHL:
22873   case ISD::SRA:
22874   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22875   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22876   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22877   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22878   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22879   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22880   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22881   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22882   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22883   case X86ISD::FXOR:
22884   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22885   case X86ISD::FMIN:
22886   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22887   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22888   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22889   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22890   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22891   case ISD::ANY_EXTEND:
22892   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22893   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22894   case ISD::SIGN_EXTEND_INREG:
22895     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22896   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22897   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22898   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22899   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22900   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22901   case X86ISD::SHUFP:       // Handle all target specific shuffles
22902   case X86ISD::PALIGNR:
22903   case X86ISD::UNPCKH:
22904   case X86ISD::UNPCKL:
22905   case X86ISD::MOVHLPS:
22906   case X86ISD::MOVLHPS:
22907   case X86ISD::PSHUFB:
22908   case X86ISD::PSHUFD:
22909   case X86ISD::PSHUFHW:
22910   case X86ISD::PSHUFLW:
22911   case X86ISD::MOVSS:
22912   case X86ISD::MOVSD:
22913   case X86ISD::VPERMILP:
22914   case X86ISD::VPERM2X128:
22915   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22916   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22917   case ISD::INTRINSIC_WO_CHAIN:
22918     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22919   case X86ISD::INSERTPS:
22920     return PerformINSERTPSCombine(N, DAG, Subtarget);
22921   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22922   }
22923
22924   return SDValue();
22925 }
22926
22927 /// isTypeDesirableForOp - Return true if the target has native support for
22928 /// the specified value type and it is 'desirable' to use the type for the
22929 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22930 /// instruction encodings are longer and some i16 instructions are slow.
22931 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22932   if (!isTypeLegal(VT))
22933     return false;
22934   if (VT != MVT::i16)
22935     return true;
22936
22937   switch (Opc) {
22938   default:
22939     return true;
22940   case ISD::LOAD:
22941   case ISD::SIGN_EXTEND:
22942   case ISD::ZERO_EXTEND:
22943   case ISD::ANY_EXTEND:
22944   case ISD::SHL:
22945   case ISD::SRL:
22946   case ISD::SUB:
22947   case ISD::ADD:
22948   case ISD::MUL:
22949   case ISD::AND:
22950   case ISD::OR:
22951   case ISD::XOR:
22952     return false;
22953   }
22954 }
22955
22956 /// IsDesirableToPromoteOp - This method query the target whether it is
22957 /// beneficial for dag combiner to promote the specified node. If true, it
22958 /// should return the desired promotion type by reference.
22959 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22960   EVT VT = Op.getValueType();
22961   if (VT != MVT::i16)
22962     return false;
22963
22964   bool Promote = false;
22965   bool Commute = false;
22966   switch (Op.getOpcode()) {
22967   default: break;
22968   case ISD::LOAD: {
22969     LoadSDNode *LD = cast<LoadSDNode>(Op);
22970     // If the non-extending load has a single use and it's not live out, then it
22971     // might be folded.
22972     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22973                                                      Op.hasOneUse()*/) {
22974       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22975              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22976         // The only case where we'd want to promote LOAD (rather then it being
22977         // promoted as an operand is when it's only use is liveout.
22978         if (UI->getOpcode() != ISD::CopyToReg)
22979           return false;
22980       }
22981     }
22982     Promote = true;
22983     break;
22984   }
22985   case ISD::SIGN_EXTEND:
22986   case ISD::ZERO_EXTEND:
22987   case ISD::ANY_EXTEND:
22988     Promote = true;
22989     break;
22990   case ISD::SHL:
22991   case ISD::SRL: {
22992     SDValue N0 = Op.getOperand(0);
22993     // Look out for (store (shl (load), x)).
22994     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22995       return false;
22996     Promote = true;
22997     break;
22998   }
22999   case ISD::ADD:
23000   case ISD::MUL:
23001   case ISD::AND:
23002   case ISD::OR:
23003   case ISD::XOR:
23004     Commute = true;
23005     // fallthrough
23006   case ISD::SUB: {
23007     SDValue N0 = Op.getOperand(0);
23008     SDValue N1 = Op.getOperand(1);
23009     if (!Commute && MayFoldLoad(N1))
23010       return false;
23011     // Avoid disabling potential load folding opportunities.
23012     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23013       return false;
23014     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23015       return false;
23016     Promote = true;
23017   }
23018   }
23019
23020   PVT = MVT::i32;
23021   return Promote;
23022 }
23023
23024 //===----------------------------------------------------------------------===//
23025 //                           X86 Inline Assembly Support
23026 //===----------------------------------------------------------------------===//
23027
23028 namespace {
23029   // Helper to match a string separated by whitespace.
23030   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
23031     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
23032
23033     for (unsigned i = 0, e = args.size(); i != e; ++i) {
23034       StringRef piece(*args[i]);
23035       if (!s.startswith(piece)) // Check if the piece matches.
23036         return false;
23037
23038       s = s.substr(piece.size());
23039       StringRef::size_type pos = s.find_first_not_of(" \t");
23040       if (pos == 0) // We matched a prefix.
23041         return false;
23042
23043       s = s.substr(pos);
23044     }
23045
23046     return s.empty();
23047   }
23048   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
23049 }
23050
23051 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23052
23053   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23054     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23055         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23056         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23057
23058       if (AsmPieces.size() == 3)
23059         return true;
23060       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23061         return true;
23062     }
23063   }
23064   return false;
23065 }
23066
23067 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23068   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23069
23070   std::string AsmStr = IA->getAsmString();
23071
23072   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23073   if (!Ty || Ty->getBitWidth() % 16 != 0)
23074     return false;
23075
23076   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23077   SmallVector<StringRef, 4> AsmPieces;
23078   SplitString(AsmStr, AsmPieces, ";\n");
23079
23080   switch (AsmPieces.size()) {
23081   default: return false;
23082   case 1:
23083     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23084     // we will turn this bswap into something that will be lowered to logical
23085     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23086     // lower so don't worry about this.
23087     // bswap $0
23088     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23089         matchAsm(AsmPieces[0], "bswapl", "$0") ||
23090         matchAsm(AsmPieces[0], "bswapq", "$0") ||
23091         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23092         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23093         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23094       // No need to check constraints, nothing other than the equivalent of
23095       // "=r,0" would be valid here.
23096       return IntrinsicLowering::LowerToByteSwap(CI);
23097     }
23098
23099     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23100     if (CI->getType()->isIntegerTy(16) &&
23101         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23102         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23103          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23104       AsmPieces.clear();
23105       const std::string &ConstraintsStr = IA->getConstraintString();
23106       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23107       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23108       if (clobbersFlagRegisters(AsmPieces))
23109         return IntrinsicLowering::LowerToByteSwap(CI);
23110     }
23111     break;
23112   case 3:
23113     if (CI->getType()->isIntegerTy(32) &&
23114         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23115         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23116         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23117         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23118       AsmPieces.clear();
23119       const std::string &ConstraintsStr = IA->getConstraintString();
23120       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23121       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23122       if (clobbersFlagRegisters(AsmPieces))
23123         return IntrinsicLowering::LowerToByteSwap(CI);
23124     }
23125
23126     if (CI->getType()->isIntegerTy(64)) {
23127       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23128       if (Constraints.size() >= 2 &&
23129           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23130           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23131         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23132         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23133             matchAsm(AsmPieces[1], "bswap", "%edx") &&
23134             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23135           return IntrinsicLowering::LowerToByteSwap(CI);
23136       }
23137     }
23138     break;
23139   }
23140   return false;
23141 }
23142
23143 /// getConstraintType - Given a constraint letter, return the type of
23144 /// constraint it is for this target.
23145 X86TargetLowering::ConstraintType
23146 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23147   if (Constraint.size() == 1) {
23148     switch (Constraint[0]) {
23149     case 'R':
23150     case 'q':
23151     case 'Q':
23152     case 'f':
23153     case 't':
23154     case 'u':
23155     case 'y':
23156     case 'x':
23157     case 'Y':
23158     case 'l':
23159       return C_RegisterClass;
23160     case 'a':
23161     case 'b':
23162     case 'c':
23163     case 'd':
23164     case 'S':
23165     case 'D':
23166     case 'A':
23167       return C_Register;
23168     case 'I':
23169     case 'J':
23170     case 'K':
23171     case 'L':
23172     case 'M':
23173     case 'N':
23174     case 'G':
23175     case 'C':
23176     case 'e':
23177     case 'Z':
23178       return C_Other;
23179     default:
23180       break;
23181     }
23182   }
23183   return TargetLowering::getConstraintType(Constraint);
23184 }
23185
23186 /// Examine constraint type and operand type and determine a weight value.
23187 /// This object must already have been set up with the operand type
23188 /// and the current alternative constraint selected.
23189 TargetLowering::ConstraintWeight
23190   X86TargetLowering::getSingleConstraintMatchWeight(
23191     AsmOperandInfo &info, const char *constraint) const {
23192   ConstraintWeight weight = CW_Invalid;
23193   Value *CallOperandVal = info.CallOperandVal;
23194     // If we don't have a value, we can't do a match,
23195     // but allow it at the lowest weight.
23196   if (!CallOperandVal)
23197     return CW_Default;
23198   Type *type = CallOperandVal->getType();
23199   // Look at the constraint type.
23200   switch (*constraint) {
23201   default:
23202     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23203   case 'R':
23204   case 'q':
23205   case 'Q':
23206   case 'a':
23207   case 'b':
23208   case 'c':
23209   case 'd':
23210   case 'S':
23211   case 'D':
23212   case 'A':
23213     if (CallOperandVal->getType()->isIntegerTy())
23214       weight = CW_SpecificReg;
23215     break;
23216   case 'f':
23217   case 't':
23218   case 'u':
23219     if (type->isFloatingPointTy())
23220       weight = CW_SpecificReg;
23221     break;
23222   case 'y':
23223     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23224       weight = CW_SpecificReg;
23225     break;
23226   case 'x':
23227   case 'Y':
23228     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23229         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23230       weight = CW_Register;
23231     break;
23232   case 'I':
23233     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23234       if (C->getZExtValue() <= 31)
23235         weight = CW_Constant;
23236     }
23237     break;
23238   case 'J':
23239     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23240       if (C->getZExtValue() <= 63)
23241         weight = CW_Constant;
23242     }
23243     break;
23244   case 'K':
23245     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23246       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23247         weight = CW_Constant;
23248     }
23249     break;
23250   case 'L':
23251     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23252       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23253         weight = CW_Constant;
23254     }
23255     break;
23256   case 'M':
23257     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23258       if (C->getZExtValue() <= 3)
23259         weight = CW_Constant;
23260     }
23261     break;
23262   case 'N':
23263     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23264       if (C->getZExtValue() <= 0xff)
23265         weight = CW_Constant;
23266     }
23267     break;
23268   case 'G':
23269   case 'C':
23270     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23271       weight = CW_Constant;
23272     }
23273     break;
23274   case 'e':
23275     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23276       if ((C->getSExtValue() >= -0x80000000LL) &&
23277           (C->getSExtValue() <= 0x7fffffffLL))
23278         weight = CW_Constant;
23279     }
23280     break;
23281   case 'Z':
23282     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23283       if (C->getZExtValue() <= 0xffffffff)
23284         weight = CW_Constant;
23285     }
23286     break;
23287   }
23288   return weight;
23289 }
23290
23291 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23292 /// with another that has more specific requirements based on the type of the
23293 /// corresponding operand.
23294 const char *X86TargetLowering::
23295 LowerXConstraint(EVT ConstraintVT) const {
23296   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23297   // 'f' like normal targets.
23298   if (ConstraintVT.isFloatingPoint()) {
23299     if (Subtarget->hasSSE2())
23300       return "Y";
23301     if (Subtarget->hasSSE1())
23302       return "x";
23303   }
23304
23305   return TargetLowering::LowerXConstraint(ConstraintVT);
23306 }
23307
23308 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23309 /// vector.  If it is invalid, don't add anything to Ops.
23310 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23311                                                      std::string &Constraint,
23312                                                      std::vector<SDValue>&Ops,
23313                                                      SelectionDAG &DAG) const {
23314   SDValue Result;
23315
23316   // Only support length 1 constraints for now.
23317   if (Constraint.length() > 1) return;
23318
23319   char ConstraintLetter = Constraint[0];
23320   switch (ConstraintLetter) {
23321   default: break;
23322   case 'I':
23323     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23324       if (C->getZExtValue() <= 31) {
23325         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23326         break;
23327       }
23328     }
23329     return;
23330   case 'J':
23331     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23332       if (C->getZExtValue() <= 63) {
23333         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23334         break;
23335       }
23336     }
23337     return;
23338   case 'K':
23339     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23340       if (isInt<8>(C->getSExtValue())) {
23341         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23342         break;
23343       }
23344     }
23345     return;
23346   case 'N':
23347     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23348       if (C->getZExtValue() <= 255) {
23349         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23350         break;
23351       }
23352     }
23353     return;
23354   case 'e': {
23355     // 32-bit signed value
23356     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23357       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23358                                            C->getSExtValue())) {
23359         // Widen to 64 bits here to get it sign extended.
23360         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23361         break;
23362       }
23363     // FIXME gcc accepts some relocatable values here too, but only in certain
23364     // memory models; it's complicated.
23365     }
23366     return;
23367   }
23368   case 'Z': {
23369     // 32-bit unsigned value
23370     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23371       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23372                                            C->getZExtValue())) {
23373         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23374         break;
23375       }
23376     }
23377     // FIXME gcc accepts some relocatable values here too, but only in certain
23378     // memory models; it's complicated.
23379     return;
23380   }
23381   case 'i': {
23382     // Literal immediates are always ok.
23383     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23384       // Widen to 64 bits here to get it sign extended.
23385       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23386       break;
23387     }
23388
23389     // In any sort of PIC mode addresses need to be computed at runtime by
23390     // adding in a register or some sort of table lookup.  These can't
23391     // be used as immediates.
23392     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23393       return;
23394
23395     // If we are in non-pic codegen mode, we allow the address of a global (with
23396     // an optional displacement) to be used with 'i'.
23397     GlobalAddressSDNode *GA = nullptr;
23398     int64_t Offset = 0;
23399
23400     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23401     while (1) {
23402       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23403         Offset += GA->getOffset();
23404         break;
23405       } else if (Op.getOpcode() == ISD::ADD) {
23406         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23407           Offset += C->getZExtValue();
23408           Op = Op.getOperand(0);
23409           continue;
23410         }
23411       } else if (Op.getOpcode() == ISD::SUB) {
23412         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23413           Offset += -C->getZExtValue();
23414           Op = Op.getOperand(0);
23415           continue;
23416         }
23417       }
23418
23419       // Otherwise, this isn't something we can handle, reject it.
23420       return;
23421     }
23422
23423     const GlobalValue *GV = GA->getGlobal();
23424     // If we require an extra load to get this address, as in PIC mode, we
23425     // can't accept it.
23426     if (isGlobalStubReference(
23427             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23428       return;
23429
23430     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23431                                         GA->getValueType(0), Offset);
23432     break;
23433   }
23434   }
23435
23436   if (Result.getNode()) {
23437     Ops.push_back(Result);
23438     return;
23439   }
23440   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23441 }
23442
23443 std::pair<unsigned, const TargetRegisterClass*>
23444 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23445                                                 MVT VT) const {
23446   // First, see if this is a constraint that directly corresponds to an LLVM
23447   // register class.
23448   if (Constraint.size() == 1) {
23449     // GCC Constraint Letters
23450     switch (Constraint[0]) {
23451     default: break;
23452       // TODO: Slight differences here in allocation order and leaving
23453       // RIP in the class. Do they matter any more here than they do
23454       // in the normal allocation?
23455     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23456       if (Subtarget->is64Bit()) {
23457         if (VT == MVT::i32 || VT == MVT::f32)
23458           return std::make_pair(0U, &X86::GR32RegClass);
23459         if (VT == MVT::i16)
23460           return std::make_pair(0U, &X86::GR16RegClass);
23461         if (VT == MVT::i8 || VT == MVT::i1)
23462           return std::make_pair(0U, &X86::GR8RegClass);
23463         if (VT == MVT::i64 || VT == MVT::f64)
23464           return std::make_pair(0U, &X86::GR64RegClass);
23465         break;
23466       }
23467       // 32-bit fallthrough
23468     case 'Q':   // Q_REGS
23469       if (VT == MVT::i32 || VT == MVT::f32)
23470         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23471       if (VT == MVT::i16)
23472         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23473       if (VT == MVT::i8 || VT == MVT::i1)
23474         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23475       if (VT == MVT::i64)
23476         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23477       break;
23478     case 'r':   // GENERAL_REGS
23479     case 'l':   // INDEX_REGS
23480       if (VT == MVT::i8 || VT == MVT::i1)
23481         return std::make_pair(0U, &X86::GR8RegClass);
23482       if (VT == MVT::i16)
23483         return std::make_pair(0U, &X86::GR16RegClass);
23484       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23485         return std::make_pair(0U, &X86::GR32RegClass);
23486       return std::make_pair(0U, &X86::GR64RegClass);
23487     case 'R':   // LEGACY_REGS
23488       if (VT == MVT::i8 || VT == MVT::i1)
23489         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23490       if (VT == MVT::i16)
23491         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23492       if (VT == MVT::i32 || !Subtarget->is64Bit())
23493         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23494       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23495     case 'f':  // FP Stack registers.
23496       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23497       // value to the correct fpstack register class.
23498       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23499         return std::make_pair(0U, &X86::RFP32RegClass);
23500       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23501         return std::make_pair(0U, &X86::RFP64RegClass);
23502       return std::make_pair(0U, &X86::RFP80RegClass);
23503     case 'y':   // MMX_REGS if MMX allowed.
23504       if (!Subtarget->hasMMX()) break;
23505       return std::make_pair(0U, &X86::VR64RegClass);
23506     case 'Y':   // SSE_REGS if SSE2 allowed
23507       if (!Subtarget->hasSSE2()) break;
23508       // FALL THROUGH.
23509     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23510       if (!Subtarget->hasSSE1()) break;
23511
23512       switch (VT.SimpleTy) {
23513       default: break;
23514       // Scalar SSE types.
23515       case MVT::f32:
23516       case MVT::i32:
23517         return std::make_pair(0U, &X86::FR32RegClass);
23518       case MVT::f64:
23519       case MVT::i64:
23520         return std::make_pair(0U, &X86::FR64RegClass);
23521       // Vector types.
23522       case MVT::v16i8:
23523       case MVT::v8i16:
23524       case MVT::v4i32:
23525       case MVT::v2i64:
23526       case MVT::v4f32:
23527       case MVT::v2f64:
23528         return std::make_pair(0U, &X86::VR128RegClass);
23529       // AVX types.
23530       case MVT::v32i8:
23531       case MVT::v16i16:
23532       case MVT::v8i32:
23533       case MVT::v4i64:
23534       case MVT::v8f32:
23535       case MVT::v4f64:
23536         return std::make_pair(0U, &X86::VR256RegClass);
23537       case MVT::v8f64:
23538       case MVT::v16f32:
23539       case MVT::v16i32:
23540       case MVT::v8i64:
23541         return std::make_pair(0U, &X86::VR512RegClass);
23542       }
23543       break;
23544     }
23545   }
23546
23547   // Use the default implementation in TargetLowering to convert the register
23548   // constraint into a member of a register class.
23549   std::pair<unsigned, const TargetRegisterClass*> Res;
23550   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23551
23552   // Not found as a standard register?
23553   if (!Res.second) {
23554     // Map st(0) -> st(7) -> ST0
23555     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23556         tolower(Constraint[1]) == 's' &&
23557         tolower(Constraint[2]) == 't' &&
23558         Constraint[3] == '(' &&
23559         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23560         Constraint[5] == ')' &&
23561         Constraint[6] == '}') {
23562
23563       Res.first = X86::FP0+Constraint[4]-'0';
23564       Res.second = &X86::RFP80RegClass;
23565       return Res;
23566     }
23567
23568     // GCC allows "st(0)" to be called just plain "st".
23569     if (StringRef("{st}").equals_lower(Constraint)) {
23570       Res.first = X86::FP0;
23571       Res.second = &X86::RFP80RegClass;
23572       return Res;
23573     }
23574
23575     // flags -> EFLAGS
23576     if (StringRef("{flags}").equals_lower(Constraint)) {
23577       Res.first = X86::EFLAGS;
23578       Res.second = &X86::CCRRegClass;
23579       return Res;
23580     }
23581
23582     // 'A' means EAX + EDX.
23583     if (Constraint == "A") {
23584       Res.first = X86::EAX;
23585       Res.second = &X86::GR32_ADRegClass;
23586       return Res;
23587     }
23588     return Res;
23589   }
23590
23591   // Otherwise, check to see if this is a register class of the wrong value
23592   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23593   // turn into {ax},{dx}.
23594   if (Res.second->hasType(VT))
23595     return Res;   // Correct type already, nothing to do.
23596
23597   // All of the single-register GCC register classes map their values onto
23598   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23599   // really want an 8-bit or 32-bit register, map to the appropriate register
23600   // class and return the appropriate register.
23601   if (Res.second == &X86::GR16RegClass) {
23602     if (VT == MVT::i8 || VT == MVT::i1) {
23603       unsigned DestReg = 0;
23604       switch (Res.first) {
23605       default: break;
23606       case X86::AX: DestReg = X86::AL; break;
23607       case X86::DX: DestReg = X86::DL; break;
23608       case X86::CX: DestReg = X86::CL; break;
23609       case X86::BX: DestReg = X86::BL; break;
23610       }
23611       if (DestReg) {
23612         Res.first = DestReg;
23613         Res.second = &X86::GR8RegClass;
23614       }
23615     } else if (VT == MVT::i32 || VT == MVT::f32) {
23616       unsigned DestReg = 0;
23617       switch (Res.first) {
23618       default: break;
23619       case X86::AX: DestReg = X86::EAX; break;
23620       case X86::DX: DestReg = X86::EDX; break;
23621       case X86::CX: DestReg = X86::ECX; break;
23622       case X86::BX: DestReg = X86::EBX; break;
23623       case X86::SI: DestReg = X86::ESI; break;
23624       case X86::DI: DestReg = X86::EDI; break;
23625       case X86::BP: DestReg = X86::EBP; break;
23626       case X86::SP: DestReg = X86::ESP; break;
23627       }
23628       if (DestReg) {
23629         Res.first = DestReg;
23630         Res.second = &X86::GR32RegClass;
23631       }
23632     } else if (VT == MVT::i64 || VT == MVT::f64) {
23633       unsigned DestReg = 0;
23634       switch (Res.first) {
23635       default: break;
23636       case X86::AX: DestReg = X86::RAX; break;
23637       case X86::DX: DestReg = X86::RDX; break;
23638       case X86::CX: DestReg = X86::RCX; break;
23639       case X86::BX: DestReg = X86::RBX; break;
23640       case X86::SI: DestReg = X86::RSI; break;
23641       case X86::DI: DestReg = X86::RDI; break;
23642       case X86::BP: DestReg = X86::RBP; break;
23643       case X86::SP: DestReg = X86::RSP; break;
23644       }
23645       if (DestReg) {
23646         Res.first = DestReg;
23647         Res.second = &X86::GR64RegClass;
23648       }
23649     }
23650   } else if (Res.second == &X86::FR32RegClass ||
23651              Res.second == &X86::FR64RegClass ||
23652              Res.second == &X86::VR128RegClass ||
23653              Res.second == &X86::VR256RegClass ||
23654              Res.second == &X86::FR32XRegClass ||
23655              Res.second == &X86::FR64XRegClass ||
23656              Res.second == &X86::VR128XRegClass ||
23657              Res.second == &X86::VR256XRegClass ||
23658              Res.second == &X86::VR512RegClass) {
23659     // Handle references to XMM physical registers that got mapped into the
23660     // wrong class.  This can happen with constraints like {xmm0} where the
23661     // target independent register mapper will just pick the first match it can
23662     // find, ignoring the required type.
23663
23664     if (VT == MVT::f32 || VT == MVT::i32)
23665       Res.second = &X86::FR32RegClass;
23666     else if (VT == MVT::f64 || VT == MVT::i64)
23667       Res.second = &X86::FR64RegClass;
23668     else if (X86::VR128RegClass.hasType(VT))
23669       Res.second = &X86::VR128RegClass;
23670     else if (X86::VR256RegClass.hasType(VT))
23671       Res.second = &X86::VR256RegClass;
23672     else if (X86::VR512RegClass.hasType(VT))
23673       Res.second = &X86::VR512RegClass;
23674   }
23675
23676   return Res;
23677 }
23678
23679 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23680                                             Type *Ty) const {
23681   // Scaling factors are not free at all.
23682   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23683   // will take 2 allocations in the out of order engine instead of 1
23684   // for plain addressing mode, i.e. inst (reg1).
23685   // E.g.,
23686   // vaddps (%rsi,%drx), %ymm0, %ymm1
23687   // Requires two allocations (one for the load, one for the computation)
23688   // whereas:
23689   // vaddps (%rsi), %ymm0, %ymm1
23690   // Requires just 1 allocation, i.e., freeing allocations for other operations
23691   // and having less micro operations to execute.
23692   //
23693   // For some X86 architectures, this is even worse because for instance for
23694   // stores, the complex addressing mode forces the instruction to use the
23695   // "load" ports instead of the dedicated "store" port.
23696   // E.g., on Haswell:
23697   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23698   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23699   if (isLegalAddressingMode(AM, Ty))
23700     // Scale represents reg2 * scale, thus account for 1
23701     // as soon as we use a second register.
23702     return AM.Scale != 0;
23703   return -1;
23704 }
23705
23706 bool X86TargetLowering::isTargetFTOL() const {
23707   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23708 }